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