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