xref: /llvm-project/lldb/source/Core/Module.cpp (revision c46d9af26cefb0b24646d3235b75ae7a1b8548d4)
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 
11 #include "lldb/Core/AddressRange.h"
12 #include "lldb/Core/AddressResolverFileLine.h"
13 #include "lldb/Core/DataFileCache.h"
14 #include "lldb/Core/Debugger.h"
15 #include "lldb/Core/FileSpecList.h"
16 #include "lldb/Core/Mangled.h"
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Core/SearchFilter.h"
19 #include "lldb/Core/Section.h"
20 #include "lldb/Host/FileSystem.h"
21 #include "lldb/Host/Host.h"
22 #include "lldb/Host/HostInfo.h"
23 #include "lldb/Interpreter/CommandInterpreter.h"
24 #include "lldb/Interpreter/ScriptInterpreter.h"
25 #include "lldb/Symbol/CompileUnit.h"
26 #include "lldb/Symbol/Function.h"
27 #include "lldb/Symbol/LocateSymbolFile.h"
28 #include "lldb/Symbol/ObjectFile.h"
29 #include "lldb/Symbol/Symbol.h"
30 #include "lldb/Symbol/SymbolContext.h"
31 #include "lldb/Symbol/SymbolFile.h"
32 #include "lldb/Symbol/SymbolVendor.h"
33 #include "lldb/Symbol/Symtab.h"
34 #include "lldb/Symbol/Type.h"
35 #include "lldb/Symbol/TypeList.h"
36 #include "lldb/Symbol/TypeMap.h"
37 #include "lldb/Symbol/TypeSystem.h"
38 #include "lldb/Target/Language.h"
39 #include "lldb/Target/Process.h"
40 #include "lldb/Target/Target.h"
41 #include "lldb/Utility/DataBufferHeap.h"
42 #include "lldb/Utility/LLDBAssert.h"
43 #include "lldb/Utility/LLDBLog.h"
44 #include "lldb/Utility/Log.h"
45 #include "lldb/Utility/RegularExpression.h"
46 #include "lldb/Utility/Status.h"
47 #include "lldb/Utility/Stream.h"
48 #include "lldb/Utility/StreamString.h"
49 #include "lldb/Utility/Timer.h"
50 
51 #if defined(_WIN32)
52 #include "lldb/Host/windows/PosixApi.h"
53 #endif
54 
55 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
56 #include "Plugins/Language/ObjC/ObjCLanguage.h"
57 
58 #include "llvm/ADT/STLExtras.h"
59 #include "llvm/Support/Compiler.h"
60 #include "llvm/Support/DJB.h"
61 #include "llvm/Support/FileSystem.h"
62 #include "llvm/Support/FormatVariadic.h"
63 #include "llvm/Support/JSON.h"
64 #include "llvm/Support/Signals.h"
65 #include "llvm/Support/raw_ostream.h"
66 
67 #include <cassert>
68 #include <cinttypes>
69 #include <cstdarg>
70 #include <cstdint>
71 #include <cstring>
72 #include <map>
73 #include <optional>
74 #include <type_traits>
75 #include <utility>
76 
77 namespace lldb_private {
78 class CompilerDeclContext;
79 }
80 namespace lldb_private {
81 class VariableList;
82 }
83 
84 using namespace lldb;
85 using namespace lldb_private;
86 
87 // Shared pointers to modules track module lifetimes in targets and in the
88 // global module, but this collection will track all module objects that are
89 // still alive
90 typedef std::vector<Module *> ModuleCollection;
91 
92 static ModuleCollection &GetModuleCollection() {
93   // This module collection needs to live past any module, so we could either
94   // make it a shared pointer in each module or just leak is.  Since it is only
95   // an empty vector by the time all the modules have gone away, we just leak
96   // it for now.  If we decide this is a big problem we can introduce a
97   // Finalize method that will tear everything down in a predictable order.
98 
99   static ModuleCollection *g_module_collection = nullptr;
100   if (g_module_collection == nullptr)
101     g_module_collection = new ModuleCollection();
102 
103   return *g_module_collection;
104 }
105 
106 std::recursive_mutex &Module::GetAllocationModuleCollectionMutex() {
107   // NOTE: The mutex below must be leaked since the global module list in
108   // the ModuleList class will get torn at some point, and we can't know if it
109   // will tear itself down before the "g_module_collection_mutex" below will.
110   // So we leak a Mutex object below to safeguard against that
111 
112   static std::recursive_mutex *g_module_collection_mutex = nullptr;
113   if (g_module_collection_mutex == nullptr)
114     g_module_collection_mutex = new std::recursive_mutex; // NOTE: known leak
115   return *g_module_collection_mutex;
116 }
117 
118 size_t Module::GetNumberAllocatedModules() {
119   std::lock_guard<std::recursive_mutex> guard(
120       GetAllocationModuleCollectionMutex());
121   return GetModuleCollection().size();
122 }
123 
124 Module *Module::GetAllocatedModuleAtIndex(size_t idx) {
125   std::lock_guard<std::recursive_mutex> guard(
126       GetAllocationModuleCollectionMutex());
127   ModuleCollection &modules = GetModuleCollection();
128   if (idx < modules.size())
129     return modules[idx];
130   return nullptr;
131 }
132 
133 Module::Module(const ModuleSpec &module_spec)
134     : m_file_has_changed(false), m_first_file_changed_log(false) {
135   // Scope for locker below...
136   {
137     std::lock_guard<std::recursive_mutex> guard(
138         GetAllocationModuleCollectionMutex());
139     GetModuleCollection().push_back(this);
140   }
141 
142   Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
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;
160   if (ObjectFile::GetModuleSpecifications(
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 =
189           FileSystem::Instance().GetModificationTime(module_spec.GetFileSpec());
190     else if (matching_module_spec.GetFileSpec())
191       m_mod_time = FileSystem::Instance().GetModificationTime(
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 
235 Module::Module(const FileSpec &file_spec, const ArchSpec &arch,
236                const ConstString *object_name, lldb::offset_t object_offset,
237                const llvm::sys::TimePoint<> &object_mod_time)
238     : m_mod_time(FileSystem::Instance().GetModificationTime(file_spec)),
239       m_arch(arch), m_file(file_spec), m_object_offset(object_offset),
240       m_object_mod_time(object_mod_time), m_file_has_changed(false),
241       m_first_file_changed_log(false) {
242   // Scope for locker below...
243   {
244     std::lock_guard<std::recursive_mutex> guard(
245         GetAllocationModuleCollectionMutex());
246     GetModuleCollection().push_back(this);
247   }
248 
249   if (object_name)
250     m_object_name = *object_name;
251 
252   Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
253   if (log != nullptr)
254     LLDB_LOGF(log, "%p Module::Module((%s) '%s%s%s%s')",
255               static_cast<void *>(this), m_arch.GetArchitectureName(),
256               m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
257               m_object_name.AsCString(""), m_object_name.IsEmpty() ? "" : ")");
258 }
259 
260 Module::Module() : m_file_has_changed(false), m_first_file_changed_log(false) {
261   std::lock_guard<std::recursive_mutex> guard(
262       GetAllocationModuleCollectionMutex());
263   GetModuleCollection().push_back(this);
264 }
265 
266 Module::~Module() {
267   // Lock our module down while we tear everything down to make sure we don't
268   // get any access to the module while it is being destroyed
269   std::lock_guard<std::recursive_mutex> guard(m_mutex);
270   // Scope for locker below...
271   {
272     std::lock_guard<std::recursive_mutex> guard(
273         GetAllocationModuleCollectionMutex());
274     ModuleCollection &modules = GetModuleCollection();
275     ModuleCollection::iterator end = modules.end();
276     ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
277     assert(pos != end);
278     modules.erase(pos);
279   }
280   Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
281   if (log != nullptr)
282     LLDB_LOGF(log, "%p Module::~Module((%s) '%s%s%s%s')",
283               static_cast<void *>(this), m_arch.GetArchitectureName(),
284               m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
285               m_object_name.AsCString(""), m_object_name.IsEmpty() ? "" : ")");
286   // Release any auto pointers before we start tearing down our member
287   // variables since the object file and symbol files might need to make
288   // function calls back into this module object. The ordering is important
289   // here because symbol files can require the module object file. So we tear
290   // down the symbol file first, then the object file.
291   m_sections_up.reset();
292   m_symfile_up.reset();
293   m_objfile_sp.reset();
294 }
295 
296 ObjectFile *Module::GetMemoryObjectFile(const lldb::ProcessSP &process_sp,
297                                         lldb::addr_t header_addr, Status &error,
298                                         size_t size_to_read) {
299   if (m_objfile_sp) {
300     error.SetErrorString("object file already exists");
301   } else {
302     std::lock_guard<std::recursive_mutex> guard(m_mutex);
303     if (process_sp) {
304       m_did_load_objfile = true;
305       std::shared_ptr<DataBufferHeap> data_sp =
306           std::make_shared<DataBufferHeap>(size_to_read, 0);
307       Status readmem_error;
308       const size_t bytes_read =
309           process_sp->ReadMemory(header_addr, data_sp->GetBytes(),
310                                  data_sp->GetByteSize(), readmem_error);
311       if (bytes_read < size_to_read)
312         data_sp->SetByteSize(bytes_read);
313       if (data_sp->GetByteSize() > 0) {
314         m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp,
315                                               header_addr, data_sp);
316         if (m_objfile_sp) {
317           StreamString s;
318           s.Printf("0x%16.16" PRIx64, header_addr);
319           m_object_name.SetString(s.GetString());
320 
321           // Once we get the object file, update our module with the object
322           // file's architecture since it might differ in vendor/os if some
323           // parts were unknown.
324           m_arch = m_objfile_sp->GetArchitecture();
325 
326           // Augment the arch with the target's information in case
327           // we are unable to extract the os/environment from memory.
328           m_arch.MergeFrom(process_sp->GetTarget().GetArchitecture());
329         } else {
330           error.SetErrorString("unable to find suitable object file plug-in");
331         }
332       } else {
333         error.SetErrorStringWithFormat("unable to read header from memory: %s",
334                                        readmem_error.AsCString());
335       }
336     } else {
337       error.SetErrorString("invalid process");
338     }
339   }
340   return m_objfile_sp.get();
341 }
342 
343 const lldb_private::UUID &Module::GetUUID() {
344   if (!m_did_set_uuid.load()) {
345     std::lock_guard<std::recursive_mutex> guard(m_mutex);
346     if (!m_did_set_uuid.load()) {
347       ObjectFile *obj_file = GetObjectFile();
348 
349       if (obj_file != nullptr) {
350         m_uuid = obj_file->GetUUID();
351         m_did_set_uuid = true;
352       }
353     }
354   }
355   return m_uuid;
356 }
357 
358 void Module::SetUUID(const lldb_private::UUID &uuid) {
359   std::lock_guard<std::recursive_mutex> guard(m_mutex);
360   if (!m_did_set_uuid) {
361     m_uuid = uuid;
362     m_did_set_uuid = true;
363   } else {
364     lldbassert(0 && "Attempting to overwrite the existing module UUID");
365   }
366 }
367 
368 llvm::Expected<TypeSystemSP>
369 Module::GetTypeSystemForLanguage(LanguageType language) {
370   return m_type_system_map.GetTypeSystemForLanguage(language, this, true);
371 }
372 
373 void Module::ForEachTypeSystem(
374     llvm::function_ref<bool(lldb::TypeSystemSP)> callback) {
375   m_type_system_map.ForEach(callback);
376 }
377 
378 void Module::ParseAllDebugSymbols() {
379   std::lock_guard<std::recursive_mutex> guard(m_mutex);
380   size_t num_comp_units = GetNumCompileUnits();
381   if (num_comp_units == 0)
382     return;
383 
384   SymbolFile *symbols = GetSymbolFile();
385 
386   for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++) {
387     SymbolContext sc;
388     sc.module_sp = shared_from_this();
389     sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get();
390     if (!sc.comp_unit)
391       continue;
392 
393     symbols->ParseVariablesForContext(sc);
394 
395     symbols->ParseFunctions(*sc.comp_unit);
396 
397     sc.comp_unit->ForeachFunction([&sc, &symbols](const FunctionSP &f) {
398       symbols->ParseBlocksRecursive(*f);
399 
400       // Parse the variables for this function and all its blocks
401       sc.function = f.get();
402       symbols->ParseVariablesForContext(sc);
403       return false;
404     });
405 
406     // Parse all types for this compile unit
407     symbols->ParseTypes(*sc.comp_unit);
408   }
409 }
410 
411 void Module::CalculateSymbolContext(SymbolContext *sc) {
412   sc->module_sp = shared_from_this();
413 }
414 
415 ModuleSP Module::CalculateSymbolContextModule() { return shared_from_this(); }
416 
417 void Module::DumpSymbolContext(Stream *s) {
418   s->Printf(", Module{%p}", static_cast<void *>(this));
419 }
420 
421 size_t Module::GetNumCompileUnits() {
422   std::lock_guard<std::recursive_mutex> guard(m_mutex);
423   if (SymbolFile *symbols = GetSymbolFile())
424     return symbols->GetNumCompileUnits();
425   return 0;
426 }
427 
428 CompUnitSP Module::GetCompileUnitAtIndex(size_t index) {
429   std::lock_guard<std::recursive_mutex> guard(m_mutex);
430   size_t num_comp_units = GetNumCompileUnits();
431   CompUnitSP cu_sp;
432 
433   if (index < num_comp_units) {
434     if (SymbolFile *symbols = GetSymbolFile())
435       cu_sp = symbols->GetCompileUnitAtIndex(index);
436   }
437   return cu_sp;
438 }
439 
440 bool Module::ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) {
441   std::lock_guard<std::recursive_mutex> guard(m_mutex);
442   SectionList *section_list = GetSectionList();
443   if (section_list)
444     return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
445   return false;
446 }
447 
448 uint32_t Module::ResolveSymbolContextForAddress(
449     const Address &so_addr, lldb::SymbolContextItem resolve_scope,
450     SymbolContext &sc, bool resolve_tail_call_address) {
451   std::lock_guard<std::recursive_mutex> guard(m_mutex);
452   uint32_t resolved_flags = 0;
453 
454   // Clear the result symbol context in case we don't find anything, but don't
455   // clear the target
456   sc.Clear(false);
457 
458   // Get the section from the section/offset address.
459   SectionSP section_sp(so_addr.GetSection());
460 
461   // Make sure the section matches this module before we try and match anything
462   if (section_sp && section_sp->GetModule().get() == this) {
463     // If the section offset based address resolved itself, then this is the
464     // right module.
465     sc.module_sp = shared_from_this();
466     resolved_flags |= eSymbolContextModule;
467 
468     SymbolFile *symfile = GetSymbolFile();
469     if (!symfile)
470       return resolved_flags;
471 
472     // Resolve the compile unit, function, block, line table or line entry if
473     // requested.
474     if (resolve_scope & eSymbolContextCompUnit ||
475         resolve_scope & eSymbolContextFunction ||
476         resolve_scope & eSymbolContextBlock ||
477         resolve_scope & eSymbolContextLineEntry ||
478         resolve_scope & eSymbolContextVariable) {
479       symfile->SetLoadDebugInfoEnabled();
480       resolved_flags |=
481           symfile->ResolveSymbolContext(so_addr, resolve_scope, sc);
482     }
483 
484     // Resolve the symbol if requested, but don't re-look it up if we've
485     // already found it.
486     if (resolve_scope & eSymbolContextSymbol &&
487         !(resolved_flags & eSymbolContextSymbol)) {
488       Symtab *symtab = symfile->GetSymtab();
489       if (symtab && so_addr.IsSectionOffset()) {
490         Symbol *matching_symbol = nullptr;
491 
492         symtab->ForEachSymbolContainingFileAddress(
493             so_addr.GetFileAddress(),
494             [&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         sc.symbol = matching_symbol;
502         if (!sc.symbol && resolve_scope & eSymbolContextFunction &&
503             !(resolved_flags & eSymbolContextFunction)) {
504           bool verify_unique = false; // No need to check again since
505                                       // ResolveSymbolContext failed to find a
506                                       // symbol at this address.
507           if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
508             sc.symbol =
509                 obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
510         }
511 
512         if (sc.symbol) {
513           if (sc.symbol->IsSynthetic()) {
514             // We have a synthetic symbol so lets check if the object file from
515             // the symbol file in the symbol vendor is different than the
516             // object file for the module, and if so search its symbol table to
517             // see if we can come up with a better symbol. For example dSYM
518             // files on MacOSX have an unstripped symbol table inside of them.
519             ObjectFile *symtab_objfile = symtab->GetObjectFile();
520             if (symtab_objfile && symtab_objfile->IsStripped()) {
521               ObjectFile *symfile_objfile = symfile->GetObjectFile();
522               if (symfile_objfile != symtab_objfile) {
523                 Symtab *symfile_symtab = symfile_objfile->GetSymtab();
524                 if (symfile_symtab) {
525                   Symbol *symbol =
526                       symfile_symtab->FindSymbolContainingFileAddress(
527                           so_addr.GetFileAddress());
528                   if (symbol && !symbol->IsSynthetic()) {
529                     sc.symbol = symbol;
530                   }
531                 }
532               }
533             }
534           }
535           resolved_flags |= eSymbolContextSymbol;
536         }
537       }
538     }
539 
540     // For function symbols, so_addr may be off by one.  This is a convention
541     // consistent with FDE row indices in eh_frame sections, but requires extra
542     // logic here to permit symbol lookup for disassembly and unwind.
543     if (resolve_scope & eSymbolContextSymbol &&
544         !(resolved_flags & eSymbolContextSymbol) && resolve_tail_call_address &&
545         so_addr.IsSectionOffset()) {
546       Address previous_addr = so_addr;
547       previous_addr.Slide(-1);
548 
549       bool do_resolve_tail_call_address = false; // prevent recursion
550       const uint32_t flags = ResolveSymbolContextForAddress(
551           previous_addr, resolve_scope, sc, do_resolve_tail_call_address);
552       if (flags & eSymbolContextSymbol) {
553         AddressRange addr_range;
554         if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
555                                false, addr_range)) {
556           if (addr_range.GetBaseAddress().GetSection() ==
557               so_addr.GetSection()) {
558             // If the requested address is one past the address range of a
559             // function (i.e. a tail call), or the decremented address is the
560             // start of a function (i.e. some forms of trampoline), indicate
561             // that the symbol has been resolved.
562             if (so_addr.GetOffset() ==
563                     addr_range.GetBaseAddress().GetOffset() ||
564                 so_addr.GetOffset() == addr_range.GetBaseAddress().GetOffset() +
565                                            addr_range.GetByteSize()) {
566               resolved_flags |= flags;
567             }
568           } else {
569             sc.symbol =
570                 nullptr; // Don't trust the symbol if the sections didn't match.
571           }
572         }
573       }
574     }
575   }
576   return resolved_flags;
577 }
578 
579 uint32_t Module::ResolveSymbolContextForFilePath(
580     const char *file_path, uint32_t line, bool check_inlines,
581     lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
582   FileSpec file_spec(file_path);
583   return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
584                                           resolve_scope, sc_list);
585 }
586 
587 uint32_t Module::ResolveSymbolContextsForFileSpec(
588     const FileSpec &file_spec, uint32_t line, bool check_inlines,
589     lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
590   std::lock_guard<std::recursive_mutex> guard(m_mutex);
591   LLDB_SCOPED_TIMERF("Module::ResolveSymbolContextForFilePath (%s:%u, "
592                      "check_inlines = %s, resolve_scope = 0x%8.8x)",
593                      file_spec.GetPath().c_str(), line,
594                      check_inlines ? "yes" : "no", resolve_scope);
595 
596   const uint32_t initial_count = sc_list.GetSize();
597 
598   if (SymbolFile *symbols = GetSymbolFile()) {
599     // TODO: Handle SourceLocationSpec column information
600     SourceLocationSpec location_spec(file_spec, line, /*column=*/std::nullopt,
601                                      check_inlines, /*exact_match=*/false);
602 
603     symbols->ResolveSymbolContext(location_spec, resolve_scope, sc_list);
604   }
605 
606   return sc_list.GetSize() - initial_count;
607 }
608 
609 void Module::FindGlobalVariables(ConstString name,
610                                  const CompilerDeclContext &parent_decl_ctx,
611                                  size_t max_matches, VariableList &variables) {
612   if (SymbolFile *symbols = GetSymbolFile())
613     symbols->FindGlobalVariables(name, parent_decl_ctx, max_matches, variables);
614 }
615 
616 void Module::FindGlobalVariables(const RegularExpression &regex,
617                                  size_t max_matches, VariableList &variables) {
618   SymbolFile *symbols = GetSymbolFile();
619   if (symbols)
620     symbols->FindGlobalVariables(regex, max_matches, variables);
621 }
622 
623 void Module::FindCompileUnits(const FileSpec &path,
624                               SymbolContextList &sc_list) {
625   const size_t num_compile_units = GetNumCompileUnits();
626   SymbolContext sc;
627   sc.module_sp = shared_from_this();
628   for (size_t i = 0; i < num_compile_units; ++i) {
629     sc.comp_unit = GetCompileUnitAtIndex(i).get();
630     if (sc.comp_unit) {
631       if (FileSpec::Match(path, sc.comp_unit->GetPrimaryFile()))
632         sc_list.Append(sc);
633     }
634   }
635 }
636 
637 Module::LookupInfo::LookupInfo(ConstString name,
638                                FunctionNameType name_type_mask,
639                                LanguageType language)
640     : m_name(name), m_lookup_name(), m_language(language) {
641   const char *name_cstr = name.GetCString();
642   llvm::StringRef basename;
643   llvm::StringRef context;
644 
645   if (name_type_mask & eFunctionNameTypeAuto) {
646     if (CPlusPlusLanguage::IsCPPMangledName(name_cstr))
647       m_name_type_mask = eFunctionNameTypeFull;
648     else if ((language == eLanguageTypeUnknown ||
649               Language::LanguageIsObjC(language)) &&
650              ObjCLanguage::IsPossibleObjCMethodName(name_cstr))
651       m_name_type_mask = eFunctionNameTypeFull;
652     else if (Language::LanguageIsC(language)) {
653       m_name_type_mask = eFunctionNameTypeFull;
654     } else {
655       if ((language == eLanguageTypeUnknown ||
656            Language::LanguageIsObjC(language)) &&
657           ObjCLanguage::IsPossibleObjCSelector(name_cstr))
658         m_name_type_mask |= eFunctionNameTypeSelector;
659 
660       CPlusPlusLanguage::MethodName cpp_method(name);
661       basename = cpp_method.GetBasename();
662       if (basename.empty()) {
663         if (CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
664                                                            basename))
665           m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
666         else
667           m_name_type_mask |= eFunctionNameTypeFull;
668       } else {
669         m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
670       }
671     }
672   } else {
673     m_name_type_mask = name_type_mask;
674     if (name_type_mask & eFunctionNameTypeMethod ||
675         name_type_mask & eFunctionNameTypeBase) {
676       // If they've asked for a CPP method or function name and it can't be
677       // that, we don't even need to search for CPP methods or names.
678       CPlusPlusLanguage::MethodName cpp_method(name);
679       if (cpp_method.IsValid()) {
680         basename = cpp_method.GetBasename();
681 
682         if (!cpp_method.GetQualifiers().empty()) {
683           // There is a "const" or other qualifier following the end of the
684           // function parens, this can't be a eFunctionNameTypeBase
685           m_name_type_mask &= ~(eFunctionNameTypeBase);
686           if (m_name_type_mask == eFunctionNameTypeNone)
687             return;
688         }
689       } else {
690         // If the CPP method parser didn't manage to chop this up, try to fill
691         // in the base name if we can. If a::b::c is passed in, we need to just
692         // look up "c", and then we'll filter the result later.
693         CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
694                                                        basename);
695       }
696     }
697 
698     if (name_type_mask & eFunctionNameTypeSelector) {
699       if (!ObjCLanguage::IsPossibleObjCSelector(name_cstr)) {
700         m_name_type_mask &= ~(eFunctionNameTypeSelector);
701         if (m_name_type_mask == eFunctionNameTypeNone)
702           return;
703       }
704     }
705 
706     // Still try and get a basename in case someone specifies a name type mask
707     // of eFunctionNameTypeFull and a name like "A::func"
708     if (basename.empty()) {
709       if (name_type_mask & eFunctionNameTypeFull &&
710           !CPlusPlusLanguage::IsCPPMangledName(name_cstr)) {
711         CPlusPlusLanguage::MethodName cpp_method(name);
712         basename = cpp_method.GetBasename();
713         if (basename.empty())
714           CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
715                                                          basename);
716       }
717     }
718   }
719 
720   if (!basename.empty()) {
721     // The name supplied was a partial C++ path like "a::count". In this case
722     // we want to do a lookup on the basename "count" and then make sure any
723     // matching results contain "a::count" so that it would match "b::a::count"
724     // and "a::count". This is why we set "match_name_after_lookup" to true
725     m_lookup_name.SetString(basename);
726     m_match_name_after_lookup = true;
727   } else {
728     // The name is already correct, just use the exact name as supplied, and we
729     // won't need to check if any matches contain "name"
730     m_lookup_name = name;
731     m_match_name_after_lookup = false;
732   }
733 }
734 
735 bool Module::LookupInfo::NameMatchesLookupInfo(
736     ConstString function_name, LanguageType language_type) const {
737   // We always keep unnamed symbols
738   if (!function_name)
739     return true;
740 
741   // If we match exactly, we can return early
742   if (m_name == function_name)
743     return true;
744 
745   // If function_name is mangled, we'll need to demangle it.
746   // In the pathologial case where the function name "looks" mangled but is
747   // actually demangled (e.g. a method named _Zonk), this operation should be
748   // relatively inexpensive since no demangling is actually occuring. See
749   // Mangled::SetValue for more context.
750   const bool function_name_may_be_mangled =
751       Mangled::GetManglingScheme(function_name) != Mangled::eManglingSchemeNone;
752   ConstString demangled_function_name = function_name;
753   if (function_name_may_be_mangled) {
754     Mangled mangled_function_name(function_name);
755     demangled_function_name = mangled_function_name.GetDemangledName();
756   }
757 
758   // If the symbol has a language, then let the language make the match.
759   // Otherwise just check that the demangled function name contains the
760   // demangled user-provided name.
761   if (Language *language = Language::FindPlugin(language_type))
762     return language->DemangledNameContainsPath(m_name, demangled_function_name);
763 
764   llvm::StringRef function_name_ref = demangled_function_name;
765   return function_name_ref.contains(m_name);
766 }
767 
768 void Module::LookupInfo::Prune(SymbolContextList &sc_list,
769                                size_t start_idx) const {
770   if (m_match_name_after_lookup && m_name) {
771     SymbolContext sc;
772     size_t i = start_idx;
773     while (i < sc_list.GetSize()) {
774       if (!sc_list.GetContextAtIndex(i, sc))
775         break;
776 
777       bool keep_it =
778           NameMatchesLookupInfo(sc.GetFunctionName(), sc.GetLanguage());
779       if (keep_it)
780         ++i;
781       else
782         sc_list.RemoveContextAtIndex(i);
783     }
784   }
785 
786   // If we have only full name matches we might have tried to set breakpoint on
787   // "func" and specified eFunctionNameTypeFull, but we might have found
788   // "a::func()", "a::b::func()", "c::func()", "func()" and "func". Only
789   // "func()" and "func" should end up matching.
790   if (m_name_type_mask == eFunctionNameTypeFull) {
791     SymbolContext sc;
792     size_t i = start_idx;
793     while (i < sc_list.GetSize()) {
794       if (!sc_list.GetContextAtIndex(i, sc))
795         break;
796       // Make sure the mangled and demangled names don't match before we try to
797       // pull anything out
798       ConstString mangled_name(sc.GetFunctionName(Mangled::ePreferMangled));
799       ConstString full_name(sc.GetFunctionName());
800       if (mangled_name != m_name && full_name != m_name) {
801         CPlusPlusLanguage::MethodName cpp_method(full_name);
802         if (cpp_method.IsValid()) {
803           if (cpp_method.GetContext().empty()) {
804             if (cpp_method.GetBasename().compare(m_name) != 0) {
805               sc_list.RemoveContextAtIndex(i);
806               continue;
807             }
808           } else {
809             std::string qualified_name;
810             llvm::StringRef anon_prefix("(anonymous namespace)");
811             if (cpp_method.GetContext() == anon_prefix)
812               qualified_name = cpp_method.GetBasename().str();
813             else
814               qualified_name = cpp_method.GetScopeQualifiedName();
815             if (qualified_name != m_name.GetCString()) {
816               sc_list.RemoveContextAtIndex(i);
817               continue;
818             }
819           }
820         }
821       }
822       ++i;
823     }
824   }
825 }
826 
827 void Module::FindFunctions(const Module::LookupInfo &lookup_info,
828                            const CompilerDeclContext &parent_decl_ctx,
829                            const ModuleFunctionSearchOptions &options,
830                            SymbolContextList &sc_list) {
831   // Find all the functions (not symbols, but debug information functions...
832   if (SymbolFile *symbols = GetSymbolFile()) {
833     symbols->FindFunctions(lookup_info, parent_decl_ctx,
834                            options.include_inlines, sc_list);
835     // Now check our symbol table for symbols that are code symbols if
836     // requested
837     if (options.include_symbols) {
838       if (Symtab *symtab = symbols->GetSymtab()) {
839         symtab->FindFunctionSymbols(lookup_info.GetLookupName(),
840                                     lookup_info.GetNameTypeMask(), sc_list);
841       }
842     }
843   }
844 }
845 
846 void Module::FindFunctions(ConstString name,
847                            const CompilerDeclContext &parent_decl_ctx,
848                            FunctionNameType name_type_mask,
849                            const ModuleFunctionSearchOptions &options,
850                            SymbolContextList &sc_list) {
851   const size_t old_size = sc_list.GetSize();
852   LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
853   FindFunctions(lookup_info, parent_decl_ctx, options, sc_list);
854   if (name_type_mask & eFunctionNameTypeAuto) {
855     const size_t new_size = sc_list.GetSize();
856     if (old_size < new_size)
857       lookup_info.Prune(sc_list, old_size);
858   }
859 }
860 
861 void Module::FindFunctions(const RegularExpression &regex,
862                            const ModuleFunctionSearchOptions &options,
863                            SymbolContextList &sc_list) {
864   const size_t start_size = sc_list.GetSize();
865 
866   if (SymbolFile *symbols = GetSymbolFile()) {
867     symbols->FindFunctions(regex, options.include_inlines, sc_list);
868 
869     // Now check our symbol table for symbols that are code symbols if
870     // requested
871     if (options.include_symbols) {
872       Symtab *symtab = symbols->GetSymtab();
873       if (symtab) {
874         std::vector<uint32_t> symbol_indexes;
875         symtab->AppendSymbolIndexesMatchingRegExAndType(
876             regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny,
877             symbol_indexes);
878         const size_t num_matches = symbol_indexes.size();
879         if (num_matches) {
880           SymbolContext sc(this);
881           const size_t end_functions_added_index = sc_list.GetSize();
882           size_t num_functions_added_to_sc_list =
883               end_functions_added_index - start_size;
884           if (num_functions_added_to_sc_list == 0) {
885             // No functions were added, just symbols, so we can just append
886             // them
887             for (size_t i = 0; i < num_matches; ++i) {
888               sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
889               SymbolType sym_type = sc.symbol->GetType();
890               if (sc.symbol && (sym_type == eSymbolTypeCode ||
891                                 sym_type == eSymbolTypeResolver))
892                 sc_list.Append(sc);
893             }
894           } else {
895             typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
896             FileAddrToIndexMap file_addr_to_index;
897             for (size_t i = start_size; i < end_functions_added_index; ++i) {
898               const SymbolContext &sc = sc_list[i];
899               if (sc.block)
900                 continue;
901               file_addr_to_index[sc.function->GetAddressRange()
902                                      .GetBaseAddress()
903                                      .GetFileAddress()] = i;
904             }
905 
906             FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
907             // Functions were added so we need to merge symbols into any
908             // existing function symbol contexts
909             for (size_t i = start_size; i < num_matches; ++i) {
910               sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
911               SymbolType sym_type = sc.symbol->GetType();
912               if (sc.symbol && sc.symbol->ValueIsAddress() &&
913                   (sym_type == eSymbolTypeCode ||
914                    sym_type == eSymbolTypeResolver)) {
915                 FileAddrToIndexMap::const_iterator pos =
916                     file_addr_to_index.find(
917                         sc.symbol->GetAddressRef().GetFileAddress());
918                 if (pos == end)
919                   sc_list.Append(sc);
920                 else
921                   sc_list[pos->second].symbol = sc.symbol;
922               }
923             }
924           }
925         }
926       }
927     }
928   }
929 }
930 
931 void Module::FindAddressesForLine(const lldb::TargetSP target_sp,
932                                   const FileSpec &file, uint32_t line,
933                                   Function *function,
934                                   std::vector<Address> &output_local,
935                                   std::vector<Address> &output_extern) {
936   SearchFilterByModule filter(target_sp, m_file);
937 
938   // TODO: Handle SourceLocationSpec column information
939   SourceLocationSpec location_spec(file, line, /*column=*/std::nullopt,
940                                    /*check_inlines=*/true,
941                                    /*exact_match=*/false);
942   AddressResolverFileLine resolver(location_spec);
943   resolver.ResolveAddress(filter);
944 
945   for (size_t n = 0; n < resolver.GetNumberOfAddresses(); n++) {
946     Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
947     Function *f = addr.CalculateSymbolContextFunction();
948     if (f && f == function)
949       output_local.push_back(addr);
950     else
951       output_extern.push_back(addr);
952   }
953 }
954 
955 void Module::FindTypes_Impl(
956     ConstString name, const CompilerDeclContext &parent_decl_ctx,
957     size_t max_matches,
958     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
959     TypeMap &types) {
960   if (SymbolFile *symbols = GetSymbolFile())
961     symbols->FindTypes(name, parent_decl_ctx, max_matches,
962                        searched_symbol_files, types);
963 }
964 
965 void Module::FindTypesInNamespace(ConstString type_name,
966                                   const CompilerDeclContext &parent_decl_ctx,
967                                   size_t max_matches, TypeList &type_list) {
968   TypeMap types_map;
969   llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
970   FindTypes_Impl(type_name, parent_decl_ctx, max_matches, searched_symbol_files,
971                  types_map);
972   if (types_map.GetSize()) {
973     SymbolContext sc;
974     sc.module_sp = shared_from_this();
975     sc.SortTypeList(types_map, type_list);
976   }
977 }
978 
979 lldb::TypeSP Module::FindFirstType(const SymbolContext &sc, ConstString name,
980                                    bool exact_match) {
981   TypeList type_list;
982   llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
983   FindTypes(name, exact_match, 1, searched_symbol_files, type_list);
984   if (type_list.GetSize())
985     return type_list.GetTypeAtIndex(0);
986   return TypeSP();
987 }
988 
989 void Module::FindTypes(
990     ConstString name, bool exact_match, size_t max_matches,
991     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
992     TypeList &types) {
993   const char *type_name_cstr = name.GetCString();
994   llvm::StringRef type_scope;
995   llvm::StringRef type_basename;
996   TypeClass type_class = eTypeClassAny;
997   TypeMap typesmap;
998 
999   if (Type::GetTypeScopeAndBasename(type_name_cstr, type_scope, type_basename,
1000                                     type_class)) {
1001     // Check if "name" starts with "::" which means the qualified type starts
1002     // from the root namespace and implies and exact match. The typenames we
1003     // get back from clang do not start with "::" so we need to strip this off
1004     // in order to get the qualified names to match
1005     exact_match = type_scope.consume_front("::");
1006 
1007     ConstString type_basename_const_str(type_basename);
1008     FindTypes_Impl(type_basename_const_str, CompilerDeclContext(), max_matches,
1009                    searched_symbol_files, typesmap);
1010     if (typesmap.GetSize())
1011       typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1012                                      exact_match);
1013   } else {
1014     // The type is not in a namespace/class scope, just search for it by
1015     // basename
1016     if (type_class != eTypeClassAny && !type_basename.empty()) {
1017       // The "type_name_cstr" will have been modified if we have a valid type
1018       // class prefix (like "struct", "class", "union", "typedef" etc).
1019       FindTypes_Impl(ConstString(type_basename), CompilerDeclContext(),
1020                      UINT_MAX, searched_symbol_files, typesmap);
1021       typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1022                                      exact_match);
1023     } else {
1024       FindTypes_Impl(name, CompilerDeclContext(), UINT_MAX,
1025                      searched_symbol_files, typesmap);
1026       if (exact_match) {
1027         typesmap.RemoveMismatchedTypes(type_scope, name, type_class,
1028                                        exact_match);
1029       }
1030     }
1031   }
1032   if (typesmap.GetSize()) {
1033     SymbolContext sc;
1034     sc.module_sp = shared_from_this();
1035     sc.SortTypeList(typesmap, types);
1036   }
1037 }
1038 
1039 void Module::FindTypes(
1040     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1041     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1042     TypeMap &types) {
1043   // If a scoped timer is needed, place it in a SymbolFile::FindTypes override.
1044   // A timer here is too high volume for some cases, for example when calling
1045   // FindTypes on each object file.
1046   if (SymbolFile *symbols = GetSymbolFile())
1047     symbols->FindTypes(pattern, languages, searched_symbol_files, types);
1048 }
1049 
1050 SymbolFile *Module::GetSymbolFile(bool can_create, Stream *feedback_strm) {
1051   if (!m_did_load_symfile.load()) {
1052     std::lock_guard<std::recursive_mutex> guard(m_mutex);
1053     if (!m_did_load_symfile.load() && can_create) {
1054       ObjectFile *obj_file = GetObjectFile();
1055       if (obj_file != nullptr) {
1056         LLDB_SCOPED_TIMER();
1057         m_symfile_up.reset(
1058             SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
1059         m_did_load_symfile = true;
1060       }
1061     }
1062   }
1063   return m_symfile_up ? m_symfile_up->GetSymbolFile() : nullptr;
1064 }
1065 
1066 Symtab *Module::GetSymtab() {
1067   if (SymbolFile *symbols = GetSymbolFile())
1068     return symbols->GetSymtab();
1069   return nullptr;
1070 }
1071 
1072 void Module::SetFileSpecAndObjectName(const FileSpec &file,
1073                                       ConstString object_name) {
1074   // Container objects whose paths do not specify a file directly can call this
1075   // function to correct the file and object names.
1076   m_file = file;
1077   m_mod_time = FileSystem::Instance().GetModificationTime(file);
1078   m_object_name = object_name;
1079 }
1080 
1081 const ArchSpec &Module::GetArchitecture() const { return m_arch; }
1082 
1083 std::string Module::GetSpecificationDescription() const {
1084   std::string spec(GetFileSpec().GetPath());
1085   if (m_object_name) {
1086     spec += '(';
1087     spec += m_object_name.GetCString();
1088     spec += ')';
1089   }
1090   return spec;
1091 }
1092 
1093 void Module::GetDescription(llvm::raw_ostream &s,
1094                             lldb::DescriptionLevel level) {
1095   if (level >= eDescriptionLevelFull) {
1096     if (m_arch.IsValid())
1097       s << llvm::formatv("({0}) ", m_arch.GetArchitectureName());
1098   }
1099 
1100   if (level == eDescriptionLevelBrief) {
1101     const char *filename = m_file.GetFilename().GetCString();
1102     if (filename)
1103       s << filename;
1104   } else {
1105     char path[PATH_MAX];
1106     if (m_file.GetPath(path, sizeof(path)))
1107       s << path;
1108   }
1109 
1110   const char *object_name = m_object_name.GetCString();
1111   if (object_name)
1112     s << llvm::formatv("({0})", object_name);
1113 }
1114 
1115 bool Module::FileHasChanged() const {
1116   // We have provided the DataBuffer for this module to avoid accessing the
1117   // filesystem. We never want to reload those files.
1118   if (m_data_sp)
1119     return false;
1120   if (!m_file_has_changed)
1121     m_file_has_changed =
1122         (FileSystem::Instance().GetModificationTime(m_file) != m_mod_time);
1123   return m_file_has_changed;
1124 }
1125 
1126 void Module::ReportWarningOptimization(
1127     std::optional<lldb::user_id_t> debugger_id) {
1128   ConstString file_name = GetFileSpec().GetFilename();
1129   if (file_name.IsEmpty())
1130     return;
1131 
1132   StreamString ss;
1133   ss << file_name
1134      << " was compiled with optimization - stepping may behave "
1135         "oddly; variables may not be available.";
1136   Debugger::ReportWarning(std::string(ss.GetString()), debugger_id,
1137                           &m_optimization_warning);
1138 }
1139 
1140 void Module::ReportWarningUnsupportedLanguage(
1141     LanguageType language, std::optional<lldb::user_id_t> debugger_id) {
1142   StreamString ss;
1143   ss << "This version of LLDB has no plugin for the language \""
1144      << Language::GetNameForLanguageType(language)
1145      << "\". "
1146         "Inspection of frame variables will be limited.";
1147   Debugger::ReportWarning(std::string(ss.GetString()), debugger_id,
1148                           &m_language_warning);
1149 }
1150 
1151 void Module::ReportErrorIfModifyDetected(
1152     const llvm::formatv_object_base &payload) {
1153   if (!m_first_file_changed_log) {
1154     if (FileHasChanged()) {
1155       m_first_file_changed_log = true;
1156       StreamString strm;
1157       strm.PutCString("the object file ");
1158       GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelFull);
1159       strm.PutCString(" has been modified\n");
1160       strm.PutCString(payload.str());
1161       strm.PutCString("The debug session should be aborted as the original "
1162                       "debug information has been overwritten.");
1163       Debugger::ReportError(std::string(strm.GetString()));
1164     }
1165   }
1166 }
1167 
1168 void Module::ReportError(const llvm::formatv_object_base &payload) {
1169   StreamString strm;
1170   GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelBrief);
1171   strm.PutChar(' ');
1172   strm.PutCString(payload.str());
1173   Debugger::ReportError(strm.GetString().str());
1174 }
1175 
1176 void Module::ReportWarning(const llvm::formatv_object_base &payload) {
1177   StreamString strm;
1178   GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelFull);
1179   strm.PutChar(' ');
1180   strm.PutCString(payload.str());
1181   Debugger::ReportWarning(std::string(strm.GetString()));
1182 }
1183 
1184 void Module::LogMessage(Log *log, const llvm::formatv_object_base &payload) {
1185   StreamString log_message;
1186   GetDescription(log_message.AsRawOstream(), lldb::eDescriptionLevelFull);
1187   log_message.PutCString(": ");
1188   log_message.PutCString(payload.str());
1189   log->PutCString(log_message.GetData());
1190 }
1191 
1192 void Module::LogMessageVerboseBacktrace(
1193     Log *log, const llvm::formatv_object_base &payload) {
1194   StreamString log_message;
1195   GetDescription(log_message.AsRawOstream(), lldb::eDescriptionLevelFull);
1196   log_message.PutCString(": ");
1197   log_message.PutCString(payload.str());
1198   if (log->GetVerbose()) {
1199     std::string back_trace;
1200     llvm::raw_string_ostream stream(back_trace);
1201     llvm::sys::PrintStackTrace(stream);
1202     log_message.PutCString(back_trace);
1203   }
1204   log->PutCString(log_message.GetData());
1205 }
1206 
1207 void Module::Dump(Stream *s) {
1208   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1209   // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1210   s->Indent();
1211   s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(),
1212             m_object_name ? "(" : "",
1213             m_object_name ? m_object_name.GetCString() : "",
1214             m_object_name ? ")" : "");
1215 
1216   s->IndentMore();
1217 
1218   ObjectFile *objfile = GetObjectFile();
1219   if (objfile)
1220     objfile->Dump(s);
1221 
1222   if (SymbolFile *symbols = GetSymbolFile())
1223     symbols->Dump(*s);
1224 
1225   s->IndentLess();
1226 }
1227 
1228 ConstString Module::GetObjectName() const { return m_object_name; }
1229 
1230 ObjectFile *Module::GetObjectFile() {
1231   if (!m_did_load_objfile.load()) {
1232     std::lock_guard<std::recursive_mutex> guard(m_mutex);
1233     if (!m_did_load_objfile.load()) {
1234       LLDB_SCOPED_TIMERF("Module::GetObjectFile () module = %s",
1235                          GetFileSpec().GetFilename().AsCString(""));
1236       lldb::offset_t data_offset = 0;
1237       lldb::offset_t file_size = 0;
1238 
1239       if (m_data_sp)
1240         file_size = m_data_sp->GetByteSize();
1241       else if (m_file)
1242         file_size = FileSystem::Instance().GetByteSize(m_file);
1243 
1244       if (file_size > m_object_offset) {
1245         m_did_load_objfile = true;
1246         // FindPlugin will modify its data_sp argument. Do not let it
1247         // modify our m_data_sp member.
1248         auto data_sp = m_data_sp;
1249         m_objfile_sp = ObjectFile::FindPlugin(
1250             shared_from_this(), &m_file, m_object_offset,
1251             file_size - m_object_offset, data_sp, data_offset);
1252         if (m_objfile_sp) {
1253           // Once we get the object file, update our module with the object
1254           // file's architecture since it might differ in vendor/os if some
1255           // parts were unknown.  But since the matching arch might already be
1256           // more specific than the generic COFF architecture, only merge in
1257           // those values that overwrite unspecified unknown values.
1258           m_arch.MergeFrom(m_objfile_sp->GetArchitecture());
1259         } else {
1260           ReportError("failed to load objfile for {0}",
1261                       GetFileSpec().GetPath().c_str());
1262         }
1263       }
1264     }
1265   }
1266   return m_objfile_sp.get();
1267 }
1268 
1269 SectionList *Module::GetSectionList() {
1270   // Populate m_sections_up with sections from objfile.
1271   if (!m_sections_up) {
1272     ObjectFile *obj_file = GetObjectFile();
1273     if (obj_file != nullptr)
1274       obj_file->CreateSections(*GetUnifiedSectionList());
1275   }
1276   return m_sections_up.get();
1277 }
1278 
1279 void Module::SectionFileAddressesChanged() {
1280   ObjectFile *obj_file = GetObjectFile();
1281   if (obj_file)
1282     obj_file->SectionFileAddressesChanged();
1283   if (SymbolFile *symbols = GetSymbolFile())
1284     symbols->SectionFileAddressesChanged();
1285 }
1286 
1287 UnwindTable &Module::GetUnwindTable() {
1288   if (!m_unwind_table) {
1289     m_unwind_table.emplace(*this);
1290     if (!m_symfile_spec)
1291       Symbols::DownloadSymbolFileAsync(GetUUID());
1292   }
1293   return *m_unwind_table;
1294 }
1295 
1296 SectionList *Module::GetUnifiedSectionList() {
1297   if (!m_sections_up)
1298     m_sections_up = std::make_unique<SectionList>();
1299   return m_sections_up.get();
1300 }
1301 
1302 const Symbol *Module::FindFirstSymbolWithNameAndType(ConstString name,
1303                                                      SymbolType symbol_type) {
1304   LLDB_SCOPED_TIMERF(
1305       "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1306       name.AsCString(), symbol_type);
1307   if (Symtab *symtab = GetSymtab())
1308     return symtab->FindFirstSymbolWithNameAndType(
1309         name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1310   return nullptr;
1311 }
1312 void Module::SymbolIndicesToSymbolContextList(
1313     Symtab *symtab, std::vector<uint32_t> &symbol_indexes,
1314     SymbolContextList &sc_list) {
1315   // No need to protect this call using m_mutex all other method calls are
1316   // already thread safe.
1317 
1318   size_t num_indices = symbol_indexes.size();
1319   if (num_indices > 0) {
1320     SymbolContext sc;
1321     CalculateSymbolContext(&sc);
1322     for (size_t i = 0; i < num_indices; i++) {
1323       sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
1324       if (sc.symbol)
1325         sc_list.Append(sc);
1326     }
1327   }
1328 }
1329 
1330 void Module::FindFunctionSymbols(ConstString name, uint32_t name_type_mask,
1331                                  SymbolContextList &sc_list) {
1332   LLDB_SCOPED_TIMERF("Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1333                      name.AsCString(), name_type_mask);
1334   if (Symtab *symtab = GetSymtab())
1335     symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
1336 }
1337 
1338 void Module::FindSymbolsWithNameAndType(ConstString name,
1339                                         SymbolType symbol_type,
1340                                         SymbolContextList &sc_list) {
1341   // No need to protect this call using m_mutex all other method calls are
1342   // already thread safe.
1343   if (Symtab *symtab = GetSymtab()) {
1344     std::vector<uint32_t> symbol_indexes;
1345     symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes);
1346     SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1347   }
1348 }
1349 
1350 void Module::FindSymbolsMatchingRegExAndType(
1351     const RegularExpression &regex, SymbolType symbol_type,
1352     SymbolContextList &sc_list, Mangled::NamePreference mangling_preference) {
1353   // No need to protect this call using m_mutex all other method calls are
1354   // already thread safe.
1355   LLDB_SCOPED_TIMERF(
1356       "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1357       regex.GetText().str().c_str(), symbol_type);
1358   if (Symtab *symtab = GetSymtab()) {
1359     std::vector<uint32_t> symbol_indexes;
1360     symtab->FindAllSymbolsMatchingRexExAndType(
1361         regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny,
1362         symbol_indexes, mangling_preference);
1363     SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1364   }
1365 }
1366 
1367 void Module::PreloadSymbols() {
1368   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1369   SymbolFile *sym_file = GetSymbolFile();
1370   if (!sym_file)
1371     return;
1372 
1373   // Load the object file symbol table and any symbols from the SymbolFile that
1374   // get appended using SymbolFile::AddSymbols(...).
1375   if (Symtab *symtab = sym_file->GetSymtab())
1376     symtab->PreloadSymbols();
1377 
1378   // Now let the symbol file preload its data and the symbol table will be
1379   // available without needing to take the module lock.
1380   sym_file->PreloadSymbols();
1381 }
1382 
1383 void Module::SetSymbolFileFileSpec(const FileSpec &file) {
1384   if (!FileSystem::Instance().Exists(file))
1385     return;
1386   if (m_symfile_up) {
1387     // Remove any sections in the unified section list that come from the
1388     // current symbol vendor.
1389     SectionList *section_list = GetSectionList();
1390     SymbolFile *symbol_file = GetSymbolFile();
1391     if (section_list && symbol_file) {
1392       ObjectFile *obj_file = symbol_file->GetObjectFile();
1393       // Make sure we have an object file and that the symbol vendor's objfile
1394       // isn't the same as the module's objfile before we remove any sections
1395       // for it...
1396       if (obj_file) {
1397         // Check to make sure we aren't trying to specify the file we already
1398         // have
1399         if (obj_file->GetFileSpec() == file) {
1400           // We are being told to add the exact same file that we already have
1401           // we don't have to do anything.
1402           return;
1403         }
1404 
1405         // Cleare the current symtab as we are going to replace it with a new
1406         // one
1407         obj_file->ClearSymtab();
1408 
1409         // Clear the unwind table too, as that may also be affected by the
1410         // symbol file information.
1411         m_unwind_table.reset();
1412 
1413         // The symbol file might be a directory bundle ("/tmp/a.out.dSYM")
1414         // instead of a full path to the symbol file within the bundle
1415         // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to
1416         // check this
1417 
1418         if (FileSystem::Instance().IsDirectory(file)) {
1419           std::string new_path(file.GetPath());
1420           std::string old_path(obj_file->GetFileSpec().GetPath());
1421           if (llvm::StringRef(old_path).startswith(new_path)) {
1422             // We specified the same bundle as the symbol file that we already
1423             // have
1424             return;
1425           }
1426         }
1427 
1428         if (obj_file != m_objfile_sp.get()) {
1429           size_t num_sections = section_list->GetNumSections(0);
1430           for (size_t idx = num_sections; idx > 0; --idx) {
1431             lldb::SectionSP section_sp(
1432                 section_list->GetSectionAtIndex(idx - 1));
1433             if (section_sp->GetObjectFile() == obj_file) {
1434               section_list->DeleteSection(idx - 1);
1435             }
1436           }
1437         }
1438       }
1439     }
1440     // Keep all old symbol files around in case there are any lingering type
1441     // references in any SBValue objects that might have been handed out.
1442     m_old_symfiles.push_back(std::move(m_symfile_up));
1443   }
1444   m_symfile_spec = file;
1445   m_symfile_up.reset();
1446   m_did_load_symfile = false;
1447 }
1448 
1449 bool Module::IsExecutable() {
1450   if (GetObjectFile() == nullptr)
1451     return false;
1452   else
1453     return GetObjectFile()->IsExecutable();
1454 }
1455 
1456 bool Module::IsLoadedInTarget(Target *target) {
1457   ObjectFile *obj_file = GetObjectFile();
1458   if (obj_file) {
1459     SectionList *sections = GetSectionList();
1460     if (sections != nullptr) {
1461       size_t num_sections = sections->GetSize();
1462       for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) {
1463         SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1464         if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) {
1465           return true;
1466         }
1467       }
1468     }
1469   }
1470   return false;
1471 }
1472 
1473 bool Module::LoadScriptingResourceInTarget(Target *target, Status &error,
1474                                            Stream *feedback_stream) {
1475   if (!target) {
1476     error.SetErrorString("invalid destination Target");
1477     return false;
1478   }
1479 
1480   LoadScriptFromSymFile should_load =
1481       target->TargetProperties::GetLoadScriptFromSymbolFile();
1482 
1483   if (should_load == eLoadScriptFromSymFileFalse)
1484     return false;
1485 
1486   Debugger &debugger = target->GetDebugger();
1487   const ScriptLanguage script_language = debugger.GetScriptLanguage();
1488   if (script_language != eScriptLanguageNone) {
1489 
1490     PlatformSP platform_sp(target->GetPlatform());
1491 
1492     if (!platform_sp) {
1493       error.SetErrorString("invalid Platform");
1494       return false;
1495     }
1496 
1497     FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources(
1498         target, *this, feedback_stream);
1499 
1500     const uint32_t num_specs = file_specs.GetSize();
1501     if (num_specs) {
1502       ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
1503       if (script_interpreter) {
1504         for (uint32_t i = 0; i < num_specs; ++i) {
1505           FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i));
1506           if (scripting_fspec &&
1507               FileSystem::Instance().Exists(scripting_fspec)) {
1508             if (should_load == eLoadScriptFromSymFileWarn) {
1509               if (feedback_stream)
1510                 feedback_stream->Printf(
1511                     "warning: '%s' contains a debug script. To run this script "
1512                     "in "
1513                     "this debug session:\n\n    command script import "
1514                     "\"%s\"\n\n"
1515                     "To run all discovered debug scripts in this session:\n\n"
1516                     "    settings set target.load-script-from-symbol-file "
1517                     "true\n",
1518                     GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1519                     scripting_fspec.GetPath().c_str());
1520               return false;
1521             }
1522             StreamString scripting_stream;
1523             scripting_fspec.Dump(scripting_stream.AsRawOstream());
1524             LoadScriptOptions options;
1525             bool did_load = script_interpreter->LoadScriptingModule(
1526                 scripting_stream.GetData(), options, error);
1527             if (!did_load)
1528               return false;
1529           }
1530         }
1531       } else {
1532         error.SetErrorString("invalid ScriptInterpreter");
1533         return false;
1534       }
1535     }
1536   }
1537   return true;
1538 }
1539 
1540 bool Module::SetArchitecture(const ArchSpec &new_arch) {
1541   if (!m_arch.IsValid()) {
1542     m_arch = new_arch;
1543     return true;
1544   }
1545   return m_arch.IsCompatibleMatch(new_arch);
1546 }
1547 
1548 bool Module::SetLoadAddress(Target &target, lldb::addr_t value,
1549                             bool value_is_offset, bool &changed) {
1550   ObjectFile *object_file = GetObjectFile();
1551   if (object_file != nullptr) {
1552     changed = object_file->SetLoadAddress(target, value, value_is_offset);
1553     return true;
1554   } else {
1555     changed = false;
1556   }
1557   return false;
1558 }
1559 
1560 bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) {
1561   const UUID &uuid = module_ref.GetUUID();
1562 
1563   if (uuid.IsValid()) {
1564     // If the UUID matches, then nothing more needs to match...
1565     return (uuid == GetUUID());
1566   }
1567 
1568   const FileSpec &file_spec = module_ref.GetFileSpec();
1569   if (!FileSpec::Match(file_spec, m_file) &&
1570       !FileSpec::Match(file_spec, m_platform_file))
1571     return false;
1572 
1573   const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1574   if (!FileSpec::Match(platform_file_spec, GetPlatformFileSpec()))
1575     return false;
1576 
1577   const ArchSpec &arch = module_ref.GetArchitecture();
1578   if (arch.IsValid()) {
1579     if (!m_arch.IsCompatibleMatch(arch))
1580       return false;
1581   }
1582 
1583   ConstString object_name = module_ref.GetObjectName();
1584   if (object_name) {
1585     if (object_name != GetObjectName())
1586       return false;
1587   }
1588   return true;
1589 }
1590 
1591 bool Module::FindSourceFile(const FileSpec &orig_spec,
1592                             FileSpec &new_spec) const {
1593   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1594   if (auto remapped = m_source_mappings.FindFile(orig_spec)) {
1595     new_spec = *remapped;
1596     return true;
1597   }
1598   return false;
1599 }
1600 
1601 std::optional<std::string> Module::RemapSourceFile(llvm::StringRef path) const {
1602   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1603   if (auto remapped = m_source_mappings.RemapPath(path))
1604     return remapped->GetPath();
1605   return {};
1606 }
1607 
1608 void Module::RegisterXcodeSDK(llvm::StringRef sdk_name,
1609                               llvm::StringRef sysroot) {
1610   XcodeSDK sdk(sdk_name.str());
1611   auto sdk_path_or_err = HostInfo::GetXcodeSDKPath(sdk);
1612 
1613   if (!sdk_path_or_err) {
1614     Debugger::ReportError("Error while searching for Xcode SDK: " +
1615                           toString(sdk_path_or_err.takeError()));
1616     return;
1617   }
1618 
1619   auto sdk_path = *sdk_path_or_err;
1620   if (sdk_path.empty())
1621     return;
1622   // If the SDK changed for a previously registered source path, update it.
1623   // This could happend with -fdebug-prefix-map, otherwise it's unlikely.
1624   if (!m_source_mappings.Replace(sysroot, sdk_path, true))
1625     // In the general case, however, append it to the list.
1626     m_source_mappings.Append(sysroot, sdk_path, false);
1627 }
1628 
1629 bool Module::MergeArchitecture(const ArchSpec &arch_spec) {
1630   if (!arch_spec.IsValid())
1631     return false;
1632   LLDB_LOGF(GetLog(LLDBLog::Object | LLDBLog::Modules),
1633             "module has arch %s, merging/replacing with arch %s",
1634             m_arch.GetTriple().getTriple().c_str(),
1635             arch_spec.GetTriple().getTriple().c_str());
1636   if (!m_arch.IsCompatibleMatch(arch_spec)) {
1637     // The new architecture is different, we just need to replace it.
1638     return SetArchitecture(arch_spec);
1639   }
1640 
1641   // Merge bits from arch_spec into "merged_arch" and set our architecture.
1642   ArchSpec merged_arch(m_arch);
1643   merged_arch.MergeFrom(arch_spec);
1644   // SetArchitecture() is a no-op if m_arch is already valid.
1645   m_arch = ArchSpec();
1646   return SetArchitecture(merged_arch);
1647 }
1648 
1649 llvm::VersionTuple Module::GetVersion() {
1650   if (ObjectFile *obj_file = GetObjectFile())
1651     return obj_file->GetVersion();
1652   return llvm::VersionTuple();
1653 }
1654 
1655 bool Module::GetIsDynamicLinkEditor() {
1656   ObjectFile *obj_file = GetObjectFile();
1657 
1658   if (obj_file)
1659     return obj_file->GetIsDynamicLinkEditor();
1660 
1661   return false;
1662 }
1663 
1664 uint32_t Module::Hash() {
1665   std::string identifier;
1666   llvm::raw_string_ostream id_strm(identifier);
1667   id_strm << m_arch.GetTriple().str() << '-' << m_file.GetPath();
1668   if (m_object_name)
1669     id_strm << '(' << m_object_name << ')';
1670   if (m_object_offset > 0)
1671     id_strm << m_object_offset;
1672   const auto mtime = llvm::sys::toTimeT(m_object_mod_time);
1673   if (mtime > 0)
1674     id_strm << mtime;
1675   return llvm::djbHash(id_strm.str());
1676 }
1677 
1678 std::string Module::GetCacheKey() {
1679   std::string key;
1680   llvm::raw_string_ostream strm(key);
1681   strm << m_arch.GetTriple().str() << '-' << m_file.GetFilename();
1682   if (m_object_name)
1683     strm << '(' << m_object_name << ')';
1684   strm << '-' << llvm::format_hex(Hash(), 10);
1685   return strm.str();
1686 }
1687 
1688 DataFileCache *Module::GetIndexCache() {
1689   if (!ModuleList::GetGlobalModuleListProperties().GetEnableLLDBIndexCache())
1690     return nullptr;
1691   // NOTE: intentional leak so we don't crash if global destructor chain gets
1692   // called as other threads still use the result of this function
1693   static DataFileCache *g_data_file_cache =
1694       new DataFileCache(ModuleList::GetGlobalModuleListProperties()
1695                             .GetLLDBIndexCachePath()
1696                             .GetPath());
1697   return g_data_file_cache;
1698 }
1699