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