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