LLDB mainline
Module.cpp
Go to the documentation of this file.
1//===-- Module.cpp --------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "lldb/Core/Module.h"
10
14#include "lldb/Core/Debugger.h"
15#include "lldb/Core/Mangled.h"
18#include "lldb/Core/Section.h"
20#include "lldb/Host/Host.h"
21#include "lldb/Host/HostInfo.h"
27#include "lldb/Symbol/Symbol.h"
32#include "lldb/Symbol/Symtab.h"
33#include "lldb/Symbol/Type.h"
35#include "lldb/Symbol/TypeMap.h"
38#include "lldb/Target/Process.h"
39#include "lldb/Target/Target.h"
44#include "lldb/Utility/Log.h"
46#include "lldb/Utility/Status.h"
47#include "lldb/Utility/Stream.h"
49#include "lldb/Utility/Timer.h"
50
51#if defined(_WIN32)
53#endif
54
55#include "llvm/ADT/STLExtras.h"
56#include "llvm/Support/Compiler.h"
57#include "llvm/Support/DJB.h"
58#include "llvm/Support/FileSystem.h"
59#include "llvm/Support/FormatVariadic.h"
60#include "llvm/Support/JSON.h"
61#include "llvm/Support/Signals.h"
62#include "llvm/Support/raw_ostream.h"
63
64#include <cassert>
65#include <cinttypes>
66#include <cstdarg>
67#include <cstdint>
68#include <cstring>
69#include <map>
70#include <optional>
71#include <type_traits>
72#include <utility>
73
74namespace lldb_private {
76}
77namespace lldb_private {
78class VariableList;
79}
80
81using namespace lldb;
82using namespace lldb_private;
83
84// Shared pointers to modules track module lifetimes in targets and in the
85// global module, but this collection will track all module objects that are
86// still alive
87typedef std::vector<Module *> ModuleCollection;
88
90 // This module collection needs to live past any module, so we could either
91 // make it a shared pointer in each module or just leak is. Since it is only
92 // an empty vector by the time all the modules have gone away, we just leak
93 // it for now. If we decide this is a big problem we can introduce a
94 // Finalize method that will tear everything down in a predictable order.
95
96 static ModuleCollection *g_module_collection = nullptr;
97 if (g_module_collection == nullptr)
98 g_module_collection = new ModuleCollection();
99
100 return *g_module_collection;
101}
102
104 // NOTE: The mutex below must be leaked since the global module list in
105 // the ModuleList class will get torn at some point, and we can't know if it
106 // will tear itself down before the "g_module_collection_mutex" below will.
107 // So we leak a Mutex object below to safeguard against that
108
109 static std::recursive_mutex *g_module_collection_mutex = nullptr;
110 if (g_module_collection_mutex == nullptr)
111 g_module_collection_mutex = new std::recursive_mutex; // NOTE: known leak
112 return *g_module_collection_mutex;
113}
114
116 std::lock_guard<std::recursive_mutex> guard(
118 return GetModuleCollection().size();
119}
120
122 std::lock_guard<std::recursive_mutex> guard(
125 if (idx < modules.size())
126 return modules[idx];
127 return nullptr;
128}
129
130static std::atomic<lldb::user_id_t> g_unique_id = 1;
131
132Module::Module(const ModuleSpec &module_spec)
135 // Scope for locker below...
136 {
137 std::lock_guard<std::recursive_mutex> guard(
139 GetModuleCollection().push_back(this);
140 }
141
143 if (log != nullptr)
144 LLDB_LOGF(log, "%p Module::Module((%s) '%s%s%s%s')",
145 static_cast<void *>(this),
146 module_spec.GetArchitecture().GetArchitectureName(),
147 module_spec.GetFileSpec().GetPath().c_str(),
148 module_spec.GetObjectName().IsEmpty() ? "" : "(",
149 module_spec.GetObjectName().AsCString(""),
150 module_spec.GetObjectName().IsEmpty() ? "" : ")");
151
152 auto data_sp = module_spec.GetData();
153 lldb::offset_t file_size = 0;
154 if (data_sp)
155 file_size = data_sp->GetByteSize();
156
157 // First extract all module specifications from the file using the local file
158 // path. If there are no specifications, then don't fill anything in
159 ModuleSpecList modules_specs;
161 module_spec.GetFileSpec(), 0, file_size, modules_specs, data_sp) == 0)
162 return;
163
164 // Now make sure that one of the module specifications matches what we just
165 // extract. We might have a module specification that specifies a file
166 // "/usr/lib/dyld" with UUID XXX, but we might have a local version of
167 // "/usr/lib/dyld" that has
168 // UUID YYY and we don't want those to match. If they don't match, just don't
169 // fill any ivars in so we don't accidentally grab the wrong file later since
170 // they don't match...
171 ModuleSpec matching_module_spec;
172 if (!modules_specs.FindMatchingModuleSpec(module_spec,
173 matching_module_spec)) {
174 if (log) {
175 LLDB_LOGF(log, "Found local object file but the specs didn't match");
176 }
177 return;
178 }
179
180 // Set m_data_sp if it was initially provided in the ModuleSpec. Note that
181 // we cannot use the data_sp variable here, because it will have been
182 // modified by GetModuleSpecifications().
183 if (auto module_spec_data_sp = module_spec.GetData()) {
184 m_data_sp = module_spec_data_sp;
185 m_mod_time = {};
186 } else {
187 if (module_spec.GetFileSpec())
188 m_mod_time =
190 else if (matching_module_spec.GetFileSpec())
192 matching_module_spec.GetFileSpec());
193 }
194
195 // Copy the architecture from the actual spec if we got one back, else use
196 // the one that was specified
197 if (matching_module_spec.GetArchitecture().IsValid())
198 m_arch = matching_module_spec.GetArchitecture();
199 else if (module_spec.GetArchitecture().IsValid())
200 m_arch = module_spec.GetArchitecture();
201
202 // Copy the file spec over and use the specified one (if there was one) so we
203 // don't use a path that might have gotten resolved a path in
204 // 'matching_module_spec'
205 if (module_spec.GetFileSpec())
206 m_file = module_spec.GetFileSpec();
207 else if (matching_module_spec.GetFileSpec())
208 m_file = matching_module_spec.GetFileSpec();
209
210 // Copy the platform file spec over
211 if (module_spec.GetPlatformFileSpec())
212 m_platform_file = module_spec.GetPlatformFileSpec();
213 else if (matching_module_spec.GetPlatformFileSpec())
214 m_platform_file = matching_module_spec.GetPlatformFileSpec();
215
216 // Copy the symbol file spec over
217 if (module_spec.GetSymbolFileSpec())
218 m_symfile_spec = module_spec.GetSymbolFileSpec();
219 else if (matching_module_spec.GetSymbolFileSpec())
220 m_symfile_spec = matching_module_spec.GetSymbolFileSpec();
221
222 // Copy the object name over
223 if (matching_module_spec.GetObjectName())
224 m_object_name = matching_module_spec.GetObjectName();
225 else
226 m_object_name = module_spec.GetObjectName();
227
228 // Always trust the object offset (file offset) and object modification time
229 // (for mod time in a BSD static archive) of from the matching module
230 // specification
231 m_object_offset = matching_module_spec.GetObjectOffset();
232 m_object_mod_time = matching_module_spec.GetObjectModificationTime();
233}
234
235Module::Module(const FileSpec &file_spec, const ArchSpec &arch,
236 ConstString object_name, lldb::offset_t object_offset,
237 const llvm::sys::TimePoint<> &object_mod_time)
238 : UserID(g_unique_id++),
239 m_mod_time(FileSystem::Instance().GetModificationTime(file_spec)),
240 m_arch(arch), m_file(file_spec), m_object_name(object_name),
241 m_object_offset(object_offset), m_object_mod_time(object_mod_time),
242 m_unwind_table(*this), m_file_has_changed(false),
244 // Scope for locker below...
245 {
246 std::lock_guard<std::recursive_mutex> guard(
248 GetModuleCollection().push_back(this);
249 }
250
252 if (log != nullptr)
253 LLDB_LOGF(log, "%p Module::Module((%s) '%s%s%s%s')",
254 static_cast<void *>(this), m_arch.GetArchitectureName(),
255 m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
256 m_object_name.AsCString(""), m_object_name.IsEmpty() ? "" : ")");
257}
258
262 std::lock_guard<std::recursive_mutex> guard(
264 GetModuleCollection().push_back(this);
265}
266
268 // Lock our module down while we tear everything down to make sure we don't
269 // get any access to the module while it is being destroyed
270 std::lock_guard<std::recursive_mutex> guard(m_mutex);
271 // Scope for locker below...
272 {
273 std::lock_guard<std::recursive_mutex> guard(
276 ModuleCollection::iterator end = modules.end();
277 ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
278 assert(pos != end);
279 modules.erase(pos);
280 }
282 if (log != nullptr)
283 LLDB_LOGF(log, "%p Module::~Module((%s) '%s%s%s%s')",
284 static_cast<void *>(this), m_arch.GetArchitectureName(),
285 m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
286 m_object_name.AsCString(""), m_object_name.IsEmpty() ? "" : ")");
287 // Release any auto pointers before we start tearing down our member
288 // variables since the object file and symbol files might need to make
289 // function calls back into this module object. The ordering is important
290 // here because symbol files can require the module object file. So we tear
291 // down the symbol file first, then the object file.
292 m_sections_up.reset();
293 m_symfile_up.reset();
294 m_objfile_sp.reset();
295}
296
298 lldb::addr_t header_addr, Status &error,
299 size_t size_to_read) {
300 if (m_objfile_sp) {
301 error = Status::FromErrorString("object file already exists");
302 } else {
303 std::lock_guard<std::recursive_mutex> guard(m_mutex);
304 if (process_sp) {
305 m_did_load_objfile = true;
306 std::shared_ptr<DataBufferHeap> data_sp =
307 std::make_shared<DataBufferHeap>(size_to_read, 0);
308 Status readmem_error;
309 const size_t bytes_read =
310 process_sp->ReadMemory(header_addr, data_sp->GetBytes(),
311 data_sp->GetByteSize(), readmem_error);
312 if (bytes_read < size_to_read)
313 data_sp->SetByteSize(bytes_read);
314 if (data_sp->GetByteSize() > 0) {
315 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp,
316 header_addr, data_sp);
317 if (m_objfile_sp) {
318 StreamString s;
319 s.Printf("0x%16.16" PRIx64, header_addr);
320 m_object_name.SetString(s.GetString());
321
322 // Once we get the object file, update our module with the object
323 // file's architecture since it might differ in vendor/os if some
324 // parts were unknown.
325 m_arch = m_objfile_sp->GetArchitecture();
326
327 // Augment the arch with the target's information in case
328 // we are unable to extract the os/environment from memory.
329 m_arch.MergeFrom(process_sp->GetTarget().GetArchitecture());
330
331 m_unwind_table.ModuleWasUpdated();
332 } else {
334 "unable to find suitable object file plug-in");
335 }
336 } else {
338 "unable to read header from memory: %s", readmem_error.AsCString());
339 }
340 } else {
341 error = Status::FromErrorString("invalid process");
342 }
343 }
344 return m_objfile_sp.get();
345}
346
348 if (!m_did_set_uuid.load()) {
349 std::lock_guard<std::recursive_mutex> guard(m_mutex);
350 if (!m_did_set_uuid.load()) {
351 ObjectFile *obj_file = GetObjectFile();
352
353 if (obj_file != nullptr) {
354 m_uuid = obj_file->GetUUID();
355 m_did_set_uuid = true;
356 }
357 }
358 }
359 return m_uuid;
360}
361
363 std::lock_guard<std::recursive_mutex> guard(m_mutex);
364 if (!m_did_set_uuid) {
365 m_uuid = uuid;
366 m_did_set_uuid = true;
367 } else {
368 lldbassert(0 && "Attempting to overwrite the existing module UUID");
369 }
370}
371
372llvm::Expected<TypeSystemSP>
374 return m_type_system_map.GetTypeSystemForLanguage(language, this, true);
375}
376
378 llvm::function_ref<bool(lldb::TypeSystemSP)> callback) {
379 m_type_system_map.ForEach(callback);
380}
381
383 std::lock_guard<std::recursive_mutex> guard(m_mutex);
384 size_t num_comp_units = GetNumCompileUnits();
385 if (num_comp_units == 0)
386 return;
387
388 SymbolFile *symbols = GetSymbolFile();
389
390 for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++) {
391 SymbolContext sc;
392 sc.module_sp = shared_from_this();
393 sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
394 if (!sc.comp_unit)
395 continue;
396
397 symbols->ParseVariablesForContext(sc);
398
399 symbols->ParseFunctions(*sc.comp_unit);
400
401 sc.comp_unit->ForeachFunction([&sc, &symbols](const FunctionSP &f) {
402 symbols->ParseBlocksRecursive(*f);
403
404 // Parse the variables for this function and all its blocks
405 sc.function = f.get();
406 symbols->ParseVariablesForContext(sc);
407 return false;
408 });
409
410 // Parse all types for this compile unit
411 symbols->ParseTypes(*sc.comp_unit);
412 }
413}
414
416 sc->module_sp = shared_from_this();
417}
418
419ModuleSP Module::CalculateSymbolContextModule() { return shared_from_this(); }
420
422 s->Printf(", Module{%p}", static_cast<void *>(this));
423}
424
426 std::lock_guard<std::recursive_mutex> guard(m_mutex);
427 if (SymbolFile *symbols = GetSymbolFile())
428 return symbols->GetNumCompileUnits();
429 return 0;
430}
431
433 std::lock_guard<std::recursive_mutex> guard(m_mutex);
434 size_t num_comp_units = GetNumCompileUnits();
435 CompUnitSP cu_sp;
436
437 if (index < num_comp_units) {
438 if (SymbolFile *symbols = GetSymbolFile())
439 cu_sp = symbols->GetCompileUnitAtIndex(index);
440 }
441 return cu_sp;
442}
443
445 std::lock_guard<std::recursive_mutex> guard(m_mutex);
446 SectionList *section_list = GetSectionList();
447 if (section_list)
448 return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
449 return false;
450}
451
453 const Address &so_addr, lldb::SymbolContextItem resolve_scope,
454 SymbolContext &sc, bool resolve_tail_call_address) {
455 std::lock_guard<std::recursive_mutex> guard(m_mutex);
456 uint32_t resolved_flags = 0;
457
458 // Clear the result symbol context in case we don't find anything, but don't
459 // clear the target
460 sc.Clear(false);
461
462 // Get the section from the section/offset address.
463 SectionSP section_sp(so_addr.GetSection());
464
465 // Make sure the section matches this module before we try and match anything
466 if (section_sp && section_sp->GetModule().get() == this) {
467 // If the section offset based address resolved itself, then this is the
468 // right module.
469 sc.module_sp = shared_from_this();
470 resolved_flags |= eSymbolContextModule;
471
472 SymbolFile *symfile = GetSymbolFile();
473 if (!symfile)
474 return resolved_flags;
475
476 // Resolve the compile unit, function, block, line table or line entry if
477 // requested.
478 if (resolve_scope & eSymbolContextCompUnit ||
479 resolve_scope & eSymbolContextFunction ||
480 resolve_scope & eSymbolContextBlock ||
481 resolve_scope & eSymbolContextLineEntry ||
482 resolve_scope & eSymbolContextVariable) {
483 symfile->SetLoadDebugInfoEnabled();
484 resolved_flags |=
485 symfile->ResolveSymbolContext(so_addr, resolve_scope, sc);
486
487 if ((resolve_scope & eSymbolContextLineEntry) && sc.line_entry.IsValid())
489 }
490
491 // Resolve the symbol if requested, but don't re-look it up if we've
492 // already found it.
493 if (resolve_scope & eSymbolContextSymbol &&
494 !(resolved_flags & eSymbolContextSymbol)) {
495 Symtab *symtab = symfile->GetSymtab();
496 if (symtab && so_addr.IsSectionOffset()) {
497 Symbol *matching_symbol = nullptr;
498
499 addr_t file_address = so_addr.GetFileAddress();
500 Symbol *symbol_at_address =
501 symtab->FindSymbolAtFileAddress(file_address);
502 if (symbol_at_address &&
503 symbol_at_address->GetType() != lldb::eSymbolTypeInvalid) {
504 matching_symbol = symbol_at_address;
505 } else {
507 file_address, [&matching_symbol](Symbol *symbol) -> bool {
508 if (symbol->GetType() != eSymbolTypeInvalid) {
509 matching_symbol = symbol;
510 return false; // Stop iterating
511 }
512 return true; // Keep iterating
513 });
514 }
515
516 sc.symbol = matching_symbol;
517 if (!sc.symbol && resolve_scope & eSymbolContextFunction &&
518 !(resolved_flags & eSymbolContextFunction)) {
519 bool verify_unique = false; // No need to check again since
520 // ResolveSymbolContext failed to find a
521 // symbol at this address.
522 if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
523 sc.symbol =
524 obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
525 }
526
527 if (sc.symbol) {
528 if (sc.symbol->IsSynthetic()) {
529 // We have a synthetic symbol so lets check if the object file from
530 // the symbol file in the symbol vendor is different than the
531 // object file for the module, and if so search its symbol table to
532 // see if we can come up with a better symbol. For example dSYM
533 // files on MacOSX have an unstripped symbol table inside of them.
534 ObjectFile *symtab_objfile = symtab->GetObjectFile();
535 if (symtab_objfile && symtab_objfile->IsStripped()) {
536 ObjectFile *symfile_objfile = symfile->GetObjectFile();
537 if (symfile_objfile != symtab_objfile) {
538 Symtab *symfile_symtab = symfile_objfile->GetSymtab();
539 if (symfile_symtab) {
540 Symbol *symbol =
541 symfile_symtab->FindSymbolContainingFileAddress(
542 so_addr.GetFileAddress());
543 if (symbol && !symbol->IsSynthetic()) {
544 sc.symbol = symbol;
545 }
546 }
547 }
548 }
549 }
550 resolved_flags |= eSymbolContextSymbol;
551 }
552 }
553 }
554
555 // For function symbols, so_addr may be off by one. This is a convention
556 // consistent with FDE row indices in eh_frame sections, but requires extra
557 // logic here to permit symbol lookup for disassembly and unwind.
558 if (resolve_scope & eSymbolContextSymbol &&
559 !(resolved_flags & eSymbolContextSymbol) && resolve_tail_call_address &&
560 so_addr.IsSectionOffset()) {
561 Address previous_addr = so_addr;
562 previous_addr.Slide(-1);
563
564 bool do_resolve_tail_call_address = false; // prevent recursion
565 const uint32_t flags = ResolveSymbolContextForAddress(
566 previous_addr, resolve_scope, sc, do_resolve_tail_call_address);
567 if (flags & eSymbolContextSymbol) {
568 AddressRange addr_range;
569 if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
570 false, addr_range)) {
571 if (addr_range.GetBaseAddress().GetSection() ==
572 so_addr.GetSection()) {
573 // If the requested address is one past the address range of a
574 // function (i.e. a tail call), or the decremented address is the
575 // start of a function (i.e. some forms of trampoline), indicate
576 // that the symbol has been resolved.
577 if (so_addr.GetOffset() ==
578 addr_range.GetBaseAddress().GetOffset() ||
579 so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() +
580 addr_range.GetByteSize()) {
581 resolved_flags |= flags;
582 }
583 } else {
584 sc.symbol =
585 nullptr; // Don't trust the symbol if the sections didn't match.
586 }
587 }
588 }
589 }
590 }
591 return resolved_flags;
592}
593
595 const char *file_path, uint32_t line, bool check_inlines,
596 lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
597 FileSpec file_spec(file_path);
598 return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
599 resolve_scope, sc_list);
600}
601
603 const FileSpec &file_spec, uint32_t line, bool check_inlines,
604 lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
605 std::lock_guard<std::recursive_mutex> guard(m_mutex);
606 LLDB_SCOPED_TIMERF("Module::ResolveSymbolContextForFilePath (%s:%u, "
607 "check_inlines = %s, resolve_scope = 0x%8.8x)",
608 file_spec.GetPath().c_str(), line,
609 check_inlines ? "yes" : "no", resolve_scope);
610
611 const uint32_t initial_count = sc_list.GetSize();
612
613 if (SymbolFile *symbols = GetSymbolFile()) {
614 // TODO: Handle SourceLocationSpec column information
615 SourceLocationSpec location_spec(file_spec, line, /*column=*/std::nullopt,
616 check_inlines, /*exact_match=*/false);
617
618 symbols->ResolveSymbolContext(location_spec, resolve_scope, sc_list);
619 }
620
621 return sc_list.GetSize() - initial_count;
622}
623
625 const CompilerDeclContext &parent_decl_ctx,
626 size_t max_matches, VariableList &variables) {
627 if (SymbolFile *symbols = GetSymbolFile())
628 symbols->FindGlobalVariables(name, parent_decl_ctx, max_matches, variables);
629}
630
632 size_t max_matches, VariableList &variables) {
633 SymbolFile *symbols = GetSymbolFile();
634 if (symbols)
635 symbols->FindGlobalVariables(regex, max_matches, variables);
636}
637
639 SymbolContextList &sc_list) {
640 const size_t num_compile_units = GetNumCompileUnits();
641 SymbolContext sc;
642 sc.module_sp = shared_from_this();
643 for (size_t i = 0; i < num_compile_units; ++i) {
644 sc.comp_unit = GetCompileUnitAtIndex(i).get();
645 if (sc.comp_unit) {
647 sc_list.Append(sc);
648 }
649 }
650}
651
653 ConstString lookup_name)
654 : m_name(lookup_info.GetName()), m_lookup_name(lookup_name),
655 m_language(lookup_info.GetLanguageType()),
656 m_name_type_mask(lookup_info.GetNameTypeMask()) {}
657
659 FunctionNameType name_type_mask,
660 LanguageType lang_type)
661 : m_name(name), m_lookup_name(lookup_name), m_language(lang_type) {
662 std::optional<ConstString> basename;
663 Language *lang = Language::FindPlugin(lang_type);
664
665 if (name_type_mask & eFunctionNameTypeAuto) {
666 if (lang) {
667 auto info = lang->GetFunctionNameInfo(name);
668 if (info.first != eFunctionNameTypeNone) {
669 m_name_type_mask |= info.first;
670 if (!basename && info.second)
671 basename = info.second;
672 }
673 }
674
675 // NOTE: There are several ways to get here, but this is a fallback path in
676 // case the above does not succeed at extracting any useful information from
677 // the loaded language plugins.
678 if (m_name_type_mask == eFunctionNameTypeNone)
679 m_name_type_mask = eFunctionNameTypeFull;
680
681 } else {
682 m_name_type_mask = name_type_mask;
683 if (lang) {
684 auto info = lang->GetFunctionNameInfo(name);
685 if (info.first & m_name_type_mask) {
686 // If the user asked for FunctionNameTypes that aren't possible,
687 // then filter those out. (e.g. asking for Selectors on
688 // C++ symbols, or even if the symbol given can't be a selector in
689 // ObjC)
690 m_name_type_mask &= info.first;
691 basename = info.second;
692 } else if (name_type_mask & eFunctionNameTypeFull &&
693 info.first != eFunctionNameTypeNone && !basename &&
694 info.second) {
695 // Still try and get a basename in case someone specifies a name type
696 // mask of eFunctionNameTypeFull and a name like "A::func"
697 basename = info.second;
698 }
699 }
700 }
701
702 if (basename) {
703 // The name supplied was incomplete for lookup purposes. For example, in C++
704 // we may have gotten something like "a::count". In this case, we want to do
705 // a lookup on the basename "count" and then make sure any matching results
706 // contain "a::count" so that it would match "b::a::count" and "a::count".
707 // This is why we set match_name_after_lookup to true.
708 m_lookup_name.SetString(*basename);
710 }
711}
712
713std::vector<Module::LookupInfo> Module::LookupInfo::MakeLookupInfos(
714 ConstString name, lldb::FunctionNameType name_type_mask,
715 lldb::LanguageType lang_type, ConstString lookup_name_override) {
716 std::vector<LanguageType> lang_types;
717 if (lang_type != eLanguageTypeUnknown) {
718 lang_types.push_back(lang_type);
719 } else {
720 // If the language type was not specified, look up in every language
721 // available.
722 Language::ForEach([&](Language *lang) {
723 auto lang_type = lang->GetLanguageType();
724 if (!llvm::is_contained(lang_types, lang_type))
725 lang_types.push_back(lang_type);
727 });
728
729 if (lang_types.empty())
731 }
732
733 ConstString lookup_name = lookup_name_override ? lookup_name_override : name;
734
735 std::vector<Module::LookupInfo> infos;
736 infos.reserve(lang_types.size());
737 for (LanguageType lang_type : lang_types) {
738 Module::LookupInfo info(name, lookup_name, name_type_mask, lang_type);
739 infos.push_back(info);
740 }
741 return infos;
742}
743
745 ConstString function_name, LanguageType language_type) const {
746 // We always keep unnamed symbols
747 if (!function_name)
748 return true;
749
750 // If we match exactly, we can return early
751 if (m_name == function_name)
752 return true;
753
754 // If function_name is mangled, we'll need to demangle it.
755 // In the pathologial case where the function name "looks" mangled but is
756 // actually demangled (e.g. a method named _Zonk), this operation should be
757 // relatively inexpensive since no demangling is actually occuring. See
758 // Mangled::SetValue for more context.
759 const bool function_name_may_be_mangled =
761 ConstString demangled_function_name = function_name;
762 if (function_name_may_be_mangled) {
763 Mangled mangled_function_name(function_name);
764 demangled_function_name = mangled_function_name.GetDemangledName();
765 }
766
767 // If the symbol has a language, then let the language make the match.
768 // Otherwise just check that the demangled function name contains the
769 // demangled user-provided name.
770 if (Language *language = Language::FindPlugin(language_type))
771 return language->DemangledNameContainsPath(m_name, demangled_function_name);
772
773 llvm::StringRef function_name_ref = demangled_function_name;
774 return function_name_ref.contains(m_name);
775}
776
778 size_t start_idx) const {
780 SymbolContext sc;
781 size_t i = start_idx;
782 while (i < sc_list.GetSize()) {
783 if (!sc_list.GetContextAtIndex(i, sc))
784 break;
785
786 bool keep_it =
788 if (keep_it)
789 ++i;
790 else
791 sc_list.RemoveContextAtIndex(i);
792 }
793 }
794
795 // If we have only full name matches we might have tried to set breakpoint on
796 // "func" and specified eFunctionNameTypeFull, but we might have found
797 // "a::func()", "a::b::func()", "c::func()", "func()" and "func". Only
798 // "func()" and "func" should end up matching.
800 if (lang && m_name_type_mask == eFunctionNameTypeFull) {
801 SymbolContext sc;
802 size_t i = start_idx;
803 while (i < sc_list.GetSize()) {
804 if (!sc_list.GetContextAtIndex(i, sc))
805 break;
806 // Make sure the mangled and demangled names don't match before we try to
807 // pull anything out
809 ConstString full_name(sc.GetFunctionName());
810 if (mangled_name != m_name && full_name != m_name) {
811 std::unique_ptr<Language::MethodName> cpp_method =
812 lang->GetMethodName(full_name);
813 if (cpp_method->IsValid()) {
814 if (cpp_method->GetContext().empty()) {
815 if (cpp_method->GetBasename().compare(m_name) != 0) {
816 sc_list.RemoveContextAtIndex(i);
817 continue;
818 }
819 } else {
820 std::string qualified_name;
821 llvm::StringRef anon_prefix("(anonymous namespace)");
822 if (cpp_method->GetContext() == anon_prefix)
823 qualified_name = cpp_method->GetBasename().str();
824 else
825 qualified_name = cpp_method->GetScopeQualifiedName();
826 if (qualified_name != m_name.GetCString()) {
827 sc_list.RemoveContextAtIndex(i);
828 continue;
829 }
830 }
831 }
832 }
833 ++i;
834 }
835 }
836}
837
838void Module::FindFunctions(llvm::ArrayRef<Module::LookupInfo> lookup_infos,
839 const CompilerDeclContext &parent_decl_ctx,
840 const ModuleFunctionSearchOptions &options,
841 SymbolContextList &sc_list) {
842 for (auto &lookup_info : lookup_infos) {
843 SymbolFile *symbols = GetSymbolFile();
844 if (!symbols)
845 continue;
846
847 symbols->FindFunctions(lookup_info, parent_decl_ctx,
848 options.include_inlines, sc_list);
849 if (options.include_symbols)
850 if (Symtab *symtab = symbols->GetSymtab())
851 symtab->FindFunctionSymbols(lookup_info.GetLookupName(),
852 lookup_info.GetNameTypeMask(), sc_list);
853 }
854}
855
857 const CompilerDeclContext &parent_decl_ctx,
858 FunctionNameType name_type_mask,
859 const ModuleFunctionSearchOptions &options,
860 SymbolContextList &sc_list) {
861 std::vector<LookupInfo> lookup_infos =
863 for (auto &lookup_info : lookup_infos) {
864 const size_t old_size = sc_list.GetSize();
865 FindFunctions(lookup_info, parent_decl_ctx, options, sc_list);
866 if (name_type_mask & eFunctionNameTypeAuto) {
867 const size_t new_size = sc_list.GetSize();
868 if (old_size < new_size)
869 lookup_info.Prune(sc_list, old_size);
870 }
871 }
872}
873
874void Module::FindFunctions(llvm::ArrayRef<CompilerContext> compiler_ctx,
875 FunctionNameType name_type_mask,
876 const ModuleFunctionSearchOptions &options,
877 SymbolContextList &sc_list) {
878 if (compiler_ctx.empty() ||
879 compiler_ctx.back().kind != CompilerContextKind::Function)
880 return;
881 ConstString name = compiler_ctx.back().name;
882 SymbolContextList unfiltered;
883 FindFunctions(name, CompilerDeclContext(), name_type_mask, options,
884 unfiltered);
885 // Filter by context.
886 for (auto &sc : unfiltered)
887 if (sc.function && compiler_ctx.equals(sc.function->GetCompilerContext()))
888 sc_list.Append(sc);
889}
890
892 const ModuleFunctionSearchOptions &options,
893 SymbolContextList &sc_list) {
894 const size_t start_size = sc_list.GetSize();
895
896 if (SymbolFile *symbols = GetSymbolFile()) {
897 symbols->FindFunctions(regex, options.include_inlines, sc_list);
898
899 // Now check our symbol table for symbols that are code symbols if
900 // requested
901 if (options.include_symbols) {
902 Symtab *symtab = symbols->GetSymtab();
903 if (symtab) {
904 std::vector<uint32_t> symbol_indexes;
907 symbol_indexes);
908 const size_t num_matches = symbol_indexes.size();
909 if (num_matches) {
910 SymbolContext sc(this);
911 const size_t end_functions_added_index = sc_list.GetSize();
912 size_t num_functions_added_to_sc_list =
913 end_functions_added_index - start_size;
914 if (num_functions_added_to_sc_list == 0) {
915 // No functions were added, just symbols, so we can just append
916 // them
917 for (size_t i = 0; i < num_matches; ++i) {
918 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
919 SymbolType sym_type = sc.symbol->GetType();
920 if (sc.symbol && (sym_type == eSymbolTypeCode ||
921 sym_type == eSymbolTypeResolver))
922 sc_list.Append(sc);
923 }
924 } else {
925 typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
926 FileAddrToIndexMap file_addr_to_index;
927 for (size_t i = start_size; i < end_functions_added_index; ++i) {
928 const SymbolContext &sc = sc_list[i];
929 if (sc.block)
930 continue;
931 file_addr_to_index[sc.function->GetAddress().GetFileAddress()] =
932 i;
933 }
934
935 FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
936 // Functions were added so we need to merge symbols into any
937 // existing function symbol contexts
938 for (size_t i = start_size; i < num_matches; ++i) {
939 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
940 SymbolType sym_type = sc.symbol->GetType();
941 if (sc.symbol && sc.symbol->ValueIsAddress() &&
942 (sym_type == eSymbolTypeCode ||
943 sym_type == eSymbolTypeResolver)) {
944 FileAddrToIndexMap::const_iterator pos =
945 file_addr_to_index.find(
947 if (pos == end)
948 sc_list.Append(sc);
949 else
950 sc_list[pos->second].symbol = sc.symbol;
951 }
952 }
953 }
954 }
955 }
956 }
957 }
958}
959
961 const FileSpec &file, uint32_t line,
962 Function *function,
963 std::vector<Address> &output_local,
964 std::vector<Address> &output_extern) {
965 SearchFilterByModule filter(target_sp, m_file);
966
967 // TODO: Handle SourceLocationSpec column information
968 SourceLocationSpec location_spec(file, line, /*column=*/std::nullopt,
969 /*check_inlines=*/true,
970 /*exact_match=*/false);
971 AddressResolverFileLine resolver(location_spec);
972 resolver.ResolveAddress(filter);
973
974 for (size_t n = 0; n < resolver.GetNumberOfAddresses(); n++) {
975 Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
977 if (f && f == function)
978 output_local.push_back(addr);
979 else
980 output_extern.push_back(addr);
981 }
982}
983
984void Module::FindTypes(const TypeQuery &query, TypeResults &results) {
985 if (SymbolFile *symbols = GetSymbolFile())
986 symbols->FindTypes(query, results);
987}
988
991 Debugger::DebuggerList requestors =
993 Debugger::DebuggerList interruptors;
994 if (requestors.empty())
995 return interruptors;
996
997 for (auto debugger_sp : requestors) {
998 if (!debugger_sp->InterruptRequested())
999 continue;
1000 if (debugger_sp->GetTargetList().AnyTargetContainsModule(module))
1001 interruptors.push_back(debugger_sp);
1002 }
1003 return interruptors;
1004}
1005
1006SymbolFile *Module::GetSymbolFile(bool can_create, Stream *feedback_strm) {
1007 if (!m_did_load_symfile.load()) {
1008 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1009 if (!m_did_load_symfile.load() && can_create) {
1010 Debugger::DebuggerList interruptors =
1012 if (!interruptors.empty()) {
1013 for (auto debugger_sp : interruptors) {
1014 REPORT_INTERRUPTION(*(debugger_sp.get()),
1015 "Interrupted fetching symbols for module {0}",
1016 this->GetFileSpec());
1017 }
1018 return nullptr;
1019 }
1020 ObjectFile *obj_file = GetObjectFile();
1021 if (obj_file != nullptr) {
1023 m_symfile_up.reset(
1024 SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
1025 m_did_load_symfile = true;
1026 m_unwind_table.ModuleWasUpdated();
1027 }
1028 }
1029 }
1030 return m_symfile_up ? m_symfile_up->GetSymbolFile() : nullptr;
1031}
1032
1033Symtab *Module::GetSymtab(bool can_create) {
1034 if (SymbolFile *symbols = GetSymbolFile(can_create))
1035 return symbols->GetSymtab(can_create);
1036 return nullptr;
1037}
1038
1040 ConstString object_name) {
1041 // Container objects whose paths do not specify a file directly can call this
1042 // function to correct the file and object names.
1043 m_file = file;
1045 m_object_name = object_name;
1046}
1047
1048const ArchSpec &Module::GetArchitecture() const { return m_arch; }
1049
1051 std::string spec(GetFileSpec().GetPath());
1052 if (m_object_name) {
1053 spec += '(';
1054 spec += m_object_name.GetCString();
1055 spec += ')';
1056 }
1057 return spec;
1058}
1059
1060void Module::GetDescription(llvm::raw_ostream &s,
1061 lldb::DescriptionLevel level) {
1062 if (level >= eDescriptionLevelFull) {
1063 if (m_arch.IsValid())
1064 s << llvm::formatv("({0}) ", m_arch.GetArchitectureName());
1065 }
1066
1067 if (level == eDescriptionLevelBrief) {
1068 const char *filename = m_file.GetFilename().GetCString();
1069 if (filename)
1070 s << filename;
1071 } else {
1072 char path[PATH_MAX];
1073 if (m_file.GetPath(path, sizeof(path)))
1074 s << path;
1075 }
1076
1077 const char *object_name = m_object_name.GetCString();
1078 if (object_name)
1079 s << llvm::formatv("({0})", object_name);
1080}
1081
1083 // We have provided the DataBuffer for this module to avoid accessing the
1084 // filesystem. We never want to reload those files.
1085 if (m_data_sp)
1086 return false;
1087 if (!m_file_has_changed)
1090 return m_file_has_changed;
1091}
1092
1094 std::optional<lldb::user_id_t> debugger_id) {
1095 ConstString file_name = GetFileSpec().GetFilename();
1096 if (file_name.IsEmpty())
1097 return;
1098
1099 StreamString ss;
1100 ss << file_name
1101 << " was compiled with optimization - stepping may behave "
1102 "oddly; variables may not be available.";
1103 llvm::StringRef msg = ss.GetString();
1104 Debugger::ReportWarning(msg.str(), debugger_id, GetDiagnosticOnceFlag(msg));
1105}
1106
1108 LanguageType language, std::optional<lldb::user_id_t> debugger_id) {
1109 StreamString ss;
1110 ss << "This version of LLDB has no plugin for the language \""
1112 << "\". "
1113 "Inspection of frame variables will be limited.";
1114 llvm::StringRef msg = ss.GetString();
1115 Debugger::ReportWarning(msg.str(), debugger_id, GetDiagnosticOnceFlag(msg));
1116}
1117
1119 const llvm::formatv_object_base &payload) {
1121 if (FileHasChanged()) {
1123 StreamString strm;
1124 strm.PutCString("the object file ");
1126 strm.PutCString(" has been modified\n");
1127 strm.PutCString(payload.str());
1128 strm.PutCString("The debug session should be aborted as the original "
1129 "debug information has been overwritten.");
1130 Debugger::ReportError(std::string(strm.GetString()));
1131 }
1132 }
1133}
1134
1135std::once_flag *Module::GetDiagnosticOnceFlag(llvm::StringRef msg) {
1136 std::lock_guard<std::recursive_mutex> guard(m_diagnostic_mutex);
1137 auto &once_ptr = m_shown_diagnostics[llvm::stable_hash_name(msg)];
1138 if (!once_ptr)
1139 once_ptr = std::make_unique<std::once_flag>();
1140 return once_ptr.get();
1141}
1142
1143void Module::ReportError(const llvm::formatv_object_base &payload) {
1144 StreamString strm;
1146 std::string msg = payload.str();
1147 strm << ' ' << msg;
1149}
1150
1151void Module::ReportWarning(const llvm::formatv_object_base &payload) {
1152 StreamString strm;
1154 std::string msg = payload.str();
1155 strm << ' ' << msg;
1156 Debugger::ReportWarning(strm.GetString().str(), {},
1158}
1159
1160void Module::LogMessage(Log *log, const llvm::formatv_object_base &payload) {
1161 StreamString log_message;
1163 log_message.PutCString(": ");
1164 log_message.PutCString(payload.str());
1165 log->PutCString(log_message.GetData());
1166}
1167
1169 Log *log, const llvm::formatv_object_base &payload) {
1170 StreamString log_message;
1172 log_message.PutCString(": ");
1173 log_message.PutCString(payload.str());
1174 if (log->GetVerbose()) {
1175 std::string back_trace;
1176 llvm::raw_string_ostream stream(back_trace);
1177 llvm::sys::PrintStackTrace(stream);
1178 log_message.PutCString(back_trace);
1179 }
1180 log->PutCString(log_message.GetData());
1181}
1182
1184 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1185 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1186 s->Indent();
1187 s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(),
1188 m_object_name ? "(" : "",
1189 m_object_name ? m_object_name.GetCString() : "",
1190 m_object_name ? ")" : "");
1191
1192 s->IndentMore();
1193
1194 ObjectFile *objfile = GetObjectFile();
1195 if (objfile)
1196 objfile->Dump(s);
1197
1198 if (SymbolFile *symbols = GetSymbolFile())
1199 symbols->Dump(*s);
1200
1201 s->IndentLess();
1202}
1203
1205
1207 if (!m_did_load_objfile.load()) {
1208 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1209 if (!m_did_load_objfile.load()) {
1210 LLDB_SCOPED_TIMERF("Module::GetObjectFile () module = %s",
1211 GetFileSpec().GetFilename().AsCString(""));
1212 lldb::offset_t data_offset = 0;
1213 lldb::offset_t file_size = 0;
1214
1215 if (m_data_sp)
1216 file_size = m_data_sp->GetByteSize();
1217 else if (m_file)
1219
1220 if (file_size > m_object_offset) {
1221 m_did_load_objfile = true;
1222 // FindPlugin will modify its data_sp argument. Do not let it
1223 // modify our m_data_sp member.
1224 DataExtractorSP extractor_sp;
1225 if (m_data_sp)
1226 extractor_sp = std::make_shared<DataExtractor>(m_data_sp);
1228 shared_from_this(), &m_file, m_object_offset,
1229 file_size - m_object_offset, extractor_sp, data_offset);
1230 if (m_objfile_sp) {
1231 // Once we get the object file, update our module with the object
1232 // file's architecture since it might differ in vendor/os if some
1233 // parts were unknown. But since the matching arch might already be
1234 // more specific than the generic COFF architecture, only merge in
1235 // those values that overwrite unspecified unknown values.
1236 m_arch.MergeFrom(m_objfile_sp->GetArchitecture());
1237
1238 m_unwind_table.ModuleWasUpdated();
1239 } else {
1240 ReportError("failed to load objfile for {0}\nDebugging will be "
1241 "degraded for this module.",
1242 GetFileSpec().GetPath().c_str());
1243 }
1244 }
1245 }
1246 }
1247 return m_objfile_sp.get();
1248}
1249
1251 // Populate m_sections_up with sections from objfile.
1252 if (!m_sections_up) {
1253 ObjectFile *obj_file = GetObjectFile();
1254 if (obj_file != nullptr)
1256 }
1257 return m_sections_up.get();
1258}
1259
1261 ObjectFile *obj_file = GetObjectFile();
1262 if (obj_file)
1263 obj_file->SectionFileAddressesChanged();
1264 if (SymbolFile *symbols = GetSymbolFile())
1265 symbols->SectionFileAddressesChanged();
1266}
1267
1273
1275 if (!m_sections_up)
1276 m_sections_up = std::make_unique<SectionList>();
1277 return m_sections_up.get();
1278}
1279
1281 SymbolType symbol_type) {
1283 "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1284 name.AsCString(), symbol_type);
1285 if (Symtab *symtab = GetSymtab())
1286 return symtab->FindFirstSymbolWithNameAndType(
1287 name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1288 return nullptr;
1289}
1291 Symtab *symtab, std::vector<uint32_t> &symbol_indexes,
1292 SymbolContextList &sc_list) {
1293 // No need to protect this call using m_mutex all other method calls are
1294 // already thread safe.
1295
1296 size_t num_indices = symbol_indexes.size();
1297 if (num_indices > 0) {
1298 SymbolContext sc;
1300 for (size_t i = 0; i < num_indices; i++) {
1301 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
1302 if (sc.symbol)
1303 sc_list.Append(sc);
1304 }
1305 }
1306}
1307
1308void Module::FindFunctionSymbols(ConstString name, uint32_t name_type_mask,
1309 SymbolContextList &sc_list) {
1310 LLDB_SCOPED_TIMERF("Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1311 name.AsCString(), name_type_mask);
1312 if (Symtab *symtab = GetSymtab())
1313 symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
1314}
1315
1317 SymbolType symbol_type,
1318 SymbolContextList &sc_list) {
1319 // No need to protect this call using m_mutex all other method calls are
1320 // already thread safe.
1321 if (Symtab *symtab = GetSymtab()) {
1322 std::vector<uint32_t> symbol_indexes;
1323 symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes);
1324 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1325 }
1326}
1327
1329 const RegularExpression &regex, SymbolType symbol_type,
1330 SymbolContextList &sc_list, Mangled::NamePreference mangling_preference) {
1331 // No need to protect this call using m_mutex all other method calls are
1332 // already thread safe.
1334 "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1335 regex.GetText().str().c_str(), symbol_type);
1336 if (Symtab *symtab = GetSymtab()) {
1337 std::vector<uint32_t> symbol_indexes;
1338 symtab->FindAllSymbolsMatchingRexExAndType(
1339 regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny,
1340 symbol_indexes, mangling_preference);
1341 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1342 }
1343}
1344
1346 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1347 SymbolFile *sym_file = GetSymbolFile();
1348 if (!sym_file)
1349 return;
1350
1351 // Load the object file symbol table and any symbols from the SymbolFile that
1352 // get appended using SymbolFile::AddSymbols(...).
1353 if (Symtab *symtab = sym_file->GetSymtab())
1354 symtab->PreloadSymbols();
1355
1356 // Now let the symbol file preload its data and the symbol table will be
1357 // available without needing to take the module lock.
1358 sym_file->PreloadSymbols();
1359}
1360
1362 if (!FileSystem::Instance().Exists(file))
1363 return;
1364 if (m_symfile_up) {
1365 // Remove any sections in the unified section list that come from the
1366 // current symbol vendor.
1367 SectionList *section_list = GetSectionList();
1368 SymbolFile *symbol_file = GetSymbolFile();
1369 if (section_list && symbol_file) {
1370 ObjectFile *obj_file = symbol_file->GetObjectFile();
1371 // Make sure we have an object file and that the symbol vendor's objfile
1372 // isn't the same as the module's objfile before we remove any sections
1373 // for it...
1374 if (obj_file) {
1375 // Check to make sure we aren't trying to specify the file we already
1376 // have
1377 if (obj_file->GetFileSpec() == file) {
1378 // We are being told to add the exact same file that we already have
1379 // we don't have to do anything.
1380 return;
1381 }
1382
1383 // Cleare the current symtab as we are going to replace it with a new
1384 // one
1385 obj_file->ClearSymtab();
1386
1387 // The symbol file might be a directory bundle ("/tmp/a.out.dSYM")
1388 // instead of a full path to the symbol file within the bundle
1389 // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to
1390 // check this
1391 if (FileSystem::Instance().IsDirectory(file)) {
1392 std::string new_path(file.GetPath());
1393 std::string old_path(obj_file->GetFileSpec().GetPath());
1394 if (llvm::StringRef(old_path).starts_with(new_path)) {
1395 // We specified the same bundle as the symbol file that we already
1396 // have
1397 return;
1398 }
1399 }
1400
1401 if (obj_file != m_objfile_sp.get()) {
1402 size_t num_sections = section_list->GetNumSections(0);
1403 for (size_t idx = num_sections; idx > 0; --idx) {
1404 lldb::SectionSP section_sp(
1405 section_list->GetSectionAtIndex(idx - 1));
1406 if (section_sp->GetObjectFile() == obj_file) {
1407 section_list->DeleteSection(idx - 1);
1408 }
1409 }
1410 }
1411 }
1412 }
1413 // Keep all old symbol files around in case there are any lingering type
1414 // references in any SBValue objects that might have been handed out.
1415 m_old_symfiles.push_back(std::move(m_symfile_up));
1416 }
1417 m_symfile_spec = file;
1418 m_symfile_up.reset();
1419 m_did_load_symfile = false;
1420}
1421
1423 if (GetObjectFile() == nullptr)
1424 return false;
1425 else
1426 return GetObjectFile()->IsExecutable();
1427}
1428
1430 ObjectFile *obj_file = GetObjectFile();
1431 if (obj_file) {
1432 SectionList *sections = GetSectionList();
1433 if (sections != nullptr) {
1434 size_t num_sections = sections->GetSize();
1435 for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) {
1436 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1437 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) {
1438 return true;
1439 }
1440 }
1441 }
1442 }
1443 return false;
1444}
1445
1447 Stream &feedback_stream) {
1448 if (!target) {
1449 error = Status::FromErrorString("invalid destination Target");
1450 return false;
1451 }
1452
1453 LoadScriptFromSymFile should_load =
1454 target->TargetProperties::GetLoadScriptFromSymbolFile();
1455
1456 if (should_load == eLoadScriptFromSymFileFalse)
1457 return false;
1458
1459 Debugger &debugger = target->GetDebugger();
1460 const ScriptLanguage script_language = debugger.GetScriptLanguage();
1461 if (script_language != eScriptLanguageNone) {
1462
1463 PlatformSP platform_sp(target->GetPlatform());
1464
1465 if (!platform_sp) {
1466 error = Status::FromErrorString("invalid Platform");
1467 return false;
1468 }
1469
1470 FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources(
1471 target, *this, feedback_stream);
1472
1473 const uint32_t num_specs = file_specs.GetSize();
1474 if (num_specs) {
1475 ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
1476 if (script_interpreter) {
1477 for (uint32_t i = 0; i < num_specs; ++i) {
1478 FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i));
1479 if (scripting_fspec &&
1480 FileSystem::Instance().Exists(scripting_fspec)) {
1481 if (should_load == eLoadScriptFromSymFileWarn) {
1482 feedback_stream.Printf(
1483 "warning: '%s' contains a debug script. To run this script "
1484 "in "
1485 "this debug session:\n\n command script import "
1486 "\"%s\"\n\n"
1487 "To run all discovered debug scripts in this session:\n\n"
1488 " settings set target.load-script-from-symbol-file "
1489 "true\n",
1490 GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1491 scripting_fspec.GetPath().c_str());
1492 return false;
1493 }
1494 StreamString scripting_stream;
1495 scripting_fspec.Dump(scripting_stream.AsRawOstream());
1496 LoadScriptOptions options;
1497 bool did_load = script_interpreter->LoadScriptingModule(
1498 scripting_stream.GetData(), options, error,
1499 /*module_sp*/ nullptr, /*extra_path*/ {},
1500 target->shared_from_this());
1501 if (!did_load)
1502 return false;
1503 }
1504 }
1505 } else {
1506 error = Status::FromErrorString("invalid ScriptInterpreter");
1507 return false;
1508 }
1509 }
1510 }
1511 return true;
1512}
1513
1514bool Module::SetArchitecture(const ArchSpec &new_arch) {
1515 if (!m_arch.IsValid()) {
1516 m_arch = new_arch;
1517 return true;
1518 }
1519 return m_arch.IsCompatibleMatch(new_arch);
1520}
1521
1523 bool value_is_offset, bool &changed) {
1524 ObjectFile *object_file = GetObjectFile();
1525 if (object_file != nullptr) {
1526 changed = object_file->SetLoadAddress(target, value, value_is_offset);
1527 return true;
1528 } else {
1529 changed = false;
1530 }
1531 return false;
1532}
1533
1534bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) {
1535 const UUID &uuid = module_ref.GetUUID();
1536
1537 if (uuid.IsValid()) {
1538 // If the UUID matches, then nothing more needs to match...
1539 return (uuid == GetUUID());
1540 }
1541
1542 const FileSpec &file_spec = module_ref.GetFileSpec();
1543 if (!FileSpec::Match(file_spec, m_file) &&
1544 !FileSpec::Match(file_spec, m_platform_file))
1545 return false;
1546
1547 const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1548 if (!FileSpec::Match(platform_file_spec, GetPlatformFileSpec()))
1549 return false;
1550
1551 const ArchSpec &arch = module_ref.GetArchitecture();
1552 if (arch.IsValid()) {
1553 if (!m_arch.IsCompatibleMatch(arch))
1554 return false;
1555 }
1556
1557 ConstString object_name = module_ref.GetObjectName();
1558 if (object_name) {
1559 if (object_name != GetObjectName())
1560 return false;
1561 }
1562 return true;
1563}
1564
1565bool Module::FindSourceFile(const FileSpec &orig_spec,
1566 FileSpec &new_spec) const {
1567 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1568 if (auto remapped = m_source_mappings.FindFile(orig_spec)) {
1569 new_spec = *remapped;
1570 return true;
1571 }
1572 return false;
1573}
1574
1575std::optional<std::string> Module::RemapSourceFile(llvm::StringRef path) const {
1576 std::lock_guard<std::recursive_mutex> guard(m_mutex);
1577 if (auto remapped = m_source_mappings.RemapPath(path))
1578 return remapped->GetPath();
1579 return {};
1580}
1581
1582void Module::RegisterXcodeSDK(llvm::StringRef sdk_name,
1583 llvm::StringRef sysroot) {
1584 auto sdk_path_or_err =
1585 HostInfo::GetSDKRoot(HostInfo::SDKOptions{sdk_name.str()});
1586
1587 if (!sdk_path_or_err) {
1588 Debugger::ReportError("Error while searching for Xcode SDK: " +
1589 toString(sdk_path_or_err.takeError()),
1590 /*debugger_id=*/std::nullopt,
1591 GetDiagnosticOnceFlag(sdk_name));
1592 return;
1593 }
1594
1595 auto sdk_path = *sdk_path_or_err;
1596 if (sdk_path.empty())
1597 return;
1598 // If the SDK changed for a previously registered source path, update it.
1599 // This could happend with -fdebug-prefix-map, otherwise it's unlikely.
1600 if (!m_source_mappings.Replace(sysroot, sdk_path, true))
1601 // In the general case, however, append it to the list.
1602 m_source_mappings.Append(sysroot, sdk_path, false);
1603}
1604
1605bool Module::MergeArchitecture(const ArchSpec &arch_spec) {
1606 if (!arch_spec.IsValid())
1607 return false;
1609 "module has arch %s, merging/replacing with arch %s",
1610 m_arch.GetTriple().getTriple().c_str(),
1611 arch_spec.GetTriple().getTriple().c_str());
1612 if (!m_arch.IsCompatibleMatch(arch_spec)) {
1613 // The new architecture is different, we just need to replace it.
1614 return SetArchitecture(arch_spec);
1615 }
1616
1617 // Merge bits from arch_spec into "merged_arch" and set our architecture.
1618 ArchSpec merged_arch(m_arch);
1619 merged_arch.MergeFrom(arch_spec);
1620 // SetArchitecture() is a no-op if m_arch is already valid.
1621 m_arch = ArchSpec();
1622 return SetArchitecture(merged_arch);
1623}
1624
1626 m_symtab_parse_time.reset();
1627 m_symtab_index_time.reset();
1628 SymbolFile *sym_file = GetSymbolFile();
1629 if (sym_file)
1630 sym_file->ResetStatistics();
1631}
1632
1633llvm::VersionTuple Module::GetVersion() {
1634 if (ObjectFile *obj_file = GetObjectFile())
1635 return obj_file->GetVersion();
1636 return llvm::VersionTuple();
1637}
1638
1640 ObjectFile *obj_file = GetObjectFile();
1641
1642 if (obj_file)
1643 return obj_file->GetIsDynamicLinkEditor();
1644
1645 return false;
1646}
1647
1648uint32_t Module::Hash() {
1649 std::string identifier;
1650 llvm::raw_string_ostream id_strm(identifier);
1651 id_strm << m_arch.GetTriple().str() << '-' << m_file.GetPath();
1652 if (m_object_name)
1653 id_strm << '(' << m_object_name << ')';
1654 if (m_object_offset > 0)
1655 id_strm << m_object_offset;
1656 const auto mtime = llvm::sys::toTimeT(m_object_mod_time);
1657 if (mtime > 0)
1658 id_strm << mtime;
1659 return llvm::djbHash(identifier);
1660}
1661
1662std::string Module::GetCacheKey() {
1663 std::string key;
1664 llvm::raw_string_ostream strm(key);
1665 strm << m_arch.GetTriple().str() << '-' << m_file.GetFilename();
1666 if (m_object_name)
1667 strm << '(' << m_object_name << ')';
1668 strm << '-' << llvm::format_hex(Hash(), 10);
1669 return key;
1670}
1671
1673 if (!ModuleList::GetGlobalModuleListProperties().GetEnableLLDBIndexCache())
1674 return nullptr;
1675 // NOTE: intentional leak so we don't crash if global destructor chain gets
1676 // called as other threads still use the result of this function
1677 static DataFileCache *g_data_file_cache =
1679 .GetLLDBIndexCachePath()
1680 .GetPath());
1681 return g_data_file_cache;
1682}
static llvm::raw_ostream & error(Stream &strm)
static lldb::user_id_t g_unique_id
Definition Debugger.cpp:105
#define REPORT_INTERRUPTION(debugger,...)
Definition Debugger.h:500
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOGF(log,...)
Definition Log.h:376
std::vector< Module * > ModuleCollection
Definition Module.cpp:87
static ModuleCollection & GetModuleCollection()
Definition Module.cpp:89
static Debugger::DebuggerList DebuggersOwningModuleRequestingInterruption(Module &module)
Definition Module.cpp:990
#define LLDB_SCOPED_TIMER()
Definition Timer.h:83
#define LLDB_SCOPED_TIMERF(...)
Definition Timer.h:86
A section + offset based address range class.
Address & GetBaseAddress()
Get accessor for the base address of the range.
lldb::addr_t GetByteSize() const
Get accessor for the byte size of this range.
"lldb/Core/AddressResolverFileLine.h" This class finds address for source file and line.
virtual void ResolveAddress(SearchFilter &filter)
AddressRange & GetAddressRangeAtIndex(size_t idx)
A section + offset based address class.
Definition Address.h:62
bool ResolveAddressUsingFileSections(lldb::addr_t addr, const SectionList *sections)
Resolve a file virtual address using a section list.
Definition Address.cpp:249
lldb::SectionSP GetSection() const
Get const accessor for the section.
Definition Address.h:432
Function * CalculateSymbolContextFunction() const
Definition Address.cpp:860
bool Slide(int64_t offset)
Definition Address.h:452
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:281
lldb::addr_t GetOffset() const
Get the section relative offset value.
Definition Address.h:329
bool IsSectionOffset() const
Check if an address is section offset.
Definition Address.h:342
An architecture specification class.
Definition ArchSpec.h:31
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:366
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:468
void MergeFrom(const ArchSpec &other)
Merges fields from another ArchSpec into this ArchSpec.
Definition ArchSpec.cpp:803
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:548
const FileSpec & GetPrimaryFile() const
Return the primary source spec associated with this compile unit.
void ForeachFunction(llvm::function_ref< bool(const lldb::FunctionSP &)> lambda) const
Apply a lambda to each function in this compile unit.
Represents a generic declaration context in a program.
A uniqued constant string class.
Definition ConstString.h:40
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
bool IsEmpty() const
Test for empty string.
This class enables data to be cached into a directory using the llvm caching code.
A class to manage flag bits.
Definition Debugger.h:80
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
lldb::ScriptLanguage GetScriptLanguage() const
Definition Debugger.cpp:368
static void ReportError(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report error events.
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
std::vector< lldb::DebuggerSP > DebuggerList
Definition Debugger.h:82
static DebuggerList DebuggersRequestingInterruption()
A file collection class.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
Get file at index.
size_t GetSize() const
Get the number of files in the file list.
A file utility class.
Definition FileSpec.h:57
static bool Match(const FileSpec &pattern, const FileSpec &file)
Match FileSpec pattern against FileSpec file.
Definition FileSpec.cpp:301
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:251
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
void Dump(llvm::raw_ostream &s) const
Dump this object to a Stream.
Definition FileSpec.cpp:325
uint64_t GetByteSize(const FileSpec &file_spec) const
Returns the on-disk size of the given file in bytes.
llvm::sys::TimePoint GetModificationTime(const FileSpec &file_spec) const
Returns the modification time of the given file.
static FileSystem & Instance()
A class that describes a function.
Definition Function.h:400
const Address & GetAddress() const
Return the address of the function (its entry point).
Definition Function.h:453
static void ForEach(llvm::function_ref< IterationAction(Language *)> callback)
Definition Language.cpp:131
static Language * FindPlugin(lldb::LanguageType language)
Definition Language.cpp:84
static const char * GetNameForLanguageType(lldb::LanguageType language)
Returns the internal LLDB name for the specified language.
Definition Language.cpp:309
virtual std::unique_ptr< Language::MethodName > GetMethodName(ConstString name) const
Definition Language.h:309
virtual lldb::LanguageType GetLanguageType() const =0
virtual std::pair< lldb::FunctionNameType, std::optional< ConstString > > GetFunctionNameInfo(ConstString name) const
Definition Language.h:314
void PutCString(const char *cstr)
Definition Log.cpp:145
bool GetVerbose() const
Definition Log.cpp:326
A class that handles mangled names.
Definition Mangled.h:34
ConstString GetDemangledName() const
Demangled name get accessor.
Definition Mangled.cpp:284
static Mangled::ManglingScheme GetManglingScheme(llvm::StringRef name)
Try to identify the mangling scheme used.
Definition Mangled.cpp:43
static ModuleListProperties & GetGlobalModuleListProperties()
bool FindMatchingModuleSpec(const ModuleSpec &module_spec, ModuleSpec &match_module_spec) const
Definition ModuleSpec.h:351
uint64_t GetObjectOffset() const
Definition ModuleSpec.h:109
ConstString & GetObjectName()
Definition ModuleSpec.h:105
FileSpec & GetPlatformFileSpec()
Definition ModuleSpec.h:67
FileSpec & GetFileSpec()
Definition ModuleSpec.h:55
lldb::DataBufferSP GetData() const
Definition ModuleSpec.h:129
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:91
FileSpec & GetSymbolFileSpec()
Definition ModuleSpec.h:79
llvm::sys::TimePoint & GetObjectModificationTime()
Definition ModuleSpec.h:119
A class that encapsulates name lookup information.
Definition Module.h:908
lldb::FunctionNameType GetNameTypeMask() const
Definition Module.h:949
lldb::LanguageType GetLanguageType() const
Definition Module.h:951
ConstString m_lookup_name
The actual name will lookup when calling in the object or symbol file.
Definition Module.h:964
lldb::FunctionNameType m_name_type_mask
One or more bits from lldb::FunctionNameType that indicate what kind of names we are looking for.
Definition Module.h:971
bool NameMatchesLookupInfo(ConstString function_name, lldb::LanguageType language_type=lldb::eLanguageTypeUnknown) const
Definition Module.cpp:744
lldb::LanguageType m_language
Limit matches to only be for this language.
Definition Module.h:967
ConstString m_name
What the user originally typed.
Definition Module.h:961
ConstString GetName() const
Definition Module.h:945
static std::vector< LookupInfo > MakeLookupInfos(ConstString name, lldb::FunctionNameType name_type_mask, lldb::LanguageType lang_type, ConstString lookup_name_override={})
Creates a vector of lookup infos for function name resolution.
Definition Module.cpp:713
void Prune(SymbolContextList &sc_list, size_t start_idx) const
Definition Module.cpp:777
bool m_match_name_after_lookup
If true, then demangled names that match will need to contain "m_name" in order to be considered a ma...
Definition Module.h:975
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:90
const lldb_private::UUID & GetUUID()
Get a reference to the UUID value contained in this object.
Definition Module.cpp:347
uint32_t ResolveSymbolContextForFilePath(const char *file_path, uint32_t line, bool check_inlines, lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list)
Resolve items in the symbol context for a given file and line.
Definition Module.cpp:594
std::atomic< bool > m_did_set_uuid
Definition Module.h:1078
void ReportWarningOptimization(std::optional< lldb::user_id_t > debugger_id)
Definition Module.cpp:1093
PathMappingList m_source_mappings
Module specific source remappings for when you have debug info for a module that doesn't match where ...
Definition Module.h:1069
llvm::sys::TimePoint m_object_mod_time
Definition Module.h:1045
virtual ObjectFile * GetObjectFile()
Get the object file representation for the current architecture.
Definition Module.cpp:1206
void FindGlobalVariables(ConstString name, const CompilerDeclContext &parent_decl_ctx, size_t max_matches, VariableList &variable_list)
Find global and static variables by name.
Definition Module.cpp:624
void ReportWarning(const char *format, Args &&...args)
Definition Module.h:793
FileSpec m_file
The file representation on disk for this module (if there is one).
Definition Module.h:1031
virtual SymbolFile * GetSymbolFile(bool can_create=true, Stream *feedback_strm=nullptr)
Get the module's symbol file.
Definition Module.cpp:1006
static DataFileCache * GetIndexCache()
Get the global index file cache.
Definition Module.cpp:1672
std::vector< lldb::SymbolVendorUP > m_old_symfiles
If anyone calls Module::SetSymbolFileFileSpec() and changes the symbol file,.
Definition Module.h:1061
void ReportWarningUnsupportedLanguage(lldb::LanguageType language, std::optional< lldb::user_id_t > debugger_id)
Definition Module.cpp:1107
std::once_flag * GetDiagnosticOnceFlag(llvm::StringRef msg)
Definition Module.cpp:1135
void FindCompileUnits(const FileSpec &path, SymbolContextList &sc_list)
Find compile units by partial or full path.
Definition Module.cpp:638
ConstString GetObjectName() const
Definition Module.cpp:1204
uint32_t Hash()
Get a unique hash for this module.
Definition Module.cpp:1648
lldb::ModuleSP CalculateSymbolContextModule() override
Definition Module.cpp:419
static Module * GetAllocatedModuleAtIndex(size_t idx)
Definition Module.cpp:121
std::recursive_mutex m_diagnostic_mutex
Definition Module.h:1097
void FindFunctions(llvm::ArrayRef< LookupInfo > lookup_infos, const CompilerDeclContext &parent_decl_ctx, const ModuleFunctionSearchOptions &options, SymbolContextList &sc_list)
Find functions by a vector of lookup infos.
UUID m_uuid
Each module is assumed to have a unique identifier to help match it up to debug symbols.
Definition Module.h:1029
std::optional< std::string > RemapSourceFile(llvm::StringRef path) const
Remaps a source file given path into new_path.
Definition Module.cpp:1575
llvm::sys::TimePoint m_mod_time
The modification time for this module when it was created.
Definition Module.h:1026
lldb::CompUnitSP GetCompileUnitAtIndex(size_t idx)
Definition Module.cpp:432
uint32_t ResolveSymbolContextForAddress(const Address &so_addr, lldb::SymbolContextItem resolve_scope, SymbolContext &sc, bool resolve_tail_call_address=false)
Resolve the symbol context for the given address.
Definition Module.cpp:452
void SetFileSpecAndObjectName(const FileSpec &file, ConstString object_name)
Definition Module.cpp:1039
std::recursive_mutex m_mutex
A mutex to keep this object happy in multi-threaded environments.
Definition Module.h:1022
static std::recursive_mutex & GetAllocationModuleCollectionMutex()
Definition Module.cpp:103
lldb::DataBufferSP m_data_sp
DataBuffer containing the module image, if it was provided at construction time.
Definition Module.h:1050
bool SetLoadAddress(Target &target, lldb::addr_t value, bool value_is_offset, bool &changed)
Set the load address for all sections in a module to be the file address plus slide.
Definition Module.cpp:1522
void SetSymbolFileFileSpec(const FileSpec &file)
Definition Module.cpp:1361
void RegisterXcodeSDK(llvm::StringRef sdk, llvm::StringRef sysroot)
This callback will be called by SymbolFile implementations when parsing a compile unit that contains ...
Definition Module.cpp:1582
void FindSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, SymbolContextList &sc_list)
Definition Module.cpp:1316
void CalculateSymbolContext(SymbolContext *sc) override
Reconstruct the object's symbol context into sc.
Definition Module.cpp:415
FileSpec m_symfile_spec
If this path is valid, then this is the file that will be used as the symbol file for this module.
Definition Module.h:1038
StatsDuration m_symtab_index_time
We store a symbol named index time duration here because we might have an object file and a symbol fi...
Definition Module.h:1089
bool ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr)
Definition Module.cpp:444
ArchSpec m_arch
The architecture for this module.
Definition Module.h:1028
void ReportError(const char *format, Args &&...args)
Definition Module.h:798
const FileSpec & GetPlatformFileSpec() const
Get accessor for the module platform file specification.
Definition Module.h:460
lldb::SymbolVendorUP m_symfile_up
A pointer to the symbol vendor for this module.
Definition Module.h:1059
const Symbol * FindFirstSymbolWithNameAndType(ConstString name, lldb::SymbolType symbol_type=lldb::eSymbolTypeAny)
Find a symbol in the object file's symbol table.
Definition Module.cpp:1280
llvm::DenseMap< llvm::stable_hash, std::unique_ptr< std::once_flag > > m_shown_diagnostics
A set of hashes of all warnings and errors, to avoid reporting them multiple times to the same Debugg...
Definition Module.h:1096
Module(const FileSpec &file_spec, const ArchSpec &arch, ConstString object_name=ConstString(), lldb::offset_t object_offset=0, const llvm::sys::TimePoint<> &object_mod_time=llvm::sys::TimePoint<>())
Construct with file specification and architecture.
Definition Module.cpp:235
llvm::VersionTuple GetVersion()
Definition Module.cpp:1633
void FindAddressesForLine(const lldb::TargetSP target_sp, const FileSpec &file, uint32_t line, Function *function, std::vector< Address > &output_local, std::vector< Address > &output_extern)
Find addresses by file/line.
Definition Module.cpp:960
void DumpSymbolContext(Stream *s) override
Dump the object's symbol context to the stream s.
Definition Module.cpp:421
void FindFunctionSymbols(ConstString name, uint32_t name_type_mask, SymbolContextList &sc_list)
Find a function symbols in the object file's symbol table.
Definition Module.cpp:1308
Symtab * GetSymtab(bool can_create=true)
Get the module's symbol table.
Definition Module.cpp:1033
size_t GetNumCompileUnits()
Get the number of compile units for this module.
Definition Module.cpp:425
ConstString m_object_name
The name an object within this module that is selected, or empty of the module is represented by m_fi...
Definition Module.h:1041
void LogMessage(Log *log, const char *format, Args &&...args)
Definition Module.h:781
bool MatchesModuleSpec(const ModuleSpec &module_ref)
Definition Module.cpp:1534
~Module() override
Destructor.
Definition Module.cpp:267
static size_t GetNumberAllocatedModules()
Definition Module.cpp:115
ObjectFile * GetMemoryObjectFile(const lldb::ProcessSP &process_sp, lldb::addr_t header_addr, Status &error, size_t size_to_read=512)
Load an object file from memory.
Definition Module.cpp:297
bool LoadScriptingResourceInTarget(Target *target, Status &error, Stream &feedback_stream)
Definition Module.cpp:1446
TypeSystemMap m_type_system_map
A map of any type systems associated with this module.
Definition Module.h:1065
uint64_t m_object_offset
Definition Module.h:1044
void ForEachTypeSystem(llvm::function_ref< bool(lldb::TypeSystemSP)> callback)
Call callback for each TypeSystem in this Module.
Definition Module.cpp:377
lldb::SectionListUP m_sections_up
Unified section list for module that is used by the ObjectFile and ObjectFile instances for the debug...
Definition Module.h:1072
bool IsExecutable()
Tells whether this module is capable of being the main executable for a process.
Definition Module.cpp:1422
FileSpec m_platform_file
The path to the module on the platform on which it is being debugged.
Definition Module.h:1033
bool MergeArchitecture(const ArchSpec &arch_spec)
Update the ArchSpec to a more specific variant.
Definition Module.cpp:1605
bool FileHasChanged() const
Definition Module.cpp:1082
const ArchSpec & GetArchitecture() const
Get const accessor for the module architecture.
Definition Module.cpp:1048
friend class ObjectFile
Definition Module.h:1110
void LogMessageVerboseBacktrace(Log *log, const char *format, Args &&...args)
Definition Module.h:786
bool GetIsDynamicLinkEditor()
Definition Module.cpp:1639
std::string GetCacheKey()
Get a unique cache key for the current module.
Definition Module.cpp:1662
virtual SectionList * GetSectionList()
Get the unified section list for the module.
Definition Module.cpp:1250
llvm::Expected< lldb::TypeSystemSP > GetTypeSystemForLanguage(lldb::LanguageType language)
Definition Module.cpp:373
void Dump(Stream *s)
Dump a description of this object to a Stream.
Definition Module.cpp:1183
uint32_t ResolveSymbolContextsForFileSpec(const FileSpec &file_spec, uint32_t line, bool check_inlines, lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list)
Resolve items in the symbol context for a given file and line.
Definition Module.cpp:602
lldb::ObjectFileSP m_objfile_sp
A shared pointer to the object file parser for this module as it may or may not be shared with the Sy...
Definition Module.h:1052
void ReportErrorIfModifyDetected(const char *format, Args &&...args)
Definition Module.h:805
void FindSymbolsMatchingRegExAndType(const RegularExpression &regex, lldb::SymbolType symbol_type, SymbolContextList &sc_list, Mangled::NamePreference mangling_preference=Mangled::ePreferDemangled)
Definition Module.cpp:1328
std::atomic< bool > m_did_load_symfile
Definition Module.h:1077
UnwindTable & GetUnwindTable()
Returns a reference to the UnwindTable for this Module.
Definition Module.cpp:1268
std::string GetSpecificationDescription() const
Get the module path and object name.
Definition Module.cpp:1050
UnwindTable m_unwind_table
Table of FuncUnwinders objects created for this Module's functions.
Definition Module.h:1055
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition Module.h:446
bool IsLoadedInTarget(Target *target)
Tells whether this module has been loaded in the target passed in.
Definition Module.cpp:1429
void GetDescription(llvm::raw_ostream &s, lldb::DescriptionLevel level=lldb::eDescriptionLevelFull)
Definition Module.cpp:1060
void SetUUID(const lldb_private::UUID &uuid)
Definition Module.cpp:362
bool m_first_file_changed_log
Definition Module.h:1080
void SymbolIndicesToSymbolContextList(Symtab *symtab, std::vector< uint32_t > &symbol_indexes, SymbolContextList &sc_list)
Definition Module.cpp:1290
const llvm::sys::TimePoint & GetModificationTime() const
Definition Module.h:482
virtual void SectionFileAddressesChanged()
Notify the module that the file addresses for the Sections have been updated.
Definition Module.cpp:1260
std::atomic< bool > m_did_load_objfile
Definition Module.h:1076
bool FindSourceFile(const FileSpec &orig_spec, FileSpec &new_spec) const
Finds a source file given a file spec using the module source path remappings (if any).
Definition Module.cpp:1565
friend class SymbolFile
Definition Module.h:1111
void FindTypes(const TypeQuery &query, TypeResults &results)
Find types using a type-matching object that contains all search parameters.
Definition Module.cpp:984
bool SetArchitecture(const ArchSpec &new_arch)
Definition Module.cpp:1514
SectionList * GetUnifiedSectionList()
Definition Module.cpp:1274
StatsDuration m_symtab_parse_time
See if the module was modified after it was initially opened.
Definition Module.h:1085
void ParseAllDebugSymbols()
A debugging function that will cause everything in a module to be parsed.
Definition Module.cpp:382
virtual bool SetLoadAddress(Target &target, lldb::addr_t value, bool value_is_offset)
Sets the load address for an entire module, assuming a rigid slide of sections, if possible in the im...
Definition ObjectFile.h:406
virtual void Dump(Stream *s)=0
Dump a description of this object to a Stream.
static lldb::ObjectFileSP FindPlugin(const lldb::ModuleSP &module_sp, const FileSpec *file_spec, lldb::offset_t file_offset, lldb::offset_t file_size, lldb::DataExtractorSP extractor_sp, lldb::offset_t &data_offset)
Find a ObjectFile plug-in that can parse file_spec.
virtual bool IsStripped()=0
Detect if this object file has been stripped of local symbols.
Symtab * GetSymtab(bool can_create=true)
Gets the symbol table for the currently selected architecture (and object for archives).
virtual bool IsExecutable() const =0
Tells whether this object file is capable of being the main executable for a process.
virtual void ClearSymtab()
Frees the symbol table.
virtual FileSpec & GetFileSpec()
Get accessor to the object file specification.
Definition ObjectFile.h:282
virtual void CreateSections(SectionList &unified_section_list)=0
virtual void SectionFileAddressesChanged()
Notify the ObjectFile that the file addresses in the Sections for this module have been changed.
Definition ObjectFile.h:312
virtual UUID GetUUID()=0
Gets the UUID for this object file.
virtual bool GetIsDynamicLinkEditor()
Return true if this file is a dynamic link editor (dyld)
Definition ObjectFile.h:660
static size_t GetModuleSpecifications(const FileSpec &file, lldb::offset_t file_offset, lldb::offset_t file_size, ModuleSpecList &specs, lldb::DataBufferSP data_sp=lldb::DataBufferSP())
llvm::StringRef GetText() const
Access the regular expression text.
virtual bool LoadScriptingModule(const char *filename, const LoadScriptOptions &options, lldb_private::Status &error, StructuredData::ObjectSP *module_sp=nullptr, FileSpec extra_search_dir={}, lldb::TargetSP loaded_into_target_sp={})
This is a SearchFilter that restricts the search to a given module.
size_t GetNumSections(uint32_t depth) const
Definition Section.cpp:546
size_t GetSize() const
Definition Section.h:77
bool DeleteSection(size_t idx)
Definition Section.cpp:499
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:557
"lldb/Core/SourceLocationSpec.h" A source location specifier class.
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:195
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:406
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:65
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:198
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:195
Defines a list of symbol context objects.
bool GetContextAtIndex(size_t idx, SymbolContext &sc) const
Get accessor for a symbol context at index idx.
uint32_t GetSize() const
Get accessor for a symbol context list size.
void Append(const SymbolContext &sc)
Append a new symbol context to the list.
Defines a symbol context baton that can be handed other debug core functions.
lldb::LanguageType GetLanguage() const
Function * function
The Function for a given query.
ConstString GetFunctionName(Mangled::NamePreference preference=Mangled::ePreferDemangled) const
Find a name of the innermost function for the symbol context.
Block * block
The Block for a given query.
lldb::ModuleSP module_sp
The Module for a given query.
CompileUnit * comp_unit
The CompileUnit for a given query.
void Clear(bool clear_target)
Clear the object's state.
bool GetAddressRange(uint32_t scope, uint32_t range_idx, bool use_inline_block_range, AddressRange &range) const
Get the address range contained within a symbol context.
Symbol * symbol
The Symbol for a given query.
lldb::TargetSP target_sp
The Target for a given query.
LineEntry line_entry
The LineEntry for a given query.
virtual size_t ParseTypes(CompileUnit &comp_unit)=0
virtual void SectionFileAddressesChanged()=0
Notify the SymbolFile that the file addresses in the Sections for this module have been changed.
virtual void SetLoadDebugInfoEnabled()
Specify debug info should be loaded.
Definition SymbolFile.h:141
virtual void PreloadSymbols()
virtual void FindGlobalVariables(ConstString name, const CompilerDeclContext &parent_decl_ctx, uint32_t max_matches, VariableList &variables)
virtual Symtab * GetSymtab(bool can_create=true)=0
virtual size_t ParseFunctions(CompileUnit &comp_unit)=0
virtual size_t ParseBlocksRecursive(Function &func)=0
virtual lldb::CompUnitSP GetCompileUnitAtIndex(uint32_t idx)=0
virtual void FindTypes(const TypeQuery &query, TypeResults &results)
Find types using a type-matching object that contains all search parameters.
Definition SymbolFile.h:330
virtual void FindFunctions(const Module::LookupInfo &lookup_info, const CompilerDeclContext &parent_decl_ctx, bool include_inlines, SymbolContextList &sc_list)
virtual size_t ParseVariablesForContext(const SymbolContext &sc)=0
virtual ObjectFile * GetObjectFile()=0
virtual void ResetStatistics()
Reset the statistics for the symbol file.
Definition SymbolFile.h:443
virtual uint32_t ResolveSymbolContext(const Address &so_addr, lldb::SymbolContextItem resolve_scope, SymbolContext &sc)=0
virtual void Dump(Stream &s)=0
static void DownloadSymbolFileAsync(const UUID &uuid)
Locate the symbol file for the given UUID on a background thread.
static SymbolVendor * FindPlugin(const lldb::ModuleSP &module_sp, Stream *feedback_strm)
bool ValueIsAddress() const
Definition Symbol.cpp:165
bool IsSynthetic() const
Definition Symbol.h:183
Address & GetAddressRef()
Definition Symbol.h:73
lldb::SymbolType GetType() const
Definition Symbol.h:169
Symbol * SymbolAtIndex(size_t idx)
Definition Symtab.cpp:228
void ForEachSymbolContainingFileAddress(lldb::addr_t file_addr, std::function< bool(Symbol *)> const &callback)
Definition Symtab.cpp:1053
Symbol * FindSymbolAtFileAddress(lldb::addr_t file_addr)
Definition Symtab.cpp:1022
Symbol * FindSymbolContainingFileAddress(lldb::addr_t file_addr)
Definition Symtab.cpp:1037
ObjectFile * GetObjectFile() const
Definition Symtab.h:137
uint32_t AppendSymbolIndexesMatchingRegExAndType(const RegularExpression &regex, lldb::SymbolType symbol_type, std::vector< uint32_t > &indexes, Mangled::NamePreference name_preference=Mangled::ePreferDemangled)
Definition Symtab.cpp:750
Debugger & GetDebugger() const
Definition Target.h:1194
lldb::PlatformSP GetPlatform()
Definition Target.h:1648
A class that contains all state required for type lookups.
Definition Type.h:104
This class tracks the state and results of a TypeQuery.
Definition Type.h:344
Represents UUID's of various sizes.
Definition UUID.h:27
bool IsValid() const
Definition UUID.h:69
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
LoadScriptFromSymFile
Definition Target.h:55
@ eLoadScriptFromSymFileFalse
Definition Target.h:57
@ eLoadScriptFromSymFileWarn
Definition Target.h:58
const char * toString(AppleArm64ExceptionClass EC)
std::shared_ptr< lldb_private::Function > FunctionSP
ScriptLanguage
Script interpreter types.
@ eScriptLanguageNone
std::shared_ptr< lldb_private::TypeSystem > TypeSystemSP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
@ eDescriptionLevelBrief
@ eDescriptionLevelFull
std::shared_ptr< lldb_private::Platform > PlatformSP
uint64_t offset_t
Definition lldb-types.h:85
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeObjC
Objective-C.
@ eLanguageTypeC_plus_plus
ISO C++:1998.
std::shared_ptr< lldb_private::Process > ProcessSP
SymbolType
Symbol types.
@ eSymbolTypeResolver
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
std::shared_ptr< lldb_private::Module > ModuleSP
std::shared_ptr< lldb_private::CompileUnit > CompUnitSP
bool IsValid() const
Check if a line entry object is valid.
Definition LineEntry.cpp:35
void ApplyFileMappings(lldb::TargetSP target_sp)
Apply file mappings from target.source-map to the LineEntry's file.
Options used by Module::FindFunctions.
Definition Module.h:66
bool include_inlines
Include inlined functions.
Definition Module.h:70
bool include_symbols
Include the symbol table.
Definition Module.h:68
UserID(lldb::user_id_t uid=LLDB_INVALID_UID)
Construct with optional user ID.
Definition UserID.h:33
#define PATH_MAX