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