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