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