1 //===-- SymbolFileDWARFDebugMap.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 "SymbolFileDWARFDebugMap.h"
11 
12 #include "DWARFDebugAranges.h"
13 
14 #include "lldb/Core/RangeMap.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleList.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/RegularExpression.h"
19 #include "lldb/Core/Section.h"
20 
21 //#define DEBUG_OSO_DMAP // DO NOT CHECKIN WITH THIS NOT COMMENTED OUT
22 #if defined(DEBUG_OSO_DMAP)
23 #include "lldb/Core/StreamFile.h"
24 #endif
25 #include "lldb/Core/Timer.h"
26 
27 #include "lldb/Symbol/ClangExternalASTSourceCallbacks.h"
28 #include "lldb/Symbol/CompileUnit.h"
29 #include "lldb/Symbol/LineTable.h"
30 #include "lldb/Symbol/ObjectFile.h"
31 #include "lldb/Symbol/SymbolVendor.h"
32 #include "lldb/Symbol/VariableList.h"
33 
34 #include "LogChannelDWARF.h"
35 #include "SymbolFileDWARF.h"
36 
37 using namespace lldb;
38 using namespace lldb_private;
39 
40 // Subclass lldb_private::Module so we can intercept the "Module::GetObjectFile()"
41 // (so we can fixup the object file sections) and also for "Module::GetSymbolVendor()"
42 // (so we can fixup the symbol file id.
43 
44 
45 
46 
47 const SymbolFileDWARFDebugMap::FileRangeMap &
48 SymbolFileDWARFDebugMap::CompileUnitInfo::GetFileRangeMap(SymbolFileDWARFDebugMap *exe_symfile)
49 {
50     if (file_range_map_valid)
51         return file_range_map;
52 
53     file_range_map_valid = true;
54 
55     Module *oso_module = exe_symfile->GetModuleByCompUnitInfo (this);
56     if (!oso_module)
57         return file_range_map;
58 
59     ObjectFile *oso_objfile = oso_module->GetObjectFile();
60     if (!oso_objfile)
61         return file_range_map;
62 
63     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_MAP));
64     if (log)
65     {
66         ConstString object_name (oso_module->GetObjectName());
67         log->Printf("%p: SymbolFileDWARFDebugMap::CompileUnitInfo::GetFileRangeMap ('%s')",
68                     static_cast<void*>(this),
69                     oso_module->GetSpecificationDescription().c_str());
70     }
71 
72     std::vector<SymbolFileDWARFDebugMap::CompileUnitInfo *> cu_infos;
73     if (exe_symfile->GetCompUnitInfosForModule(oso_module, cu_infos))
74     {
75         for (auto comp_unit_info : cu_infos)
76         {
77             Symtab *exe_symtab = exe_symfile->GetObjectFile()->GetSymtab();
78             ModuleSP oso_module_sp (oso_objfile->GetModule());
79             Symtab *oso_symtab = oso_objfile->GetSymtab();
80 
81             ///const uint32_t fun_resolve_flags = SymbolContext::Module | eSymbolContextCompUnit | eSymbolContextFunction;
82             //SectionList *oso_sections = oso_objfile->Sections();
83             // Now we need to make sections that map from zero based object
84             // file addresses to where things ended up in the main executable.
85 
86             assert (comp_unit_info->first_symbol_index != UINT32_MAX);
87             // End index is one past the last valid symbol index
88             const uint32_t oso_end_idx = comp_unit_info->last_symbol_index + 1;
89             for (uint32_t idx = comp_unit_info->first_symbol_index + 2; // Skip the N_SO and N_OSO
90                  idx < oso_end_idx;
91                  ++idx)
92             {
93                 Symbol *exe_symbol = exe_symtab->SymbolAtIndex(idx);
94                 if (exe_symbol)
95                 {
96                     if (exe_symbol->IsDebug() == false)
97                         continue;
98 
99                     switch (exe_symbol->GetType())
100                     {
101                     default:
102                         break;
103 
104                     case eSymbolTypeCode:
105                         {
106                             // For each N_FUN, or function that we run into in the debug map
107                             // we make a new section that we add to the sections found in the
108                             // .o file. This new section has the file address set to what the
109                             // addresses are in the .o file, and the load address is adjusted
110                             // to match where it ended up in the final executable! We do this
111                             // before we parse any dwarf info so that when it goes get parsed
112                             // all section/offset addresses that get registered will resolve
113                             // correctly to the new addresses in the main executable.
114 
115                             // First we find the original symbol in the .o file's symbol table
116                             Symbol *oso_fun_symbol = oso_symtab->FindFirstSymbolWithNameAndType (exe_symbol->GetMangled().GetName(lldb::eLanguageTypeUnknown, Mangled::ePreferMangled),
117                                                                                                  eSymbolTypeCode,
118                                                                                                  Symtab::eDebugNo,
119                                                                                                  Symtab::eVisibilityAny);
120                             if (oso_fun_symbol)
121                             {
122                                 // Add the inverse OSO file address to debug map entry mapping
123                                 exe_symfile->AddOSOFileRange (this,
124                                                               exe_symbol->GetAddressRef().GetFileAddress(),
125                                                               oso_fun_symbol->GetAddressRef().GetFileAddress(),
126                                                               std::min<addr_t>(exe_symbol->GetByteSize(), oso_fun_symbol->GetByteSize()));
127 
128                             }
129                         }
130                         break;
131 
132                     case eSymbolTypeData:
133                         {
134                             // For each N_GSYM we remap the address for the global by making
135                             // a new section that we add to the sections found in the .o file.
136                             // This new section has the file address set to what the
137                             // addresses are in the .o file, and the load address is adjusted
138                             // to match where it ended up in the final executable! We do this
139                             // before we parse any dwarf info so that when it goes get parsed
140                             // all section/offset addresses that get registered will resolve
141                             // correctly to the new addresses in the main executable. We
142                             // initially set the section size to be 1 byte, but will need to
143                             // fix up these addresses further after all globals have been
144                             // parsed to span the gaps, or we can find the global variable
145                             // sizes from the DWARF info as we are parsing.
146 
147                             // Next we find the non-stab entry that corresponds to the N_GSYM in the .o file
148                             Symbol *oso_gsym_symbol = oso_symtab->FindFirstSymbolWithNameAndType (exe_symbol->GetMangled().GetName(lldb::eLanguageTypeUnknown, Mangled::ePreferMangled),
149                                                                                                   eSymbolTypeData,
150                                                                                                   Symtab::eDebugNo,
151                                                                                                   Symtab::eVisibilityAny);
152                             if (exe_symbol && oso_gsym_symbol &&
153                                 exe_symbol->ValueIsAddress() &&
154                                 oso_gsym_symbol->ValueIsAddress())
155                             {
156                                 // Add the inverse OSO file address to debug map entry mapping
157                                 exe_symfile->AddOSOFileRange (this,
158                                                               exe_symbol->GetAddressRef().GetFileAddress(),
159                                                               oso_gsym_symbol->GetAddressRef().GetFileAddress(),
160                                                               std::min<addr_t>(exe_symbol->GetByteSize(), oso_gsym_symbol->GetByteSize()));
161                             }
162                         }
163                         break;
164                     }
165                 }
166             }
167 
168             exe_symfile->FinalizeOSOFileRanges (this);
169             // We don't need the symbols anymore for the .o files
170             oso_objfile->ClearSymtab();
171         }
172     }
173     return file_range_map;
174 }
175 
176 
177 class DebugMapModule : public Module
178 {
179 public:
180     DebugMapModule (const ModuleSP &exe_module_sp,
181                     uint32_t cu_idx,
182                     const FileSpec& file_spec,
183                     const ArchSpec& arch,
184                     const ConstString *object_name,
185                     off_t object_offset,
186                     const TimeValue *object_mod_time_ptr) :
187         Module (file_spec, arch, object_name, object_offset, object_mod_time_ptr),
188         m_exe_module_wp (exe_module_sp),
189         m_cu_idx (cu_idx)
190     {
191     }
192 
193     virtual
194     ~DebugMapModule ()
195     {
196     }
197 
198 
199     virtual SymbolVendor*
200     GetSymbolVendor(bool can_create = true, lldb_private::Stream *feedback_strm = NULL)
201     {
202         // Scope for locker
203         if (m_symfile_ap.get() || can_create == false)
204             return m_symfile_ap.get();
205 
206         ModuleSP exe_module_sp (m_exe_module_wp.lock());
207         if (exe_module_sp)
208         {
209             // Now get the object file outside of a locking scope
210             ObjectFile *oso_objfile = GetObjectFile ();
211             if (oso_objfile)
212             {
213                 Mutex::Locker locker (m_mutex);
214                 SymbolVendor* symbol_vendor = Module::GetSymbolVendor(can_create, feedback_strm);
215                 if (symbol_vendor)
216                 {
217                     // Set a pointer to this class to set our OSO DWARF file know
218                     // that the DWARF is being used along with a debug map and that
219                     // it will have the remapped sections that we do below.
220                     SymbolFileDWARF *oso_symfile = SymbolFileDWARFDebugMap::GetSymbolFileAsSymbolFileDWARF(symbol_vendor->GetSymbolFile());
221 
222                     if (!oso_symfile)
223                         return NULL;
224 
225                     ObjectFile *exe_objfile = exe_module_sp->GetObjectFile();
226                     SymbolVendor *exe_sym_vendor = exe_module_sp->GetSymbolVendor();
227 
228                     if (exe_objfile && exe_sym_vendor)
229                     {
230                         oso_symfile->SetDebugMapModule(exe_module_sp);
231                         // Set the ID of the symbol file DWARF to the index of the OSO
232                         // shifted left by 32 bits to provide a unique prefix for any
233                         // UserID's that get created in the symbol file.
234                         oso_symfile->SetID (((uint64_t)m_cu_idx + 1ull) << 32ull);
235                     }
236                     return symbol_vendor;
237                 }
238             }
239         }
240         return NULL;
241     }
242 
243 protected:
244     ModuleWP m_exe_module_wp;
245     const uint32_t m_cu_idx;
246 };
247 
248 void
249 SymbolFileDWARFDebugMap::Initialize()
250 {
251     PluginManager::RegisterPlugin (GetPluginNameStatic(),
252                                    GetPluginDescriptionStatic(),
253                                    CreateInstance);
254 }
255 
256 void
257 SymbolFileDWARFDebugMap::Terminate()
258 {
259     PluginManager::UnregisterPlugin (CreateInstance);
260 }
261 
262 
263 lldb_private::ConstString
264 SymbolFileDWARFDebugMap::GetPluginNameStatic()
265 {
266     static ConstString g_name("dwarf-debugmap");
267     return g_name;
268 }
269 
270 const char *
271 SymbolFileDWARFDebugMap::GetPluginDescriptionStatic()
272 {
273     return "DWARF and DWARF3 debug symbol file reader (debug map).";
274 }
275 
276 SymbolFile*
277 SymbolFileDWARFDebugMap::CreateInstance (ObjectFile* obj_file)
278 {
279     return new SymbolFileDWARFDebugMap (obj_file);
280 }
281 
282 
283 SymbolFileDWARFDebugMap::SymbolFileDWARFDebugMap (ObjectFile* ofile) :
284     SymbolFile(ofile),
285     m_flags(),
286     m_compile_unit_infos(),
287     m_func_indexes(),
288     m_glob_indexes(),
289     m_supports_DW_AT_APPLE_objc_complete_type (eLazyBoolCalculate)
290 {
291 }
292 
293 
294 SymbolFileDWARFDebugMap::~SymbolFileDWARFDebugMap()
295 {
296 }
297 
298 void
299 SymbolFileDWARFDebugMap::InitializeObject()
300 {
301     // Install our external AST source callbacks so we can complete Clang types.
302     llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_ap (
303         new ClangExternalASTSourceCallbacks (SymbolFileDWARFDebugMap::CompleteTagDecl,
304                                              SymbolFileDWARFDebugMap::CompleteObjCInterfaceDecl,
305                                              NULL,
306                                              SymbolFileDWARFDebugMap::LayoutRecordType,
307                                              this));
308 
309     GetClangASTContext().SetExternalSource (ast_source_ap);
310 }
311 
312 void
313 SymbolFileDWARFDebugMap::InitOSO()
314 {
315     if (m_flags.test(kHaveInitializedOSOs))
316         return;
317 
318     m_flags.set(kHaveInitializedOSOs);
319 
320     // If the object file has been stripped, there is no sense in looking further
321     // as all of the debug symbols for the debug map will not be available
322     if (m_obj_file->IsStripped())
323         return;
324 
325     // Also make sure the file type is some sort of executable. Core files, debug
326     // info files (dSYM), object files (.o files), and stub libraries all can
327     switch (m_obj_file->GetType())
328     {
329         case ObjectFile::eTypeInvalid:
330         case ObjectFile::eTypeCoreFile:
331         case ObjectFile::eTypeDebugInfo:
332         case ObjectFile::eTypeObjectFile:
333         case ObjectFile::eTypeStubLibrary:
334         case ObjectFile::eTypeUnknown:
335         case ObjectFile::eTypeJIT:
336             return;
337 
338         case ObjectFile::eTypeExecutable:
339         case ObjectFile::eTypeDynamicLinker:
340         case ObjectFile::eTypeSharedLibrary:
341             break;
342     }
343 
344     // In order to get the abilities of this plug-in, we look at the list of
345     // N_OSO entries (object files) from the symbol table and make sure that
346     // these files exist and also contain valid DWARF. If we get any of that
347     // then we return the abilities of the first N_OSO's DWARF.
348 
349     Symtab* symtab = m_obj_file->GetSymtab();
350     if (symtab)
351     {
352         Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_MAP));
353 
354         std::vector<uint32_t> oso_indexes;
355         // When a mach-o symbol is encoded, the n_type field is encoded in bits
356         // 23:16, and the n_desc field is encoded in bits 15:0.
357         //
358         // To find all N_OSO entries that are part of the DWARF + debug map
359         // we find only object file symbols with the flags value as follows:
360         // bits 23:16 == 0x66 (N_OSO)
361         // bits 15: 0 == 0x0001 (specifies this is a debug map object file)
362         const uint32_t k_oso_symbol_flags_value = 0x660001u;
363 
364         const uint32_t oso_index_count = symtab->AppendSymbolIndexesWithTypeAndFlagsValue(eSymbolTypeObjectFile, k_oso_symbol_flags_value, oso_indexes);
365 
366         if (oso_index_count > 0)
367         {
368             symtab->AppendSymbolIndexesWithType (eSymbolTypeCode, Symtab::eDebugYes, Symtab::eVisibilityAny, m_func_indexes);
369             symtab->AppendSymbolIndexesWithType (eSymbolTypeData, Symtab::eDebugYes, Symtab::eVisibilityAny, m_glob_indexes);
370 
371             symtab->SortSymbolIndexesByValue(m_func_indexes, true);
372             symtab->SortSymbolIndexesByValue(m_glob_indexes, true);
373 
374             for (uint32_t sym_idx : m_func_indexes)
375             {
376                 const Symbol *symbol = symtab->SymbolAtIndex(sym_idx);
377                 lldb::addr_t file_addr = symbol->GetAddressRef().GetFileAddress();
378                 lldb::addr_t byte_size = symbol->GetByteSize();
379                 DebugMap::Entry debug_map_entry(file_addr, byte_size, OSOEntry(sym_idx, LLDB_INVALID_ADDRESS));
380                 m_debug_map.Append(debug_map_entry);
381             }
382             for (uint32_t sym_idx : m_glob_indexes)
383             {
384                 const Symbol *symbol = symtab->SymbolAtIndex(sym_idx);
385                 lldb::addr_t file_addr = symbol->GetAddressRef().GetFileAddress();
386                 lldb::addr_t byte_size = symbol->GetByteSize();
387                 DebugMap::Entry debug_map_entry(file_addr, byte_size, OSOEntry(sym_idx, LLDB_INVALID_ADDRESS));
388                 m_debug_map.Append(debug_map_entry);
389             }
390             m_debug_map.Sort();
391 
392             m_compile_unit_infos.resize(oso_index_count);
393 
394             for (uint32_t i=0; i<oso_index_count; ++i)
395             {
396                 const uint32_t so_idx = oso_indexes[i] - 1;
397                 const uint32_t oso_idx = oso_indexes[i];
398                 const Symbol *so_symbol = symtab->SymbolAtIndex(so_idx);
399                 const Symbol *oso_symbol = symtab->SymbolAtIndex(oso_idx);
400                 if (so_symbol &&
401                     oso_symbol &&
402                     so_symbol->GetType() == eSymbolTypeSourceFile &&
403                     oso_symbol->GetType() == eSymbolTypeObjectFile)
404                 {
405                     m_compile_unit_infos[i].so_file.SetFile(so_symbol->GetName().AsCString(), false);
406                     m_compile_unit_infos[i].oso_path = oso_symbol->GetName();
407                     TimeValue oso_mod_time;
408                     oso_mod_time.OffsetWithSeconds(oso_symbol->GetIntegerValue(0));
409                     m_compile_unit_infos[i].oso_mod_time = oso_mod_time;
410                     uint32_t sibling_idx = so_symbol->GetSiblingIndex();
411                     // The sibling index can't be less that or equal to the current index "i"
412                     if (sibling_idx == UINT32_MAX)
413                     {
414                         m_obj_file->GetModule()->ReportError ("N_SO in symbol with UID %u has invalid sibling in debug map, please file a bug and attach the binary listed in this error", so_symbol->GetID());
415                     }
416                     else
417                     {
418                         const Symbol* last_symbol = symtab->SymbolAtIndex (sibling_idx - 1);
419                         m_compile_unit_infos[i].first_symbol_index = so_idx;
420                         m_compile_unit_infos[i].last_symbol_index = sibling_idx - 1;
421                         m_compile_unit_infos[i].first_symbol_id = so_symbol->GetID();
422                         m_compile_unit_infos[i].last_symbol_id = last_symbol->GetID();
423 
424                         if (log)
425                             log->Printf("Initialized OSO 0x%8.8x: file=%s", i, oso_symbol->GetName().GetCString());
426                     }
427                 }
428                 else
429                 {
430                     if (oso_symbol == NULL)
431                         m_obj_file->GetModule()->ReportError ("N_OSO symbol[%u] can't be found, please file a bug and attach the binary listed in this error", oso_idx);
432                     else if (so_symbol == NULL)
433                         m_obj_file->GetModule()->ReportError ("N_SO not found for N_OSO symbol[%u], please file a bug and attach the binary listed in this error", oso_idx);
434                     else if (so_symbol->GetType() != eSymbolTypeSourceFile)
435                         m_obj_file->GetModule()->ReportError ("N_SO has incorrect symbol type (%u) for N_OSO symbol[%u], please file a bug and attach the binary listed in this error", so_symbol->GetType(), oso_idx);
436                     else if (oso_symbol->GetType() != eSymbolTypeSourceFile)
437                         m_obj_file->GetModule()->ReportError ("N_OSO has incorrect symbol type (%u) for N_OSO symbol[%u], please file a bug and attach the binary listed in this error", oso_symbol->GetType(), oso_idx);
438                 }
439             }
440         }
441     }
442 }
443 
444 Module *
445 SymbolFileDWARFDebugMap::GetModuleByOSOIndex (uint32_t oso_idx)
446 {
447     const uint32_t cu_count = GetNumCompileUnits();
448     if (oso_idx < cu_count)
449         return GetModuleByCompUnitInfo (&m_compile_unit_infos[oso_idx]);
450     return NULL;
451 }
452 
453 Module *
454 SymbolFileDWARFDebugMap::GetModuleByCompUnitInfo (CompileUnitInfo *comp_unit_info)
455 {
456     if (!comp_unit_info->oso_sp)
457     {
458         auto pos = m_oso_map.find (comp_unit_info->oso_path);
459         if (pos != m_oso_map.end())
460         {
461             comp_unit_info->oso_sp = pos->second;
462         }
463         else
464         {
465             ObjectFile *obj_file = GetObjectFile();
466             comp_unit_info->oso_sp.reset (new OSOInfo());
467             m_oso_map[comp_unit_info->oso_path] = comp_unit_info->oso_sp;
468             const char *oso_path = comp_unit_info->oso_path.GetCString();
469             FileSpec oso_file (oso_path, false);
470             ConstString oso_object;
471             if (oso_file.Exists())
472             {
473                 TimeValue oso_mod_time (oso_file.GetModificationTime());
474                 if (oso_mod_time != comp_unit_info->oso_mod_time)
475                 {
476                     obj_file->GetModule()->ReportError ("debug map object file '%s' has changed (actual time is 0x%" PRIx64 ", debug map time is 0x%" PRIx64 ") since this executable was linked, file will be ignored",
477                                                         oso_file.GetPath().c_str(),
478                                                         oso_mod_time.GetAsSecondsSinceJan1_1970(),
479                                                         comp_unit_info->oso_mod_time.GetAsSecondsSinceJan1_1970());
480                     return NULL;
481                 }
482 
483             }
484             else
485             {
486                 const bool must_exist = true;
487 
488                 if (!ObjectFile::SplitArchivePathWithObject (oso_path,
489                                                              oso_file,
490                                                              oso_object,
491                                                              must_exist))
492                 {
493                     return NULL;
494                 }
495             }
496             // Always create a new module for .o files. Why? Because we
497             // use the debug map, to add new sections to each .o file and
498             // even though a .o file might not have changed, the sections
499             // that get added to the .o file can change.
500             ArchSpec oso_arch;
501             // Only adopt the architecture from the module (not the vendor or OS)
502             // since .o files for "i386-apple-ios" will historically show up as "i386-apple-macosx"
503             // due to the lack of a LC_VERSION_MIN_MACOSX or LC_VERSION_MIN_IPHONEOS
504             // load command...
505             oso_arch.SetTriple(m_obj_file->GetModule()->GetArchitecture().GetTriple().getArchName().str().c_str());
506             comp_unit_info->oso_sp->module_sp.reset (new DebugMapModule (obj_file->GetModule(),
507                                                                          GetCompUnitInfoIndex(comp_unit_info),
508                                                                          oso_file,
509                                                                          oso_arch,
510                                                                          oso_object ? &oso_object : NULL,
511                                                                          0,
512                                                                          oso_object ? &comp_unit_info->oso_mod_time : NULL));
513         }
514     }
515     if (comp_unit_info->oso_sp)
516         return comp_unit_info->oso_sp->module_sp.get();
517     return NULL;
518 }
519 
520 
521 bool
522 SymbolFileDWARFDebugMap::GetFileSpecForSO (uint32_t oso_idx, FileSpec &file_spec)
523 {
524     if (oso_idx < m_compile_unit_infos.size())
525     {
526         if (m_compile_unit_infos[oso_idx].so_file)
527         {
528             file_spec = m_compile_unit_infos[oso_idx].so_file;
529             return true;
530         }
531     }
532     return false;
533 }
534 
535 
536 
537 ObjectFile *
538 SymbolFileDWARFDebugMap::GetObjectFileByOSOIndex (uint32_t oso_idx)
539 {
540     Module *oso_module = GetModuleByOSOIndex (oso_idx);
541     if (oso_module)
542         return oso_module->GetObjectFile();
543     return NULL;
544 }
545 
546 SymbolFileDWARF *
547 SymbolFileDWARFDebugMap::GetSymbolFile (const SymbolContext& sc)
548 {
549     CompileUnitInfo *comp_unit_info = GetCompUnitInfo (sc);
550     if (comp_unit_info)
551         return GetSymbolFileByCompUnitInfo (comp_unit_info);
552     return NULL;
553 }
554 
555 ObjectFile *
556 SymbolFileDWARFDebugMap::GetObjectFileByCompUnitInfo (CompileUnitInfo *comp_unit_info)
557 {
558     Module *oso_module = GetModuleByCompUnitInfo (comp_unit_info);
559     if (oso_module)
560         return oso_module->GetObjectFile();
561     return NULL;
562 }
563 
564 
565 uint32_t
566 SymbolFileDWARFDebugMap::GetCompUnitInfoIndex (const CompileUnitInfo *comp_unit_info)
567 {
568     if (!m_compile_unit_infos.empty())
569     {
570         const CompileUnitInfo *first_comp_unit_info = &m_compile_unit_infos.front();
571         const CompileUnitInfo *last_comp_unit_info = &m_compile_unit_infos.back();
572         if (first_comp_unit_info <= comp_unit_info && comp_unit_info <= last_comp_unit_info)
573             return comp_unit_info - first_comp_unit_info;
574     }
575     return UINT32_MAX;
576 }
577 
578 SymbolFileDWARF *
579 SymbolFileDWARFDebugMap::GetSymbolFileByOSOIndex (uint32_t oso_idx)
580 {
581     if (oso_idx < m_compile_unit_infos.size())
582         return GetSymbolFileByCompUnitInfo (&m_compile_unit_infos[oso_idx]);
583     return NULL;
584 }
585 
586 SymbolFileDWARF *
587 SymbolFileDWARFDebugMap::GetSymbolFileAsSymbolFileDWARF (SymbolFile *sym_file)
588 {
589     if (sym_file && sym_file->GetPluginName() == SymbolFileDWARF::GetPluginNameStatic())
590         return (SymbolFileDWARF *)sym_file;
591     return NULL;
592 }
593 
594 SymbolFileDWARF *
595 SymbolFileDWARFDebugMap::GetSymbolFileByCompUnitInfo (CompileUnitInfo *comp_unit_info)
596 {
597     Module *oso_module = GetModuleByCompUnitInfo (comp_unit_info);
598     if (oso_module)
599     {
600         SymbolVendor *sym_vendor = oso_module->GetSymbolVendor();
601         if (sym_vendor)
602             return GetSymbolFileAsSymbolFileDWARF (sym_vendor->GetSymbolFile());
603     }
604     return NULL;
605 }
606 
607 uint32_t
608 SymbolFileDWARFDebugMap::CalculateAbilities ()
609 {
610     // In order to get the abilities of this plug-in, we look at the list of
611     // N_OSO entries (object files) from the symbol table and make sure that
612     // these files exist and also contain valid DWARF. If we get any of that
613     // then we return the abilities of the first N_OSO's DWARF.
614 
615     const uint32_t oso_index_count = GetNumCompileUnits();
616     if (oso_index_count > 0)
617     {
618         InitOSO();
619         if (!m_compile_unit_infos.empty())
620         {
621             return SymbolFile::CompileUnits    |
622                    SymbolFile::Functions       |
623                    SymbolFile::Blocks          |
624                    SymbolFile::GlobalVariables |
625                    SymbolFile::LocalVariables  |
626                    SymbolFile::VariableTypes   |
627                    SymbolFile::LineTables      ;
628         }
629     }
630     return 0;
631 }
632 
633 uint32_t
634 SymbolFileDWARFDebugMap::GetNumCompileUnits()
635 {
636     InitOSO ();
637     return m_compile_unit_infos.size();
638 }
639 
640 
641 CompUnitSP
642 SymbolFileDWARFDebugMap::ParseCompileUnitAtIndex(uint32_t cu_idx)
643 {
644     CompUnitSP comp_unit_sp;
645     const uint32_t cu_count = GetNumCompileUnits();
646 
647     if (cu_idx < cu_count)
648     {
649         Module *oso_module = GetModuleByCompUnitInfo (&m_compile_unit_infos[cu_idx]);
650         if (oso_module)
651         {
652             FileSpec so_file_spec;
653             if (GetFileSpecForSO (cu_idx, so_file_spec))
654             {
655                 // User zero as the ID to match the compile unit at offset
656                 // zero in each .o file since each .o file can only have
657                 // one compile unit for now.
658                 lldb::user_id_t cu_id = 0;
659                 m_compile_unit_infos[cu_idx].compile_unit_sp.reset(new CompileUnit (m_obj_file->GetModule(),
660                                                                                     NULL,
661                                                                                     so_file_spec,
662                                                                                     cu_id,
663                                                                                     eLanguageTypeUnknown,
664                                                                                     false));
665 
666                 if (m_compile_unit_infos[cu_idx].compile_unit_sp)
667                 {
668                     // Let our symbol vendor know about this compile unit
669                     m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex (cu_idx, m_compile_unit_infos[cu_idx].compile_unit_sp);
670                 }
671             }
672         }
673         comp_unit_sp = m_compile_unit_infos[cu_idx].compile_unit_sp;
674     }
675 
676     return comp_unit_sp;
677 }
678 
679 SymbolFileDWARFDebugMap::CompileUnitInfo *
680 SymbolFileDWARFDebugMap::GetCompUnitInfo (const SymbolContext& sc)
681 {
682     const uint32_t cu_count = GetNumCompileUnits();
683     for (uint32_t i=0; i<cu_count; ++i)
684     {
685         if (sc.comp_unit == m_compile_unit_infos[i].compile_unit_sp.get())
686             return &m_compile_unit_infos[i];
687     }
688     return NULL;
689 }
690 
691 
692 size_t
693 SymbolFileDWARFDebugMap::GetCompUnitInfosForModule (const lldb_private::Module *module, std::vector<CompileUnitInfo *>& cu_infos)
694 {
695     const uint32_t cu_count = GetNumCompileUnits();
696     for (uint32_t i=0; i<cu_count; ++i)
697     {
698         if (module == GetModuleByCompUnitInfo (&m_compile_unit_infos[i]))
699             cu_infos.push_back (&m_compile_unit_infos[i]);
700     }
701     return cu_infos.size();
702 }
703 
704 lldb::LanguageType
705 SymbolFileDWARFDebugMap::ParseCompileUnitLanguage (const SymbolContext& sc)
706 {
707     SymbolFileDWARF *oso_dwarf = GetSymbolFile (sc);
708     if (oso_dwarf)
709         return oso_dwarf->ParseCompileUnitLanguage (sc);
710     return eLanguageTypeUnknown;
711 }
712 
713 size_t
714 SymbolFileDWARFDebugMap::ParseCompileUnitFunctions (const SymbolContext& sc)
715 {
716     SymbolFileDWARF *oso_dwarf = GetSymbolFile (sc);
717     if (oso_dwarf)
718         return oso_dwarf->ParseCompileUnitFunctions (sc);
719     return 0;
720 }
721 
722 bool
723 SymbolFileDWARFDebugMap::ParseCompileUnitLineTable (const SymbolContext& sc)
724 {
725     SymbolFileDWARF *oso_dwarf = GetSymbolFile (sc);
726     if (oso_dwarf)
727         return oso_dwarf->ParseCompileUnitLineTable (sc);
728     return false;
729 }
730 
731 bool
732 SymbolFileDWARFDebugMap::ParseCompileUnitSupportFiles (const SymbolContext& sc, FileSpecList &support_files)
733 {
734     SymbolFileDWARF *oso_dwarf = GetSymbolFile (sc);
735     if (oso_dwarf)
736         return oso_dwarf->ParseCompileUnitSupportFiles (sc, support_files);
737     return false;
738 }
739 
740 bool
741 SymbolFileDWARFDebugMap::ParseImportedModules (const SymbolContext &sc, std::vector<ConstString> &imported_modules)
742 {
743     SymbolFileDWARF *oso_dwarf = GetSymbolFile (sc);
744     if (oso_dwarf)
745         return oso_dwarf->ParseImportedModules(sc, imported_modules);
746     return false;
747 }
748 
749 size_t
750 SymbolFileDWARFDebugMap::ParseFunctionBlocks (const SymbolContext& sc)
751 {
752     SymbolFileDWARF *oso_dwarf = GetSymbolFile (sc);
753     if (oso_dwarf)
754         return oso_dwarf->ParseFunctionBlocks (sc);
755     return 0;
756 }
757 
758 
759 size_t
760 SymbolFileDWARFDebugMap::ParseTypes (const SymbolContext& sc)
761 {
762     SymbolFileDWARF *oso_dwarf = GetSymbolFile (sc);
763     if (oso_dwarf)
764         return oso_dwarf->ParseTypes (sc);
765     return 0;
766 }
767 
768 
769 size_t
770 SymbolFileDWARFDebugMap::ParseVariablesForContext (const SymbolContext& sc)
771 {
772     SymbolFileDWARF *oso_dwarf = GetSymbolFile (sc);
773     if (oso_dwarf)
774         return oso_dwarf->ParseVariablesForContext (sc);
775     return 0;
776 }
777 
778 
779 
780 Type*
781 SymbolFileDWARFDebugMap::ResolveTypeUID(lldb::user_id_t type_uid)
782 {
783     const uint64_t oso_idx = GetOSOIndexFromUserID (type_uid);
784     SymbolFileDWARF *oso_dwarf = GetSymbolFileByOSOIndex (oso_idx);
785     if (oso_dwarf)
786         return oso_dwarf->ResolveTypeUID (type_uid);
787     return NULL;
788 }
789 
790 bool
791 SymbolFileDWARFDebugMap::ResolveClangOpaqueTypeDefinition (CompilerType& clang_type)
792 {
793     // We have a struct/union/class/enum that needs to be fully resolved.
794     return false;
795 }
796 
797 uint32_t
798 SymbolFileDWARFDebugMap::ResolveSymbolContext (const Address& exe_so_addr, uint32_t resolve_scope, SymbolContext& sc)
799 {
800     uint32_t resolved_flags = 0;
801     Symtab* symtab = m_obj_file->GetSymtab();
802     if (symtab)
803     {
804         const addr_t exe_file_addr = exe_so_addr.GetFileAddress();
805 
806         const DebugMap::Entry *debug_map_entry = m_debug_map.FindEntryThatContains (exe_file_addr);
807         if (debug_map_entry)
808         {
809 
810             sc.symbol = symtab->SymbolAtIndex(debug_map_entry->data.GetExeSymbolIndex());
811 
812             if (sc.symbol != NULL)
813             {
814                 resolved_flags |= eSymbolContextSymbol;
815 
816                 uint32_t oso_idx = 0;
817                 CompileUnitInfo* comp_unit_info = GetCompileUnitInfoForSymbolWithID (sc.symbol->GetID(), &oso_idx);
818                 if (comp_unit_info)
819                 {
820                     comp_unit_info->GetFileRangeMap(this);
821                     Module *oso_module = GetModuleByCompUnitInfo (comp_unit_info);
822                     if (oso_module)
823                     {
824                         lldb::addr_t oso_file_addr = exe_file_addr - debug_map_entry->GetRangeBase() + debug_map_entry->data.GetOSOFileAddress();
825                         Address oso_so_addr;
826                         if (oso_module->ResolveFileAddress(oso_file_addr, oso_so_addr))
827                         {
828                             resolved_flags |= oso_module->GetSymbolVendor()->ResolveSymbolContext (oso_so_addr, resolve_scope, sc);
829                         }
830                     }
831                 }
832             }
833         }
834     }
835     return resolved_flags;
836 }
837 
838 
839 uint32_t
840 SymbolFileDWARFDebugMap::ResolveSymbolContext (const FileSpec& file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
841 {
842     const uint32_t initial = sc_list.GetSize();
843     const uint32_t cu_count = GetNumCompileUnits();
844 
845     for (uint32_t i=0; i<cu_count; ++i)
846     {
847         // If we are checking for inlines, then we need to look through all
848         // compile units no matter if "file_spec" matches.
849         bool resolve = check_inlines;
850 
851         if (!resolve)
852         {
853             FileSpec so_file_spec;
854             if (GetFileSpecForSO (i, so_file_spec))
855             {
856                 // Match the full path if the incoming file_spec has a directory (not just a basename)
857                 const bool full_match = (bool)file_spec.GetDirectory();
858                 resolve = FileSpec::Equal (file_spec, so_file_spec, full_match);
859             }
860         }
861         if (resolve)
862         {
863             SymbolFileDWARF *oso_dwarf = GetSymbolFileByOSOIndex (i);
864             if (oso_dwarf)
865                 oso_dwarf->ResolveSymbolContext(file_spec, line, check_inlines, resolve_scope, sc_list);
866         }
867     }
868     return sc_list.GetSize() - initial;
869 }
870 
871 uint32_t
872 SymbolFileDWARFDebugMap::PrivateFindGlobalVariables
873 (
874     const ConstString &name,
875     const ClangNamespaceDecl *namespace_decl,
876     const std::vector<uint32_t> &indexes,   // Indexes into the symbol table that match "name"
877     uint32_t max_matches,
878     VariableList& variables
879 )
880 {
881     const uint32_t original_size = variables.GetSize();
882     const size_t match_count = indexes.size();
883     for (size_t i=0; i<match_count; ++i)
884     {
885         uint32_t oso_idx;
886         CompileUnitInfo* comp_unit_info = GetCompileUnitInfoForSymbolWithIndex (indexes[i], &oso_idx);
887         if (comp_unit_info)
888         {
889             SymbolFileDWARF *oso_dwarf = GetSymbolFileByOSOIndex (oso_idx);
890             if (oso_dwarf)
891             {
892                 if (oso_dwarf->FindGlobalVariables(name, namespace_decl, true, max_matches, variables))
893                     if (variables.GetSize() > max_matches)
894                         break;
895             }
896         }
897     }
898     return variables.GetSize() - original_size;
899 }
900 
901 uint32_t
902 SymbolFileDWARFDebugMap::FindGlobalVariables (const ConstString &name, const ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, VariableList& variables)
903 {
904 
905     // If we aren't appending the results to this list, then clear the list
906     if (!append)
907         variables.Clear();
908 
909     // Remember how many variables are in the list before we search in case
910     // we are appending the results to a variable list.
911     const uint32_t original_size = variables.GetSize();
912 
913     uint32_t total_matches = 0;
914 
915     ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
916         const uint32_t oso_matches = oso_dwarf->FindGlobalVariables (name,
917                                                                      namespace_decl,
918                                                                      true,
919                                                                      max_matches,
920                                                                      variables);
921         if (oso_matches > 0)
922         {
923             total_matches += oso_matches;
924 
925             // Are we getting all matches?
926             if (max_matches == UINT32_MAX)
927                 return false;   // Yep, continue getting everything
928 
929             // If we have found enough matches, lets get out
930             if (max_matches >= total_matches)
931                 return true;
932 
933             // Update the max matches for any subsequent calls to find globals
934             // in any other object files with DWARF
935             max_matches -= oso_matches;
936         }
937 
938         return false;
939     });
940 
941     // Return the number of variable that were appended to the list
942     return variables.GetSize() - original_size;
943 }
944 
945 
946 uint32_t
947 SymbolFileDWARFDebugMap::FindGlobalVariables (const RegularExpression& regex, bool append, uint32_t max_matches, VariableList& variables)
948 {
949     // If we aren't appending the results to this list, then clear the list
950     if (!append)
951         variables.Clear();
952 
953     // Remember how many variables are in the list before we search in case
954     // we are appending the results to a variable list.
955     const uint32_t original_size = variables.GetSize();
956 
957     uint32_t total_matches = 0;
958     ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
959         const uint32_t oso_matches = oso_dwarf->FindGlobalVariables (regex,
960                                                                      true,
961                                                                      max_matches,
962                                                                      variables);
963         if (oso_matches > 0)
964         {
965             total_matches += oso_matches;
966 
967             // Are we getting all matches?
968             if (max_matches == UINT32_MAX)
969                 return false;   // Yep, continue getting everything
970 
971             // If we have found enough matches, lets get out
972             if (max_matches >= total_matches)
973                 return true;
974 
975             // Update the max matches for any subsequent calls to find globals
976             // in any other object files with DWARF
977             max_matches -= oso_matches;
978         }
979 
980         return false;
981     });
982 
983     // Return the number of variable that were appended to the list
984     return variables.GetSize() - original_size;
985 }
986 
987 
988 int
989 SymbolFileDWARFDebugMap::SymbolContainsSymbolWithIndex (uint32_t *symbol_idx_ptr, const CompileUnitInfo *comp_unit_info)
990 {
991     const uint32_t symbol_idx = *symbol_idx_ptr;
992 
993     if (symbol_idx < comp_unit_info->first_symbol_index)
994         return -1;
995 
996     if (symbol_idx <= comp_unit_info->last_symbol_index)
997         return 0;
998 
999     return 1;
1000 }
1001 
1002 
1003 int
1004 SymbolFileDWARFDebugMap::SymbolContainsSymbolWithID (user_id_t *symbol_idx_ptr, const CompileUnitInfo *comp_unit_info)
1005 {
1006     const user_id_t symbol_id = *symbol_idx_ptr;
1007 
1008     if (symbol_id < comp_unit_info->first_symbol_id)
1009         return -1;
1010 
1011     if (symbol_id <= comp_unit_info->last_symbol_id)
1012         return 0;
1013 
1014     return 1;
1015 }
1016 
1017 
1018 SymbolFileDWARFDebugMap::CompileUnitInfo*
1019 SymbolFileDWARFDebugMap::GetCompileUnitInfoForSymbolWithIndex (uint32_t symbol_idx, uint32_t *oso_idx_ptr)
1020 {
1021     const uint32_t oso_index_count = m_compile_unit_infos.size();
1022     CompileUnitInfo *comp_unit_info = NULL;
1023     if (oso_index_count)
1024     {
1025         comp_unit_info = (CompileUnitInfo*)bsearch(&symbol_idx,
1026                                                    &m_compile_unit_infos[0],
1027                                                    m_compile_unit_infos.size(),
1028                                                    sizeof(CompileUnitInfo),
1029                                                    (ComparisonFunction)SymbolContainsSymbolWithIndex);
1030     }
1031 
1032     if (oso_idx_ptr)
1033     {
1034         if (comp_unit_info != NULL)
1035             *oso_idx_ptr = comp_unit_info - &m_compile_unit_infos[0];
1036         else
1037             *oso_idx_ptr = UINT32_MAX;
1038     }
1039     return comp_unit_info;
1040 }
1041 
1042 SymbolFileDWARFDebugMap::CompileUnitInfo*
1043 SymbolFileDWARFDebugMap::GetCompileUnitInfoForSymbolWithID (user_id_t symbol_id, uint32_t *oso_idx_ptr)
1044 {
1045     const uint32_t oso_index_count = m_compile_unit_infos.size();
1046     CompileUnitInfo *comp_unit_info = NULL;
1047     if (oso_index_count)
1048     {
1049         comp_unit_info = (CompileUnitInfo*)::bsearch (&symbol_id,
1050                                                       &m_compile_unit_infos[0],
1051                                                       m_compile_unit_infos.size(),
1052                                                       sizeof(CompileUnitInfo),
1053                                                       (ComparisonFunction)SymbolContainsSymbolWithID);
1054     }
1055 
1056     if (oso_idx_ptr)
1057     {
1058         if (comp_unit_info != NULL)
1059             *oso_idx_ptr = comp_unit_info - &m_compile_unit_infos[0];
1060         else
1061             *oso_idx_ptr = UINT32_MAX;
1062     }
1063     return comp_unit_info;
1064 }
1065 
1066 
1067 static void
1068 RemoveFunctionsWithModuleNotEqualTo (const ModuleSP &module_sp, SymbolContextList &sc_list, uint32_t start_idx)
1069 {
1070     // We found functions in .o files. Not all functions in the .o files
1071     // will have made it into the final output file. The ones that did
1072     // make it into the final output file will have a section whose module
1073     // matches the module from the ObjectFile for this SymbolFile. When
1074     // the modules don't match, then we have something that was in a
1075     // .o file, but doesn't map to anything in the final executable.
1076     uint32_t i=start_idx;
1077     while (i < sc_list.GetSize())
1078     {
1079         SymbolContext sc;
1080         sc_list.GetContextAtIndex(i, sc);
1081         if (sc.function)
1082         {
1083             const SectionSP section_sp (sc.function->GetAddressRange().GetBaseAddress().GetSection());
1084             if (section_sp->GetModule() != module_sp)
1085             {
1086                 sc_list.RemoveContextAtIndex(i);
1087                 continue;
1088             }
1089         }
1090         ++i;
1091     }
1092 }
1093 
1094 uint32_t
1095 SymbolFileDWARFDebugMap::FindFunctions(const ConstString &name, const ClangNamespaceDecl *namespace_decl, uint32_t name_type_mask, bool include_inlines, bool append, SymbolContextList& sc_list)
1096 {
1097     Timer scoped_timer (__PRETTY_FUNCTION__,
1098                         "SymbolFileDWARFDebugMap::FindFunctions (name = %s)",
1099                         name.GetCString());
1100 
1101     uint32_t initial_size = 0;
1102     if (append)
1103         initial_size = sc_list.GetSize();
1104     else
1105         sc_list.Clear();
1106 
1107     ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
1108         uint32_t sc_idx = sc_list.GetSize();
1109         if (oso_dwarf->FindFunctions(name, namespace_decl, name_type_mask, include_inlines, true, sc_list))
1110         {
1111             RemoveFunctionsWithModuleNotEqualTo (m_obj_file->GetModule(), sc_list, sc_idx);
1112         }
1113         return false;
1114     });
1115 
1116     return sc_list.GetSize() - initial_size;
1117 }
1118 
1119 
1120 uint32_t
1121 SymbolFileDWARFDebugMap::FindFunctions (const RegularExpression& regex, bool include_inlines, bool append, SymbolContextList& sc_list)
1122 {
1123     Timer scoped_timer (__PRETTY_FUNCTION__,
1124                         "SymbolFileDWARFDebugMap::FindFunctions (regex = '%s')",
1125                         regex.GetText());
1126 
1127     uint32_t initial_size = 0;
1128     if (append)
1129         initial_size = sc_list.GetSize();
1130     else
1131         sc_list.Clear();
1132 
1133     ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
1134         uint32_t sc_idx = sc_list.GetSize();
1135 
1136         if (oso_dwarf->FindFunctions(regex, include_inlines, true, sc_list))
1137         {
1138             RemoveFunctionsWithModuleNotEqualTo (m_obj_file->GetModule(), sc_list, sc_idx);
1139         }
1140         return false;
1141     });
1142 
1143     return sc_list.GetSize() - initial_size;
1144 }
1145 
1146 size_t
1147 SymbolFileDWARFDebugMap::GetTypes (SymbolContextScope *sc_scope,
1148                                    uint32_t type_mask,
1149                                    TypeList &type_list)
1150 {
1151     Timer scoped_timer (__PRETTY_FUNCTION__,
1152                         "SymbolFileDWARFDebugMap::GetTypes (type_mask = 0x%8.8x)",
1153                         type_mask);
1154 
1155 
1156     uint32_t initial_size = type_list.GetSize();
1157     SymbolFileDWARF *oso_dwarf = NULL;
1158     if (sc_scope)
1159     {
1160         SymbolContext sc;
1161         sc_scope->CalculateSymbolContext(&sc);
1162 
1163         CompileUnitInfo *cu_info = GetCompUnitInfo (sc);
1164         if (cu_info)
1165         {
1166             oso_dwarf = GetSymbolFileByCompUnitInfo (cu_info);
1167             if (oso_dwarf)
1168                 oso_dwarf->GetTypes (sc_scope, type_mask, type_list);
1169         }
1170     }
1171     else
1172     {
1173         ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
1174             oso_dwarf->GetTypes (sc_scope, type_mask, type_list);
1175             return false;
1176         });
1177     }
1178     return type_list.GetSize() - initial_size;
1179 }
1180 
1181 
1182 TypeSP
1183 SymbolFileDWARFDebugMap::FindDefinitionTypeForDWARFDeclContext (const DWARFDeclContext &die_decl_ctx)
1184 {
1185     TypeSP type_sp;
1186     ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
1187         type_sp = oso_dwarf->FindDefinitionTypeForDWARFDeclContext (die_decl_ctx);
1188         return ((bool)type_sp);
1189     });
1190     return type_sp;
1191 }
1192 
1193 
1194 
1195 bool
1196 SymbolFileDWARFDebugMap::Supports_DW_AT_APPLE_objc_complete_type (SymbolFileDWARF *skip_dwarf_oso)
1197 {
1198     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate)
1199     {
1200         m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
1201         ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
1202             if (skip_dwarf_oso != oso_dwarf && oso_dwarf->Supports_DW_AT_APPLE_objc_complete_type(NULL))
1203             {
1204                 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
1205                 return true;
1206             }
1207             return false;
1208         });
1209     }
1210     return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
1211 }
1212 
1213 TypeSP
1214 SymbolFileDWARFDebugMap::FindCompleteObjCDefinitionTypeForDIE (const DWARFDebugInfoEntry *die,
1215                                                                const ConstString &type_name,
1216                                                                bool must_be_implementation)
1217 {
1218     // If we have a debug map, we will have an Objective C symbol whose name is
1219     // the type name and whose type is eSymbolTypeObjCClass. If we can find that
1220     // symbol and find its containing parent, we can locate the .o file that will
1221     // contain the implementation definition since it will be scoped inside the N_SO
1222     // and we can then locate the SymbolFileDWARF that corresponds to that N_SO.
1223     SymbolFileDWARF *oso_dwarf = NULL;
1224     TypeSP type_sp;
1225     ObjectFile *module_objfile = m_obj_file->GetModule()->GetObjectFile();
1226     if (module_objfile)
1227     {
1228         Symtab *symtab = module_objfile->GetSymtab();
1229         if (symtab)
1230         {
1231             Symbol *objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(type_name, eSymbolTypeObjCClass, Symtab::eDebugAny, Symtab::eVisibilityAny);
1232             if (objc_class_symbol)
1233             {
1234                 // Get the N_SO symbol that contains the objective C class symbol as this
1235                 // should be the .o file that contains the real definition...
1236                 const Symbol *source_file_symbol = symtab->GetParent(objc_class_symbol);
1237 
1238                 if (source_file_symbol && source_file_symbol->GetType() == eSymbolTypeSourceFile)
1239                 {
1240                     const uint32_t source_file_symbol_idx = symtab->GetIndexForSymbol(source_file_symbol);
1241                     if (source_file_symbol_idx != UINT32_MAX)
1242                     {
1243                         CompileUnitInfo *compile_unit_info = GetCompileUnitInfoForSymbolWithIndex (source_file_symbol_idx, NULL);
1244                         if (compile_unit_info)
1245                         {
1246                             oso_dwarf = GetSymbolFileByCompUnitInfo (compile_unit_info);
1247                             if (oso_dwarf)
1248                             {
1249                                 TypeSP type_sp (oso_dwarf->FindCompleteObjCDefinitionTypeForDIE (die, type_name, must_be_implementation));
1250                                 if (type_sp)
1251                                 {
1252                                     return type_sp;
1253                                 }
1254                             }
1255                         }
1256                     }
1257                 }
1258             }
1259         }
1260     }
1261 
1262     // Only search all .o files for the definition if we don't need the implementation
1263     // because otherwise, with a valid debug map we should have the ObjC class symbol and
1264     // the code above should have found it.
1265     if (must_be_implementation == false)
1266     {
1267         TypeSP type_sp;
1268 
1269         ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
1270             type_sp = oso_dwarf->FindCompleteObjCDefinitionTypeForDIE (die, type_name, must_be_implementation);
1271             return (bool)type_sp;
1272         });
1273 
1274         return type_sp;
1275     }
1276     return TypeSP();
1277 }
1278 
1279 uint32_t
1280 SymbolFileDWARFDebugMap::FindTypes
1281 (
1282     const SymbolContext& sc,
1283     const ConstString &name,
1284     const ClangNamespaceDecl *namespace_decl,
1285     bool append,
1286     uint32_t max_matches,
1287     TypeList& types
1288 )
1289 {
1290     if (!append)
1291         types.Clear();
1292 
1293     const uint32_t initial_types_size = types.GetSize();
1294     SymbolFileDWARF *oso_dwarf;
1295 
1296     if (sc.comp_unit)
1297     {
1298         oso_dwarf = GetSymbolFile (sc);
1299         if (oso_dwarf)
1300             return oso_dwarf->FindTypes (sc, name, namespace_decl, append, max_matches, types);
1301     }
1302     else
1303     {
1304         ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
1305             oso_dwarf->FindTypes (sc, name, namespace_decl, append, max_matches, types);
1306             return false;
1307         });
1308     }
1309 
1310     return types.GetSize() - initial_types_size;
1311 }
1312 
1313 //
1314 //uint32_t
1315 //SymbolFileDWARFDebugMap::FindTypes (const SymbolContext& sc, const RegularExpression& regex, bool append, uint32_t max_matches, Type::Encoding encoding, lldb::user_id_t udt_uid, TypeList& types)
1316 //{
1317 //  SymbolFileDWARF *oso_dwarf = GetSymbolFile (sc);
1318 //  if (oso_dwarf)
1319 //      return oso_dwarf->FindTypes (sc, regex, append, max_matches, encoding, udt_uid, types);
1320 //  return 0;
1321 //}
1322 
1323 
1324 ClangNamespaceDecl
1325 SymbolFileDWARFDebugMap::FindNamespace (const lldb_private::SymbolContext& sc,
1326                                         const lldb_private::ConstString &name,
1327                                         const ClangNamespaceDecl *parent_namespace_decl)
1328 {
1329     ClangNamespaceDecl matching_namespace;
1330     SymbolFileDWARF *oso_dwarf;
1331 
1332     if (sc.comp_unit)
1333     {
1334         oso_dwarf = GetSymbolFile (sc);
1335         if (oso_dwarf)
1336             matching_namespace = oso_dwarf->FindNamespace (sc, name, parent_namespace_decl);
1337     }
1338     else
1339     {
1340         ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
1341             matching_namespace = oso_dwarf->FindNamespace (sc, name, parent_namespace_decl);
1342 
1343             return (bool)matching_namespace;
1344         });
1345     }
1346 
1347     return matching_namespace;
1348 }
1349 
1350 //------------------------------------------------------------------
1351 // PluginInterface protocol
1352 //------------------------------------------------------------------
1353 lldb_private::ConstString
1354 SymbolFileDWARFDebugMap::GetPluginName()
1355 {
1356     return GetPluginNameStatic();
1357 }
1358 
1359 uint32_t
1360 SymbolFileDWARFDebugMap::GetPluginVersion()
1361 {
1362     return 1;
1363 }
1364 
1365 lldb::CompUnitSP
1366 SymbolFileDWARFDebugMap::GetCompileUnit (SymbolFileDWARF *oso_dwarf)
1367 {
1368     if (oso_dwarf)
1369     {
1370         const uint32_t cu_count = GetNumCompileUnits();
1371         for (uint32_t cu_idx=0; cu_idx<cu_count; ++cu_idx)
1372         {
1373             SymbolFileDWARF *oso_symfile = GetSymbolFileByCompUnitInfo (&m_compile_unit_infos[cu_idx]);
1374             if (oso_symfile == oso_dwarf)
1375             {
1376                 if (!m_compile_unit_infos[cu_idx].compile_unit_sp)
1377                     m_compile_unit_infos[cu_idx].compile_unit_sp = ParseCompileUnitAtIndex (cu_idx);
1378 
1379                 return m_compile_unit_infos[cu_idx].compile_unit_sp;
1380             }
1381         }
1382     }
1383     assert(!"this shouldn't happen");
1384     return lldb::CompUnitSP();
1385 }
1386 
1387 SymbolFileDWARFDebugMap::CompileUnitInfo *
1388 SymbolFileDWARFDebugMap::GetCompileUnitInfo (SymbolFileDWARF *oso_dwarf)
1389 {
1390     if (oso_dwarf)
1391     {
1392         const uint32_t cu_count = GetNumCompileUnits();
1393         for (uint32_t cu_idx=0; cu_idx<cu_count; ++cu_idx)
1394         {
1395             SymbolFileDWARF *oso_symfile = GetSymbolFileByCompUnitInfo (&m_compile_unit_infos[cu_idx]);
1396             if (oso_symfile == oso_dwarf)
1397             {
1398                 return &m_compile_unit_infos[cu_idx];
1399             }
1400         }
1401     }
1402     return NULL;
1403 }
1404 
1405 
1406 void
1407 SymbolFileDWARFDebugMap::SetCompileUnit (SymbolFileDWARF *oso_dwarf, const CompUnitSP &cu_sp)
1408 {
1409     if (oso_dwarf)
1410     {
1411         const uint32_t cu_count = GetNumCompileUnits();
1412         for (uint32_t cu_idx=0; cu_idx<cu_count; ++cu_idx)
1413         {
1414             SymbolFileDWARF *oso_symfile = GetSymbolFileByCompUnitInfo (&m_compile_unit_infos[cu_idx]);
1415             if (oso_symfile == oso_dwarf)
1416             {
1417                 if (m_compile_unit_infos[cu_idx].compile_unit_sp)
1418                 {
1419                     assert (m_compile_unit_infos[cu_idx].compile_unit_sp.get() == cu_sp.get());
1420                 }
1421                 else
1422                 {
1423                     m_compile_unit_infos[cu_idx].compile_unit_sp = cu_sp;
1424                     m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(cu_idx, cu_sp);
1425                 }
1426             }
1427         }
1428     }
1429 }
1430 
1431 
1432 void
1433 SymbolFileDWARFDebugMap::CompleteTagDecl (void *baton, clang::TagDecl *decl)
1434 {
1435     SymbolFileDWARFDebugMap *symbol_file_dwarf = (SymbolFileDWARFDebugMap *)baton;
1436     CompilerType clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
1437     if (clang_type)
1438     {
1439         symbol_file_dwarf->ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
1440             if (oso_dwarf->HasForwardDeclForClangType (clang_type))
1441             {
1442                 oso_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
1443                 return true;
1444             }
1445             return false;
1446         });
1447     }
1448 }
1449 
1450 void
1451 SymbolFileDWARFDebugMap::CompleteObjCInterfaceDecl (void *baton, clang::ObjCInterfaceDecl *decl)
1452 {
1453     SymbolFileDWARFDebugMap *symbol_file_dwarf = (SymbolFileDWARFDebugMap *)baton;
1454     CompilerType clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
1455     if (clang_type)
1456     {
1457         symbol_file_dwarf->ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
1458             if (oso_dwarf->HasForwardDeclForClangType (clang_type))
1459             {
1460                 oso_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
1461                 return true;
1462             }
1463             return false;
1464         });
1465     }
1466 }
1467 
1468 bool
1469 SymbolFileDWARFDebugMap::LayoutRecordType(void *baton, const clang::RecordDecl *record_decl, uint64_t &size,
1470                                           uint64_t &alignment,
1471                                           llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
1472                                           llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> &base_offsets,
1473                                           llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> &vbase_offsets)
1474 {
1475     SymbolFileDWARFDebugMap *symbol_file_dwarf = (SymbolFileDWARFDebugMap *)baton;
1476     bool laid_out = false;
1477     symbol_file_dwarf->ForEachSymbolFile([&](SymbolFileDWARF *oso_dwarf) -> bool {
1478         return (laid_out = oso_dwarf->LayoutRecordType (record_decl, size, alignment, field_offsets, base_offsets, vbase_offsets));
1479     });
1480     return laid_out;
1481 }
1482 
1483 
1484 
1485 clang::DeclContext*
1486 SymbolFileDWARFDebugMap::GetClangDeclContextContainingTypeUID (lldb::user_id_t type_uid)
1487 {
1488     const uint64_t oso_idx = GetOSOIndexFromUserID (type_uid);
1489     SymbolFileDWARF *oso_dwarf = GetSymbolFileByOSOIndex (oso_idx);
1490     if (oso_dwarf)
1491         return oso_dwarf->GetClangDeclContextContainingTypeUID (type_uid);
1492     return NULL;
1493 }
1494 
1495 clang::DeclContext*
1496 SymbolFileDWARFDebugMap::GetClangDeclContextForTypeUID (const lldb_private::SymbolContext &sc, lldb::user_id_t type_uid)
1497 {
1498     const uint64_t oso_idx = GetOSOIndexFromUserID (type_uid);
1499     SymbolFileDWARF *oso_dwarf = GetSymbolFileByOSOIndex (oso_idx);
1500     if (oso_dwarf)
1501         return oso_dwarf->GetClangDeclContextForTypeUID (sc, type_uid);
1502     return NULL;
1503 }
1504 
1505 bool
1506 SymbolFileDWARFDebugMap::AddOSOFileRange (CompileUnitInfo *cu_info,
1507                                           lldb::addr_t exe_file_addr,
1508                                           lldb::addr_t oso_file_addr,
1509                                           lldb::addr_t oso_byte_size)
1510 {
1511     const uint32_t debug_map_idx = m_debug_map.FindEntryIndexThatContains(exe_file_addr);
1512     if (debug_map_idx != UINT32_MAX)
1513     {
1514         DebugMap::Entry *debug_map_entry = m_debug_map.FindEntryThatContains(exe_file_addr);
1515         debug_map_entry->data.SetOSOFileAddress(oso_file_addr);
1516         cu_info->file_range_map.Append(FileRangeMap::Entry(oso_file_addr, oso_byte_size, exe_file_addr));
1517         return true;
1518     }
1519     return false;
1520 }
1521 
1522 void
1523 SymbolFileDWARFDebugMap::FinalizeOSOFileRanges (CompileUnitInfo *cu_info)
1524 {
1525     cu_info->file_range_map.Sort();
1526 #if defined(DEBUG_OSO_DMAP)
1527     const FileRangeMap &oso_file_range_map = cu_info->GetFileRangeMap(this);
1528     const size_t n = oso_file_range_map.GetSize();
1529     printf ("SymbolFileDWARFDebugMap::FinalizeOSOFileRanges (cu_info = %p) %s\n",
1530             cu_info,
1531             cu_info->oso_sp->module_sp->GetFileSpec().GetPath().c_str());
1532     for (size_t i=0; i<n; ++i)
1533     {
1534         const FileRangeMap::Entry &entry = oso_file_range_map.GetEntryRef(i);
1535         printf ("oso [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") ==> exe [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")\n",
1536                 entry.GetRangeBase(), entry.GetRangeEnd(),
1537                 entry.data, entry.data + entry.GetByteSize());
1538     }
1539 #endif
1540 }
1541 
1542 lldb::addr_t
1543 SymbolFileDWARFDebugMap::LinkOSOFileAddress (SymbolFileDWARF *oso_symfile, lldb::addr_t oso_file_addr)
1544 {
1545     CompileUnitInfo *cu_info = GetCompileUnitInfo (oso_symfile);
1546     if (cu_info)
1547     {
1548         const FileRangeMap::Entry *oso_range_entry = cu_info->GetFileRangeMap(this).FindEntryThatContains(oso_file_addr);
1549         if (oso_range_entry)
1550         {
1551             const DebugMap::Entry *debug_map_entry = m_debug_map.FindEntryThatContains(oso_range_entry->data);
1552             if (debug_map_entry)
1553             {
1554                 const lldb::addr_t offset = oso_file_addr - oso_range_entry->GetRangeBase();
1555                 const lldb::addr_t exe_file_addr = debug_map_entry->GetRangeBase() + offset;
1556                 return exe_file_addr;
1557             }
1558         }
1559     }
1560     return LLDB_INVALID_ADDRESS;
1561 }
1562 
1563 bool
1564 SymbolFileDWARFDebugMap::LinkOSOAddress (Address &addr)
1565 {
1566     // Make sure this address hasn't been fixed already
1567     Module *exe_module = GetObjectFile()->GetModule().get();
1568     Module *addr_module = addr.GetModule().get();
1569     if (addr_module == exe_module)
1570         return true; // Address is already in terms of the main executable module
1571 
1572     CompileUnitInfo *cu_info = GetCompileUnitInfo (GetSymbolFileAsSymbolFileDWARF(addr_module->GetSymbolVendor()->GetSymbolFile()));
1573     if (cu_info)
1574     {
1575         const lldb::addr_t oso_file_addr = addr.GetFileAddress();
1576         const FileRangeMap::Entry *oso_range_entry = cu_info->GetFileRangeMap(this).FindEntryThatContains(oso_file_addr);
1577         if (oso_range_entry)
1578         {
1579             const DebugMap::Entry *debug_map_entry = m_debug_map.FindEntryThatContains(oso_range_entry->data);
1580             if (debug_map_entry)
1581             {
1582                 const lldb::addr_t offset = oso_file_addr - oso_range_entry->GetRangeBase();
1583                 const lldb::addr_t exe_file_addr = debug_map_entry->GetRangeBase() + offset;
1584                 return exe_module->ResolveFileAddress(exe_file_addr, addr);
1585             }
1586         }
1587     }
1588     return true;
1589 }
1590 
1591 LineTable *
1592 SymbolFileDWARFDebugMap::LinkOSOLineTable (SymbolFileDWARF *oso_dwarf, LineTable *line_table)
1593 {
1594     CompileUnitInfo *cu_info = GetCompileUnitInfo (oso_dwarf);
1595     if (cu_info)
1596         return line_table->LinkLineTable(cu_info->GetFileRangeMap(this));
1597     return NULL;
1598 }
1599 
1600 size_t
1601 SymbolFileDWARFDebugMap::AddOSOARanges (SymbolFileDWARF* dwarf2Data, DWARFDebugAranges* debug_aranges)
1602 {
1603     size_t num_line_entries_added = 0;
1604     if (debug_aranges && dwarf2Data)
1605     {
1606         CompileUnitInfo *compile_unit_info = GetCompileUnitInfo(dwarf2Data);
1607         if (compile_unit_info)
1608         {
1609             const FileRangeMap &file_range_map = compile_unit_info->GetFileRangeMap(this);
1610             for (size_t idx = 0;
1611                  idx < file_range_map.GetSize();
1612                  idx++)
1613             {
1614                 const FileRangeMap::Entry* entry = file_range_map.GetEntryAtIndex(idx);
1615                 if (entry)
1616                 {
1617                     printf ("[0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")\n", entry->GetRangeBase(), entry->GetRangeEnd());
1618                     debug_aranges->AppendRange(dwarf2Data->GetID(), entry->GetRangeBase(), entry->GetRangeEnd());
1619                     num_line_entries_added++;
1620                 }
1621             }
1622         }
1623     }
1624     return num_line_entries_added;
1625 }
1626 
1627