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/Log.h"
25 #include "lldb/Core/ModuleList.h"
26 #include "lldb/Core/ModuleSpec.h"
27 #include "lldb/Core/PluginManager.h"
28 #include "lldb/Core/Section.h"
29 #include "lldb/Core/Timer.h"
30 #include "lldb/Host/FileSystem.h"
31 #include "lldb/Host/Host.h"
32 #include "lldb/Host/Symbols.h"
33 #include "lldb/Interpreter/CommandInterpreter.h"
34 #include "lldb/Interpreter/ScriptInterpreter.h"
35 #include "lldb/Symbol/CompileUnit.h"
36 #include "lldb/Symbol/ObjectFile.h"
37 #include "lldb/Symbol/SymbolContext.h"
38 #include "lldb/Symbol/SymbolFile.h"
39 #include "lldb/Symbol/SymbolVendor.h"
40 #include "lldb/Symbol/TypeMap.h"
41 #include "lldb/Symbol/TypeSystem.h"
42 #include "lldb/Target/Language.h"
43 #include "lldb/Target/Process.h"
44 #include "lldb/Target/SectionLoadList.h"
45 #include "lldb/Target/Target.h"
46 #include "lldb/Utility/Error.h"
47 #include "lldb/Utility/RegularExpression.h"
48 #include "lldb/Utility/StreamString.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 eFunctionNameTypeFull and a name like "A::func"
723     if (basename.empty()) {
724       if (name_type_mask & eFunctionNameTypeFull &&
725           !CPlusPlusLanguage::IsCPPMangledName(name_cstr)) {
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" and specified eFunctionNameTypeFull, but we might have found
774   // "a::func()", "a::b::func()", "c::func()", "func()" and "func". Only
775   // "func()" and "func" should end up matching.
776   if (m_name_type_mask == eFunctionNameTypeFull) {
777     SymbolContext sc;
778     size_t i = start_idx;
779     while (i < sc_list.GetSize()) {
780       if (!sc_list.GetContextAtIndex(i, sc))
781         break;
782       // Make sure the mangled and demangled names don't match before we try
783       // to pull anything out
784       ConstString mangled_name(sc.GetFunctionName(Mangled::ePreferMangled));
785       ConstString full_name(sc.GetFunctionName());
786       if (mangled_name != m_name && full_name != m_name)
787       {
788         CPlusPlusLanguage::MethodName cpp_method(full_name);
789         if (cpp_method.IsValid()) {
790           if (cpp_method.GetContext().empty()) {
791             if (cpp_method.GetBasename().compare(m_name.GetStringRef()) != 0) {
792               sc_list.RemoveContextAtIndex(i);
793               continue;
794             }
795           } else {
796             std::string qualified_name;
797             llvm::StringRef anon_prefix("(anonymous namespace)");
798             if (cpp_method.GetContext() == anon_prefix)
799               qualified_name = cpp_method.GetBasename().str();
800             else
801               qualified_name = cpp_method.GetScopeQualifiedName();
802             if (qualified_name.compare(m_name.GetCString()) != 0) {
803               sc_list.RemoveContextAtIndex(i);
804               continue;
805             }
806           }
807         }
808       }
809       ++i;
810     }
811   }
812 }
813 
814 size_t Module::FindFunctions(const ConstString &name,
815                              const CompilerDeclContext *parent_decl_ctx,
816                              uint32_t name_type_mask, bool include_symbols,
817                              bool include_inlines, bool append,
818                              SymbolContextList &sc_list) {
819   if (!append)
820     sc_list.Clear();
821 
822   const size_t old_size = sc_list.GetSize();
823 
824   // Find all the functions (not symbols, but debug information functions...
825   SymbolVendor *symbols = GetSymbolVendor();
826 
827   if (name_type_mask & eFunctionNameTypeAuto) {
828     LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown);
829 
830     if (symbols) {
831       symbols->FindFunctions(lookup_info.GetLookupName(), parent_decl_ctx,
832                              lookup_info.GetNameTypeMask(), include_inlines,
833                              append, sc_list);
834 
835       // Now check our symbol table for symbols that are code symbols if
836       // requested
837       if (include_symbols) {
838         Symtab *symtab = symbols->GetSymtab();
839         if (symtab)
840           symtab->FindFunctionSymbols(lookup_info.GetLookupName(),
841                                       lookup_info.GetNameTypeMask(), sc_list);
842       }
843     }
844 
845     const size_t new_size = sc_list.GetSize();
846 
847     if (old_size < new_size)
848       lookup_info.Prune(sc_list, old_size);
849   } else {
850     if (symbols) {
851       symbols->FindFunctions(name, parent_decl_ctx, name_type_mask,
852                              include_inlines, append, sc_list);
853 
854       // Now check our symbol table for symbols that are code symbols if
855       // requested
856       if (include_symbols) {
857         Symtab *symtab = symbols->GetSymtab();
858         if (symtab)
859           symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
860       }
861     }
862   }
863 
864   return sc_list.GetSize() - old_size;
865 }
866 
867 size_t Module::FindFunctions(const RegularExpression &regex,
868                              bool include_symbols, bool include_inlines,
869                              bool append, SymbolContextList &sc_list) {
870   if (!append)
871     sc_list.Clear();
872 
873   const size_t start_size = sc_list.GetSize();
874 
875   SymbolVendor *symbols = GetSymbolVendor();
876   if (symbols) {
877     symbols->FindFunctions(regex, include_inlines, append, sc_list);
878 
879     // Now check our symbol table for symbols that are code symbols if requested
880     if (include_symbols) {
881       Symtab *symtab = symbols->GetSymtab();
882       if (symtab) {
883         std::vector<uint32_t> symbol_indexes;
884         symtab->AppendSymbolIndexesMatchingRegExAndType(
885             regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny,
886             symbol_indexes);
887         const size_t num_matches = symbol_indexes.size();
888         if (num_matches) {
889           SymbolContext sc(this);
890           const size_t end_functions_added_index = sc_list.GetSize();
891           size_t num_functions_added_to_sc_list =
892               end_functions_added_index - start_size;
893           if (num_functions_added_to_sc_list == 0) {
894             // No functions were added, just symbols, so we can just append them
895             for (size_t i = 0; i < num_matches; ++i) {
896               sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
897               SymbolType sym_type = sc.symbol->GetType();
898               if (sc.symbol && (sym_type == eSymbolTypeCode ||
899                                 sym_type == eSymbolTypeResolver))
900                 sc_list.Append(sc);
901             }
902           } else {
903             typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap;
904             FileAddrToIndexMap file_addr_to_index;
905             for (size_t i = start_size; i < end_functions_added_index; ++i) {
906               const SymbolContext &sc = sc_list[i];
907               if (sc.block)
908                 continue;
909               file_addr_to_index[sc.function->GetAddressRange()
910                                      .GetBaseAddress()
911                                      .GetFileAddress()] = i;
912             }
913 
914             FileAddrToIndexMap::const_iterator end = file_addr_to_index.end();
915             // Functions were added so we need to merge symbols into any
916             // existing function symbol contexts
917             for (size_t i = start_size; i < num_matches; ++i) {
918               sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
919               SymbolType sym_type = sc.symbol->GetType();
920               if (sc.symbol && sc.symbol->ValueIsAddress() &&
921                   (sym_type == eSymbolTypeCode ||
922                    sym_type == eSymbolTypeResolver)) {
923                 FileAddrToIndexMap::const_iterator pos =
924                     file_addr_to_index.find(
925                         sc.symbol->GetAddressRef().GetFileAddress());
926                 if (pos == end)
927                   sc_list.Append(sc);
928                 else
929                   sc_list[pos->second].symbol = sc.symbol;
930               }
931             }
932           }
933         }
934       }
935     }
936   }
937   return sc_list.GetSize() - start_size;
938 }
939 
940 void Module::FindAddressesForLine(const lldb::TargetSP target_sp,
941                                   const FileSpec &file, uint32_t line,
942                                   Function *function,
943                                   std::vector<Address> &output_local,
944                                   std::vector<Address> &output_extern) {
945   SearchFilterByModule filter(target_sp, m_file);
946   AddressResolverFileLine resolver(file, line, true);
947   resolver.ResolveAddress(filter);
948 
949   for (size_t n = 0; n < resolver.GetNumberOfAddresses(); n++) {
950     Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress();
951     Function *f = addr.CalculateSymbolContextFunction();
952     if (f && f == function)
953       output_local.push_back(addr);
954     else
955       output_extern.push_back(addr);
956   }
957 }
958 
959 size_t Module::FindTypes_Impl(
960     const SymbolContext &sc, const ConstString &name,
961     const CompilerDeclContext *parent_decl_ctx, bool append, size_t max_matches,
962     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
963     TypeMap &types) {
964   Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION);
965   if (!sc.module_sp || sc.module_sp.get() == this) {
966     SymbolVendor *symbols = GetSymbolVendor();
967     if (symbols)
968       return symbols->FindTypes(sc, name, parent_decl_ctx, append, max_matches,
969                                 searched_symbol_files, types);
970   }
971   return 0;
972 }
973 
974 size_t Module::FindTypesInNamespace(const SymbolContext &sc,
975                                     const ConstString &type_name,
976                                     const CompilerDeclContext *parent_decl_ctx,
977                                     size_t max_matches, TypeList &type_list) {
978   const bool append = true;
979   TypeMap types_map;
980   llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
981   size_t num_types =
982       FindTypes_Impl(sc, type_name, parent_decl_ctx, append, max_matches,
983                      searched_symbol_files, types_map);
984   if (num_types > 0)
985     sc.SortTypeList(types_map, type_list);
986   return num_types;
987 }
988 
989 lldb::TypeSP Module::FindFirstType(const SymbolContext &sc,
990                                    const ConstString &name, bool exact_match) {
991   TypeList type_list;
992   llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
993   const size_t num_matches =
994       FindTypes(sc, name, exact_match, 1, searched_symbol_files, type_list);
995   if (num_matches)
996     return type_list.GetTypeAtIndex(0);
997   return TypeSP();
998 }
999 
1000 size_t Module::FindTypes(
1001     const SymbolContext &sc, const ConstString &name, bool exact_match,
1002     size_t max_matches,
1003     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1004     TypeList &types) {
1005   size_t num_matches = 0;
1006   const char *type_name_cstr = name.GetCString();
1007   llvm::StringRef type_scope;
1008   llvm::StringRef type_basename;
1009   const bool append = true;
1010   TypeClass type_class = eTypeClassAny;
1011   TypeMap typesmap;
1012   if (Type::GetTypeScopeAndBasename(type_name_cstr, type_scope, type_basename,
1013                                     type_class)) {
1014     // Check if "name" starts with "::" which means the qualified type starts
1015     // from the root namespace and implies and exact match. The typenames we
1016     // get back from clang do not start with "::" so we need to strip this off
1017     // in order to get the qualified names to match
1018     exact_match = type_scope.consume_front("::");
1019 
1020     ConstString type_basename_const_str(type_basename);
1021     if (FindTypes_Impl(sc, type_basename_const_str, nullptr, append,
1022                        max_matches, searched_symbol_files, typesmap)) {
1023       typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class,
1024                                      exact_match);
1025       num_matches = typesmap.GetSize();
1026     }
1027   } else {
1028     // The type is not in a namespace/class scope, just search for it by
1029     // basename
1030     if (type_class != eTypeClassAny) {
1031       // The "type_name_cstr" will have been modified if we have a valid type
1032       // class
1033       // prefix (like "struct", "class", "union", "typedef" etc).
1034       FindTypes_Impl(sc, ConstString(type_name_cstr), nullptr, append,
1035                      max_matches, searched_symbol_files, typesmap);
1036       typesmap.RemoveMismatchedTypes(type_class);
1037       num_matches = typesmap.GetSize();
1038     } else {
1039       num_matches = FindTypes_Impl(sc, name, nullptr, append, max_matches,
1040                                    searched_symbol_files, typesmap);
1041     }
1042   }
1043   if (num_matches > 0)
1044     sc.SortTypeList(typesmap, types);
1045   return num_matches;
1046 }
1047 
1048 SymbolVendor *Module::GetSymbolVendor(bool can_create,
1049                                       lldb_private::Stream *feedback_strm) {
1050   if (!m_did_load_symbol_vendor.load()) {
1051     std::lock_guard<std::recursive_mutex> guard(m_mutex);
1052     if (!m_did_load_symbol_vendor.load() && can_create) {
1053       ObjectFile *obj_file = GetObjectFile();
1054       if (obj_file != nullptr) {
1055         Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION);
1056         m_symfile_ap.reset(
1057             SymbolVendor::FindPlugin(shared_from_this(), feedback_strm));
1058         m_did_load_symbol_vendor = true;
1059       }
1060     }
1061   }
1062   return m_symfile_ap.get();
1063 }
1064 
1065 void Module::SetFileSpecAndObjectName(const FileSpec &file,
1066                                       const ConstString &object_name) {
1067   // Container objects whose paths do not specify a file directly can call
1068   // this function to correct the file and object names.
1069   m_file = file;
1070   m_mod_time = FileSystem::GetModificationTime(file);
1071   m_object_name = object_name;
1072 }
1073 
1074 const ArchSpec &Module::GetArchitecture() const { return m_arch; }
1075 
1076 std::string Module::GetSpecificationDescription() const {
1077   std::string spec(GetFileSpec().GetPath());
1078   if (m_object_name) {
1079     spec += '(';
1080     spec += m_object_name.GetCString();
1081     spec += ')';
1082   }
1083   return spec;
1084 }
1085 
1086 void Module::GetDescription(Stream *s, lldb::DescriptionLevel level) {
1087   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1088 
1089   if (level >= eDescriptionLevelFull) {
1090     if (m_arch.IsValid())
1091       s->Printf("(%s) ", m_arch.GetArchitectureName());
1092   }
1093 
1094   if (level == eDescriptionLevelBrief) {
1095     const char *filename = m_file.GetFilename().GetCString();
1096     if (filename)
1097       s->PutCString(filename);
1098   } else {
1099     char path[PATH_MAX];
1100     if (m_file.GetPath(path, sizeof(path)))
1101       s->PutCString(path);
1102   }
1103 
1104   const char *object_name = m_object_name.GetCString();
1105   if (object_name)
1106     s->Printf("(%s)", object_name);
1107 }
1108 
1109 void Module::ReportError(const char *format, ...) {
1110   if (format && format[0]) {
1111     StreamString strm;
1112     strm.PutCString("error: ");
1113     GetDescription(&strm, lldb::eDescriptionLevelBrief);
1114     strm.PutChar(' ');
1115     va_list args;
1116     va_start(args, format);
1117     strm.PrintfVarArg(format, args);
1118     va_end(args);
1119 
1120     const int format_len = strlen(format);
1121     if (format_len > 0) {
1122       const char last_char = format[format_len - 1];
1123       if (last_char != '\n' || last_char != '\r')
1124         strm.EOL();
1125     }
1126     Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1127   }
1128 }
1129 
1130 bool Module::FileHasChanged() const {
1131   if (!m_file_has_changed)
1132     m_file_has_changed =
1133         (FileSystem::GetModificationTime(m_file) != m_mod_time);
1134   return m_file_has_changed;
1135 }
1136 
1137 void Module::ReportErrorIfModifyDetected(const char *format, ...) {
1138   if (!m_first_file_changed_log) {
1139     if (FileHasChanged()) {
1140       m_first_file_changed_log = true;
1141       if (format) {
1142         StreamString strm;
1143         strm.PutCString("error: the object file ");
1144         GetDescription(&strm, lldb::eDescriptionLevelFull);
1145         strm.PutCString(" has been modified\n");
1146 
1147         va_list args;
1148         va_start(args, format);
1149         strm.PrintfVarArg(format, args);
1150         va_end(args);
1151 
1152         const int format_len = strlen(format);
1153         if (format_len > 0) {
1154           const char last_char = format[format_len - 1];
1155           if (last_char != '\n' || last_char != '\r')
1156             strm.EOL();
1157         }
1158         strm.PutCString("The debug session should be aborted as the original "
1159                         "debug information has been overwritten.\n");
1160         Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData());
1161       }
1162     }
1163   }
1164 }
1165 
1166 void Module::ReportWarning(const char *format, ...) {
1167   if (format && format[0]) {
1168     StreamString strm;
1169     strm.PutCString("warning: ");
1170     GetDescription(&strm, lldb::eDescriptionLevelFull);
1171     strm.PutChar(' ');
1172 
1173     va_list args;
1174     va_start(args, format);
1175     strm.PrintfVarArg(format, args);
1176     va_end(args);
1177 
1178     const int format_len = strlen(format);
1179     if (format_len > 0) {
1180       const char last_char = format[format_len - 1];
1181       if (last_char != '\n' || last_char != '\r')
1182         strm.EOL();
1183     }
1184     Host::SystemLog(Host::eSystemLogWarning, "%s", strm.GetData());
1185   }
1186 }
1187 
1188 void Module::LogMessage(Log *log, const char *format, ...) {
1189   if (log != nullptr) {
1190     StreamString log_message;
1191     GetDescription(&log_message, lldb::eDescriptionLevelFull);
1192     log_message.PutCString(": ");
1193     va_list args;
1194     va_start(args, format);
1195     log_message.PrintfVarArg(format, args);
1196     va_end(args);
1197     log->PutCString(log_message.GetData());
1198   }
1199 }
1200 
1201 void Module::LogMessageVerboseBacktrace(Log *log, const char *format, ...) {
1202   if (log != nullptr) {
1203     StreamString log_message;
1204     GetDescription(&log_message, lldb::eDescriptionLevelFull);
1205     log_message.PutCString(": ");
1206     va_list args;
1207     va_start(args, format);
1208     log_message.PrintfVarArg(format, args);
1209     va_end(args);
1210     if (log->GetVerbose()) {
1211       std::string back_trace;
1212       llvm::raw_string_ostream stream(back_trace);
1213       llvm::sys::PrintStackTrace(stream);
1214       log_message.PutCString(back_trace);
1215     }
1216     log->PutCString(log_message.GetData());
1217   }
1218 }
1219 
1220 void Module::Dump(Stream *s) {
1221   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1222   // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
1223   s->Indent();
1224   s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(),
1225             m_object_name ? "(" : "",
1226             m_object_name ? m_object_name.GetCString() : "",
1227             m_object_name ? ")" : "");
1228 
1229   s->IndentMore();
1230 
1231   ObjectFile *objfile = GetObjectFile();
1232   if (objfile)
1233     objfile->Dump(s);
1234 
1235   SymbolVendor *symbols = GetSymbolVendor();
1236   if (symbols)
1237     symbols->Dump(s);
1238 
1239   s->IndentLess();
1240 }
1241 
1242 TypeList *Module::GetTypeList() {
1243   SymbolVendor *symbols = GetSymbolVendor();
1244   if (symbols)
1245     return &symbols->GetTypeList();
1246   return nullptr;
1247 }
1248 
1249 const ConstString &Module::GetObjectName() const { return m_object_name; }
1250 
1251 ObjectFile *Module::GetObjectFile() {
1252   if (!m_did_load_objfile.load()) {
1253     std::lock_guard<std::recursive_mutex> guard(m_mutex);
1254     if (!m_did_load_objfile.load()) {
1255       Timer scoped_timer(LLVM_PRETTY_FUNCTION,
1256                          "Module::GetObjectFile () module = %s",
1257                          GetFileSpec().GetFilename().AsCString(""));
1258       DataBufferSP data_sp;
1259       lldb::offset_t data_offset = 0;
1260       const lldb::offset_t file_size = m_file.GetByteSize();
1261       if (file_size > m_object_offset) {
1262         m_did_load_objfile = true;
1263         m_objfile_sp = ObjectFile::FindPlugin(
1264             shared_from_this(), &m_file, m_object_offset,
1265             file_size - m_object_offset, data_sp, data_offset);
1266         if (m_objfile_sp) {
1267           // Once we get the object file, update our module with the object
1268           // file's
1269           // architecture since it might differ in vendor/os if some parts were
1270           // unknown.  But since the matching arch might already be more
1271           // specific
1272           // than the generic COFF architecture, only merge in those values that
1273           // overwrite unspecified unknown values.
1274           ArchSpec new_arch;
1275           m_objfile_sp->GetArchitecture(new_arch);
1276           m_arch.MergeFrom(new_arch);
1277         } else {
1278           ReportError("failed to load objfile for %s",
1279                       GetFileSpec().GetPath().c_str());
1280         }
1281       }
1282     }
1283   }
1284   return m_objfile_sp.get();
1285 }
1286 
1287 SectionList *Module::GetSectionList() {
1288   // Populate m_unified_sections_ap with sections from objfile.
1289   if (!m_sections_ap) {
1290     ObjectFile *obj_file = GetObjectFile();
1291     if (obj_file != nullptr)
1292       obj_file->CreateSections(*GetUnifiedSectionList());
1293   }
1294   return m_sections_ap.get();
1295 }
1296 
1297 void Module::SectionFileAddressesChanged() {
1298   ObjectFile *obj_file = GetObjectFile();
1299   if (obj_file)
1300     obj_file->SectionFileAddressesChanged();
1301   SymbolVendor *sym_vendor = GetSymbolVendor();
1302   if (sym_vendor != nullptr)
1303     sym_vendor->SectionFileAddressesChanged();
1304 }
1305 
1306 SectionList *Module::GetUnifiedSectionList() {
1307   // Populate m_unified_sections_ap with sections from objfile.
1308   if (!m_sections_ap)
1309     m_sections_ap.reset(new SectionList());
1310   return m_sections_ap.get();
1311 }
1312 
1313 const Symbol *Module::FindFirstSymbolWithNameAndType(const ConstString &name,
1314                                                      SymbolType symbol_type) {
1315   Timer scoped_timer(
1316       LLVM_PRETTY_FUNCTION,
1317       "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)",
1318       name.AsCString(), symbol_type);
1319   SymbolVendor *sym_vendor = GetSymbolVendor();
1320   if (sym_vendor) {
1321     Symtab *symtab = sym_vendor->GetSymtab();
1322     if (symtab)
1323       return symtab->FindFirstSymbolWithNameAndType(
1324           name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny);
1325   }
1326   return nullptr;
1327 }
1328 void Module::SymbolIndicesToSymbolContextList(
1329     Symtab *symtab, std::vector<uint32_t> &symbol_indexes,
1330     SymbolContextList &sc_list) {
1331   // No need to protect this call using m_mutex all other method calls are
1332   // already thread safe.
1333 
1334   size_t num_indices = symbol_indexes.size();
1335   if (num_indices > 0) {
1336     SymbolContext sc;
1337     CalculateSymbolContext(&sc);
1338     for (size_t i = 0; i < num_indices; i++) {
1339       sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]);
1340       if (sc.symbol)
1341         sc_list.Append(sc);
1342     }
1343   }
1344 }
1345 
1346 size_t Module::FindFunctionSymbols(const ConstString &name,
1347                                    uint32_t name_type_mask,
1348                                    SymbolContextList &sc_list) {
1349   Timer scoped_timer(LLVM_PRETTY_FUNCTION,
1350                      "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)",
1351                      name.AsCString(), name_type_mask);
1352   SymbolVendor *sym_vendor = GetSymbolVendor();
1353   if (sym_vendor) {
1354     Symtab *symtab = sym_vendor->GetSymtab();
1355     if (symtab)
1356       return symtab->FindFunctionSymbols(name, name_type_mask, sc_list);
1357   }
1358   return 0;
1359 }
1360 
1361 size_t Module::FindSymbolsWithNameAndType(const ConstString &name,
1362                                           SymbolType symbol_type,
1363                                           SymbolContextList &sc_list) {
1364   // No need to protect this call using m_mutex all other method calls are
1365   // already thread safe.
1366 
1367   Timer scoped_timer(
1368       LLVM_PRETTY_FUNCTION,
1369       "Module::FindSymbolsWithNameAndType (name = %s, type = %i)",
1370       name.AsCString(), symbol_type);
1371   const size_t initial_size = sc_list.GetSize();
1372   SymbolVendor *sym_vendor = GetSymbolVendor();
1373   if (sym_vendor) {
1374     Symtab *symtab = sym_vendor->GetSymtab();
1375     if (symtab) {
1376       std::vector<uint32_t> symbol_indexes;
1377       symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes);
1378       SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1379     }
1380   }
1381   return sc_list.GetSize() - initial_size;
1382 }
1383 
1384 size_t Module::FindSymbolsMatchingRegExAndType(const RegularExpression &regex,
1385                                                SymbolType symbol_type,
1386                                                SymbolContextList &sc_list) {
1387   // No need to protect this call using m_mutex all other method calls are
1388   // already thread safe.
1389 
1390   Timer scoped_timer(
1391       LLVM_PRETTY_FUNCTION,
1392       "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)",
1393       regex.GetText().str().c_str(), symbol_type);
1394   const size_t initial_size = sc_list.GetSize();
1395   SymbolVendor *sym_vendor = GetSymbolVendor();
1396   if (sym_vendor) {
1397     Symtab *symtab = sym_vendor->GetSymtab();
1398     if (symtab) {
1399       std::vector<uint32_t> symbol_indexes;
1400       symtab->FindAllSymbolsMatchingRexExAndType(
1401           regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny,
1402           symbol_indexes);
1403       SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list);
1404     }
1405   }
1406   return sc_list.GetSize() - initial_size;
1407 }
1408 
1409 void Module::SetSymbolFileFileSpec(const FileSpec &file) {
1410   if (!file.Exists())
1411     return;
1412   if (m_symfile_ap) {
1413     // Remove any sections in the unified section list that come from the
1414     // current symbol vendor.
1415     SectionList *section_list = GetSectionList();
1416     SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile();
1417     if (section_list && symbol_file) {
1418       ObjectFile *obj_file = symbol_file->GetObjectFile();
1419       // Make sure we have an object file and that the symbol vendor's objfile
1420       // isn't
1421       // the same as the module's objfile before we remove any sections for
1422       // it...
1423       if (obj_file) {
1424         // Check to make sure we aren't trying to specify the file we already
1425         // have
1426         if (obj_file->GetFileSpec() == file) {
1427           // We are being told to add the exact same file that we already have
1428           // we don't have to do anything.
1429           return;
1430         }
1431 
1432         // Cleare the current symtab as we are going to replace it with a new
1433         // one
1434         obj_file->ClearSymtab();
1435 
1436         // The symbol file might be a directory bundle ("/tmp/a.out.dSYM")
1437         // instead
1438         // of a full path to the symbol file within the bundle
1439         // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to
1440         // check this
1441 
1442         if (file.IsDirectory()) {
1443           std::string new_path(file.GetPath());
1444           std::string old_path(obj_file->GetFileSpec().GetPath());
1445           if (old_path.find(new_path) == 0) {
1446             // We specified the same bundle as the symbol file that we already
1447             // have
1448             return;
1449           }
1450         }
1451 
1452         if (obj_file != m_objfile_sp.get()) {
1453           size_t num_sections = section_list->GetNumSections(0);
1454           for (size_t idx = num_sections; idx > 0; --idx) {
1455             lldb::SectionSP section_sp(
1456                 section_list->GetSectionAtIndex(idx - 1));
1457             if (section_sp->GetObjectFile() == obj_file) {
1458               section_list->DeleteSection(idx - 1);
1459             }
1460           }
1461         }
1462       }
1463     }
1464     // Keep all old symbol files around in case there are any lingering type
1465     // references in
1466     // any SBValue objects that might have been handed out.
1467     m_old_symfiles.push_back(std::move(m_symfile_ap));
1468   }
1469   m_symfile_spec = file;
1470   m_symfile_ap.reset();
1471   m_did_load_symbol_vendor = false;
1472 }
1473 
1474 bool Module::IsExecutable() {
1475   if (GetObjectFile() == nullptr)
1476     return false;
1477   else
1478     return GetObjectFile()->IsExecutable();
1479 }
1480 
1481 bool Module::IsLoadedInTarget(Target *target) {
1482   ObjectFile *obj_file = GetObjectFile();
1483   if (obj_file) {
1484     SectionList *sections = GetSectionList();
1485     if (sections != nullptr) {
1486       size_t num_sections = sections->GetSize();
1487       for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) {
1488         SectionSP section_sp = sections->GetSectionAtIndex(sect_idx);
1489         if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) {
1490           return true;
1491         }
1492       }
1493     }
1494   }
1495   return false;
1496 }
1497 
1498 bool Module::LoadScriptingResourceInTarget(Target *target, Error &error,
1499                                            Stream *feedback_stream) {
1500   if (!target) {
1501     error.SetErrorString("invalid destination Target");
1502     return false;
1503   }
1504 
1505   LoadScriptFromSymFile should_load =
1506       target->TargetProperties::GetLoadScriptFromSymbolFile();
1507 
1508   if (should_load == eLoadScriptFromSymFileFalse)
1509     return false;
1510 
1511   Debugger &debugger = target->GetDebugger();
1512   const ScriptLanguage script_language = debugger.GetScriptLanguage();
1513   if (script_language != eScriptLanguageNone) {
1514 
1515     PlatformSP platform_sp(target->GetPlatform());
1516 
1517     if (!platform_sp) {
1518       error.SetErrorString("invalid Platform");
1519       return false;
1520     }
1521 
1522     FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources(
1523         target, *this, feedback_stream);
1524 
1525     const uint32_t num_specs = file_specs.GetSize();
1526     if (num_specs) {
1527       ScriptInterpreter *script_interpreter =
1528           debugger.GetCommandInterpreter().GetScriptInterpreter();
1529       if (script_interpreter) {
1530         for (uint32_t i = 0; i < num_specs; ++i) {
1531           FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i));
1532           if (scripting_fspec && scripting_fspec.Exists()) {
1533             if (should_load == eLoadScriptFromSymFileWarn) {
1534               if (feedback_stream)
1535                 feedback_stream->Printf(
1536                     "warning: '%s' contains a debug script. To run this script "
1537                     "in "
1538                     "this debug session:\n\n    command script import "
1539                     "\"%s\"\n\n"
1540                     "To run all discovered debug scripts in this session:\n\n"
1541                     "    settings set target.load-script-from-symbol-file "
1542                     "true\n",
1543                     GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1544                     scripting_fspec.GetPath().c_str());
1545               return false;
1546             }
1547             StreamString scripting_stream;
1548             scripting_fspec.Dump(&scripting_stream);
1549             const bool can_reload = true;
1550             const bool init_lldb_globals = false;
1551             bool did_load = script_interpreter->LoadScriptingModule(
1552                 scripting_stream.GetData(), can_reload, init_lldb_globals,
1553                 error);
1554             if (!did_load)
1555               return false;
1556           }
1557         }
1558       } else {
1559         error.SetErrorString("invalid ScriptInterpreter");
1560         return false;
1561       }
1562     }
1563   }
1564   return true;
1565 }
1566 
1567 bool Module::SetArchitecture(const ArchSpec &new_arch) {
1568   if (!m_arch.IsValid()) {
1569     m_arch = new_arch;
1570     return true;
1571   }
1572   return m_arch.IsCompatibleMatch(new_arch);
1573 }
1574 
1575 bool Module::SetLoadAddress(Target &target, lldb::addr_t value,
1576                             bool value_is_offset, bool &changed) {
1577   ObjectFile *object_file = GetObjectFile();
1578   if (object_file != nullptr) {
1579     changed = object_file->SetLoadAddress(target, value, value_is_offset);
1580     return true;
1581   } else {
1582     changed = false;
1583   }
1584   return false;
1585 }
1586 
1587 bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) {
1588   const UUID &uuid = module_ref.GetUUID();
1589 
1590   if (uuid.IsValid()) {
1591     // If the UUID matches, then nothing more needs to match...
1592     return (uuid == GetUUID());
1593   }
1594 
1595   const FileSpec &file_spec = module_ref.GetFileSpec();
1596   if (file_spec) {
1597     if (!FileSpec::Equal(file_spec, m_file, (bool)file_spec.GetDirectory()) &&
1598         !FileSpec::Equal(file_spec, m_platform_file,
1599                          (bool)file_spec.GetDirectory()))
1600       return false;
1601   }
1602 
1603   const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec();
1604   if (platform_file_spec) {
1605     if (!FileSpec::Equal(platform_file_spec, GetPlatformFileSpec(),
1606                          (bool)platform_file_spec.GetDirectory()))
1607       return false;
1608   }
1609 
1610   const ArchSpec &arch = module_ref.GetArchitecture();
1611   if (arch.IsValid()) {
1612     if (!m_arch.IsCompatibleMatch(arch))
1613       return false;
1614   }
1615 
1616   const ConstString &object_name = module_ref.GetObjectName();
1617   if (object_name) {
1618     if (object_name != GetObjectName())
1619       return false;
1620   }
1621   return true;
1622 }
1623 
1624 bool Module::FindSourceFile(const FileSpec &orig_spec,
1625                             FileSpec &new_spec) const {
1626   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1627   return m_source_mappings.FindFile(orig_spec, new_spec);
1628 }
1629 
1630 bool Module::RemapSourceFile(llvm::StringRef path,
1631                              std::string &new_path) const {
1632   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1633   return m_source_mappings.RemapPath(path, new_path);
1634 }
1635 
1636 uint32_t Module::GetVersion(uint32_t *versions, uint32_t num_versions) {
1637   ObjectFile *obj_file = GetObjectFile();
1638   if (obj_file)
1639     return obj_file->GetVersion(versions, num_versions);
1640 
1641   if (versions != nullptr && num_versions != 0) {
1642     for (uint32_t i = 0; i < num_versions; ++i)
1643       versions[i] = LLDB_INVALID_MODULE_VERSION;
1644   }
1645   return 0;
1646 }
1647 
1648 ModuleSP
1649 Module::CreateJITModule(const lldb::ObjectFileJITDelegateSP &delegate_sp) {
1650   if (delegate_sp) {
1651     // Must create a module and place it into a shared pointer before
1652     // we can create an object file since it has a std::weak_ptr back
1653     // to the module, so we need to control the creation carefully in
1654     // this static function
1655     ModuleSP module_sp(new Module());
1656     module_sp->m_objfile_sp.reset(new ObjectFileJIT(module_sp, delegate_sp));
1657     if (module_sp->m_objfile_sp) {
1658       // Once we get the object file, update our module with the object file's
1659       // architecture since it might differ in vendor/os if some parts were
1660       // unknown.
1661       module_sp->m_objfile_sp->GetArchitecture(module_sp->m_arch);
1662     }
1663     return module_sp;
1664   }
1665   return ModuleSP();
1666 }
1667 
1668 bool Module::GetIsDynamicLinkEditor() {
1669   ObjectFile *obj_file = GetObjectFile();
1670 
1671   if (obj_file)
1672     return obj_file->GetIsDynamicLinkEditor();
1673 
1674   return false;
1675 }
1676 
1677 Error Module::LoadInMemory(Target &target, bool set_pc) {
1678   return m_objfile_sp->LoadInMemory(target, set_pc);
1679 }
1680