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