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