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