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