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