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