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