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