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