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