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