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