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