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