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       sc.comp_unit->ForeachFunction([&sc, &symbols](const FunctionSP &f) {
375         sc.function = f.get();
376         symbols->ParseFunctionBlocks(sc);
377         // Parse the variables for this function and all its blocks
378         symbols->ParseVariablesForContext(sc);
379         return false;
380       });
381 
382       // Parse all types for this compile unit
383       sc.function = nullptr;
384       symbols->ParseTypes(sc);
385     }
386   }
387 }
388 
389 void Module::CalculateSymbolContext(SymbolContext *sc) {
390   sc->module_sp = shared_from_this();
391 }
392 
393 ModuleSP Module::CalculateSymbolContextModule() { return shared_from_this(); }
394 
395 void Module::DumpSymbolContext(Stream *s) {
396   s->Printf(", Module{%p}", static_cast<void *>(this));
397 }
398 
399 size_t Module::GetNumCompileUnits() {
400   std::lock_guard<std::recursive_mutex> guard(m_mutex);
401   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
402   Timer scoped_timer(func_cat, "Module::GetNumCompileUnits (module = %p)",
403                      static_cast<void *>(this));
404   SymbolVendor *symbols = GetSymbolVendor();
405   if (symbols)
406     return symbols->GetNumCompileUnits();
407   return 0;
408 }
409 
410 CompUnitSP Module::GetCompileUnitAtIndex(size_t index) {
411   std::lock_guard<std::recursive_mutex> guard(m_mutex);
412   size_t num_comp_units = GetNumCompileUnits();
413   CompUnitSP cu_sp;
414 
415   if (index < num_comp_units) {
416     SymbolVendor *symbols = GetSymbolVendor();
417     if (symbols)
418       cu_sp = symbols->GetCompileUnitAtIndex(index);
419   }
420   return cu_sp;
421 }
422 
423 bool Module::ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) {
424   std::lock_guard<std::recursive_mutex> guard(m_mutex);
425   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
426   Timer scoped_timer(func_cat,
427                      "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")",
428                      vm_addr);
429   SectionList *section_list = GetSectionList();
430   if (section_list)
431     return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list);
432   return false;
433 }
434 
435 uint32_t Module::ResolveSymbolContextForAddress(
436     const Address &so_addr, uint32_t resolve_scope, SymbolContext &sc,
437     bool resolve_tail_call_address) {
438   std::lock_guard<std::recursive_mutex> guard(m_mutex);
439   uint32_t resolved_flags = 0;
440 
441   // Clear the result symbol context in case we don't find anything, but don't
442   // clear the target
443   sc.Clear(false);
444 
445   // Get the section from the section/offset address.
446   SectionSP section_sp(so_addr.GetSection());
447 
448   // Make sure the section matches this module before we try and match anything
449   if (section_sp && section_sp->GetModule().get() == this) {
450     // If the section offset based address resolved itself, then this is the
451     // right module.
452     sc.module_sp = shared_from_this();
453     resolved_flags |= eSymbolContextModule;
454 
455     SymbolVendor *sym_vendor = GetSymbolVendor();
456     if (!sym_vendor)
457       return resolved_flags;
458 
459     // Resolve the compile unit, function, block, line table or line entry if
460     // requested.
461     if (resolve_scope & eSymbolContextCompUnit ||
462         resolve_scope & eSymbolContextFunction ||
463         resolve_scope & eSymbolContextBlock ||
464         resolve_scope & eSymbolContextLineEntry ||
465         resolve_scope & eSymbolContextVariable) {
466       resolved_flags |=
467           sym_vendor->ResolveSymbolContext(so_addr, resolve_scope, sc);
468     }
469 
470     // Resolve the symbol if requested, but don't re-look it up if we've
471     // already found it.
472     if (resolve_scope & eSymbolContextSymbol &&
473         !(resolved_flags & eSymbolContextSymbol)) {
474       Symtab *symtab = sym_vendor->GetSymtab();
475       if (symtab && so_addr.IsSectionOffset()) {
476         Symbol *matching_symbol = nullptr;
477 
478         symtab->ForEachSymbolContainingFileAddress(
479             so_addr.GetFileAddress(),
480             [&matching_symbol](Symbol *symbol) -> bool {
481               if (symbol->GetType() != eSymbolTypeInvalid) {
482                 matching_symbol = symbol;
483                 return false; // Stop iterating
484               }
485               return true; // Keep iterating
486             });
487         sc.symbol = matching_symbol;
488         if (!sc.symbol && resolve_scope & eSymbolContextFunction &&
489             !(resolved_flags & eSymbolContextFunction)) {
490           bool verify_unique = false; // No need to check again since
491                                       // ResolveSymbolContext failed to find a
492                                       // symbol at this address.
493           if (ObjectFile *obj_file = sc.module_sp->GetObjectFile())
494             sc.symbol =
495                 obj_file->ResolveSymbolForAddress(so_addr, verify_unique);
496         }
497 
498         if (sc.symbol) {
499           if (sc.symbol->IsSynthetic()) {
500             // We have a synthetic symbol so lets check if the object file from
501             // the symbol file in the symbol vendor is different than the
502             // object file for the module, and if so search its symbol table to
503             // see if we can come up with a better symbol. For example dSYM
504             // files on MacOSX have an unstripped symbol table inside of them.
505             ObjectFile *symtab_objfile = symtab->GetObjectFile();
506             if (symtab_objfile && symtab_objfile->IsStripped()) {
507               SymbolFile *symfile = sym_vendor->GetSymbolFile();
508               if (symfile) {
509                 ObjectFile *symfile_objfile = symfile->GetObjectFile();
510                 if (symfile_objfile != symtab_objfile) {
511                   Symtab *symfile_symtab = symfile_objfile->GetSymtab();
512                   if (symfile_symtab) {
513                     Symbol *symbol =
514                         symfile_symtab->FindSymbolContainingFileAddress(
515                             so_addr.GetFileAddress());
516                     if (symbol && !symbol->IsSynthetic()) {
517                       sc.symbol = symbol;
518                     }
519                   }
520                 }
521               }
522             }
523           }
524           resolved_flags |= eSymbolContextSymbol;
525         }
526       }
527     }
528 
529     // For function symbols, so_addr may be off by one.  This is a convention
530     // consistent with FDE row indices in eh_frame sections, but requires extra
531     // logic here to permit symbol lookup for disassembly and unwind.
532     if (resolve_scope & eSymbolContextSymbol &&
533         !(resolved_flags & eSymbolContextSymbol) && resolve_tail_call_address &&
534         so_addr.IsSectionOffset()) {
535       Address previous_addr = so_addr;
536       previous_addr.Slide(-1);
537 
538       bool do_resolve_tail_call_address = false; // prevent recursion
539       const uint32_t flags = ResolveSymbolContextForAddress(
540           previous_addr, resolve_scope, sc, do_resolve_tail_call_address);
541       if (flags & eSymbolContextSymbol) {
542         AddressRange addr_range;
543         if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0,
544                                false, addr_range)) {
545           if (addr_range.GetBaseAddress().GetSection() ==
546               so_addr.GetSection()) {
547             // If the requested address is one past the address range of a
548             // function (i.e. a tail call), or the decremented address is the
549             // start of a function (i.e. some forms of trampoline), indicate
550             // that the symbol has been resolved.
551             if (so_addr.GetOffset() ==
552                     addr_range.GetBaseAddress().GetOffset() ||
553                 so_addr.GetOffset() ==
554                     addr_range.GetBaseAddress().GetOffset() +
555                         addr_range.GetByteSize()) {
556               resolved_flags |= flags;
557             }
558           } else {
559             sc.symbol =
560                 nullptr; // Don't trust the symbol if the sections didn't match.
561           }
562         }
563       }
564     }
565   }
566   return resolved_flags;
567 }
568 
569 uint32_t Module::ResolveSymbolContextForFilePath(const char *file_path,
570                                                  uint32_t line,
571                                                  bool check_inlines,
572                                                  uint32_t resolve_scope,
573                                                  SymbolContextList &sc_list) {
574   FileSpec file_spec(file_path, false);
575   return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines,
576                                           resolve_scope, sc_list);
577 }
578 
579 uint32_t Module::ResolveSymbolContextsForFileSpec(const FileSpec &file_spec,
580                                                   uint32_t line,
581                                                   bool check_inlines,
582                                                   uint32_t resolve_scope,
583                                                   SymbolContextList &sc_list) {
584   std::lock_guard<std::recursive_mutex> guard(m_mutex);
585   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
586   Timer scoped_timer(func_cat,
587                      "Module::ResolveSymbolContextForFilePath (%s:%u, "
588                      "check_inlines = %s, resolve_scope = 0x%8.8x)",
589                      file_spec.GetPath().c_str(), line,
590                      check_inlines ? "yes" : "no", resolve_scope);
591 
592   const uint32_t initial_count = sc_list.GetSize();
593 
594   SymbolVendor *symbols = GetSymbolVendor();
595   if (symbols)
596     symbols->ResolveSymbolContext(file_spec, line, check_inlines, resolve_scope,
597                                   sc_list);
598 
599   return sc_list.GetSize() - initial_count;
600 }
601 
602 size_t Module::FindGlobalVariables(const ConstString &name,
603                                    const CompilerDeclContext *parent_decl_ctx,
604                                    size_t max_matches,
605                                    VariableList &variables) {
606   SymbolVendor *symbols = GetSymbolVendor();
607   if (symbols)
608     return symbols->FindGlobalVariables(name, parent_decl_ctx, max_matches,
609                                         variables);
610   return 0;
611 }
612 
613 size_t Module::FindGlobalVariables(const RegularExpression &regex,
614                                    size_t max_matches,
615                                    VariableList &variables) {
616   SymbolVendor *symbols = GetSymbolVendor();
617   if (symbols)
618     return symbols->FindGlobalVariables(regex, max_matches, variables);
619   return 0;
620 }
621 
622 size_t Module::FindCompileUnits(const FileSpec &path, bool append,
623                                 SymbolContextList &sc_list) {
624   if (!append)
625     sc_list.Clear();
626 
627   const size_t start_size = sc_list.GetSize();
628   const size_t num_compile_units = GetNumCompileUnits();
629   SymbolContext sc;
630   sc.module_sp = shared_from_this();
631   const bool compare_directory = (bool)path.GetDirectory();
632   for (size_t i = 0; i < num_compile_units; ++i) {
633     sc.comp_unit = GetCompileUnitAtIndex(i).get();
634     if (sc.comp_unit) {
635       if (FileSpec::Equal(*sc.comp_unit, path, compare_directory))
636         sc_list.Append(sc);
637     }
638   }
639   return sc_list.GetSize() - start_size;
640 }
641 
642 Module::LookupInfo::LookupInfo(const ConstString &name, uint32_t name_type_mask,
643                                lldb::LanguageType language)
644     : m_name(name), m_lookup_name(), m_language(language), m_name_type_mask(0),
645       m_match_name_after_lookup(false) {
646   const char *name_cstr = name.GetCString();
647   llvm::StringRef basename;
648   llvm::StringRef context;
649 
650   if (name_type_mask & eFunctionNameTypeAuto) {
651     if (CPlusPlusLanguage::IsCPPMangledName(name_cstr))
652       m_name_type_mask = eFunctionNameTypeFull;
653     else if ((language == eLanguageTypeUnknown ||
654               Language::LanguageIsObjC(language)) &&
655              ObjCLanguage::IsPossibleObjCMethodName(name_cstr))
656       m_name_type_mask = eFunctionNameTypeFull;
657     else if (Language::LanguageIsC(language)) {
658       m_name_type_mask = eFunctionNameTypeFull;
659     } else {
660       if ((language == eLanguageTypeUnknown ||
661            Language::LanguageIsObjC(language)) &&
662           ObjCLanguage::IsPossibleObjCSelector(name_cstr))
663         m_name_type_mask |= eFunctionNameTypeSelector;
664 
665       CPlusPlusLanguage::MethodName cpp_method(name);
666       basename = cpp_method.GetBasename();
667       if (basename.empty()) {
668         if (CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
669                                                            basename))
670           m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
671         else
672           m_name_type_mask |= eFunctionNameTypeFull;
673       } else {
674         m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
675       }
676     }
677   } else {
678     m_name_type_mask = name_type_mask;
679     if (name_type_mask & eFunctionNameTypeMethod ||
680         name_type_mask & eFunctionNameTypeBase) {
681       // If they've asked for a CPP method or function name and it can't be
682       // that, we don't even need to search for CPP methods or names.
683       CPlusPlusLanguage::MethodName cpp_method(name);
684       if (cpp_method.IsValid()) {
685         basename = cpp_method.GetBasename();
686 
687         if (!cpp_method.GetQualifiers().empty()) {
688           // There is a "const" or other qualifier following the end of the
689           // function parens, this can't be a eFunctionNameTypeBase
690           m_name_type_mask &= ~(eFunctionNameTypeBase);
691           if (m_name_type_mask == eFunctionNameTypeNone)
692             return;
693         }
694       } else {
695         // If the CPP method parser didn't manage to chop this up, try to fill
696         // in the base name if we can. If a::b::c is passed in, we need to just
697         // look up "c", and then we'll filter the result later.
698         CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
699                                                        basename);
700       }
701     }
702 
703     if (name_type_mask & eFunctionNameTypeSelector) {
704       if (!ObjCLanguage::IsPossibleObjCSelector(name_cstr)) {
705         m_name_type_mask &= ~(eFunctionNameTypeSelector);
706         if (m_name_type_mask == eFunctionNameTypeNone)
707           return;
708       }
709     }
710 
711     // Still try and get a basename in case someone specifies a name type mask
712     // of eFunctionNameTypeFull and a name like "A::func"
713     if (basename.empty()) {
714       if (name_type_mask & eFunctionNameTypeFull &&
715           !CPlusPlusLanguage::IsCPPMangledName(name_cstr)) {
716         CPlusPlusLanguage::MethodName cpp_method(name);
717         basename = cpp_method.GetBasename();
718         if (basename.empty())
719           CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context,
720                                                          basename);
721       }
722     }
723   }
724 
725   if (!basename.empty()) {
726     // The name supplied was a partial C++ path like "a::count". In this case
727     // we want to do a lookup on the basename "count" and then make sure any
728     // matching results contain "a::count" so that it would match "b::a::count"
729     // and "a::count". This is why we set "match_name_after_lookup" to true
730     m_lookup_name.SetString(basename);
731     m_match_name_after_lookup = true;
732   } else {
733     // The name is already correct, just use the exact name as supplied, and we
734     // won't need to check if any matches contain "name"
735     m_lookup_name = name;
736     m_match_name_after_lookup = false;
737   }
738 }
739 
740 void Module::LookupInfo::Prune(SymbolContextList &sc_list,
741                                size_t start_idx) const {
742   if (m_match_name_after_lookup && m_name) {
743     SymbolContext sc;
744     size_t i = start_idx;
745     while (i < sc_list.GetSize()) {
746       if (!sc_list.GetContextAtIndex(i, sc))
747         break;
748       ConstString full_name(sc.GetFunctionName());
749       if (full_name &&
750           ::strstr(full_name.GetCString(), m_name.GetCString()) == nullptr) {
751         sc_list.RemoveContextAtIndex(i);
752       } else {
753         ++i;
754       }
755     }
756   }
757 
758   // If we have only full name matches we might have tried to set breakpoint on
759   // "func" and specified eFunctionNameTypeFull, but we might have found
760   // "a::func()", "a::b::func()", "c::func()", "func()" and "func". Only
761   // "func()" and "func" should end up matching.
762   if (m_name_type_mask == eFunctionNameTypeFull) {
763     SymbolContext sc;
764     size_t i = start_idx;
765     while (i < sc_list.GetSize()) {
766       if (!sc_list.GetContextAtIndex(i, sc))
767         break;
768       // Make sure the mangled and demangled names don't match before we try to
769       // pull anything out
770       ConstString mangled_name(sc.GetFunctionName(Mangled::ePreferMangled));
771       ConstString full_name(sc.GetFunctionName());
772       if (mangled_name != m_name && full_name != m_name)
773       {
774         CPlusPlusLanguage::MethodName cpp_method(full_name);
775         if (cpp_method.IsValid()) {
776           if (cpp_method.GetContext().empty()) {
777             if (cpp_method.GetBasename().compare(m_name.GetStringRef()) != 0) {
778               sc_list.RemoveContextAtIndex(i);
779               continue;
780             }
781           } else {
782             std::string qualified_name;
783             llvm::StringRef anon_prefix("(anonymous namespace)");
784             if (cpp_method.GetContext() == anon_prefix)
785               qualified_name = cpp_method.GetBasename().str();
786             else
787               qualified_name = cpp_method.GetScopeQualifiedName();
788             if (qualified_name.compare(m_name.GetCString()) != 0) {
789               sc_list.RemoveContextAtIndex(i);
790               continue;
791             }
792           }
793         }
794       }
795       ++i;
796     }
797   }
798 }
799 
800 size_t Module::FindFunctions(const ConstString &name,
801                              const CompilerDeclContext *parent_decl_ctx,
802                              uint32_t name_type_mask, bool include_symbols,
803                              bool include_inlines, bool append,
804                              SymbolContextList &sc_list) {
805   if (!append)
806     sc_list.Clear();
807 
808   const size_t old_size = sc_list.GetSize();
809 
810   // Find all the functions (not symbols, but debug information functions...
811   SymbolVendor *symbols = GetSymbolVendor();
812 
813   if (name_type_mask & eFunctionNameTypeAuto) {
814     LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
815 
816     if (symbols) {
817       symbols->FindFunctions(lookup_info.GetLookupName(), parent_decl_ctx,
818                              lookup_info.GetNameTypeMask(), include_inlines,
819                              append, sc_list);
820 
821       // Now check our symbol table for symbols that are code symbols if
822       // requested
823       if (include_symbols) {
824         Symtab *symtab = symbols->GetSymtab();
825         if (symtab)
826           symtab->FindFunctionSymbols(lookup_info.GetLookupName(),
827                                       lookup_info.GetNameTypeMask(), sc_list);
828       }
829     }
830 
831     const size_t new_size = sc_list.GetSize();
832 
833     if (old_size < new_size)
834       lookup_info.Prune(sc_list, old_size);
835   } else {
836     if (symbols) {
837       symbols->FindFunctions(name, parent_decl_ctx, name_type_mask,
838                              include_inlines, append, sc_list);
839 
840       // Now check our symbol table for symbols that are code symbols if
841       // requested
842       if (include_symbols) {
843         Symtab *symtab = symbols->GetSymtab();
844         if (symtab)
845           symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
846       }
847     }
848   }
849 
850   return sc_list.GetSize() - old_size;
851 }
852 
853 size_t Module::FindFunctions(const RegularExpression &regex,
854                              bool include_symbols, bool include_inlines,
855                              bool append, SymbolContextList &sc_list) {
856   if (!append)
857     sc_list.Clear();
858 
859   const size_t start_size = sc_list.GetSize();
860 
861   SymbolVendor *symbols = GetSymbolVendor();
862   if (symbols) {
863     symbols->FindFunctions(regex, include_inlines, append, sc_list);
864 
865     // Now check our symbol table for symbols that are code symbols if
866     // requested
867     if (include_symbols) {
868       Symtab *symtab = symbols->GetSymtab();
869       if (symtab) {
870         std::vector<uint32_t> symbol_indexes;
871         symtab->AppendSymbolIndexesMatchingRegExAndType(
872             regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny,
873             symbol_indexes);
874         const size_t num_matches = symbol_indexes.size();
875         if (num_matches) {
876           SymbolContext sc(this);
877           const size_t end_functions_added_index = sc_list.GetSize();
878           size_t num_functions_added_to_sc_list =
879               end_functions_added_index - start_size;
880           if (num_functions_added_to_sc_list == 0) {
881             // No functions were added, just symbols, so we can just append
882             // them
883             for (size_t i = 0; i < num_matches; ++i) {
884               sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
885               SymbolType sym_type = sc.symbol->GetType();
886               if (sc.symbol && (sym_type == eSymbolTypeCode ||
887                                 sym_type == eSymbolTypeResolver))
888                 sc_list.Append(sc);
889             }
890           } else {
891             typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
892             FileAddrToIndexMap file_addr_to_index;
893             for (size_t i = start_size; i < end_functions_added_index; ++i) {
894               const SymbolContext &sc = sc_list[i];
895               if (sc.block)
896                 continue;
897               file_addr_to_index[sc.function->GetAddressRange()
898                                      .GetBaseAddress()
899                                      .GetFileAddress()] = i;
900             }
901 
902             FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
903             // Functions were added so we need to merge symbols into any
904             // existing function symbol contexts
905             for (size_t i = start_size; i < num_matches; ++i) {
906               sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
907               SymbolType sym_type = sc.symbol->GetType();
908               if (sc.symbol && sc.symbol->ValueIsAddress() &&
909                   (sym_type == eSymbolTypeCode ||
910                    sym_type == eSymbolTypeResolver)) {
911                 FileAddrToIndexMap::const_iterator pos =
912                     file_addr_to_index.find(
913                         sc.symbol->GetAddressRef().GetFileAddress());
914                 if (pos == end)
915                   sc_list.Append(sc);
916                 else
917                   sc_list[pos->second].symbol = sc.symbol;
918               }
919             }
920           }
921         }
922       }
923     }
924   }
925   return sc_list.GetSize() - start_size;
926 }
927 
928 void Module::FindAddressesForLine(const lldb::TargetSP target_sp,
929                                   const FileSpec &file, uint32_t line,
930                                   Function *function,
931                                   std::vector<Address> &output_local,
932                                   std::vector<Address> &output_extern) {
933   SearchFilterByModule filter(target_sp, m_file);
934   AddressResolverFileLine resolver(file, line, true);
935   resolver.ResolveAddress(filter);
936 
937   for (size_t n = 0; n < resolver.GetNumberOfAddresses(); n++) {
938     Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
939     Function *f = addr.CalculateSymbolContextFunction();
940     if (f && f == function)
941       output_local.push_back(addr);
942     else
943       output_extern.push_back(addr);
944   }
945 }
946 
947 size_t Module::FindTypes_Impl(
948     const SymbolContext &sc, const ConstString &name,
949     const CompilerDeclContext *parent_decl_ctx, bool append, size_t max_matches,
950     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
951     TypeMap &types) {
952   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
953   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
954   if (!sc.module_sp || sc.module_sp.get() == this) {
955     SymbolVendor *symbols = GetSymbolVendor();
956     if (symbols)
957       return symbols->FindTypes(sc, name, parent_decl_ctx, append, max_matches,
958                                 searched_symbol_files, types);
959   }
960   return 0;
961 }
962 
963 size_t Module::FindTypesInNamespace(const SymbolContext &sc,
964                                     const ConstString &type_name,
965                                     const CompilerDeclContext *parent_decl_ctx,
966                                     size_t max_matches, TypeList &type_list) {
967   const bool append = true;
968   TypeMap types_map;
969   llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
970   size_t num_types =
971       FindTypes_Impl(sc, type_name, parent_decl_ctx, append, max_matches,
972                      searched_symbol_files, types_map);
973   if (num_types > 0)
974     sc.SortTypeList(types_map, type_list);
975   return num_types;
976 }
977 
978 lldb::TypeSP Module::FindFirstType(const SymbolContext &sc,
979                                    const ConstString &name, bool exact_match) {
980   TypeList type_list;
981   llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
982   const size_t num_matches =
983       FindTypes(sc, name, exact_match, 1, searched_symbol_files, type_list);
984   if (num_matches)
985     return type_list.GetTypeAtIndex(0);
986   return TypeSP();
987 }
988 
989 size_t Module::FindTypes(
990     const SymbolContext &sc, const ConstString &name, bool exact_match,
991     size_t max_matches,
992     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
993     TypeList &types) {
994   size_t num_matches = 0;
995   const char *type_name_cstr = name.GetCString();
996   llvm::StringRef type_scope;
997   llvm::StringRef type_basename;
998   const bool append = true;
999   TypeClass type_class = eTypeClassAny;
1000   TypeMap typesmap;
1001 
1002   if (Type::GetTypeScopeAndBasename(type_name_cstr, type_scope, type_basename,
1003                                     type_class)) {
1004     // Check if "name" starts with "::" which means the qualified type starts
1005     // from the root namespace and implies and exact match. The typenames we
1006     // get back from clang do not start with "::" so we need to strip this off
1007     // in order to get the qualified names to match
1008     exact_match = type_scope.consume_front("::");
1009 
1010     ConstString type_basename_const_str(type_basename);
1011     if (FindTypes_Impl(sc, type_basename_const_str, nullptr, append,
1012                        max_matches, searched_symbol_files, typesmap)) {
1013       typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1014                                      exact_match);
1015       num_matches = typesmap.GetSize();
1016     }
1017   } else {
1018     // The type is not in a namespace/class scope, just search for it by
1019     // basename
1020     if (type_class != eTypeClassAny && !type_basename.empty()) {
1021       // The "type_name_cstr" will have been modified if we have a valid type
1022       // class prefix (like "struct", "class", "union", "typedef" etc).
1023       FindTypes_Impl(sc, ConstString(type_basename), nullptr, append,
1024                      UINT_MAX, searched_symbol_files, typesmap);
1025       typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1026                                      exact_match);
1027       num_matches = typesmap.GetSize();
1028     } else {
1029       num_matches = FindTypes_Impl(sc, name, nullptr, append, UINT_MAX,
1030                                    searched_symbol_files, typesmap);
1031       if (exact_match) {
1032         std::string name_str(name.AsCString(""));
1033         typesmap.RemoveMismatchedTypes(type_scope, name_str, type_class,
1034                                        exact_match);
1035         num_matches = typesmap.GetSize();
1036       }
1037     }
1038   }
1039   if (num_matches > 0)
1040     sc.SortTypeList(typesmap, types);
1041   return num_matches;
1042 }
1043 
1044 SymbolVendor *Module::GetSymbolVendor(bool can_create,
1045                                       lldb_private::Stream *feedback_strm) {
1046   if (!m_did_load_symbol_vendor.load()) {
1047     std::lock_guard<std::recursive_mutex> guard(m_mutex);
1048     if (!m_did_load_symbol_vendor.load() && can_create) {
1049       ObjectFile *obj_file = GetObjectFile();
1050       if (obj_file != nullptr) {
1051         static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1052         Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
1053         m_symfile_ap.reset(
1054             SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
1055         m_did_load_symbol_vendor = true;
1056       }
1057     }
1058   }
1059   return m_symfile_ap.get();
1060 }
1061 
1062 void Module::SetFileSpecAndObjectName(const FileSpec &file,
1063                                       const ConstString &object_name) {
1064   // Container objects whose paths do not specify a file directly can call this
1065   // function to correct the file and object names.
1066   m_file = file;
1067   m_mod_time = FileSystem::GetModificationTime(file);
1068   m_object_name = object_name;
1069 }
1070 
1071 const ArchSpec &Module::GetArchitecture() const { return m_arch; }
1072 
1073 std::string Module::GetSpecificationDescription() const {
1074   std::string spec(GetFileSpec().GetPath());
1075   if (m_object_name) {
1076     spec += '(';
1077     spec += m_object_name.GetCString();
1078     spec += ')';
1079   }
1080   return spec;
1081 }
1082 
1083 void Module::GetDescription(Stream *s, lldb::DescriptionLevel level) {
1084   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1085 
1086   if (level >= eDescriptionLevelFull) {
1087     if (m_arch.IsValid())
1088       s->Printf("(%s) ", m_arch.GetArchitectureName());
1089   }
1090 
1091   if (level == eDescriptionLevelBrief) {
1092     const char *filename = m_file.GetFilename().GetCString();
1093     if (filename)
1094       s->PutCString(filename);
1095   } else {
1096     char path[PATH_MAX];
1097     if (m_file.GetPath(path, sizeof(path)))
1098       s->PutCString(path);
1099   }
1100 
1101   const char *object_name = m_object_name.GetCString();
1102   if (object_name)
1103     s->Printf("(%s)", object_name);
1104 }
1105 
1106 void Module::ReportError(const char *format, ...) {
1107   if (format && format[0]) {
1108     StreamString strm;
1109     strm.PutCString("error: ");
1110     GetDescription(&strm, lldb::eDescriptionLevelBrief);
1111     strm.PutChar(' ');
1112     va_list args;
1113     va_start(args, format);
1114     strm.PrintfVarArg(format, args);
1115     va_end(args);
1116 
1117     const int format_len = strlen(format);
1118     if (format_len > 0) {
1119       const char last_char = format[format_len - 1];
1120       if (last_char != '\n' || last_char != '\r')
1121         strm.EOL();
1122     }
1123     Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1124   }
1125 }
1126 
1127 bool Module::FileHasChanged() const {
1128   if (!m_file_has_changed)
1129     m_file_has_changed =
1130         (FileSystem::GetModificationTime(m_file) != m_mod_time);
1131   return m_file_has_changed;
1132 }
1133 
1134 void Module::ReportErrorIfModifyDetected(const char *format, ...) {
1135   if (!m_first_file_changed_log) {
1136     if (FileHasChanged()) {
1137       m_first_file_changed_log = true;
1138       if (format) {
1139         StreamString strm;
1140         strm.PutCString("error: the object file ");
1141         GetDescription(&strm, lldb::eDescriptionLevelFull);
1142         strm.PutCString(" has been modified\n");
1143 
1144         va_list args;
1145         va_start(args, format);
1146         strm.PrintfVarArg(format, args);
1147         va_end(args);
1148 
1149         const int format_len = strlen(format);
1150         if (format_len > 0) {
1151           const char last_char = format[format_len - 1];
1152           if (last_char != '\n' || last_char != '\r')
1153             strm.EOL();
1154         }
1155         strm.PutCString("The debug session should be aborted as the original "
1156                         "debug information has been overwritten.\n");
1157         Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1158       }
1159     }
1160   }
1161 }
1162 
1163 void Module::ReportWarning(const char *format, ...) {
1164   if (format && format[0]) {
1165     StreamString strm;
1166     strm.PutCString("warning: ");
1167     GetDescription(&strm, lldb::eDescriptionLevelFull);
1168     strm.PutChar(' ');
1169 
1170     va_list args;
1171     va_start(args, format);
1172     strm.PrintfVarArg(format, args);
1173     va_end(args);
1174 
1175     const int format_len = strlen(format);
1176     if (format_len > 0) {
1177       const char last_char = format[format_len - 1];
1178       if (last_char != '\n' || last_char != '\r')
1179         strm.EOL();
1180     }
1181     Host::SystemLog(Host::eSystemLogWarning, "%s", strm.GetData());
1182   }
1183 }
1184 
1185 void Module::LogMessage(Log *log, const char *format, ...) {
1186   if (log != nullptr) {
1187     StreamString log_message;
1188     GetDescription(&log_message, lldb::eDescriptionLevelFull);
1189     log_message.PutCString(": ");
1190     va_list args;
1191     va_start(args, format);
1192     log_message.PrintfVarArg(format, args);
1193     va_end(args);
1194     log->PutCString(log_message.GetData());
1195   }
1196 }
1197 
1198 void Module::LogMessageVerboseBacktrace(Log *log, const char *format, ...) {
1199   if (log != nullptr) {
1200     StreamString log_message;
1201     GetDescription(&log_message, lldb::eDescriptionLevelFull);
1202     log_message.PutCString(": ");
1203     va_list args;
1204     va_start(args, format);
1205     log_message.PrintfVarArg(format, args);
1206     va_end(args);
1207     if (log->GetVerbose()) {
1208       std::string back_trace;
1209       llvm::raw_string_ostream stream(back_trace);
1210       llvm::sys::PrintStackTrace(stream);
1211       log_message.PutCString(back_trace);
1212     }
1213     log->PutCString(log_message.GetData());
1214   }
1215 }
1216 
1217 void Module::Dump(Stream *s) {
1218   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1219   // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1220   s->Indent();
1221   s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(),
1222             m_object_name ? "(" : "",
1223             m_object_name ? m_object_name.GetCString() : "",
1224             m_object_name ? ")" : "");
1225 
1226   s->IndentMore();
1227 
1228   ObjectFile *objfile = GetObjectFile();
1229   if (objfile)
1230     objfile->Dump(s);
1231 
1232   SymbolVendor *symbols = GetSymbolVendor();
1233   if (symbols)
1234     symbols->Dump(s);
1235 
1236   s->IndentLess();
1237 }
1238 
1239 TypeList *Module::GetTypeList() {
1240   SymbolVendor *symbols = GetSymbolVendor();
1241   if (symbols)
1242     return &symbols->GetTypeList();
1243   return nullptr;
1244 }
1245 
1246 const ConstString &Module::GetObjectName() const { return m_object_name; }
1247 
1248 ObjectFile *Module::GetObjectFile() {
1249   if (!m_did_load_objfile.load()) {
1250     std::lock_guard<std::recursive_mutex> guard(m_mutex);
1251     if (!m_did_load_objfile.load()) {
1252       static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1253       Timer scoped_timer(func_cat, "Module::GetObjectFile () module = %s",
1254                          GetFileSpec().GetFilename().AsCString(""));
1255       DataBufferSP data_sp;
1256       lldb::offset_t data_offset = 0;
1257       const lldb::offset_t file_size = m_file.GetByteSize();
1258       if (file_size > m_object_offset) {
1259         m_did_load_objfile = true;
1260         m_objfile_sp = ObjectFile::FindPlugin(
1261             shared_from_this(), &m_file, m_object_offset,
1262             file_size - m_object_offset, data_sp, data_offset);
1263         if (m_objfile_sp) {
1264           // Once we get the object file, update our module with the object
1265           // file's architecture since it might differ in vendor/os if some
1266           // parts were unknown.  But since the matching arch might already be
1267           // more specific than the generic COFF architecture, only merge in
1268           // those values that overwrite unspecified unknown values.
1269           ArchSpec new_arch;
1270           m_objfile_sp->GetArchitecture(new_arch);
1271           m_arch.MergeFrom(new_arch);
1272         } else {
1273           ReportError("failed to load objfile for %s",
1274                       GetFileSpec().GetPath().c_str());
1275         }
1276       }
1277     }
1278   }
1279   return m_objfile_sp.get();
1280 }
1281 
1282 SectionList *Module::GetSectionList() {
1283   // Populate m_sections_ap with sections from objfile.
1284   if (!m_sections_ap) {
1285     ObjectFile *obj_file = GetObjectFile();
1286     if (obj_file != nullptr)
1287       obj_file->CreateSections(*GetUnifiedSectionList());
1288   }
1289   return m_sections_ap.get();
1290 }
1291 
1292 void Module::SectionFileAddressesChanged() {
1293   ObjectFile *obj_file = GetObjectFile();
1294   if (obj_file)
1295     obj_file->SectionFileAddressesChanged();
1296   SymbolVendor *sym_vendor = GetSymbolVendor();
1297   if (sym_vendor != nullptr)
1298     sym_vendor->SectionFileAddressesChanged();
1299 }
1300 
1301 SectionList *Module::GetUnifiedSectionList() {
1302   if (!m_sections_ap)
1303     m_sections_ap = llvm::make_unique<SectionList>();
1304   return m_sections_ap.get();
1305 }
1306 
1307 const Symbol *Module::FindFirstSymbolWithNameAndType(const ConstString &name,
1308                                                      SymbolType symbol_type) {
1309   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1310   Timer scoped_timer(
1311       func_cat, "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1312       name.AsCString(), symbol_type);
1313   SymbolVendor *sym_vendor = GetSymbolVendor();
1314   if (sym_vendor) {
1315     Symtab *symtab = sym_vendor->GetSymtab();
1316     if (symtab)
1317       return symtab->FindFirstSymbolWithNameAndType(
1318           name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1319   }
1320   return nullptr;
1321 }
1322 void Module::SymbolIndicesToSymbolContextList(
1323     Symtab *symtab, std::vector<uint32_t> &symbol_indexes,
1324     SymbolContextList &sc_list) {
1325   // No need to protect this call using m_mutex all other method calls are
1326   // already thread safe.
1327 
1328   size_t num_indices = symbol_indexes.size();
1329   if (num_indices > 0) {
1330     SymbolContext sc;
1331     CalculateSymbolContext(&sc);
1332     for (size_t i = 0; i < num_indices; i++) {
1333       sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
1334       if (sc.symbol)
1335         sc_list.Append(sc);
1336     }
1337   }
1338 }
1339 
1340 size_t Module::FindFunctionSymbols(const ConstString &name,
1341                                    uint32_t name_type_mask,
1342                                    SymbolContextList &sc_list) {
1343   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1344   Timer scoped_timer(func_cat,
1345                      "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1346                      name.AsCString(), name_type_mask);
1347   SymbolVendor *sym_vendor = GetSymbolVendor();
1348   if (sym_vendor) {
1349     Symtab *symtab = sym_vendor->GetSymtab();
1350     if (symtab)
1351       return symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
1352   }
1353   return 0;
1354 }
1355 
1356 size_t Module::FindSymbolsWithNameAndType(const ConstString &name,
1357                                           SymbolType symbol_type,
1358                                           SymbolContextList &sc_list) {
1359   // No need to protect this call using m_mutex all other method calls are
1360   // already thread safe.
1361 
1362   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1363   Timer scoped_timer(
1364       func_cat, "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1365       name.AsCString(), symbol_type);
1366   const size_t initial_size = sc_list.GetSize();
1367   SymbolVendor *sym_vendor = GetSymbolVendor();
1368   if (sym_vendor) {
1369     Symtab *symtab = sym_vendor->GetSymtab();
1370     if (symtab) {
1371       std::vector<uint32_t> symbol_indexes;
1372       symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes);
1373       SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1374     }
1375   }
1376   return sc_list.GetSize() - initial_size;
1377 }
1378 
1379 size_t Module::FindSymbolsMatchingRegExAndType(const RegularExpression &regex,
1380                                                SymbolType symbol_type,
1381                                                SymbolContextList &sc_list) {
1382   // No need to protect this call using m_mutex all other method calls are
1383   // already thread safe.
1384 
1385   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1386   Timer scoped_timer(
1387       func_cat,
1388       "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1389       regex.GetText().str().c_str(), symbol_type);
1390   const size_t initial_size = sc_list.GetSize();
1391   SymbolVendor *sym_vendor = GetSymbolVendor();
1392   if (sym_vendor) {
1393     Symtab *symtab = sym_vendor->GetSymtab();
1394     if (symtab) {
1395       std::vector<uint32_t> symbol_indexes;
1396       symtab->FindAllSymbolsMatchingRexExAndType(
1397           regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny,
1398           symbol_indexes);
1399       SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1400     }
1401   }
1402   return sc_list.GetSize() - initial_size;
1403 }
1404 
1405 void Module::PreloadSymbols() {
1406   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1407   SymbolVendor * sym_vendor = GetSymbolVendor();
1408   if (!sym_vendor) {
1409     return;
1410   }
1411   // Prime the symbol file first, since it adds symbols to the symbol table.
1412   if (SymbolFile *symbol_file = sym_vendor->GetSymbolFile()) {
1413     symbol_file->PreloadSymbols();
1414   }
1415   // Now we can prime the symbol table.
1416   if (Symtab * symtab = sym_vendor->GetSymtab()) {
1417     symtab->PreloadSymbols();
1418   }
1419 }
1420 
1421 void Module::SetSymbolFileFileSpec(const FileSpec &file) {
1422   if (!file.Exists())
1423     return;
1424   if (m_symfile_ap) {
1425     // Remove any sections in the unified section list that come from the
1426     // current symbol vendor.
1427     SectionList *section_list = GetSectionList();
1428     SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile();
1429     if (section_list && symbol_file) {
1430       ObjectFile *obj_file = symbol_file->GetObjectFile();
1431       // Make sure we have an object file and that the symbol vendor's objfile
1432       // isn't the same as the module's objfile before we remove any sections
1433       // for it...
1434       if (obj_file) {
1435         // Check to make sure we aren't trying to specify the file we already
1436         // have
1437         if (obj_file->GetFileSpec() == file) {
1438           // We are being told to add the exact same file that we already have
1439           // we don't have to do anything.
1440           return;
1441         }
1442 
1443         // Cleare the current symtab as we are going to replace it with a new
1444         // one
1445         obj_file->ClearSymtab();
1446 
1447         // The symbol file might be a directory bundle ("/tmp/a.out.dSYM")
1448         // instead of a full path to the symbol file within the bundle
1449         // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to
1450         // check this
1451 
1452         if (llvm::sys::fs::is_directory(file.GetPath())) {
1453           std::string new_path(file.GetPath());
1454           std::string old_path(obj_file->GetFileSpec().GetPath());
1455           if (old_path.find(new_path) == 0) {
1456             // We specified the same bundle as the symbol file that we already
1457             // have
1458             return;
1459           }
1460         }
1461 
1462         if (obj_file != m_objfile_sp.get()) {
1463           size_t num_sections = section_list->GetNumSections(0);
1464           for (size_t idx = num_sections; idx > 0; --idx) {
1465             lldb::SectionSP section_sp(
1466                 section_list->GetSectionAtIndex(idx - 1));
1467             if (section_sp->GetObjectFile() == obj_file) {
1468               section_list->DeleteSection(idx - 1);
1469             }
1470           }
1471         }
1472       }
1473     }
1474     // Keep all old symbol files around in case there are any lingering type
1475     // references in any SBValue objects that might have been handed out.
1476     m_old_symfiles.push_back(std::move(m_symfile_ap));
1477   }
1478   m_symfile_spec = file;
1479   m_symfile_ap.reset();
1480   m_did_load_symbol_vendor = false;
1481 }
1482 
1483 bool Module::IsExecutable() {
1484   if (GetObjectFile() == nullptr)
1485     return false;
1486   else
1487     return GetObjectFile()->IsExecutable();
1488 }
1489 
1490 bool Module::IsLoadedInTarget(Target *target) {
1491   ObjectFile *obj_file = GetObjectFile();
1492   if (obj_file) {
1493     SectionList *sections = GetSectionList();
1494     if (sections != nullptr) {
1495       size_t num_sections = sections->GetSize();
1496       for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) {
1497         SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1498         if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) {
1499           return true;
1500         }
1501       }
1502     }
1503   }
1504   return false;
1505 }
1506 
1507 bool Module::LoadScriptingResourceInTarget(Target *target, Status &error,
1508                                            Stream *feedback_stream) {
1509   if (!target) {
1510     error.SetErrorString("invalid destination Target");
1511     return false;
1512   }
1513 
1514   LoadScriptFromSymFile should_load =
1515       target->TargetProperties::GetLoadScriptFromSymbolFile();
1516 
1517   if (should_load == eLoadScriptFromSymFileFalse)
1518     return false;
1519 
1520   Debugger &debugger = target->GetDebugger();
1521   const ScriptLanguage script_language = debugger.GetScriptLanguage();
1522   if (script_language != eScriptLanguageNone) {
1523 
1524     PlatformSP platform_sp(target->GetPlatform());
1525 
1526     if (!platform_sp) {
1527       error.SetErrorString("invalid Platform");
1528       return false;
1529     }
1530 
1531     FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources(
1532         target, *this, feedback_stream);
1533 
1534     const uint32_t num_specs = file_specs.GetSize();
1535     if (num_specs) {
1536       ScriptInterpreter *script_interpreter =
1537           debugger.GetCommandInterpreter().GetScriptInterpreter();
1538       if (script_interpreter) {
1539         for (uint32_t i = 0; i < num_specs; ++i) {
1540           FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i));
1541           if (scripting_fspec && scripting_fspec.Exists()) {
1542             if (should_load == eLoadScriptFromSymFileWarn) {
1543               if (feedback_stream)
1544                 feedback_stream->Printf(
1545                     "warning: '%s' contains a debug script. To run this script "
1546                     "in "
1547                     "this debug session:\n\n    command script import "
1548                     "\"%s\"\n\n"
1549                     "To run all discovered debug scripts in this session:\n\n"
1550                     "    settings set target.load-script-from-symbol-file "
1551                     "true\n",
1552                     GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1553                     scripting_fspec.GetPath().c_str());
1554               return false;
1555             }
1556             StreamString scripting_stream;
1557             scripting_fspec.Dump(&scripting_stream);
1558             const bool can_reload = true;
1559             const bool init_lldb_globals = false;
1560             bool did_load = script_interpreter->LoadScriptingModule(
1561                 scripting_stream.GetData(), can_reload, init_lldb_globals,
1562                 error);
1563             if (!did_load)
1564               return false;
1565           }
1566         }
1567       } else {
1568         error.SetErrorString("invalid ScriptInterpreter");
1569         return false;
1570       }
1571     }
1572   }
1573   return true;
1574 }
1575 
1576 bool Module::SetArchitecture(const ArchSpec &new_arch) {
1577   if (!m_arch.IsValid()) {
1578     m_arch = new_arch;
1579     return true;
1580   }
1581   return m_arch.IsCompatibleMatch(new_arch);
1582 }
1583 
1584 bool Module::SetLoadAddress(Target &target, lldb::addr_t value,
1585                             bool value_is_offset, bool &changed) {
1586   ObjectFile *object_file = GetObjectFile();
1587   if (object_file != nullptr) {
1588     changed = object_file->SetLoadAddress(target, value, value_is_offset);
1589     return true;
1590   } else {
1591     changed = false;
1592   }
1593   return false;
1594 }
1595 
1596 bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) {
1597   const UUID &uuid = module_ref.GetUUID();
1598 
1599   if (uuid.IsValid()) {
1600     // If the UUID matches, then nothing more needs to match...
1601     return (uuid == GetUUID());
1602   }
1603 
1604   const FileSpec &file_spec = module_ref.GetFileSpec();
1605   if (file_spec) {
1606     if (!FileSpec::Equal(file_spec, m_file, (bool)file_spec.GetDirectory()) &&
1607         !FileSpec::Equal(file_spec, m_platform_file,
1608                          (bool)file_spec.GetDirectory()))
1609       return false;
1610   }
1611 
1612   const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1613   if (platform_file_spec) {
1614     if (!FileSpec::Equal(platform_file_spec, GetPlatformFileSpec(),
1615                          (bool)platform_file_spec.GetDirectory()))
1616       return false;
1617   }
1618 
1619   const ArchSpec &arch = module_ref.GetArchitecture();
1620   if (arch.IsValid()) {
1621     if (!m_arch.IsCompatibleMatch(arch))
1622       return false;
1623   }
1624 
1625   const ConstString &object_name = module_ref.GetObjectName();
1626   if (object_name) {
1627     if (object_name != GetObjectName())
1628       return false;
1629   }
1630   return true;
1631 }
1632 
1633 bool Module::FindSourceFile(const FileSpec &orig_spec,
1634                             FileSpec &new_spec) const {
1635   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1636   return m_source_mappings.FindFile(orig_spec, new_spec);
1637 }
1638 
1639 bool Module::RemapSourceFile(llvm::StringRef path,
1640                              std::string &new_path) const {
1641   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1642   return m_source_mappings.RemapPath(path, new_path);
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