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