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