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