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