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