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