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_file_has_changed(false), m_first_file_changed_log(false) {
133   // Scope for locker below...
134   {
135     std::lock_guard<std::recursive_mutex> guard(
136         GetAllocationModuleCollectionMutex());
137     GetModuleCollection().push_back(this);
138   }
139 
140   Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
141   if (log != nullptr)
142     LLDB_LOGF(log, "%p Module::Module((%s) '%s%s%s%s')",
143               static_cast<void *>(this),
144               module_spec.GetArchitecture().GetArchitectureName(),
145               module_spec.GetFileSpec().GetPath().c_str(),
146               module_spec.GetObjectName().IsEmpty() ? "" : "(",
147               module_spec.GetObjectName().IsEmpty()
148                   ? ""
149                   : module_spec.GetObjectName().AsCString(""),
150               module_spec.GetObjectName().IsEmpty() ? "" : ")");
151 
152   auto data_sp = module_spec.GetData();
153   lldb::offset_t file_size = 0;
154   if (data_sp)
155     file_size = data_sp->GetByteSize();
156 
157   // First extract all module specifications from the file using the local file
158   // path. If there are no specifications, then don't fill anything in
159   ModuleSpecList modules_specs;
160   if (ObjectFile::GetModuleSpecifications(
161           module_spec.GetFileSpec(), 0, file_size, modules_specs, data_sp) == 0)
162     return;
163 
164   // Now make sure that one of the module specifications matches what we just
165   // extract. We might have a module specification that specifies a file
166   // "/usr/lib/dyld" with UUID XXX, but we might have a local version of
167   // "/usr/lib/dyld" that has
168   // UUID YYY and we don't want those to match. If they don't match, just don't
169   // fill any ivars in so we don't accidentally grab the wrong file later since
170   // they don't match...
171   ModuleSpec matching_module_spec;
172   if (!modules_specs.FindMatchingModuleSpec(module_spec,
173                                             matching_module_spec)) {
174     if (log) {
175       LLDB_LOGF(log, "Found local object file but the specs didn't match");
176     }
177     return;
178   }
179 
180   // Set m_data_sp if it was initially provided in the ModuleSpec. Note that
181   // we cannot use the data_sp variable here, because it will have been
182   // modified by GetModuleSpecifications().
183   if (auto module_spec_data_sp = module_spec.GetData()) {
184     m_data_sp = module_spec_data_sp;
185     m_mod_time = {};
186   } else {
187     if (module_spec.GetFileSpec())
188       m_mod_time =
189           FileSystem::Instance().GetModificationTime(module_spec.GetFileSpec());
190     else if (matching_module_spec.GetFileSpec())
191       m_mod_time = FileSystem::Instance().GetModificationTime(
192           matching_module_spec.GetFileSpec());
193   }
194 
195   // Copy the architecture from the actual spec if we got one back, else use
196   // the one that was specified
197   if (matching_module_spec.GetArchitecture().IsValid())
198     m_arch = matching_module_spec.GetArchitecture();
199   else if (module_spec.GetArchitecture().IsValid())
200     m_arch = module_spec.GetArchitecture();
201 
202   // Copy the file spec over and use the specified one (if there was one) so we
203   // don't use a path that might have gotten resolved a path in
204   // 'matching_module_spec'
205   if (module_spec.GetFileSpec())
206     m_file = module_spec.GetFileSpec();
207   else if (matching_module_spec.GetFileSpec())
208     m_file = matching_module_spec.GetFileSpec();
209 
210   // Copy the platform file spec over
211   if (module_spec.GetPlatformFileSpec())
212     m_platform_file = module_spec.GetPlatformFileSpec();
213   else if (matching_module_spec.GetPlatformFileSpec())
214     m_platform_file = matching_module_spec.GetPlatformFileSpec();
215 
216   // Copy the symbol file spec over
217   if (module_spec.GetSymbolFileSpec())
218     m_symfile_spec = module_spec.GetSymbolFileSpec();
219   else if (matching_module_spec.GetSymbolFileSpec())
220     m_symfile_spec = matching_module_spec.GetSymbolFileSpec();
221 
222   // Copy the object name over
223   if (matching_module_spec.GetObjectName())
224     m_object_name = matching_module_spec.GetObjectName();
225   else
226     m_object_name = module_spec.GetObjectName();
227 
228   // Always trust the object offset (file offset) and object modification time
229   // (for mod time in a BSD static archive) of from the matching module
230   // specification
231   m_object_offset = matching_module_spec.GetObjectOffset();
232   m_object_mod_time = matching_module_spec.GetObjectModificationTime();
233 }
234 
235 Module::Module(const FileSpec &file_spec, const ArchSpec &arch,
236                const ConstString *object_name, lldb::offset_t object_offset,
237                const llvm::sys::TimePoint<> &object_mod_time)
238     : m_mod_time(FileSystem::Instance().GetModificationTime(file_spec)),
239       m_arch(arch), m_file(file_spec), m_object_offset(object_offset),
240       m_object_mod_time(object_mod_time), m_file_has_changed(false),
241       m_first_file_changed_log(false) {
242   // Scope for locker below...
243   {
244     std::lock_guard<std::recursive_mutex> guard(
245         GetAllocationModuleCollectionMutex());
246     GetModuleCollection().push_back(this);
247   }
248 
249   if (object_name)
250     m_object_name = *object_name;
251 
252   Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
253   if (log != nullptr)
254     LLDB_LOGF(log, "%p Module::Module((%s) '%s%s%s%s')",
255               static_cast<void *>(this), m_arch.GetArchitectureName(),
256               m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
257               m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
258               m_object_name.IsEmpty() ? "" : ")");
259 }
260 
261 Module::Module() : m_file_has_changed(false), m_first_file_changed_log(false) {
262   std::lock_guard<std::recursive_mutex> guard(
263       GetAllocationModuleCollectionMutex());
264   GetModuleCollection().push_back(this);
265 }
266 
267 Module::~Module() {
268   // Lock our module down while we tear everything down to make sure we don't
269   // get any access to the module while it is being destroyed
270   std::lock_guard<std::recursive_mutex> guard(m_mutex);
271   // Scope for locker below...
272   {
273     std::lock_guard<std::recursive_mutex> guard(
274         GetAllocationModuleCollectionMutex());
275     ModuleCollection &modules = GetModuleCollection();
276     ModuleCollection::iterator end = modules.end();
277     ModuleCollection::iterator pos = std::find(modules.begin(), end, this);
278     assert(pos != end);
279     modules.erase(pos);
280   }
281   Log *log(GetLog(LLDBLog::Object | LLDBLog::Modules));
282   if (log != nullptr)
283     LLDB_LOGF(log, "%p Module::~Module((%s) '%s%s%s%s')",
284               static_cast<void *>(this), m_arch.GetArchitectureName(),
285               m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(",
286               m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""),
287               m_object_name.IsEmpty() ? "" : ")");
288   // Release any auto pointers before we start tearing down our member
289   // variables since the object file and symbol files might need to make
290   // function calls back into this module object. The ordering is important
291   // here because symbol files can require the module object file. So we tear
292   // down the symbol file first, then the object file.
293   m_sections_up.reset();
294   m_symfile_up.reset();
295   m_objfile_sp.reset();
296 }
297 
298 ObjectFile *Module::GetMemoryObjectFile(const lldb::ProcessSP &process_sp,
299                                         lldb::addr_t header_addr, Status &error,
300                                         size_t size_to_read) {
301   if (m_objfile_sp) {
302     error.SetErrorString("object file already exists");
303   } else {
304     std::lock_guard<std::recursive_mutex> guard(m_mutex);
305     if (process_sp) {
306       m_did_load_objfile = true;
307       std::shared_ptr<DataBufferHeap> data_sp =
308           std::make_shared<DataBufferHeap>(size_to_read, 0);
309       Status readmem_error;
310       const size_t bytes_read =
311           process_sp->ReadMemory(header_addr, data_sp->GetBytes(),
312                                  data_sp->GetByteSize(), readmem_error);
313       if (bytes_read < size_to_read)
314         data_sp->SetByteSize(bytes_read);
315       if (data_sp->GetByteSize() > 0) {
316         m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp,
317                                               header_addr, data_sp);
318         if (m_objfile_sp) {
319           StreamString s;
320           s.Printf("0x%16.16" PRIx64, header_addr);
321           m_object_name.SetString(s.GetString());
322 
323           // Once we get the object file, update our module with the object
324           // file's architecture since it might differ in vendor/os if some
325           // parts were unknown.
326           m_arch = m_objfile_sp->GetArchitecture();
327 
328           // Augment the arch with the target's information in case
329           // we are unable to extract the os/environment from memory.
330           m_arch.MergeFrom(process_sp->GetTarget().GetArchitecture());
331         } else {
332           error.SetErrorString("unable to find suitable object file plug-in");
333         }
334       } else {
335         error.SetErrorStringWithFormat("unable to read header from memory: %s",
336                                        readmem_error.AsCString());
337       }
338     } else {
339       error.SetErrorString("invalid process");
340     }
341   }
342   return m_objfile_sp.get();
343 }
344 
345 const lldb_private::UUID &Module::GetUUID() {
346   if (!m_did_set_uuid.load()) {
347     std::lock_guard<std::recursive_mutex> guard(m_mutex);
348     if (!m_did_set_uuid.load()) {
349       ObjectFile *obj_file = GetObjectFile();
350 
351       if (obj_file != nullptr) {
352         m_uuid = obj_file->GetUUID();
353         m_did_set_uuid = true;
354       }
355     }
356   }
357   return m_uuid;
358 }
359 
360 void Module::SetUUID(const lldb_private::UUID &uuid) {
361   std::lock_guard<std::recursive_mutex> guard(m_mutex);
362   if (!m_did_set_uuid) {
363     m_uuid = uuid;
364     m_did_set_uuid = true;
365   } else {
366     lldbassert(0 && "Attempting to overwrite the existing module UUID");
367   }
368 }
369 
370 llvm::Expected<TypeSystem &>
371 Module::GetTypeSystemForLanguage(LanguageType language) {
372   return m_type_system_map.GetTypeSystemForLanguage(language, this, true);
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   LLDB_SCOPED_TIMERF("Module::GetNumCompileUnits (module = %p)",
421                      static_cast<void *>(this));
422   if (SymbolFile *symbols = GetSymbolFile())
423     return symbols->GetNumCompileUnits();
424   return 0;
425 }
426 
427 CompUnitSP Module::GetCompileUnitAtIndex(size_t index) {
428   std::lock_guard<std::recursive_mutex> guard(m_mutex);
429   size_t num_comp_units = GetNumCompileUnits();
430   CompUnitSP cu_sp;
431 
432   if (index < num_comp_units) {
433     if (SymbolFile *symbols = GetSymbolFile())
434       cu_sp = symbols->GetCompileUnitAtIndex(index);
435   }
436   return cu_sp;
437 }
438 
439 bool Module::ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) {
440   std::lock_guard<std::recursive_mutex> guard(m_mutex);
441   SectionList *section_list = GetSectionList();
442   if (section_list)
443     return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
444   return false;
445 }
446 
447 uint32_t Module::ResolveSymbolContextForAddress(
448     const Address &so_addr, lldb::SymbolContextItem resolve_scope,
449     SymbolContext &sc, bool resolve_tail_call_address) {
450   std::lock_guard<std::recursive_mutex> guard(m_mutex);
451   uint32_t resolved_flags = 0;
452 
453   // Clear the result symbol context in case we don't find anything, but don't
454   // clear the target
455   sc.Clear(false);
456 
457   // Get the section from the section/offset address.
458   SectionSP section_sp(so_addr.GetSection());
459 
460   // Make sure the section matches this module before we try and match anything
461   if (section_sp && section_sp->GetModule().get() == this) {
462     // If the section offset based address resolved itself, then this is the
463     // right module.
464     sc.module_sp = shared_from_this();
465     resolved_flags |= eSymbolContextModule;
466 
467     SymbolFile *symfile = GetSymbolFile();
468     if (!symfile)
469       return resolved_flags;
470 
471     // Resolve the compile unit, function, block, line table or line entry if
472     // requested.
473     if (resolve_scope & eSymbolContextCompUnit ||
474         resolve_scope & eSymbolContextFunction ||
475         resolve_scope & eSymbolContextBlock ||
476         resolve_scope & eSymbolContextLineEntry ||
477         resolve_scope & eSymbolContextVariable) {
478       symfile->SetLoadDebugInfoEnabled();
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   const char *name_cstr = name.GetCString();
641   llvm::StringRef basename;
642   llvm::StringRef context;
643 
644   if (name_type_mask & eFunctionNameTypeAuto) {
645     if (CPlusPlusLanguage::IsCPPMangledName(name_cstr))
646       m_name_type_mask = eFunctionNameTypeFull;
647     else if ((language == eLanguageTypeUnknown ||
648               Language::LanguageIsObjC(language)) &&
649              ObjCLanguage::IsPossibleObjCMethodName(name_cstr))
650       m_name_type_mask = eFunctionNameTypeFull;
651     else if (Language::LanguageIsC(language)) {
652       m_name_type_mask = eFunctionNameTypeFull;
653     } else {
654       if ((language == eLanguageTypeUnknown ||
655            Language::LanguageIsObjC(language)) &&
656           ObjCLanguage::IsPossibleObjCSelector(name_cstr))
657         m_name_type_mask |= eFunctionNameTypeSelector;
658 
659       CPlusPlusLanguage::MethodName cpp_method(name);
660       basename = cpp_method.GetBasename();
661       if (basename.empty()) {
662         if (CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
663                                                            basename))
664           m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
665         else
666           m_name_type_mask |= eFunctionNameTypeFull;
667       } else {
668         m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
669       }
670     }
671   } else {
672     m_name_type_mask = name_type_mask;
673     if (name_type_mask & eFunctionNameTypeMethod ||
674         name_type_mask & eFunctionNameTypeBase) {
675       // If they've asked for a CPP method or function name and it can't be
676       // that, we don't even need to search for CPP methods or names.
677       CPlusPlusLanguage::MethodName cpp_method(name);
678       if (cpp_method.IsValid()) {
679         basename = cpp_method.GetBasename();
680 
681         if (!cpp_method.GetQualifiers().empty()) {
682           // There is a "const" or other qualifier following the end of the
683           // function parens, this can't be a eFunctionNameTypeBase
684           m_name_type_mask &= ~(eFunctionNameTypeBase);
685           if (m_name_type_mask == eFunctionNameTypeNone)
686             return;
687         }
688       } else {
689         // If the CPP method parser didn't manage to chop this up, try to fill
690         // in the base name if we can. If a::b::c is passed in, we need to just
691         // look up "c", and then we'll filter the result later.
692         CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
693                                                        basename);
694       }
695     }
696 
697     if (name_type_mask & eFunctionNameTypeSelector) {
698       if (!ObjCLanguage::IsPossibleObjCSelector(name_cstr)) {
699         m_name_type_mask &= ~(eFunctionNameTypeSelector);
700         if (m_name_type_mask == eFunctionNameTypeNone)
701           return;
702       }
703     }
704 
705     // Still try and get a basename in case someone specifies a name type mask
706     // of eFunctionNameTypeFull and a name like "A::func"
707     if (basename.empty()) {
708       if (name_type_mask & eFunctionNameTypeFull &&
709           !CPlusPlusLanguage::IsCPPMangledName(name_cstr)) {
710         CPlusPlusLanguage::MethodName cpp_method(name);
711         basename = cpp_method.GetBasename();
712         if (basename.empty())
713           CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
714                                                          basename);
715       }
716     }
717   }
718 
719   if (!basename.empty()) {
720     // The name supplied was a partial C++ path like "a::count". In this case
721     // we want to do a lookup on the basename "count" and then make sure any
722     // matching results contain "a::count" so that it would match "b::a::count"
723     // and "a::count". This is why we set "match_name_after_lookup" to true
724     m_lookup_name.SetString(basename);
725     m_match_name_after_lookup = true;
726   } else {
727     // The name is already correct, just use the exact name as supplied, and we
728     // won't need to check if any matches contain "name"
729     m_lookup_name = name;
730     m_match_name_after_lookup = false;
731   }
732 }
733 
734 void Module::LookupInfo::Prune(SymbolContextList &sc_list,
735                                size_t start_idx) const {
736   if (m_match_name_after_lookup && m_name) {
737     SymbolContext sc;
738     size_t i = start_idx;
739     while (i < sc_list.GetSize()) {
740       if (!sc_list.GetContextAtIndex(i, sc))
741         break;
742 
743       llvm::StringRef user_name = m_name.GetStringRef();
744       bool keep_it = true;
745       Language *language = Language::FindPlugin(sc.GetLanguage());
746       // If the symbol has a language, then let the language make the match.
747       // Otherwise just check that the demangled name contains the user name.
748       if (language)
749         keep_it = language->DemangledNameContainsPath(m_name.GetStringRef(),
750                 sc.GetFunctionName());
751       else {
752         llvm::StringRef full_name = sc.GetFunctionName().GetStringRef();
753         // We always keep unnamed symbols:
754         if (!full_name.empty())
755           keep_it = full_name.contains(user_name);
756       }
757       if (keep_it)
758         ++i;
759       else
760         sc_list.RemoveContextAtIndex(i);
761     }
762   }
763 
764   // If we have only full name matches we might have tried to set breakpoint on
765   // "func" and specified eFunctionNameTypeFull, but we might have found
766   // "a::func()", "a::b::func()", "c::func()", "func()" and "func". Only
767   // "func()" and "func" should end up matching.
768   if (m_name_type_mask == eFunctionNameTypeFull) {
769     SymbolContext sc;
770     size_t i = start_idx;
771     while (i < sc_list.GetSize()) {
772       if (!sc_list.GetContextAtIndex(i, sc))
773         break;
774       // Make sure the mangled and demangled names don't match before we try to
775       // pull anything out
776       ConstString mangled_name(sc.GetFunctionName(Mangled::ePreferMangled));
777       ConstString full_name(sc.GetFunctionName());
778       if (mangled_name != m_name && full_name != m_name) {
779         CPlusPlusLanguage::MethodName cpp_method(full_name);
780         if (cpp_method.IsValid()) {
781           if (cpp_method.GetContext().empty()) {
782             if (cpp_method.GetBasename().compare(m_name.GetStringRef()) != 0) {
783               sc_list.RemoveContextAtIndex(i);
784               continue;
785             }
786           } else {
787             std::string qualified_name;
788             llvm::StringRef anon_prefix("(anonymous namespace)");
789             if (cpp_method.GetContext() == anon_prefix)
790               qualified_name = cpp_method.GetBasename().str();
791             else
792               qualified_name = cpp_method.GetScopeQualifiedName();
793             if (qualified_name != m_name.GetCString()) {
794               sc_list.RemoveContextAtIndex(i);
795               continue;
796             }
797           }
798         }
799       }
800       ++i;
801     }
802   }
803 }
804 
805 void Module::FindFunctions(ConstString name,
806                            const CompilerDeclContext &parent_decl_ctx,
807                            FunctionNameType name_type_mask,
808                            const ModuleFunctionSearchOptions &options,
809                            SymbolContextList &sc_list) {
810   const size_t old_size = sc_list.GetSize();
811 
812   // Find all the functions (not symbols, but debug information functions...
813   SymbolFile *symbols = GetSymbolFile();
814 
815   if (name_type_mask & eFunctionNameTypeAuto) {
816     LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
817 
818     if (symbols) {
819       symbols->FindFunctions(lookup_info.GetLookupName(), parent_decl_ctx,
820                              lookup_info.GetNameTypeMask(),
821                              options.include_inlines, sc_list);
822 
823       // Now check our symbol table for symbols that are code symbols if
824       // requested
825       if (options.include_symbols) {
826         Symtab *symtab = symbols->GetSymtab();
827         if (symtab)
828           symtab->FindFunctionSymbols(lookup_info.GetLookupName(),
829                                       lookup_info.GetNameTypeMask(), sc_list);
830       }
831     }
832 
833     const size_t new_size = sc_list.GetSize();
834 
835     if (old_size < new_size)
836       lookup_info.Prune(sc_list, old_size);
837   } else {
838     if (symbols) {
839       symbols->FindFunctions(name, parent_decl_ctx, name_type_mask,
840                              options.include_inlines, sc_list);
841 
842       // Now check our symbol table for symbols that are code symbols if
843       // requested
844       if (options.include_symbols) {
845         Symtab *symtab = symbols->GetSymtab();
846         if (symtab)
847           symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
848       }
849     }
850   }
851 }
852 
853 void Module::FindFunctions(const RegularExpression &regex,
854                            const ModuleFunctionSearchOptions &options,
855                            SymbolContextList &sc_list) {
856   const size_t start_size = sc_list.GetSize();
857 
858   if (SymbolFile *symbols = GetSymbolFile()) {
859     symbols->FindFunctions(regex, options.include_inlines, sc_list);
860 
861     // Now check our symbol table for symbols that are code symbols if
862     // requested
863     if (options.include_symbols) {
864       Symtab *symtab = symbols->GetSymtab();
865       if (symtab) {
866         std::vector<uint32_t> symbol_indexes;
867         symtab->AppendSymbolIndexesMatchingRegExAndType(
868             regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny,
869             symbol_indexes);
870         const size_t num_matches = symbol_indexes.size();
871         if (num_matches) {
872           SymbolContext sc(this);
873           const size_t end_functions_added_index = sc_list.GetSize();
874           size_t num_functions_added_to_sc_list =
875               end_functions_added_index - start_size;
876           if (num_functions_added_to_sc_list == 0) {
877             // No functions were added, just symbols, so we can just append
878             // them
879             for (size_t i = 0; i < num_matches; ++i) {
880               sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
881               SymbolType sym_type = sc.symbol->GetType();
882               if (sc.symbol && (sym_type == eSymbolTypeCode ||
883                                 sym_type == eSymbolTypeResolver))
884                 sc_list.Append(sc);
885             }
886           } else {
887             typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
888             FileAddrToIndexMap file_addr_to_index;
889             for (size_t i = start_size; i < end_functions_added_index; ++i) {
890               const SymbolContext &sc = sc_list[i];
891               if (sc.block)
892                 continue;
893               file_addr_to_index[sc.function->GetAddressRange()
894                                      .GetBaseAddress()
895                                      .GetFileAddress()] = i;
896             }
897 
898             FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
899             // Functions were added so we need to merge symbols into any
900             // existing function symbol contexts
901             for (size_t i = start_size; i < num_matches; ++i) {
902               sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
903               SymbolType sym_type = sc.symbol->GetType();
904               if (sc.symbol && sc.symbol->ValueIsAddress() &&
905                   (sym_type == eSymbolTypeCode ||
906                    sym_type == eSymbolTypeResolver)) {
907                 FileAddrToIndexMap::const_iterator pos =
908                     file_addr_to_index.find(
909                         sc.symbol->GetAddressRef().GetFileAddress());
910                 if (pos == end)
911                   sc_list.Append(sc);
912                 else
913                   sc_list[pos->second].symbol = sc.symbol;
914               }
915             }
916           }
917         }
918       }
919     }
920   }
921 }
922 
923 void Module::FindAddressesForLine(const lldb::TargetSP target_sp,
924                                   const FileSpec &file, uint32_t line,
925                                   Function *function,
926                                   std::vector<Address> &output_local,
927                                   std::vector<Address> &output_extern) {
928   SearchFilterByModule filter(target_sp, m_file);
929 
930   // TODO: Handle SourceLocationSpec column information
931   SourceLocationSpec location_spec(file, line, /*column=*/llvm::None,
932                                    /*check_inlines=*/true,
933                                    /*exact_match=*/false);
934   AddressResolverFileLine resolver(location_spec);
935   resolver.ResolveAddress(filter);
936 
937   for (size_t n = 0; n < resolver.GetNumberOfAddresses(); n++) {
938     Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
939     Function *f = addr.CalculateSymbolContextFunction();
940     if (f && f == function)
941       output_local.push_back(addr);
942     else
943       output_extern.push_back(addr);
944   }
945 }
946 
947 void Module::FindTypes_Impl(
948     ConstString name, const CompilerDeclContext &parent_decl_ctx,
949     size_t max_matches,
950     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
951     TypeMap &types) {
952   if (SymbolFile *symbols = GetSymbolFile())
953     symbols->FindTypes(name, parent_decl_ctx, max_matches,
954                        searched_symbol_files, types);
955 }
956 
957 void Module::FindTypesInNamespace(ConstString type_name,
958                                   const CompilerDeclContext &parent_decl_ctx,
959                                   size_t max_matches, TypeList &type_list) {
960   TypeMap types_map;
961   llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
962   FindTypes_Impl(type_name, parent_decl_ctx, max_matches, searched_symbol_files,
963                  types_map);
964   if (types_map.GetSize()) {
965     SymbolContext sc;
966     sc.module_sp = shared_from_this();
967     sc.SortTypeList(types_map, type_list);
968   }
969 }
970 
971 lldb::TypeSP Module::FindFirstType(const SymbolContext &sc, ConstString name,
972                                    bool exact_match) {
973   TypeList type_list;
974   llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
975   FindTypes(name, exact_match, 1, searched_symbol_files, type_list);
976   if (type_list.GetSize())
977     return type_list.GetTypeAtIndex(0);
978   return TypeSP();
979 }
980 
981 void Module::FindTypes(
982     ConstString name, bool exact_match, size_t max_matches,
983     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
984     TypeList &types) {
985   const char *type_name_cstr = name.GetCString();
986   llvm::StringRef type_scope;
987   llvm::StringRef type_basename;
988   TypeClass type_class = eTypeClassAny;
989   TypeMap typesmap;
990 
991   if (Type::GetTypeScopeAndBasename(type_name_cstr, type_scope, type_basename,
992                                     type_class)) {
993     // Check if "name" starts with "::" which means the qualified type starts
994     // from the root namespace and implies and exact match. The typenames we
995     // get back from clang do not start with "::" so we need to strip this off
996     // in order to get the qualified names to match
997     exact_match = type_scope.consume_front("::");
998 
999     ConstString type_basename_const_str(type_basename);
1000     FindTypes_Impl(type_basename_const_str, CompilerDeclContext(), max_matches,
1001                    searched_symbol_files, typesmap);
1002     if (typesmap.GetSize())
1003       typesmap.RemoveMismatchedTypes(std::string(type_scope),
1004                                      std::string(type_basename), type_class,
1005                                      exact_match);
1006   } else {
1007     // The type is not in a namespace/class scope, just search for it by
1008     // basename
1009     if (type_class != eTypeClassAny && !type_basename.empty()) {
1010       // The "type_name_cstr" will have been modified if we have a valid type
1011       // class prefix (like "struct", "class", "union", "typedef" etc).
1012       FindTypes_Impl(ConstString(type_basename), CompilerDeclContext(),
1013                      UINT_MAX, searched_symbol_files, typesmap);
1014       typesmap.RemoveMismatchedTypes(std::string(type_scope),
1015                                      std::string(type_basename), type_class,
1016                                      exact_match);
1017     } else {
1018       FindTypes_Impl(name, CompilerDeclContext(), UINT_MAX,
1019                      searched_symbol_files, typesmap);
1020       if (exact_match) {
1021         std::string name_str(name.AsCString(""));
1022         typesmap.RemoveMismatchedTypes(std::string(type_scope), name_str,
1023                                        type_class, exact_match);
1024       }
1025     }
1026   }
1027   if (typesmap.GetSize()) {
1028     SymbolContext sc;
1029     sc.module_sp = shared_from_this();
1030     sc.SortTypeList(typesmap, types);
1031   }
1032 }
1033 
1034 void Module::FindTypes(
1035     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1036     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1037     TypeMap &types) {
1038   // If a scoped timer is needed, place it in a SymbolFile::FindTypes override.
1039   // A timer here is too high volume for some cases, for example when calling
1040   // FindTypes on each object file.
1041   if (SymbolFile *symbols = GetSymbolFile())
1042     symbols->FindTypes(pattern, languages, searched_symbol_files, types);
1043 }
1044 
1045 SymbolFile *Module::GetSymbolFile(bool can_create, Stream *feedback_strm) {
1046   if (!m_did_load_symfile.load()) {
1047     std::lock_guard<std::recursive_mutex> guard(m_mutex);
1048     if (!m_did_load_symfile.load() && can_create) {
1049       ObjectFile *obj_file = GetObjectFile();
1050       if (obj_file != nullptr) {
1051         LLDB_SCOPED_TIMER();
1052         m_symfile_up.reset(
1053             SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
1054         m_did_load_symfile = true;
1055       }
1056     }
1057   }
1058   return m_symfile_up ? m_symfile_up->GetSymbolFile() : nullptr;
1059 }
1060 
1061 Symtab *Module::GetSymtab() {
1062   if (SymbolFile *symbols = GetSymbolFile())
1063     return symbols->GetSymtab();
1064   return nullptr;
1065 }
1066 
1067 void Module::SetFileSpecAndObjectName(const FileSpec &file,
1068                                       ConstString object_name) {
1069   // Container objects whose paths do not specify a file directly can call this
1070   // function to correct the file and object names.
1071   m_file = file;
1072   m_mod_time = FileSystem::Instance().GetModificationTime(file);
1073   m_object_name = object_name;
1074 }
1075 
1076 const ArchSpec &Module::GetArchitecture() const { return m_arch; }
1077 
1078 std::string Module::GetSpecificationDescription() const {
1079   std::string spec(GetFileSpec().GetPath());
1080   if (m_object_name) {
1081     spec += '(';
1082     spec += m_object_name.GetCString();
1083     spec += ')';
1084   }
1085   return spec;
1086 }
1087 
1088 void Module::GetDescription(llvm::raw_ostream &s,
1089                             lldb::DescriptionLevel level) {
1090   if (level >= eDescriptionLevelFull) {
1091     if (m_arch.IsValid())
1092       s << llvm::formatv("({0}) ", m_arch.GetArchitectureName());
1093   }
1094 
1095   if (level == eDescriptionLevelBrief) {
1096     const char *filename = m_file.GetFilename().GetCString();
1097     if (filename)
1098       s << filename;
1099   } else {
1100     char path[PATH_MAX];
1101     if (m_file.GetPath(path, sizeof(path)))
1102       s << path;
1103   }
1104 
1105   const char *object_name = m_object_name.GetCString();
1106   if (object_name)
1107     s << llvm::formatv("({0})", object_name);
1108 }
1109 
1110 void Module::ReportError(const char *format, ...) {
1111   if (format && format[0]) {
1112     StreamString strm;
1113     strm.PutCString("error: ");
1114     GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelBrief);
1115     strm.PutChar(' ');
1116     va_list args;
1117     va_start(args, format);
1118     strm.PrintfVarArg(format, args);
1119     va_end(args);
1120 
1121     const int format_len = strlen(format);
1122     if (format_len > 0) {
1123       const char last_char = format[format_len - 1];
1124       if (last_char != '\n' && last_char != '\r')
1125         strm.EOL();
1126     }
1127     Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1128   }
1129 }
1130 
1131 bool Module::FileHasChanged() const {
1132   // We have provided the DataBuffer for this module to avoid accessing the
1133   // filesystem. We never want to reload those files.
1134   if (m_data_sp)
1135     return false;
1136   if (!m_file_has_changed)
1137     m_file_has_changed =
1138         (FileSystem::Instance().GetModificationTime(m_file) != m_mod_time);
1139   return m_file_has_changed;
1140 }
1141 
1142 void Module::ReportWarningOptimization(
1143     llvm::Optional<lldb::user_id_t> debugger_id) {
1144   ConstString file_name = GetFileSpec().GetFilename();
1145   if (file_name.IsEmpty())
1146     return;
1147 
1148   StreamString ss;
1149   ss << file_name.GetStringRef()
1150      << " was compiled with optimization - stepping may behave "
1151         "oddly; variables may not be available.";
1152   Debugger::ReportWarning(std::string(ss.GetString()), debugger_id,
1153                           &m_optimization_warning);
1154 }
1155 
1156 void Module::ReportWarningUnsupportedLanguage(
1157     LanguageType language, llvm::Optional<lldb::user_id_t> debugger_id) {
1158   StreamString ss;
1159   ss << "This version of LLDB has no plugin for the language \""
1160      << Language::GetNameForLanguageType(language)
1161      << "\". "
1162         "Inspection of frame variables will be limited.";
1163   Debugger::ReportWarning(std::string(ss.GetString()), debugger_id,
1164                           &m_language_warning);
1165 }
1166 
1167 void Module::ReportErrorIfModifyDetected(const char *format, ...) {
1168   if (!m_first_file_changed_log) {
1169     if (FileHasChanged()) {
1170       m_first_file_changed_log = true;
1171       if (format) {
1172         StreamString strm;
1173         strm.PutCString("error: the object file ");
1174         GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelFull);
1175         strm.PutCString(" has been modified\n");
1176 
1177         va_list args;
1178         va_start(args, format);
1179         strm.PrintfVarArg(format, args);
1180         va_end(args);
1181 
1182         const int format_len = strlen(format);
1183         if (format_len > 0) {
1184           const char last_char = format[format_len - 1];
1185           if (last_char != '\n' && last_char != '\r')
1186             strm.EOL();
1187         }
1188         strm.PutCString("The debug session should be aborted as the original "
1189                         "debug information has been overwritten.\n");
1190         Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1191       }
1192     }
1193   }
1194 }
1195 
1196 void Module::ReportWarning(const char *format, ...) {
1197   if (format && format[0]) {
1198     StreamString strm;
1199     strm.PutCString("warning: ");
1200     GetDescription(strm.AsRawOstream(), lldb::eDescriptionLevelFull);
1201     strm.PutChar(' ');
1202 
1203     va_list args;
1204     va_start(args, format);
1205     strm.PrintfVarArg(format, args);
1206     va_end(args);
1207 
1208     const int format_len = strlen(format);
1209     if (format_len > 0) {
1210       const char last_char = format[format_len - 1];
1211       if (last_char != '\n' && last_char != '\r')
1212         strm.EOL();
1213     }
1214     Host::SystemLog(Host::eSystemLogWarning, "%s", strm.GetData());
1215   }
1216 }
1217 
1218 void Module::LogMessage(Log *log, const char *format, ...) {
1219   if (log != nullptr) {
1220     StreamString log_message;
1221     GetDescription(log_message.AsRawOstream(), lldb::eDescriptionLevelFull);
1222     log_message.PutCString(": ");
1223     va_list args;
1224     va_start(args, format);
1225     log_message.PrintfVarArg(format, args);
1226     va_end(args);
1227     log->PutCString(log_message.GetData());
1228   }
1229 }
1230 
1231 void Module::LogMessageVerboseBacktrace(Log *log, const char *format, ...) {
1232   if (log != nullptr) {
1233     StreamString log_message;
1234     GetDescription(log_message.AsRawOstream(), lldb::eDescriptionLevelFull);
1235     log_message.PutCString(": ");
1236     va_list args;
1237     va_start(args, format);
1238     log_message.PrintfVarArg(format, args);
1239     va_end(args);
1240     if (log->GetVerbose()) {
1241       std::string back_trace;
1242       llvm::raw_string_ostream stream(back_trace);
1243       llvm::sys::PrintStackTrace(stream);
1244       log_message.PutCString(back_trace);
1245     }
1246     log->PutCString(log_message.GetData());
1247   }
1248 }
1249 
1250 void Module::Dump(Stream *s) {
1251   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1252   // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1253   s->Indent();
1254   s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(),
1255             m_object_name ? "(" : "",
1256             m_object_name ? m_object_name.GetCString() : "",
1257             m_object_name ? ")" : "");
1258 
1259   s->IndentMore();
1260 
1261   ObjectFile *objfile = GetObjectFile();
1262   if (objfile)
1263     objfile->Dump(s);
1264 
1265   if (SymbolFile *symbols = GetSymbolFile())
1266     symbols->Dump(*s);
1267 
1268   s->IndentLess();
1269 }
1270 
1271 ConstString Module::GetObjectName() const { return m_object_name; }
1272 
1273 ObjectFile *Module::GetObjectFile() {
1274   if (!m_did_load_objfile.load()) {
1275     std::lock_guard<std::recursive_mutex> guard(m_mutex);
1276     if (!m_did_load_objfile.load()) {
1277       LLDB_SCOPED_TIMERF("Module::GetObjectFile () module = %s",
1278                          GetFileSpec().GetFilename().AsCString(""));
1279       lldb::offset_t data_offset = 0;
1280       lldb::offset_t file_size = 0;
1281 
1282       if (m_data_sp)
1283         file_size = m_data_sp->GetByteSize();
1284       else if (m_file)
1285         file_size = FileSystem::Instance().GetByteSize(m_file);
1286 
1287       if (file_size > m_object_offset) {
1288         m_did_load_objfile = true;
1289         // FindPlugin will modify its data_sp argument. Do not let it
1290         // modify our m_data_sp member.
1291         auto data_sp = m_data_sp;
1292         m_objfile_sp = ObjectFile::FindPlugin(
1293             shared_from_this(), &m_file, m_object_offset,
1294             file_size - m_object_offset, data_sp, data_offset);
1295         if (m_objfile_sp) {
1296           // Once we get the object file, update our module with the object
1297           // file's architecture since it might differ in vendor/os if some
1298           // parts were unknown.  But since the matching arch might already be
1299           // more specific than the generic COFF architecture, only merge in
1300           // those values that overwrite unspecified unknown values.
1301           m_arch.MergeFrom(m_objfile_sp->GetArchitecture());
1302         } else {
1303           ReportError("failed to load objfile for %s",
1304                       GetFileSpec().GetPath().c_str());
1305         }
1306       }
1307     }
1308   }
1309   return m_objfile_sp.get();
1310 }
1311 
1312 SectionList *Module::GetSectionList() {
1313   // Populate m_sections_up with sections from objfile.
1314   if (!m_sections_up) {
1315     ObjectFile *obj_file = GetObjectFile();
1316     if (obj_file != nullptr)
1317       obj_file->CreateSections(*GetUnifiedSectionList());
1318   }
1319   return m_sections_up.get();
1320 }
1321 
1322 void Module::SectionFileAddressesChanged() {
1323   ObjectFile *obj_file = GetObjectFile();
1324   if (obj_file)
1325     obj_file->SectionFileAddressesChanged();
1326   if (SymbolFile *symbols = GetSymbolFile())
1327     symbols->SectionFileAddressesChanged();
1328 }
1329 
1330 UnwindTable &Module::GetUnwindTable() {
1331   if (!m_unwind_table)
1332     m_unwind_table.emplace(*this);
1333   return *m_unwind_table;
1334 }
1335 
1336 SectionList *Module::GetUnifiedSectionList() {
1337   if (!m_sections_up)
1338     m_sections_up = std::make_unique<SectionList>();
1339   return m_sections_up.get();
1340 }
1341 
1342 const Symbol *Module::FindFirstSymbolWithNameAndType(ConstString name,
1343                                                      SymbolType symbol_type) {
1344   LLDB_SCOPED_TIMERF(
1345       "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1346       name.AsCString(), symbol_type);
1347   if (Symtab *symtab = GetSymtab())
1348     return symtab->FindFirstSymbolWithNameAndType(
1349         name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1350   return nullptr;
1351 }
1352 void Module::SymbolIndicesToSymbolContextList(
1353     Symtab *symtab, std::vector<uint32_t> &symbol_indexes,
1354     SymbolContextList &sc_list) {
1355   // No need to protect this call using m_mutex all other method calls are
1356   // already thread safe.
1357 
1358   size_t num_indices = symbol_indexes.size();
1359   if (num_indices > 0) {
1360     SymbolContext sc;
1361     CalculateSymbolContext(&sc);
1362     for (size_t i = 0; i < num_indices; i++) {
1363       sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
1364       if (sc.symbol)
1365         sc_list.Append(sc);
1366     }
1367   }
1368 }
1369 
1370 void Module::FindFunctionSymbols(ConstString name, uint32_t name_type_mask,
1371                                  SymbolContextList &sc_list) {
1372   LLDB_SCOPED_TIMERF("Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1373                      name.AsCString(), name_type_mask);
1374   if (Symtab *symtab = GetSymtab())
1375     symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
1376 }
1377 
1378 void Module::FindSymbolsWithNameAndType(ConstString name,
1379                                         SymbolType symbol_type,
1380                                         SymbolContextList &sc_list) {
1381   // No need to protect this call using m_mutex all other method calls are
1382   // already thread safe.
1383   if (Symtab *symtab = GetSymtab()) {
1384     std::vector<uint32_t> symbol_indexes;
1385     symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes);
1386     SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1387   }
1388 }
1389 
1390 void Module::FindSymbolsMatchingRegExAndType(const RegularExpression &regex,
1391                                              SymbolType symbol_type,
1392                                              SymbolContextList &sc_list) {
1393   // No need to protect this call using m_mutex all other method calls are
1394   // already thread safe.
1395   LLDB_SCOPED_TIMERF(
1396       "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1397       regex.GetText().str().c_str(), symbol_type);
1398   if (Symtab *symtab = GetSymtab()) {
1399     std::vector<uint32_t> symbol_indexes;
1400     symtab->FindAllSymbolsMatchingRexExAndType(
1401         regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny,
1402         symbol_indexes);
1403     SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1404   }
1405 }
1406 
1407 void Module::PreloadSymbols() {
1408   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1409   SymbolFile *sym_file = GetSymbolFile();
1410   if (!sym_file)
1411     return;
1412 
1413   // Load the object file symbol table and any symbols from the SymbolFile that
1414   // get appended using SymbolFile::AddSymbols(...).
1415   if (Symtab *symtab = sym_file->GetSymtab())
1416     symtab->PreloadSymbols();
1417 
1418   // Now let the symbol file preload its data and the symbol table will be
1419   // available without needing to take the module lock.
1420   sym_file->PreloadSymbols();
1421 }
1422 
1423 void Module::SetSymbolFileFileSpec(const FileSpec &file) {
1424   if (!FileSystem::Instance().Exists(file))
1425     return;
1426   if (m_symfile_up) {
1427     // Remove any sections in the unified section list that come from the
1428     // current symbol vendor.
1429     SectionList *section_list = GetSectionList();
1430     SymbolFile *symbol_file = GetSymbolFile();
1431     if (section_list && symbol_file) {
1432       ObjectFile *obj_file = symbol_file->GetObjectFile();
1433       // Make sure we have an object file and that the symbol vendor's objfile
1434       // isn't the same as the module's objfile before we remove any sections
1435       // for it...
1436       if (obj_file) {
1437         // Check to make sure we aren't trying to specify the file we already
1438         // have
1439         if (obj_file->GetFileSpec() == file) {
1440           // We are being told to add the exact same file that we already have
1441           // we don't have to do anything.
1442           return;
1443         }
1444 
1445         // Cleare the current symtab as we are going to replace it with a new
1446         // one
1447         obj_file->ClearSymtab();
1448 
1449         // Clear the unwind table too, as that may also be affected by the
1450         // symbol file information.
1451         m_unwind_table.reset();
1452 
1453         // The symbol file might be a directory bundle ("/tmp/a.out.dSYM")
1454         // instead of a full path to the symbol file within the bundle
1455         // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to
1456         // check this
1457 
1458         if (FileSystem::Instance().IsDirectory(file)) {
1459           std::string new_path(file.GetPath());
1460           std::string old_path(obj_file->GetFileSpec().GetPath());
1461           if (llvm::StringRef(old_path).startswith(new_path)) {
1462             // We specified the same bundle as the symbol file that we already
1463             // have
1464             return;
1465           }
1466         }
1467 
1468         if (obj_file != m_objfile_sp.get()) {
1469           size_t num_sections = section_list->GetNumSections(0);
1470           for (size_t idx = num_sections; idx > 0; --idx) {
1471             lldb::SectionSP section_sp(
1472                 section_list->GetSectionAtIndex(idx - 1));
1473             if (section_sp->GetObjectFile() == obj_file) {
1474               section_list->DeleteSection(idx - 1);
1475             }
1476           }
1477         }
1478       }
1479     }
1480     // Keep all old symbol files around in case there are any lingering type
1481     // references in any SBValue objects that might have been handed out.
1482     m_old_symfiles.push_back(std::move(m_symfile_up));
1483   }
1484   m_symfile_spec = file;
1485   m_symfile_up.reset();
1486   m_did_load_symfile = false;
1487 }
1488 
1489 bool Module::IsExecutable() {
1490   if (GetObjectFile() == nullptr)
1491     return false;
1492   else
1493     return GetObjectFile()->IsExecutable();
1494 }
1495 
1496 bool Module::IsLoadedInTarget(Target *target) {
1497   ObjectFile *obj_file = GetObjectFile();
1498   if (obj_file) {
1499     SectionList *sections = GetSectionList();
1500     if (sections != nullptr) {
1501       size_t num_sections = sections->GetSize();
1502       for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) {
1503         SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1504         if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) {
1505           return true;
1506         }
1507       }
1508     }
1509   }
1510   return false;
1511 }
1512 
1513 bool Module::LoadScriptingResourceInTarget(Target *target, Status &error,
1514                                            Stream *feedback_stream) {
1515   if (!target) {
1516     error.SetErrorString("invalid destination Target");
1517     return false;
1518   }
1519 
1520   LoadScriptFromSymFile should_load =
1521       target->TargetProperties::GetLoadScriptFromSymbolFile();
1522 
1523   if (should_load == eLoadScriptFromSymFileFalse)
1524     return false;
1525 
1526   Debugger &debugger = target->GetDebugger();
1527   const ScriptLanguage script_language = debugger.GetScriptLanguage();
1528   if (script_language != eScriptLanguageNone) {
1529 
1530     PlatformSP platform_sp(target->GetPlatform());
1531 
1532     if (!platform_sp) {
1533       error.SetErrorString("invalid Platform");
1534       return false;
1535     }
1536 
1537     FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources(
1538         target, *this, feedback_stream);
1539 
1540     const uint32_t num_specs = file_specs.GetSize();
1541     if (num_specs) {
1542       ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
1543       if (script_interpreter) {
1544         for (uint32_t i = 0; i < num_specs; ++i) {
1545           FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i));
1546           if (scripting_fspec &&
1547               FileSystem::Instance().Exists(scripting_fspec)) {
1548             if (should_load == eLoadScriptFromSymFileWarn) {
1549               if (feedback_stream)
1550                 feedback_stream->Printf(
1551                     "warning: '%s' contains a debug script. To run this script "
1552                     "in "
1553                     "this debug session:\n\n    command script import "
1554                     "\"%s\"\n\n"
1555                     "To run all discovered debug scripts in this session:\n\n"
1556                     "    settings set target.load-script-from-symbol-file "
1557                     "true\n",
1558                     GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1559                     scripting_fspec.GetPath().c_str());
1560               return false;
1561             }
1562             StreamString scripting_stream;
1563             scripting_fspec.Dump(scripting_stream.AsRawOstream());
1564             LoadScriptOptions options;
1565             bool did_load = script_interpreter->LoadScriptingModule(
1566                 scripting_stream.GetData(), options, error);
1567             if (!did_load)
1568               return false;
1569           }
1570         }
1571       } else {
1572         error.SetErrorString("invalid ScriptInterpreter");
1573         return false;
1574       }
1575     }
1576   }
1577   return true;
1578 }
1579 
1580 bool Module::SetArchitecture(const ArchSpec &new_arch) {
1581   if (!m_arch.IsValid()) {
1582     m_arch = new_arch;
1583     return true;
1584   }
1585   return m_arch.IsCompatibleMatch(new_arch);
1586 }
1587 
1588 bool Module::SetLoadAddress(Target &target, lldb::addr_t value,
1589                             bool value_is_offset, bool &changed) {
1590   ObjectFile *object_file = GetObjectFile();
1591   if (object_file != nullptr) {
1592     changed = object_file->SetLoadAddress(target, value, value_is_offset);
1593     return true;
1594   } else {
1595     changed = false;
1596   }
1597   return false;
1598 }
1599 
1600 bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) {
1601   const UUID &uuid = module_ref.GetUUID();
1602 
1603   if (uuid.IsValid()) {
1604     // If the UUID matches, then nothing more needs to match...
1605     return (uuid == GetUUID());
1606   }
1607 
1608   const FileSpec &file_spec = module_ref.GetFileSpec();
1609   if (!FileSpec::Match(file_spec, m_file) &&
1610       !FileSpec::Match(file_spec, m_platform_file))
1611     return false;
1612 
1613   const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1614   if (!FileSpec::Match(platform_file_spec, GetPlatformFileSpec()))
1615     return false;
1616 
1617   const ArchSpec &arch = module_ref.GetArchitecture();
1618   if (arch.IsValid()) {
1619     if (!m_arch.IsCompatibleMatch(arch))
1620       return false;
1621   }
1622 
1623   ConstString object_name = module_ref.GetObjectName();
1624   if (object_name) {
1625     if (object_name != GetObjectName())
1626       return false;
1627   }
1628   return true;
1629 }
1630 
1631 bool Module::FindSourceFile(const FileSpec &orig_spec,
1632                             FileSpec &new_spec) const {
1633   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1634   if (auto remapped = m_source_mappings.FindFile(orig_spec)) {
1635     new_spec = *remapped;
1636     return true;
1637   }
1638   return false;
1639 }
1640 
1641 llvm::Optional<std::string>
1642 Module::RemapSourceFile(llvm::StringRef path) const {
1643   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1644   if (auto remapped = m_source_mappings.RemapPath(path))
1645     return remapped->GetPath();
1646   return {};
1647 }
1648 
1649 void Module::RegisterXcodeSDK(llvm::StringRef sdk_name,
1650                               llvm::StringRef sysroot) {
1651   XcodeSDK sdk(sdk_name.str());
1652   llvm::StringRef sdk_path(HostInfo::GetXcodeSDKPath(sdk));
1653   if (sdk_path.empty())
1654     return;
1655   // If the SDK changed for a previously registered source path, update it.
1656   // This could happend with -fdebug-prefix-map, otherwise it's unlikely.
1657   if (!m_source_mappings.Replace(sysroot, sdk_path, true))
1658     // In the general case, however, append it to the list.
1659     m_source_mappings.Append(sysroot, sdk_path, false);
1660 }
1661 
1662 bool Module::MergeArchitecture(const ArchSpec &arch_spec) {
1663   if (!arch_spec.IsValid())
1664     return false;
1665   LLDB_LOGF(GetLog(LLDBLog::Object | LLDBLog::Modules),
1666             "module has arch %s, merging/replacing with arch %s",
1667             m_arch.GetTriple().getTriple().c_str(),
1668             arch_spec.GetTriple().getTriple().c_str());
1669   if (!m_arch.IsCompatibleMatch(arch_spec)) {
1670     // The new architecture is different, we just need to replace it.
1671     return SetArchitecture(arch_spec);
1672   }
1673 
1674   // Merge bits from arch_spec into "merged_arch" and set our architecture.
1675   ArchSpec merged_arch(m_arch);
1676   merged_arch.MergeFrom(arch_spec);
1677   // SetArchitecture() is a no-op if m_arch is already valid.
1678   m_arch = ArchSpec();
1679   return SetArchitecture(merged_arch);
1680 }
1681 
1682 llvm::VersionTuple Module::GetVersion() {
1683   if (ObjectFile *obj_file = GetObjectFile())
1684     return obj_file->GetVersion();
1685   return llvm::VersionTuple();
1686 }
1687 
1688 bool Module::GetIsDynamicLinkEditor() {
1689   ObjectFile *obj_file = GetObjectFile();
1690 
1691   if (obj_file)
1692     return obj_file->GetIsDynamicLinkEditor();
1693 
1694   return false;
1695 }
1696 
1697 uint32_t Module::Hash() {
1698   std::string identifier;
1699   llvm::raw_string_ostream id_strm(identifier);
1700   id_strm << m_arch.GetTriple().str() << '-' << m_file.GetPath();
1701   if (m_object_name)
1702     id_strm << '(' << m_object_name.GetStringRef() << ')';
1703   if (m_object_offset > 0)
1704     id_strm << m_object_offset;
1705   const auto mtime = llvm::sys::toTimeT(m_object_mod_time);
1706   if (mtime > 0)
1707     id_strm << mtime;
1708   return llvm::djbHash(id_strm.str());
1709 }
1710 
1711 std::string Module::GetCacheKey() {
1712   std::string key;
1713   llvm::raw_string_ostream strm(key);
1714   strm << m_arch.GetTriple().str() << '-' << m_file.GetFilename();
1715   if (m_object_name)
1716     strm << '(' << m_object_name.GetStringRef() << ')';
1717   strm << '-' << llvm::format_hex(Hash(), 10);
1718   return strm.str();
1719 }
1720 
1721 DataFileCache *Module::GetIndexCache() {
1722   if (!ModuleList::GetGlobalModuleListProperties().GetEnableLLDBIndexCache())
1723     return nullptr;
1724   // NOTE: intentional leak so we don't crash if global destructor chain gets
1725   // called as other threads still use the result of this function
1726   static DataFileCache *g_data_file_cache =
1727       new DataFileCache(ModuleList::GetGlobalModuleListProperties()
1728                             .GetLLDBIndexCachePath()
1729                             .GetPath());
1730   return g_data_file_cache;
1731 }
1732