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