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