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