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