xref: /freebsd/contrib/llvm-project/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===-- SymbolFileDWARF.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 "SymbolFileDWARF.h"
10 
11 #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
12 #include "llvm/Support/Casting.h"
13 #include "llvm/Support/FileUtilities.h"
14 #include "llvm/Support/Format.h"
15 #include "llvm/Support/Threading.h"
16 
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/ModuleList.h"
19 #include "lldb/Core/ModuleSpec.h"
20 #include "lldb/Core/PluginManager.h"
21 #include "lldb/Core/Progress.h"
22 #include "lldb/Core/Section.h"
23 #include "lldb/Core/Value.h"
24 #include "lldb/Utility/ArchSpec.h"
25 #include "lldb/Utility/LLDBLog.h"
26 #include "lldb/Utility/RegularExpression.h"
27 #include "lldb/Utility/Scalar.h"
28 #include "lldb/Utility/StreamString.h"
29 #include "lldb/Utility/StructuredData.h"
30 #include "lldb/Utility/Timer.h"
31 
32 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
33 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
34 
35 #include "lldb/Host/FileSystem.h"
36 #include "lldb/Host/Host.h"
37 
38 #include "lldb/Interpreter/OptionValueFileSpecList.h"
39 #include "lldb/Interpreter/OptionValueProperties.h"
40 
41 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
42 #include "Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.h"
43 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
44 #include "lldb/Symbol/Block.h"
45 #include "lldb/Symbol/CompileUnit.h"
46 #include "lldb/Symbol/CompilerDecl.h"
47 #include "lldb/Symbol/CompilerDeclContext.h"
48 #include "lldb/Symbol/DebugMacros.h"
49 #include "lldb/Symbol/LineTable.h"
50 #include "lldb/Symbol/ObjectFile.h"
51 #include "lldb/Symbol/SymbolFile.h"
52 #include "lldb/Symbol/TypeMap.h"
53 #include "lldb/Symbol/TypeSystem.h"
54 #include "lldb/Symbol/VariableList.h"
55 
56 #include "lldb/Target/Language.h"
57 #include "lldb/Target/Target.h"
58 
59 #include "AppleDWARFIndex.h"
60 #include "DWARFASTParser.h"
61 #include "DWARFASTParserClang.h"
62 #include "DWARFCompileUnit.h"
63 #include "DWARFDebugAranges.h"
64 #include "DWARFDebugInfo.h"
65 #include "DWARFDebugMacro.h"
66 #include "DWARFDebugRanges.h"
67 #include "DWARFDeclContext.h"
68 #include "DWARFFormValue.h"
69 #include "DWARFTypeUnit.h"
70 #include "DWARFUnit.h"
71 #include "DebugNamesDWARFIndex.h"
72 #include "LogChannelDWARF.h"
73 #include "ManualDWARFIndex.h"
74 #include "SymbolFileDWARFDebugMap.h"
75 #include "SymbolFileDWARFDwo.h"
76 
77 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
78 #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
79 #include "llvm/Support/FileSystem.h"
80 #include "llvm/Support/FormatVariadic.h"
81 
82 #include <algorithm>
83 #include <map>
84 #include <memory>
85 #include <optional>
86 
87 #include <cctype>
88 #include <cstring>
89 
90 //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
91 
92 #ifdef ENABLE_DEBUG_PRINTF
93 #include <cstdio>
94 #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
95 #else
96 #define DEBUG_PRINTF(fmt, ...)
97 #endif
98 
99 using namespace lldb;
100 using namespace lldb_private;
101 using namespace lldb_private::dwarf;
102 using namespace lldb_private::plugin::dwarf;
103 
104 LLDB_PLUGIN_DEFINE(SymbolFileDWARF)
105 
106 char SymbolFileDWARF::ID;
107 
108 namespace {
109 
110 #define LLDB_PROPERTIES_symbolfiledwarf
111 #include "SymbolFileDWARFProperties.inc"
112 
113 enum {
114 #define LLDB_PROPERTIES_symbolfiledwarf
115 #include "SymbolFileDWARFPropertiesEnum.inc"
116 };
117 
118 class PluginProperties : public Properties {
119 public:
GetSettingName()120   static llvm::StringRef GetSettingName() {
121     return SymbolFileDWARF::GetPluginNameStatic();
122   }
123 
PluginProperties()124   PluginProperties() {
125     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
126     m_collection_sp->Initialize(g_symbolfiledwarf_properties);
127   }
128 
IgnoreFileIndexes() const129   bool IgnoreFileIndexes() const {
130     return GetPropertyAtIndexAs<bool>(ePropertyIgnoreIndexes, false);
131   }
132 };
133 
134 } // namespace
135 
IsStructOrClassTag(llvm::dwarf::Tag Tag)136 bool IsStructOrClassTag(llvm::dwarf::Tag Tag) {
137   return Tag == llvm::dwarf::Tag::DW_TAG_class_type ||
138          Tag == llvm::dwarf::Tag::DW_TAG_structure_type;
139 }
140 
GetGlobalPluginProperties()141 static PluginProperties &GetGlobalPluginProperties() {
142   static PluginProperties g_settings;
143   return g_settings;
144 }
145 
146 static const llvm::DWARFDebugLine::LineTable *
ParseLLVMLineTable(DWARFContext & context,llvm::DWARFDebugLine & line,dw_offset_t line_offset,dw_offset_t unit_offset)147 ParseLLVMLineTable(DWARFContext &context, llvm::DWARFDebugLine &line,
148                    dw_offset_t line_offset, dw_offset_t unit_offset) {
149   Log *log = GetLog(DWARFLog::DebugInfo);
150 
151   llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVMDWARF();
152   llvm::DWARFContext &ctx = context.GetAsLLVM();
153   llvm::Expected<const llvm::DWARFDebugLine::LineTable *> line_table =
154       line.getOrParseLineTable(
155           data, line_offset, ctx, nullptr, [&](llvm::Error e) {
156             LLDB_LOG_ERROR(
157                 log, std::move(e),
158                 "SymbolFileDWARF::ParseLineTable failed to parse: {0}");
159           });
160 
161   if (!line_table) {
162     LLDB_LOG_ERROR(log, line_table.takeError(),
163                    "SymbolFileDWARF::ParseLineTable failed to parse: {0}");
164     return nullptr;
165   }
166   return *line_table;
167 }
168 
ParseLLVMLineTablePrologue(DWARFContext & context,llvm::DWARFDebugLine::Prologue & prologue,dw_offset_t line_offset,dw_offset_t unit_offset)169 static bool ParseLLVMLineTablePrologue(DWARFContext &context,
170                                        llvm::DWARFDebugLine::Prologue &prologue,
171                                        dw_offset_t line_offset,
172                                        dw_offset_t unit_offset) {
173   Log *log = GetLog(DWARFLog::DebugInfo);
174   bool success = true;
175   llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVMDWARF();
176   llvm::DWARFContext &ctx = context.GetAsLLVM();
177   uint64_t offset = line_offset;
178   llvm::Error error = prologue.parse(
179       data, &offset,
180       [&](llvm::Error e) {
181         success = false;
182         LLDB_LOG_ERROR(log, std::move(e),
183                        "SymbolFileDWARF::ParseSupportFiles failed to parse "
184                        "line table prologue: {0}");
185       },
186       ctx, nullptr);
187   if (error) {
188     LLDB_LOG_ERROR(log, std::move(error),
189                    "SymbolFileDWARF::ParseSupportFiles failed to parse line "
190                    "table prologue: {0}");
191     return false;
192   }
193   return success;
194 }
195 
196 static std::optional<std::string>
GetFileByIndex(const llvm::DWARFDebugLine::Prologue & prologue,size_t idx,llvm::StringRef compile_dir,FileSpec::Style style)197 GetFileByIndex(const llvm::DWARFDebugLine::Prologue &prologue, size_t idx,
198                llvm::StringRef compile_dir, FileSpec::Style style) {
199   // Try to get an absolute path first.
200   std::string abs_path;
201   auto absolute = llvm::DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath;
202   if (prologue.getFileNameByIndex(idx, compile_dir, absolute, abs_path, style))
203     return std::move(abs_path);
204 
205   // Otherwise ask for a relative path.
206   std::string rel_path;
207   auto relative = llvm::DILineInfoSpecifier::FileLineInfoKind::RawValue;
208   if (!prologue.getFileNameByIndex(idx, compile_dir, relative, rel_path, style))
209     return {};
210   return std::move(rel_path);
211 }
212 
ParseSupportFilesFromPrologue(SupportFileList & support_files,const lldb::ModuleSP & module,const llvm::DWARFDebugLine::Prologue & prologue,FileSpec::Style style,llvm::StringRef compile_dir={})213 static void ParseSupportFilesFromPrologue(
214     SupportFileList &support_files, const lldb::ModuleSP &module,
215     const llvm::DWARFDebugLine::Prologue &prologue, FileSpec::Style style,
216     llvm::StringRef compile_dir = {}) {
217   // Handle the case where there are no files first to avoid having to special
218   // case this later.
219   if (prologue.FileNames.empty())
220     return;
221 
222   // Before DWARF v5, the line table indexes were one based.
223   const bool is_one_based = prologue.getVersion() < 5;
224   const size_t file_names = prologue.FileNames.size();
225   const size_t first_file_idx = is_one_based ? 1 : 0;
226   const size_t last_file_idx = is_one_based ? file_names : file_names - 1;
227 
228   // Add a dummy entry to ensure the support file list indices match those we
229   // get from the debug info and line tables.
230   if (is_one_based)
231     support_files.Append(FileSpec());
232 
233   for (size_t idx = first_file_idx; idx <= last_file_idx; ++idx) {
234     std::string remapped_file;
235     if (auto file_path = GetFileByIndex(prologue, idx, compile_dir, style)) {
236       auto entry = prologue.getFileNameEntry(idx);
237       auto source = entry.Source.getAsCString();
238       if (!source)
239         consumeError(source.takeError());
240       else {
241         llvm::StringRef source_ref(*source);
242         if (!source_ref.empty()) {
243           /// Wrap a path for an in-DWARF source file. Lazily write it
244           /// to disk when Materialize() is called.
245           struct LazyDWARFSourceFile : public SupportFile {
LazyDWARFSourceFileParseSupportFilesFromPrologue::LazyDWARFSourceFile246             LazyDWARFSourceFile(const FileSpec &fs, llvm::StringRef source,
247                                 FileSpec::Style style)
248                 : SupportFile(fs), source(source), style(style) {}
249             FileSpec tmp_file;
250             /// The file contents buffer.
251             llvm::StringRef source;
252             /// Deletes the temporary file at the end.
253             std::unique_ptr<llvm::FileRemover> remover;
254             FileSpec::Style style;
255 
256             /// Write the file contents to a temporary file.
MaterializeParseSupportFilesFromPrologue::LazyDWARFSourceFile257             const FileSpec &Materialize() override {
258               if (tmp_file)
259                 return tmp_file;
260               llvm::SmallString<0> name;
261               int fd;
262               auto orig_name = m_file_spec.GetFilename().GetStringRef();
263               auto ec = llvm::sys::fs::createTemporaryFile(
264                   "", llvm::sys::path::filename(orig_name, style), fd, name);
265               if (ec || fd <= 0) {
266                 LLDB_LOG(GetLog(DWARFLog::DebugInfo),
267                          "Could not create temporary file");
268                 return tmp_file;
269               }
270               remover = std::make_unique<llvm::FileRemover>(name);
271               NativeFile file(fd, File::eOpenOptionWriteOnly, true);
272               size_t num_bytes = source.size();
273               file.Write(source.data(), num_bytes);
274               tmp_file.SetPath(name);
275               return tmp_file;
276             }
277           };
278           support_files.Append(std::make_unique<LazyDWARFSourceFile>(
279               FileSpec(*file_path), *source, style));
280           continue;
281         }
282       }
283       if (auto remapped = module->RemapSourceFile(llvm::StringRef(*file_path)))
284         remapped_file = *remapped;
285       else
286         remapped_file = std::move(*file_path);
287     }
288 
289     Checksum checksum;
290     if (prologue.ContentTypes.HasMD5) {
291       const llvm::DWARFDebugLine::FileNameEntry &file_name_entry =
292           prologue.getFileNameEntry(idx);
293       checksum = file_name_entry.Checksum;
294     }
295 
296     // Unconditionally add an entry, so the indices match up.
297     support_files.EmplaceBack(FileSpec(remapped_file, style), checksum);
298   }
299 }
300 
Initialize()301 void SymbolFileDWARF::Initialize() {
302   LogChannelDWARF::Initialize();
303   PluginManager::RegisterPlugin(GetPluginNameStatic(),
304                                 GetPluginDescriptionStatic(), CreateInstance,
305                                 DebuggerInitialize);
306   SymbolFileDWARFDebugMap::Initialize();
307 }
308 
DebuggerInitialize(Debugger & debugger)309 void SymbolFileDWARF::DebuggerInitialize(Debugger &debugger) {
310   if (!PluginManager::GetSettingForSymbolFilePlugin(
311           debugger, PluginProperties::GetSettingName())) {
312     const bool is_global_setting = true;
313     PluginManager::CreateSettingForSymbolFilePlugin(
314         debugger, GetGlobalPluginProperties().GetValueProperties(),
315         "Properties for the dwarf symbol-file plug-in.", is_global_setting);
316   }
317 }
318 
Terminate()319 void SymbolFileDWARF::Terminate() {
320   SymbolFileDWARFDebugMap::Terminate();
321   PluginManager::UnregisterPlugin(CreateInstance);
322   LogChannelDWARF::Terminate();
323 }
324 
GetPluginDescriptionStatic()325 llvm::StringRef SymbolFileDWARF::GetPluginDescriptionStatic() {
326   return "DWARF and DWARF3 debug symbol file reader.";
327 }
328 
CreateInstance(ObjectFileSP objfile_sp)329 SymbolFile *SymbolFileDWARF::CreateInstance(ObjectFileSP objfile_sp) {
330   return new SymbolFileDWARF(std::move(objfile_sp),
331                              /*dwo_section_list*/ nullptr);
332 }
333 
GetTypeList()334 TypeList &SymbolFileDWARF::GetTypeList() {
335   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
336   if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
337     return debug_map_symfile->GetTypeList();
338   return SymbolFileCommon::GetTypeList();
339 }
GetTypes(const DWARFDIE & die,dw_offset_t min_die_offset,dw_offset_t max_die_offset,uint32_t type_mask,TypeSet & type_set)340 void SymbolFileDWARF::GetTypes(const DWARFDIE &die, dw_offset_t min_die_offset,
341                                dw_offset_t max_die_offset, uint32_t type_mask,
342                                TypeSet &type_set) {
343   if (die) {
344     const dw_offset_t die_offset = die.GetOffset();
345 
346     if (die_offset >= max_die_offset)
347       return;
348 
349     if (die_offset >= min_die_offset) {
350       const dw_tag_t tag = die.Tag();
351 
352       bool add_type = false;
353 
354       switch (tag) {
355       case DW_TAG_array_type:
356         add_type = (type_mask & eTypeClassArray) != 0;
357         break;
358       case DW_TAG_unspecified_type:
359       case DW_TAG_base_type:
360         add_type = (type_mask & eTypeClassBuiltin) != 0;
361         break;
362       case DW_TAG_class_type:
363         add_type = (type_mask & eTypeClassClass) != 0;
364         break;
365       case DW_TAG_structure_type:
366         add_type = (type_mask & eTypeClassStruct) != 0;
367         break;
368       case DW_TAG_union_type:
369         add_type = (type_mask & eTypeClassUnion) != 0;
370         break;
371       case DW_TAG_enumeration_type:
372         add_type = (type_mask & eTypeClassEnumeration) != 0;
373         break;
374       case DW_TAG_subroutine_type:
375       case DW_TAG_subprogram:
376       case DW_TAG_inlined_subroutine:
377         add_type = (type_mask & eTypeClassFunction) != 0;
378         break;
379       case DW_TAG_pointer_type:
380         add_type = (type_mask & eTypeClassPointer) != 0;
381         break;
382       case DW_TAG_rvalue_reference_type:
383       case DW_TAG_reference_type:
384         add_type = (type_mask & eTypeClassReference) != 0;
385         break;
386       case DW_TAG_typedef:
387         add_type = (type_mask & eTypeClassTypedef) != 0;
388         break;
389       case DW_TAG_ptr_to_member_type:
390         add_type = (type_mask & eTypeClassMemberPointer) != 0;
391         break;
392       default:
393         break;
394       }
395 
396       if (add_type) {
397         const bool assert_not_being_parsed = true;
398         Type *type = ResolveTypeUID(die, assert_not_being_parsed);
399         if (type)
400           type_set.insert(type);
401       }
402     }
403 
404     for (DWARFDIE child_die : die.children()) {
405       GetTypes(child_die, min_die_offset, max_die_offset, type_mask, type_set);
406     }
407   }
408 }
409 
GetTypes(SymbolContextScope * sc_scope,TypeClass type_mask,TypeList & type_list)410 void SymbolFileDWARF::GetTypes(SymbolContextScope *sc_scope,
411                                TypeClass type_mask, TypeList &type_list)
412 
413 {
414   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
415   TypeSet type_set;
416 
417   CompileUnit *comp_unit = nullptr;
418   if (sc_scope)
419     comp_unit = sc_scope->CalculateSymbolContextCompileUnit();
420 
421   const auto &get = [&](DWARFUnit *unit) {
422     if (!unit)
423       return;
424     unit = &unit->GetNonSkeletonUnit();
425     GetTypes(unit->DIE(), unit->GetOffset(), unit->GetNextUnitOffset(),
426              type_mask, type_set);
427   };
428   if (comp_unit) {
429     get(GetDWARFCompileUnit(comp_unit));
430   } else {
431     DWARFDebugInfo &info = DebugInfo();
432     const size_t num_cus = info.GetNumUnits();
433     for (size_t cu_idx = 0; cu_idx < num_cus; ++cu_idx)
434       get(info.GetUnitAtIndex(cu_idx));
435   }
436 
437   std::set<CompilerType> compiler_type_set;
438   for (Type *type : type_set) {
439     CompilerType compiler_type = type->GetForwardCompilerType();
440     if (compiler_type_set.find(compiler_type) == compiler_type_set.end()) {
441       compiler_type_set.insert(compiler_type);
442       type_list.Insert(type->shared_from_this());
443     }
444   }
445 }
446 
447 // Gets the first parent that is a lexical block, function or inlined
448 // subroutine, or compile unit.
449 DWARFDIE
GetParentSymbolContextDIE(const DWARFDIE & child_die)450 SymbolFileDWARF::GetParentSymbolContextDIE(const DWARFDIE &child_die) {
451   DWARFDIE die;
452   for (die = child_die.GetParent(); die; die = die.GetParent()) {
453     dw_tag_t tag = die.Tag();
454 
455     switch (tag) {
456     case DW_TAG_compile_unit:
457     case DW_TAG_partial_unit:
458     case DW_TAG_subprogram:
459     case DW_TAG_inlined_subroutine:
460     case DW_TAG_lexical_block:
461       return die;
462     default:
463       break;
464     }
465   }
466   return DWARFDIE();
467 }
468 
SymbolFileDWARF(ObjectFileSP objfile_sp,SectionList * dwo_section_list)469 SymbolFileDWARF::SymbolFileDWARF(ObjectFileSP objfile_sp,
470                                  SectionList *dwo_section_list)
471     : SymbolFileCommon(std::move(objfile_sp)), m_debug_map_module_wp(),
472       m_debug_map_symfile(nullptr),
473       m_context(m_objfile_sp->GetModule()->GetSectionList(), dwo_section_list),
474       m_fetched_external_modules(false),
475       m_supports_DW_AT_APPLE_objc_complete_type(eLazyBoolCalculate) {}
476 
477 SymbolFileDWARF::~SymbolFileDWARF() = default;
478 
GetDWARFMachOSegmentName()479 static ConstString GetDWARFMachOSegmentName() {
480   static ConstString g_dwarf_section_name("__DWARF");
481   return g_dwarf_section_name;
482 }
483 
484 llvm::DenseMap<lldb::opaque_compiler_type_t, DIERef> &
GetForwardDeclCompilerTypeToDIE()485 SymbolFileDWARF::GetForwardDeclCompilerTypeToDIE() {
486   if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
487     return debug_map_symfile->GetForwardDeclCompilerTypeToDIE();
488   return m_forward_decl_compiler_type_to_die;
489 }
490 
GetUniqueDWARFASTTypeMap()491 UniqueDWARFASTTypeMap &SymbolFileDWARF::GetUniqueDWARFASTTypeMap() {
492   SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
493   if (debug_map_symfile)
494     return debug_map_symfile->GetUniqueDWARFASTTypeMap();
495   else
496     return m_unique_ast_type_map;
497 }
498 
499 llvm::Expected<lldb::TypeSystemSP>
GetTypeSystemForLanguage(LanguageType language)500 SymbolFileDWARF::GetTypeSystemForLanguage(LanguageType language) {
501   if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
502     return debug_map_symfile->GetTypeSystemForLanguage(language);
503 
504   auto type_system_or_err =
505       m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
506   if (type_system_or_err)
507     if (auto ts = *type_system_or_err)
508       ts->SetSymbolFile(this);
509   return type_system_or_err;
510 }
511 
InitializeObject()512 void SymbolFileDWARF::InitializeObject() {
513   Log *log = GetLog(DWARFLog::DebugInfo);
514 
515   InitializeFirstCodeAddress();
516 
517   if (!GetGlobalPluginProperties().IgnoreFileIndexes()) {
518     StreamString module_desc;
519     GetObjectFile()->GetModule()->GetDescription(module_desc.AsRawOstream(),
520                                                  lldb::eDescriptionLevelBrief);
521     DWARFDataExtractor apple_names, apple_namespaces, apple_types, apple_objc;
522     LoadSectionData(eSectionTypeDWARFAppleNames, apple_names);
523     LoadSectionData(eSectionTypeDWARFAppleNamespaces, apple_namespaces);
524     LoadSectionData(eSectionTypeDWARFAppleTypes, apple_types);
525     LoadSectionData(eSectionTypeDWARFAppleObjC, apple_objc);
526 
527     if (apple_names.GetByteSize() > 0 || apple_namespaces.GetByteSize() > 0 ||
528         apple_types.GetByteSize() > 0 || apple_objc.GetByteSize() > 0) {
529       m_index = AppleDWARFIndex::Create(
530           *GetObjectFile()->GetModule(), apple_names, apple_namespaces,
531           apple_types, apple_objc, m_context.getOrLoadStrData());
532 
533       if (m_index)
534         return;
535     }
536 
537     DWARFDataExtractor debug_names;
538     LoadSectionData(eSectionTypeDWARFDebugNames, debug_names);
539     if (debug_names.GetByteSize() > 0) {
540       Progress progress("Loading DWARF5 index", module_desc.GetData());
541       llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> index_or =
542           DebugNamesDWARFIndex::Create(*GetObjectFile()->GetModule(),
543                                        debug_names,
544                                        m_context.getOrLoadStrData(), *this);
545       if (index_or) {
546         m_index = std::move(*index_or);
547         return;
548       }
549       LLDB_LOG_ERROR(log, index_or.takeError(),
550                      "Unable to read .debug_names data: {0}");
551     }
552   }
553 
554   m_index =
555       std::make_unique<ManualDWARFIndex>(*GetObjectFile()->GetModule(), *this);
556 }
557 
InitializeFirstCodeAddress()558 void SymbolFileDWARF::InitializeFirstCodeAddress() {
559   InitializeFirstCodeAddressRecursive(
560       *m_objfile_sp->GetModule()->GetSectionList());
561   if (m_first_code_address == LLDB_INVALID_ADDRESS)
562     m_first_code_address = 0;
563 }
564 
InitializeFirstCodeAddressRecursive(const lldb_private::SectionList & section_list)565 void SymbolFileDWARF::InitializeFirstCodeAddressRecursive(
566     const lldb_private::SectionList &section_list) {
567   for (SectionSP section_sp : section_list) {
568     if (section_sp->GetChildren().GetSize() > 0) {
569       InitializeFirstCodeAddressRecursive(section_sp->GetChildren());
570     } else if (section_sp->GetType() == eSectionTypeCode) {
571       m_first_code_address =
572           std::min(m_first_code_address, section_sp->GetFileAddress());
573     }
574   }
575 }
576 
SupportedVersion(uint16_t version)577 bool SymbolFileDWARF::SupportedVersion(uint16_t version) {
578   return version >= 2 && version <= 5;
579 }
580 
581 static std::set<dw_form_t>
GetUnsupportedForms(llvm::DWARFDebugAbbrev * debug_abbrev)582 GetUnsupportedForms(llvm::DWARFDebugAbbrev *debug_abbrev) {
583   if (!debug_abbrev)
584     return {};
585 
586   std::set<dw_form_t> unsupported_forms;
587   for (const auto &[_, decl_set] : *debug_abbrev)
588     for (const auto &decl : decl_set)
589       for (const auto &attr : decl.attributes())
590         if (!DWARFFormValue::FormIsSupported(attr.Form))
591           unsupported_forms.insert(attr.Form);
592 
593   return unsupported_forms;
594 }
595 
CalculateAbilities()596 uint32_t SymbolFileDWARF::CalculateAbilities() {
597   uint32_t abilities = 0;
598   if (m_objfile_sp != nullptr) {
599     const Section *section = nullptr;
600     const SectionList *section_list = m_objfile_sp->GetSectionList();
601     if (section_list == nullptr)
602       return 0;
603 
604     uint64_t debug_abbrev_file_size = 0;
605     uint64_t debug_info_file_size = 0;
606     uint64_t debug_line_file_size = 0;
607 
608     section = section_list->FindSectionByName(GetDWARFMachOSegmentName()).get();
609 
610     if (section)
611       section_list = &section->GetChildren();
612 
613     section =
614         section_list->FindSectionByType(eSectionTypeDWARFDebugInfo, true).get();
615     if (section != nullptr) {
616       debug_info_file_size = section->GetFileSize();
617 
618       section =
619           section_list->FindSectionByType(eSectionTypeDWARFDebugAbbrev, true)
620               .get();
621       if (section)
622         debug_abbrev_file_size = section->GetFileSize();
623 
624       llvm::DWARFDebugAbbrev *abbrev = DebugAbbrev();
625       std::set<dw_form_t> unsupported_forms = GetUnsupportedForms(abbrev);
626       if (!unsupported_forms.empty()) {
627         StreamString error;
628         error.Printf("unsupported DW_FORM value%s:",
629                      unsupported_forms.size() > 1 ? "s" : "");
630         for (auto form : unsupported_forms)
631           error.Printf(" %#x", form);
632         m_objfile_sp->GetModule()->ReportWarning("{0}", error.GetString());
633         return 0;
634       }
635 
636       section =
637           section_list->FindSectionByType(eSectionTypeDWARFDebugLine, true)
638               .get();
639       if (section)
640         debug_line_file_size = section->GetFileSize();
641     } else {
642       llvm::StringRef symfile_dir =
643           m_objfile_sp->GetFileSpec().GetDirectory().GetStringRef();
644       if (symfile_dir.contains_insensitive(".dsym")) {
645         if (m_objfile_sp->GetType() == ObjectFile::eTypeDebugInfo) {
646           // We have a dSYM file that didn't have a any debug info. If the
647           // string table has a size of 1, then it was made from an
648           // executable with no debug info, or from an executable that was
649           // stripped.
650           section =
651               section_list->FindSectionByType(eSectionTypeDWARFDebugStr, true)
652                   .get();
653           if (section && section->GetFileSize() == 1) {
654             m_objfile_sp->GetModule()->ReportWarning(
655                 "empty dSYM file detected, dSYM was created with an "
656                 "executable with no debug info.");
657           }
658         }
659       }
660     }
661 
662     constexpr uint64_t MaxDebugInfoSize = (1ull) << DW_DIE_OFFSET_MAX_BITSIZE;
663     if (debug_info_file_size >= MaxDebugInfoSize) {
664       m_objfile_sp->GetModule()->ReportWarning(
665           "SymbolFileDWARF can't load this DWARF. It's larger then {0:x+16}",
666           MaxDebugInfoSize);
667       return 0;
668     }
669 
670     if (debug_abbrev_file_size > 0 && debug_info_file_size > 0)
671       abilities |= CompileUnits | Functions | Blocks | GlobalVariables |
672                    LocalVariables | VariableTypes;
673 
674     if (debug_line_file_size > 0)
675       abilities |= LineTables;
676   }
677   return abilities;
678 }
679 
LoadSectionData(lldb::SectionType sect_type,DWARFDataExtractor & data)680 void SymbolFileDWARF::LoadSectionData(lldb::SectionType sect_type,
681                                       DWARFDataExtractor &data) {
682   ModuleSP module_sp(m_objfile_sp->GetModule());
683   const SectionList *section_list = module_sp->GetSectionList();
684   if (!section_list)
685     return;
686 
687   SectionSP section_sp(section_list->FindSectionByType(sect_type, true));
688   if (!section_sp)
689     return;
690 
691   data.Clear();
692   m_objfile_sp->ReadSectionData(section_sp.get(), data);
693 }
694 
DebugAbbrev()695 llvm::DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() {
696   if (m_abbr)
697     return m_abbr.get();
698 
699   const DWARFDataExtractor &debug_abbrev_data = m_context.getOrLoadAbbrevData();
700   if (debug_abbrev_data.GetByteSize() == 0)
701     return nullptr;
702 
703   ElapsedTime elapsed(m_parse_time);
704   auto abbr =
705       std::make_unique<llvm::DWARFDebugAbbrev>(debug_abbrev_data.GetAsLLVM());
706   llvm::Error error = abbr->parse();
707   if (error) {
708     Log *log = GetLog(DWARFLog::DebugInfo);
709     LLDB_LOG_ERROR(log, std::move(error),
710                    "Unable to read .debug_abbrev section: {0}");
711     return nullptr;
712   }
713 
714   m_abbr = std::move(abbr);
715   return m_abbr.get();
716 }
717 
DebugInfo()718 DWARFDebugInfo &SymbolFileDWARF::DebugInfo() {
719   llvm::call_once(m_info_once_flag, [&] {
720     LLDB_SCOPED_TIMER();
721 
722     m_info = std::make_unique<DWARFDebugInfo>(*this, m_context);
723   });
724   return *m_info;
725 }
726 
GetDWARFCompileUnit(CompileUnit * comp_unit)727 DWARFCompileUnit *SymbolFileDWARF::GetDWARFCompileUnit(CompileUnit *comp_unit) {
728   if (!comp_unit)
729     return nullptr;
730 
731   // The compile unit ID is the index of the DWARF unit.
732   DWARFUnit *dwarf_cu = DebugInfo().GetUnitAtIndex(comp_unit->GetID());
733   if (dwarf_cu && dwarf_cu->GetLLDBCompUnit() == nullptr)
734     dwarf_cu->SetLLDBCompUnit(comp_unit);
735 
736   // It must be DWARFCompileUnit when it created a CompileUnit.
737   return llvm::cast_or_null<DWARFCompileUnit>(dwarf_cu);
738 }
739 
GetDebugRanges()740 DWARFDebugRanges *SymbolFileDWARF::GetDebugRanges() {
741   if (!m_ranges) {
742     LLDB_SCOPED_TIMER();
743 
744     if (m_context.getOrLoadRangesData().GetByteSize() > 0)
745       m_ranges = std::make_unique<DWARFDebugRanges>();
746 
747     if (m_ranges)
748       m_ranges->Extract(m_context);
749   }
750   return m_ranges.get();
751 }
752 
753 /// Make an absolute path out of \p file_spec and remap it using the
754 /// module's source remapping dictionary.
MakeAbsoluteAndRemap(FileSpec & file_spec,DWARFUnit & dwarf_cu,const ModuleSP & module_sp)755 static void MakeAbsoluteAndRemap(FileSpec &file_spec, DWARFUnit &dwarf_cu,
756                                  const ModuleSP &module_sp) {
757   if (!file_spec)
758     return;
759   // If we have a full path to the compile unit, we don't need to
760   // resolve the file.  This can be expensive e.g. when the source
761   // files are NFS mounted.
762   file_spec.MakeAbsolute(dwarf_cu.GetCompilationDirectory());
763 
764   if (auto remapped_file = module_sp->RemapSourceFile(file_spec.GetPath()))
765     file_spec.SetFile(*remapped_file, FileSpec::Style::native);
766 }
767 
768 /// Return the DW_AT_(GNU_)dwo_name.
GetDWOName(DWARFCompileUnit & dwarf_cu,const DWARFDebugInfoEntry & cu_die)769 static const char *GetDWOName(DWARFCompileUnit &dwarf_cu,
770                               const DWARFDebugInfoEntry &cu_die) {
771   const char *dwo_name =
772       cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_GNU_dwo_name, nullptr);
773   if (!dwo_name)
774     dwo_name =
775         cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_dwo_name, nullptr);
776   return dwo_name;
777 }
778 
ParseCompileUnit(DWARFCompileUnit & dwarf_cu)779 lldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFCompileUnit &dwarf_cu) {
780   CompUnitSP cu_sp;
781   CompileUnit *comp_unit = dwarf_cu.GetLLDBCompUnit();
782   if (comp_unit) {
783     // We already parsed this compile unit, had out a shared pointer to it
784     cu_sp = comp_unit->shared_from_this();
785   } else {
786     if (GetDebugMapSymfile()) {
787       // Let the debug map create the compile unit
788       cu_sp = m_debug_map_symfile->GetCompileUnit(this, dwarf_cu);
789       dwarf_cu.SetLLDBCompUnit(cu_sp.get());
790     } else {
791       ModuleSP module_sp(m_objfile_sp->GetModule());
792       if (module_sp) {
793         auto initialize_cu = [&](lldb::SupportFileSP support_file_sp,
794                                  LanguageType cu_language,
795                                  SupportFileList &&support_files = {}) {
796           BuildCuTranslationTable();
797           cu_sp = std::make_shared<CompileUnit>(
798               module_sp, &dwarf_cu, support_file_sp,
799               *GetDWARFUnitIndex(dwarf_cu.GetID()), cu_language,
800               eLazyBoolCalculate, std::move(support_files));
801 
802           dwarf_cu.SetLLDBCompUnit(cu_sp.get());
803 
804           SetCompileUnitAtIndex(dwarf_cu.GetID(), cu_sp);
805         };
806 
807         auto lazy_initialize_cu = [&]() {
808           // If the version is < 5, we can't do lazy initialization.
809           if (dwarf_cu.GetVersion() < 5)
810             return false;
811 
812           // If there is no DWO, there is no reason to initialize
813           // lazily; we will do eager initialization in that case.
814           if (GetDebugMapSymfile())
815             return false;
816           const DWARFBaseDIE cu_die = dwarf_cu.GetUnitDIEOnly();
817           if (!cu_die)
818             return false;
819           if (!GetDWOName(dwarf_cu, *cu_die.GetDIE()))
820             return false;
821 
822           // With DWARFv5 we can assume that the first support
823           // file is also the name of the compile unit. This
824           // allows us to avoid loading the non-skeleton unit,
825           // which may be in a separate DWO file.
826           SupportFileList support_files;
827           if (!ParseSupportFiles(dwarf_cu, module_sp, support_files))
828             return false;
829           if (support_files.GetSize() == 0)
830             return false;
831           initialize_cu(support_files.GetSupportFileAtIndex(0),
832                         eLanguageTypeUnknown, std::move(support_files));
833           return true;
834         };
835 
836         if (!lazy_initialize_cu()) {
837           // Eagerly initialize compile unit
838           const DWARFBaseDIE cu_die =
839               dwarf_cu.GetNonSkeletonUnit().GetUnitDIEOnly();
840           if (cu_die) {
841             LanguageType cu_language = SymbolFileDWARF::LanguageTypeFromDWARF(
842                 dwarf_cu.GetDWARFLanguageType());
843 
844             FileSpec cu_file_spec(cu_die.GetName(), dwarf_cu.GetPathStyle());
845 
846             // Path needs to be remapped in this case. In the support files
847             // case ParseSupportFiles takes care of the remapping.
848             MakeAbsoluteAndRemap(cu_file_spec, dwarf_cu, module_sp);
849 
850             initialize_cu(std::make_shared<SupportFile>(cu_file_spec),
851                           cu_language);
852           }
853         }
854       }
855     }
856   }
857   return cu_sp;
858 }
859 
BuildCuTranslationTable()860 void SymbolFileDWARF::BuildCuTranslationTable() {
861   if (!m_lldb_cu_to_dwarf_unit.empty())
862     return;
863 
864   DWARFDebugInfo &info = DebugInfo();
865   if (!info.ContainsTypeUnits()) {
866     // We can use a 1-to-1 mapping. No need to build a translation table.
867     return;
868   }
869   for (uint32_t i = 0, num = info.GetNumUnits(); i < num; ++i) {
870     if (auto *cu = llvm::dyn_cast<DWARFCompileUnit>(info.GetUnitAtIndex(i))) {
871       cu->SetID(m_lldb_cu_to_dwarf_unit.size());
872       m_lldb_cu_to_dwarf_unit.push_back(i);
873     }
874   }
875 }
876 
GetDWARFUnitIndex(uint32_t cu_idx)877 std::optional<uint32_t> SymbolFileDWARF::GetDWARFUnitIndex(uint32_t cu_idx) {
878   BuildCuTranslationTable();
879   if (m_lldb_cu_to_dwarf_unit.empty())
880     return cu_idx;
881   if (cu_idx >= m_lldb_cu_to_dwarf_unit.size())
882     return std::nullopt;
883   return m_lldb_cu_to_dwarf_unit[cu_idx];
884 }
885 
CalculateNumCompileUnits()886 uint32_t SymbolFileDWARF::CalculateNumCompileUnits() {
887   BuildCuTranslationTable();
888   return m_lldb_cu_to_dwarf_unit.empty() ? DebugInfo().GetNumUnits()
889                                          : m_lldb_cu_to_dwarf_unit.size();
890 }
891 
ParseCompileUnitAtIndex(uint32_t cu_idx)892 CompUnitSP SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx) {
893   ASSERT_MODULE_LOCK(this);
894   if (std::optional<uint32_t> dwarf_idx = GetDWARFUnitIndex(cu_idx)) {
895     if (auto *dwarf_cu = llvm::cast_or_null<DWARFCompileUnit>(
896             DebugInfo().GetUnitAtIndex(*dwarf_idx)))
897       return ParseCompileUnit(*dwarf_cu);
898   }
899   return {};
900 }
901 
ParseFunction(CompileUnit & comp_unit,const DWARFDIE & die)902 Function *SymbolFileDWARF::ParseFunction(CompileUnit &comp_unit,
903                                          const DWARFDIE &die) {
904   ASSERT_MODULE_LOCK(this);
905   if (!die.IsValid())
906     return nullptr;
907 
908   auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU()));
909   if (auto err = type_system_or_err.takeError()) {
910     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
911                    "Unable to parse function: {0}");
912     return nullptr;
913   }
914   auto ts = *type_system_or_err;
915   if (!ts)
916     return nullptr;
917   DWARFASTParser *dwarf_ast = ts->GetDWARFParser();
918   if (!dwarf_ast)
919     return nullptr;
920 
921   DWARFRangeList ranges = die.GetDIE()->GetAttributeAddressRanges(
922       die.GetCU(), /*check_hi_lo_pc=*/true);
923   if (ranges.IsEmpty())
924     return nullptr;
925 
926   // Union of all ranges in the function DIE (if the function is
927   // discontiguous)
928   lldb::addr_t lowest_func_addr = ranges.GetMinRangeBase(0);
929   lldb::addr_t highest_func_addr = ranges.GetMaxRangeEnd(0);
930   if (lowest_func_addr == LLDB_INVALID_ADDRESS ||
931       lowest_func_addr >= highest_func_addr ||
932       lowest_func_addr < m_first_code_address)
933     return nullptr;
934 
935   ModuleSP module_sp(die.GetModule());
936   AddressRange func_range;
937   func_range.GetBaseAddress().ResolveAddressUsingFileSections(
938       lowest_func_addr, module_sp->GetSectionList());
939   if (!func_range.GetBaseAddress().IsValid())
940     return nullptr;
941 
942   func_range.SetByteSize(highest_func_addr - lowest_func_addr);
943   if (!FixupAddress(func_range.GetBaseAddress()))
944     return nullptr;
945 
946   return dwarf_ast->ParseFunctionFromDWARF(comp_unit, die, func_range);
947 }
948 
949 ConstString
ConstructFunctionDemangledName(const DWARFDIE & die)950 SymbolFileDWARF::ConstructFunctionDemangledName(const DWARFDIE &die) {
951   ASSERT_MODULE_LOCK(this);
952   if (!die.IsValid()) {
953     return ConstString();
954   }
955 
956   auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU()));
957   if (auto err = type_system_or_err.takeError()) {
958     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
959                    "Unable to construct demangled name for function: {0}");
960     return ConstString();
961   }
962 
963   auto ts = *type_system_or_err;
964   if (!ts) {
965     LLDB_LOG(GetLog(LLDBLog::Symbols), "Type system no longer live");
966     return ConstString();
967   }
968   DWARFASTParser *dwarf_ast = ts->GetDWARFParser();
969   if (!dwarf_ast)
970     return ConstString();
971 
972   return dwarf_ast->ConstructDemangledNameFromDWARF(die);
973 }
974 
FixupAddress(lldb::addr_t file_addr)975 lldb::addr_t SymbolFileDWARF::FixupAddress(lldb::addr_t file_addr) {
976   SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
977   if (debug_map_symfile)
978     return debug_map_symfile->LinkOSOFileAddress(this, file_addr);
979   return file_addr;
980 }
981 
FixupAddress(Address & addr)982 bool SymbolFileDWARF::FixupAddress(Address &addr) {
983   SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
984   if (debug_map_symfile) {
985     return debug_map_symfile->LinkOSOAddress(addr);
986   }
987   // This is a normal DWARF file, no address fixups need to happen
988   return true;
989 }
ParseLanguage(CompileUnit & comp_unit)990 lldb::LanguageType SymbolFileDWARF::ParseLanguage(CompileUnit &comp_unit) {
991   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
992   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
993   if (dwarf_cu)
994     return GetLanguage(dwarf_cu->GetNonSkeletonUnit());
995   else
996     return eLanguageTypeUnknown;
997 }
998 
ParseXcodeSDK(CompileUnit & comp_unit)999 XcodeSDK SymbolFileDWARF::ParseXcodeSDK(CompileUnit &comp_unit) {
1000   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1001   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1002   if (!dwarf_cu)
1003     return {};
1004   const DWARFBaseDIE cu_die = dwarf_cu->GetNonSkeletonUnit().GetUnitDIEOnly();
1005   if (!cu_die)
1006     return {};
1007   const char *sdk = cu_die.GetAttributeValueAsString(DW_AT_APPLE_sdk, nullptr);
1008   if (!sdk)
1009     return {};
1010   const char *sysroot =
1011       cu_die.GetAttributeValueAsString(DW_AT_LLVM_sysroot, "");
1012   // Register the sysroot path remapping with the module belonging to
1013   // the CU as well as the one belonging to the symbol file. The two
1014   // would be different if this is an OSO object and module is the
1015   // corresponding debug map, in which case both should be updated.
1016   ModuleSP module_sp = comp_unit.GetModule();
1017   if (module_sp)
1018     module_sp->RegisterXcodeSDK(sdk, sysroot);
1019 
1020   ModuleSP local_module_sp = m_objfile_sp->GetModule();
1021   if (local_module_sp && local_module_sp != module_sp)
1022     local_module_sp->RegisterXcodeSDK(sdk, sysroot);
1023 
1024   return {sdk};
1025 }
1026 
ParseFunctions(CompileUnit & comp_unit)1027 size_t SymbolFileDWARF::ParseFunctions(CompileUnit &comp_unit) {
1028   LLDB_SCOPED_TIMER();
1029   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1030   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1031   if (!dwarf_cu)
1032     return 0;
1033 
1034   size_t functions_added = 0;
1035   dwarf_cu = &dwarf_cu->GetNonSkeletonUnit();
1036   for (DWARFDebugInfoEntry &entry : dwarf_cu->dies()) {
1037     if (entry.Tag() != DW_TAG_subprogram)
1038       continue;
1039 
1040     DWARFDIE die(dwarf_cu, &entry);
1041     if (comp_unit.FindFunctionByUID(die.GetID()))
1042       continue;
1043     if (ParseFunction(comp_unit, die))
1044       ++functions_added;
1045   }
1046   // FixupTypes();
1047   return functions_added;
1048 }
1049 
ForEachExternalModule(CompileUnit & comp_unit,llvm::DenseSet<lldb_private::SymbolFile * > & visited_symbol_files,llvm::function_ref<bool (Module &)> lambda)1050 bool SymbolFileDWARF::ForEachExternalModule(
1051     CompileUnit &comp_unit,
1052     llvm::DenseSet<lldb_private::SymbolFile *> &visited_symbol_files,
1053     llvm::function_ref<bool(Module &)> lambda) {
1054   // Only visit each symbol file once.
1055   if (!visited_symbol_files.insert(this).second)
1056     return false;
1057 
1058   UpdateExternalModuleListIfNeeded();
1059   for (auto &p : m_external_type_modules) {
1060     ModuleSP module = p.second;
1061     if (!module)
1062       continue;
1063 
1064     // Invoke the action and potentially early-exit.
1065     if (lambda(*module))
1066       return true;
1067 
1068     for (std::size_t i = 0; i < module->GetNumCompileUnits(); ++i) {
1069       auto cu = module->GetCompileUnitAtIndex(i);
1070       bool early_exit = cu->ForEachExternalModule(visited_symbol_files, lambda);
1071       if (early_exit)
1072         return true;
1073     }
1074   }
1075   return false;
1076 }
1077 
ParseSupportFiles(CompileUnit & comp_unit,SupportFileList & support_files)1078 bool SymbolFileDWARF::ParseSupportFiles(CompileUnit &comp_unit,
1079                                         SupportFileList &support_files) {
1080   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1081   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1082   if (!dwarf_cu)
1083     return false;
1084 
1085   if (!ParseSupportFiles(*dwarf_cu, comp_unit.GetModule(), support_files))
1086     return false;
1087 
1088   return true;
1089 }
1090 
ParseSupportFiles(DWARFUnit & dwarf_cu,const ModuleSP & module,SupportFileList & support_files)1091 bool SymbolFileDWARF::ParseSupportFiles(DWARFUnit &dwarf_cu,
1092                                         const ModuleSP &module,
1093                                         SupportFileList &support_files) {
1094 
1095   dw_offset_t offset = dwarf_cu.GetLineTableOffset();
1096   if (offset == DW_INVALID_OFFSET)
1097     return false;
1098 
1099   ElapsedTime elapsed(m_parse_time);
1100   llvm::DWARFDebugLine::Prologue prologue;
1101   if (!ParseLLVMLineTablePrologue(m_context, prologue, offset,
1102                                   dwarf_cu.GetOffset()))
1103     return false;
1104 
1105   std::string comp_dir = dwarf_cu.GetCompilationDirectory().GetPath();
1106   ParseSupportFilesFromPrologue(support_files, module, prologue,
1107                                 dwarf_cu.GetPathStyle(), comp_dir);
1108   return true;
1109 }
1110 
GetFile(DWARFUnit & unit,size_t file_idx)1111 FileSpec SymbolFileDWARF::GetFile(DWARFUnit &unit, size_t file_idx) {
1112   if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit)) {
1113     if (CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(*dwarf_cu))
1114       return lldb_cu->GetSupportFiles().GetFileSpecAtIndex(file_idx);
1115     return FileSpec();
1116   }
1117 
1118   auto &tu = llvm::cast<DWARFTypeUnit>(unit);
1119   if (const SupportFileList *support_files = GetTypeUnitSupportFiles(tu))
1120     return support_files->GetFileSpecAtIndex(file_idx);
1121   return {};
1122 }
1123 
1124 const SupportFileList *
GetTypeUnitSupportFiles(DWARFTypeUnit & tu)1125 SymbolFileDWARF::GetTypeUnitSupportFiles(DWARFTypeUnit &tu) {
1126   static SupportFileList empty_list;
1127 
1128   dw_offset_t offset = tu.GetLineTableOffset();
1129   if (offset == DW_INVALID_OFFSET ||
1130       offset == llvm::DenseMapInfo<dw_offset_t>::getEmptyKey() ||
1131       offset == llvm::DenseMapInfo<dw_offset_t>::getTombstoneKey())
1132     return nullptr;
1133 
1134   // Many type units can share a line table, so parse the support file list
1135   // once, and cache it based on the offset field.
1136   auto iter_bool = m_type_unit_support_files.try_emplace(offset);
1137   std::unique_ptr<SupportFileList> &list = iter_bool.first->second;
1138   if (iter_bool.second) {
1139     list = std::make_unique<SupportFileList>();
1140     uint64_t line_table_offset = offset;
1141     llvm::DWARFDataExtractor data =
1142         m_context.getOrLoadLineData().GetAsLLVMDWARF();
1143     llvm::DWARFContext &ctx = m_context.GetAsLLVM();
1144     llvm::DWARFDebugLine::Prologue prologue;
1145     auto report = [](llvm::Error error) {
1146       Log *log = GetLog(DWARFLog::DebugInfo);
1147       LLDB_LOG_ERROR(log, std::move(error),
1148                      "SymbolFileDWARF::GetTypeUnitSupportFiles failed to parse "
1149                      "the line table prologue: {0}");
1150     };
1151     ElapsedTime elapsed(m_parse_time);
1152     llvm::Error error = prologue.parse(data, &line_table_offset, report, ctx);
1153     if (error)
1154       report(std::move(error));
1155     else
1156       ParseSupportFilesFromPrologue(*list, GetObjectFile()->GetModule(),
1157                                     prologue, tu.GetPathStyle());
1158   }
1159   return list.get();
1160 }
1161 
ParseIsOptimized(CompileUnit & comp_unit)1162 bool SymbolFileDWARF::ParseIsOptimized(CompileUnit &comp_unit) {
1163   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1164   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1165   if (dwarf_cu)
1166     return dwarf_cu->GetNonSkeletonUnit().GetIsOptimized();
1167   return false;
1168 }
1169 
ParseImportedModules(const lldb_private::SymbolContext & sc,std::vector<SourceModule> & imported_modules)1170 bool SymbolFileDWARF::ParseImportedModules(
1171     const lldb_private::SymbolContext &sc,
1172     std::vector<SourceModule> &imported_modules) {
1173   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1174   assert(sc.comp_unit);
1175   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1176   if (!dwarf_cu)
1177     return false;
1178   if (!ClangModulesDeclVendor::LanguageSupportsClangModules(
1179           sc.comp_unit->GetLanguage()))
1180     return false;
1181   UpdateExternalModuleListIfNeeded();
1182 
1183   const DWARFDIE die = dwarf_cu->DIE();
1184   if (!die)
1185     return false;
1186 
1187   for (DWARFDIE child_die : die.children()) {
1188     if (child_die.Tag() != DW_TAG_imported_declaration)
1189       continue;
1190 
1191     DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import);
1192     if (module_die.Tag() != DW_TAG_module)
1193       continue;
1194 
1195     if (const char *name =
1196             module_die.GetAttributeValueAsString(DW_AT_name, nullptr)) {
1197       SourceModule module;
1198       module.path.push_back(ConstString(name));
1199 
1200       DWARFDIE parent_die = module_die;
1201       while ((parent_die = parent_die.GetParent())) {
1202         if (parent_die.Tag() != DW_TAG_module)
1203           break;
1204         if (const char *name =
1205                 parent_die.GetAttributeValueAsString(DW_AT_name, nullptr))
1206           module.path.push_back(ConstString(name));
1207       }
1208       std::reverse(module.path.begin(), module.path.end());
1209       if (const char *include_path = module_die.GetAttributeValueAsString(
1210               DW_AT_LLVM_include_path, nullptr)) {
1211         FileSpec include_spec(include_path, dwarf_cu->GetPathStyle());
1212         MakeAbsoluteAndRemap(include_spec, *dwarf_cu,
1213                              m_objfile_sp->GetModule());
1214         module.search_path = ConstString(include_spec.GetPath());
1215       }
1216       if (const char *sysroot = dwarf_cu->DIE().GetAttributeValueAsString(
1217               DW_AT_LLVM_sysroot, nullptr))
1218         module.sysroot = ConstString(sysroot);
1219       imported_modules.push_back(module);
1220     }
1221   }
1222   return true;
1223 }
1224 
ParseLineTable(CompileUnit & comp_unit)1225 bool SymbolFileDWARF::ParseLineTable(CompileUnit &comp_unit) {
1226   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1227   if (comp_unit.GetLineTable() != nullptr)
1228     return true;
1229 
1230   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1231   if (!dwarf_cu)
1232     return false;
1233 
1234   dw_offset_t offset = dwarf_cu->GetLineTableOffset();
1235   if (offset == DW_INVALID_OFFSET)
1236     return false;
1237 
1238   ElapsedTime elapsed(m_parse_time);
1239   llvm::DWARFDebugLine line;
1240   const llvm::DWARFDebugLine::LineTable *line_table =
1241       ParseLLVMLineTable(m_context, line, offset, dwarf_cu->GetOffset());
1242 
1243   if (!line_table)
1244     return false;
1245 
1246   // FIXME: Rather than parsing the whole line table and then copying it over
1247   // into LLDB, we should explore using a callback to populate the line table
1248   // while we parse to reduce memory usage.
1249   std::vector<std::unique_ptr<LineSequence>> sequences;
1250   // The Sequences view contains only valid line sequences. Don't iterate over
1251   // the Rows directly.
1252   for (const llvm::DWARFDebugLine::Sequence &seq : line_table->Sequences) {
1253     // Ignore line sequences that do not start after the first code address.
1254     // All addresses generated in a sequence are incremental so we only need
1255     // to check the first one of the sequence. Check the comment at the
1256     // m_first_code_address declaration for more details on this.
1257     if (seq.LowPC < m_first_code_address)
1258       continue;
1259     std::unique_ptr<LineSequence> sequence =
1260         LineTable::CreateLineSequenceContainer();
1261     for (unsigned idx = seq.FirstRowIndex; idx < seq.LastRowIndex; ++idx) {
1262       const llvm::DWARFDebugLine::Row &row = line_table->Rows[idx];
1263       LineTable::AppendLineEntryToSequence(
1264           sequence.get(), row.Address.Address, row.Line, row.Column, row.File,
1265           row.IsStmt, row.BasicBlock, row.PrologueEnd, row.EpilogueBegin,
1266           row.EndSequence);
1267     }
1268     sequences.push_back(std::move(sequence));
1269   }
1270 
1271   std::unique_ptr<LineTable> line_table_up =
1272       std::make_unique<LineTable>(&comp_unit, std::move(sequences));
1273 
1274   if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) {
1275     // We have an object file that has a line table with addresses that are not
1276     // linked. We need to link the line table and convert the addresses that
1277     // are relative to the .o file into addresses for the main executable.
1278     comp_unit.SetLineTable(
1279         debug_map_symfile->LinkOSOLineTable(this, line_table_up.get()));
1280   } else {
1281     comp_unit.SetLineTable(line_table_up.release());
1282   }
1283 
1284   return true;
1285 }
1286 
1287 lldb_private::DebugMacrosSP
ParseDebugMacros(lldb::offset_t * offset)1288 SymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset) {
1289   auto iter = m_debug_macros_map.find(*offset);
1290   if (iter != m_debug_macros_map.end())
1291     return iter->second;
1292 
1293   ElapsedTime elapsed(m_parse_time);
1294   const DWARFDataExtractor &debug_macro_data = m_context.getOrLoadMacroData();
1295   if (debug_macro_data.GetByteSize() == 0)
1296     return DebugMacrosSP();
1297 
1298   lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros());
1299   m_debug_macros_map[*offset] = debug_macros_sp;
1300 
1301   const DWARFDebugMacroHeader &header =
1302       DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset);
1303   DWARFDebugMacroEntry::ReadMacroEntries(
1304       debug_macro_data, m_context.getOrLoadStrData(), header.OffsetIs64Bit(),
1305       offset, this, debug_macros_sp);
1306 
1307   return debug_macros_sp;
1308 }
1309 
ParseDebugMacros(CompileUnit & comp_unit)1310 bool SymbolFileDWARF::ParseDebugMacros(CompileUnit &comp_unit) {
1311   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1312 
1313   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1314   if (dwarf_cu == nullptr)
1315     return false;
1316 
1317   const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
1318   if (!dwarf_cu_die)
1319     return false;
1320 
1321   lldb::offset_t sect_offset =
1322       dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET);
1323   if (sect_offset == DW_INVALID_OFFSET)
1324     sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros,
1325                                                            DW_INVALID_OFFSET);
1326   if (sect_offset == DW_INVALID_OFFSET)
1327     return false;
1328 
1329   comp_unit.SetDebugMacros(ParseDebugMacros(&sect_offset));
1330 
1331   return true;
1332 }
1333 
ParseBlocksRecursive(lldb_private::CompileUnit & comp_unit,Block * parent_block,const DWARFDIE & orig_die,addr_t subprogram_low_pc,uint32_t depth)1334 size_t SymbolFileDWARF::ParseBlocksRecursive(
1335     lldb_private::CompileUnit &comp_unit, Block *parent_block,
1336     const DWARFDIE &orig_die, addr_t subprogram_low_pc, uint32_t depth) {
1337   size_t blocks_added = 0;
1338   DWARFDIE die = orig_die;
1339   while (die) {
1340     dw_tag_t tag = die.Tag();
1341 
1342     switch (tag) {
1343     case DW_TAG_inlined_subroutine:
1344     case DW_TAG_subprogram:
1345     case DW_TAG_lexical_block: {
1346       Block *block = nullptr;
1347       if (tag == DW_TAG_subprogram) {
1348         // Skip any DW_TAG_subprogram DIEs that are inside of a normal or
1349         // inlined functions. These will be parsed on their own as separate
1350         // entities.
1351 
1352         if (depth > 0)
1353           break;
1354 
1355         block = parent_block;
1356       } else {
1357         BlockSP block_sp(new Block(die.GetID()));
1358         parent_block->AddChild(block_sp);
1359         block = block_sp.get();
1360       }
1361       DWARFRangeList ranges;
1362       const char *name = nullptr;
1363       const char *mangled_name = nullptr;
1364 
1365       std::optional<int> decl_file;
1366       std::optional<int> decl_line;
1367       std::optional<int> decl_column;
1368       std::optional<int> call_file;
1369       std::optional<int> call_line;
1370       std::optional<int> call_column;
1371       if (die.GetDIENamesAndRanges(name, mangled_name, ranges, decl_file,
1372                                    decl_line, decl_column, call_file, call_line,
1373                                    call_column, nullptr)) {
1374         if (tag == DW_TAG_subprogram) {
1375           assert(subprogram_low_pc == LLDB_INVALID_ADDRESS);
1376           subprogram_low_pc = ranges.GetMinRangeBase(0);
1377         } else if (tag == DW_TAG_inlined_subroutine) {
1378           // We get called here for inlined subroutines in two ways. The first
1379           // time is when we are making the Function object for this inlined
1380           // concrete instance.  Since we're creating a top level block at
1381           // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS.  So we
1382           // need to adjust the containing address. The second time is when we
1383           // are parsing the blocks inside the function that contains the
1384           // inlined concrete instance.  Since these will be blocks inside the
1385           // containing "real" function the offset will be for that function.
1386           if (subprogram_low_pc == LLDB_INVALID_ADDRESS) {
1387             subprogram_low_pc = ranges.GetMinRangeBase(0);
1388           }
1389         }
1390 
1391         const size_t num_ranges = ranges.GetSize();
1392         for (size_t i = 0; i < num_ranges; ++i) {
1393           const DWARFRangeList::Entry &range = ranges.GetEntryRef(i);
1394           const addr_t range_base = range.GetRangeBase();
1395           if (range_base >= subprogram_low_pc)
1396             block->AddRange(Block::Range(range_base - subprogram_low_pc,
1397                                          range.GetByteSize()));
1398           else {
1399             GetObjectFile()->GetModule()->ReportError(
1400                 "{0:x8}: adding range [{1:x16}-{2:x16}) which has a base "
1401                 "that is less than the function's low PC {3:x16}. Please file "
1402                 "a bug and attach the file at the "
1403                 "start of this error message",
1404                 block->GetID(), range_base, range.GetRangeEnd(),
1405                 subprogram_low_pc);
1406           }
1407         }
1408         block->FinalizeRanges();
1409 
1410         if (tag != DW_TAG_subprogram &&
1411             (name != nullptr || mangled_name != nullptr)) {
1412           std::unique_ptr<Declaration> decl_up;
1413           if (decl_file || decl_line || decl_column)
1414             decl_up = std::make_unique<Declaration>(
1415                 comp_unit.GetSupportFiles().GetFileSpecAtIndex(
1416                     decl_file ? *decl_file : 0),
1417                 decl_line ? *decl_line : 0, decl_column ? *decl_column : 0);
1418 
1419           std::unique_ptr<Declaration> call_up;
1420           if (call_file || call_line || call_column)
1421             call_up = std::make_unique<Declaration>(
1422                 comp_unit.GetSupportFiles().GetFileSpecAtIndex(
1423                     call_file ? *call_file : 0),
1424                 call_line ? *call_line : 0, call_column ? *call_column : 0);
1425 
1426           block->SetInlinedFunctionInfo(name, mangled_name, decl_up.get(),
1427                                         call_up.get());
1428         }
1429 
1430         ++blocks_added;
1431 
1432         if (die.HasChildren()) {
1433           blocks_added +=
1434               ParseBlocksRecursive(comp_unit, block, die.GetFirstChild(),
1435                                    subprogram_low_pc, depth + 1);
1436         }
1437       }
1438     } break;
1439     default:
1440       break;
1441     }
1442 
1443     // Only parse siblings of the block if we are not at depth zero. A depth of
1444     // zero indicates we are currently parsing the top level DW_TAG_subprogram
1445     // DIE
1446 
1447     if (depth == 0)
1448       die.Clear();
1449     else
1450       die = die.GetSibling();
1451   }
1452   return blocks_added;
1453 }
1454 
ClassOrStructIsVirtual(const DWARFDIE & parent_die)1455 bool SymbolFileDWARF::ClassOrStructIsVirtual(const DWARFDIE &parent_die) {
1456   if (parent_die) {
1457     for (DWARFDIE die : parent_die.children()) {
1458       dw_tag_t tag = die.Tag();
1459       bool check_virtuality = false;
1460       switch (tag) {
1461       case DW_TAG_inheritance:
1462       case DW_TAG_subprogram:
1463         check_virtuality = true;
1464         break;
1465       default:
1466         break;
1467       }
1468       if (check_virtuality) {
1469         if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0)
1470           return true;
1471       }
1472     }
1473   }
1474   return false;
1475 }
1476 
ParseDeclsForContext(CompilerDeclContext decl_ctx)1477 void SymbolFileDWARF::ParseDeclsForContext(CompilerDeclContext decl_ctx) {
1478   auto *type_system = decl_ctx.GetTypeSystem();
1479   if (type_system != nullptr)
1480     type_system->GetDWARFParser()->EnsureAllDIEsInDeclContextHaveBeenParsed(
1481         decl_ctx);
1482 }
1483 
1484 DWARFDIE
GetDIE(lldb::user_id_t uid)1485 SymbolFileDWARF::GetDIE(lldb::user_id_t uid) { return GetDIE(DIERef(uid)); }
1486 
GetDeclForUID(lldb::user_id_t type_uid)1487 CompilerDecl SymbolFileDWARF::GetDeclForUID(lldb::user_id_t type_uid) {
1488   // This method can be called without going through the symbol vendor so we
1489   // need to lock the module.
1490   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1491   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1492   // SymbolFileDWARF::GetDIE(). See comments inside the
1493   // SymbolFileDWARF::GetDIE() for details.
1494   if (DWARFDIE die = GetDIE(type_uid))
1495     return GetDecl(die);
1496   return CompilerDecl();
1497 }
1498 
1499 CompilerDeclContext
GetDeclContextForUID(lldb::user_id_t type_uid)1500 SymbolFileDWARF::GetDeclContextForUID(lldb::user_id_t type_uid) {
1501   // This method can be called without going through the symbol vendor so we
1502   // need to lock the module.
1503   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1504   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1505   // SymbolFileDWARF::GetDIE(). See comments inside the
1506   // SymbolFileDWARF::GetDIE() for details.
1507   if (DWARFDIE die = GetDIE(type_uid))
1508     return GetDeclContext(die);
1509   return CompilerDeclContext();
1510 }
1511 
1512 CompilerDeclContext
GetDeclContextContainingUID(lldb::user_id_t type_uid)1513 SymbolFileDWARF::GetDeclContextContainingUID(lldb::user_id_t type_uid) {
1514   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1515   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1516   // SymbolFileDWARF::GetDIE(). See comments inside the
1517   // SymbolFileDWARF::GetDIE() for details.
1518   if (DWARFDIE die = GetDIE(type_uid))
1519     return GetContainingDeclContext(die);
1520   return CompilerDeclContext();
1521 }
1522 
1523 std::vector<CompilerContext>
GetCompilerContextForUID(lldb::user_id_t type_uid)1524 SymbolFileDWARF::GetCompilerContextForUID(lldb::user_id_t type_uid) {
1525   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1526   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1527   // SymbolFileDWARF::GetDIE(). See comments inside the
1528   // SymbolFileDWARF::GetDIE() for details.
1529   if (DWARFDIE die = GetDIE(type_uid))
1530     return die.GetDeclContext();
1531   return {};
1532 }
1533 
ResolveTypeUID(lldb::user_id_t type_uid)1534 Type *SymbolFileDWARF::ResolveTypeUID(lldb::user_id_t type_uid) {
1535   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1536   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1537   // SymbolFileDWARF::GetDIE(). See comments inside the
1538   // SymbolFileDWARF::GetDIE() for details.
1539   if (DWARFDIE type_die = GetDIE(type_uid))
1540     return type_die.ResolveType();
1541   else
1542     return nullptr;
1543 }
1544 
GetDynamicArrayInfoForUID(lldb::user_id_t type_uid,const lldb_private::ExecutionContext * exe_ctx)1545 std::optional<SymbolFile::ArrayInfo> SymbolFileDWARF::GetDynamicArrayInfoForUID(
1546     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1547   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1548   if (DWARFDIE type_die = GetDIE(type_uid))
1549     return DWARFASTParser::ParseChildArrayInfo(type_die, exe_ctx);
1550   else
1551     return std::nullopt;
1552 }
1553 
ResolveTypeUID(const DIERef & die_ref)1554 Type *SymbolFileDWARF::ResolveTypeUID(const DIERef &die_ref) {
1555   return ResolveType(GetDIE(die_ref), true);
1556 }
1557 
ResolveTypeUID(const DWARFDIE & die,bool assert_not_being_parsed)1558 Type *SymbolFileDWARF::ResolveTypeUID(const DWARFDIE &die,
1559                                       bool assert_not_being_parsed) {
1560   if (die) {
1561     Log *log = GetLog(DWARFLog::DebugInfo);
1562     if (log)
1563       GetObjectFile()->GetModule()->LogMessage(
1564           log,
1565           "SymbolFileDWARF::ResolveTypeUID (die = {0:x16}) {1} ({2}) '{3}'",
1566           die.GetOffset(), DW_TAG_value_to_name(die.Tag()), die.Tag(),
1567           die.GetName());
1568 
1569     // We might be coming in in the middle of a type tree (a class within a
1570     // class, an enum within a class), so parse any needed parent DIEs before
1571     // we get to this one...
1572     DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die);
1573     if (decl_ctx_die) {
1574       if (log) {
1575         switch (decl_ctx_die.Tag()) {
1576         case DW_TAG_structure_type:
1577         case DW_TAG_union_type:
1578         case DW_TAG_class_type: {
1579           // Get the type, which could be a forward declaration
1580           if (log)
1581             GetObjectFile()->GetModule()->LogMessage(
1582                 log,
1583                 "SymbolFileDWARF::ResolveTypeUID (die = {0:x16}) {1} ({2}) "
1584                 "'{3}' resolve parent forward type for {4:x16})",
1585                 die.GetOffset(), DW_TAG_value_to_name(die.Tag()), die.Tag(),
1586                 die.GetName(), decl_ctx_die.GetOffset());
1587         } break;
1588 
1589         default:
1590           break;
1591         }
1592       }
1593     }
1594     return ResolveType(die);
1595   }
1596   return nullptr;
1597 }
1598 
1599 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
1600 // SymbolFileDWARF objects to detect if this DWARF file is the one that can
1601 // resolve a compiler_type.
HasForwardDeclForCompilerType(const CompilerType & compiler_type)1602 bool SymbolFileDWARF::HasForwardDeclForCompilerType(
1603     const CompilerType &compiler_type) {
1604   CompilerType compiler_type_no_qualifiers =
1605       ClangUtil::RemoveFastQualifiers(compiler_type);
1606   if (GetForwardDeclCompilerTypeToDIE().count(
1607           compiler_type_no_qualifiers.GetOpaqueQualType())) {
1608     return true;
1609   }
1610   auto type_system = compiler_type.GetTypeSystem();
1611   auto clang_type_system = type_system.dyn_cast_or_null<TypeSystemClang>();
1612   if (!clang_type_system)
1613     return false;
1614   DWARFASTParserClang *ast_parser =
1615       static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1616   return ast_parser->GetClangASTImporter().CanImport(compiler_type);
1617 }
1618 
CompleteType(CompilerType & compiler_type)1619 bool SymbolFileDWARF::CompleteType(CompilerType &compiler_type) {
1620   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1621   auto clang_type_system =
1622       compiler_type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
1623   if (clang_type_system) {
1624     DWARFASTParserClang *ast_parser =
1625         static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1626     if (ast_parser &&
1627         ast_parser->GetClangASTImporter().CanImport(compiler_type))
1628       return ast_parser->GetClangASTImporter().CompleteType(compiler_type);
1629   }
1630 
1631   // We have a struct/union/class/enum that needs to be fully resolved.
1632   CompilerType compiler_type_no_qualifiers =
1633       ClangUtil::RemoveFastQualifiers(compiler_type);
1634   auto die_it = GetForwardDeclCompilerTypeToDIE().find(
1635       compiler_type_no_qualifiers.GetOpaqueQualType());
1636   if (die_it == GetForwardDeclCompilerTypeToDIE().end()) {
1637     // We have already resolved this type...
1638     return true;
1639   }
1640 
1641   DWARFDIE decl_die = GetDIE(die_it->getSecond());
1642   // Once we start resolving this type, remove it from the forward
1643   // declaration map in case anyone's child members or other types require this
1644   // type to get resolved.
1645   GetForwardDeclCompilerTypeToDIE().erase(die_it);
1646   DWARFDIE def_die = FindDefinitionDIE(decl_die);
1647   if (!def_die) {
1648     SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
1649     if (debug_map_symfile) {
1650       // We weren't able to find a full declaration in this DWARF, see
1651       // if we have a declaration anywhere else...
1652       def_die = debug_map_symfile->FindDefinitionDIE(decl_die);
1653     }
1654   }
1655   if (!def_die) {
1656     // If we don't have definition DIE, CompleteTypeFromDWARF will forcefully
1657     // complete this type.
1658     def_die = decl_die;
1659   }
1660 
1661   DWARFASTParser *dwarf_ast = GetDWARFParser(*def_die.GetCU());
1662   if (!dwarf_ast)
1663     return false;
1664   Type *type = GetDIEToType().lookup(decl_die.GetDIE());
1665   if (decl_die != def_die) {
1666     GetDIEToType()[def_die.GetDIE()] = type;
1667     DWARFASTParserClang *ast_parser =
1668         static_cast<DWARFASTParserClang *>(dwarf_ast);
1669     ast_parser->MapDeclDIEToDefDIE(decl_die, def_die);
1670   }
1671 
1672   Log *log = GetLog(DWARFLog::DebugInfo | DWARFLog::TypeCompletion);
1673   if (log)
1674     GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
1675         log, "{0:x8}: {1} ({2}) '{3}' resolving forward declaration...",
1676         def_die.GetID(), DW_TAG_value_to_name(def_die.Tag()), def_die.Tag(),
1677         type->GetName().AsCString());
1678   assert(compiler_type);
1679   return dwarf_ast->CompleteTypeFromDWARF(def_die, type, compiler_type);
1680 }
1681 
ResolveType(const DWARFDIE & die,bool assert_not_being_parsed,bool resolve_function_context)1682 Type *SymbolFileDWARF::ResolveType(const DWARFDIE &die,
1683                                    bool assert_not_being_parsed,
1684                                    bool resolve_function_context) {
1685   if (die) {
1686     Type *type = GetTypeForDIE(die, resolve_function_context).get();
1687 
1688     if (assert_not_being_parsed) {
1689       if (type != DIE_IS_BEING_PARSED)
1690         return type;
1691 
1692       GetObjectFile()->GetModule()->ReportError(
1693           "Parsing a die that is being parsed die: {0:x16}: {1} ({2}) {3}",
1694           die.GetOffset(), DW_TAG_value_to_name(die.Tag()), die.Tag(),
1695           die.GetName());
1696 
1697     } else
1698       return type;
1699   }
1700   return nullptr;
1701 }
1702 
1703 CompileUnit *
GetCompUnitForDWARFCompUnit(DWARFCompileUnit & dwarf_cu)1704 SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu) {
1705 
1706   if (dwarf_cu.IsDWOUnit()) {
1707     DWARFCompileUnit *non_dwo_cu = dwarf_cu.GetSkeletonUnit();
1708     assert(non_dwo_cu);
1709     return non_dwo_cu->GetSymbolFileDWARF().GetCompUnitForDWARFCompUnit(
1710         *non_dwo_cu);
1711   }
1712   // Check if the symbol vendor already knows about this compile unit?
1713   CompileUnit *lldb_cu = dwarf_cu.GetLLDBCompUnit();
1714   if (lldb_cu)
1715     return lldb_cu;
1716   // The symbol vendor doesn't know about this compile unit, we need to parse
1717   // and add it to the symbol vendor object.
1718   return ParseCompileUnit(dwarf_cu).get();
1719 }
1720 
GetObjCMethods(ConstString class_name,llvm::function_ref<bool (DWARFDIE die)> callback)1721 void SymbolFileDWARF::GetObjCMethods(
1722     ConstString class_name, llvm::function_ref<bool(DWARFDIE die)> callback) {
1723   m_index->GetObjCMethods(class_name, callback);
1724 }
1725 
GetFunction(const DWARFDIE & die,SymbolContext & sc)1726 bool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) {
1727   sc.Clear(false);
1728 
1729   if (die && llvm::isa<DWARFCompileUnit>(die.GetCU())) {
1730     // Check if the symbol vendor already knows about this compile unit?
1731     sc.comp_unit =
1732         GetCompUnitForDWARFCompUnit(llvm::cast<DWARFCompileUnit>(*die.GetCU()));
1733 
1734     sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
1735     if (sc.function == nullptr)
1736       sc.function = ParseFunction(*sc.comp_unit, die);
1737 
1738     if (sc.function) {
1739       sc.module_sp = sc.function->CalculateSymbolContextModule();
1740       return true;
1741     }
1742   }
1743 
1744   return false;
1745 }
1746 
GetExternalModule(ConstString name)1747 lldb::ModuleSP SymbolFileDWARF::GetExternalModule(ConstString name) {
1748   UpdateExternalModuleListIfNeeded();
1749   const auto &pos = m_external_type_modules.find(name);
1750   if (pos == m_external_type_modules.end())
1751     return lldb::ModuleSP();
1752   return pos->second;
1753 }
1754 
GetDIERefSymbolFile(const DIERef & die_ref)1755 SymbolFileDWARF *SymbolFileDWARF::GetDIERefSymbolFile(const DIERef &die_ref) {
1756   // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we
1757   // must make sure we use the correct DWARF file when resolving things. On
1758   // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1759   // SymbolFileDWARF classes, one for each .o file. We can often end up with
1760   // references to other DWARF objects and we must be ready to receive a
1761   // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1762   // instance.
1763 
1764   std::optional<uint32_t> file_index = die_ref.file_index();
1765 
1766   // If the file index matches, then we have the right SymbolFileDWARF already.
1767   // This will work for both .dwo file and DWARF in .o files for mac. Also if
1768   // both the file indexes are invalid, then we have a match.
1769   if (GetFileIndex() == file_index)
1770     return this;
1771 
1772   if (file_index) {
1773       // We have a SymbolFileDWARFDebugMap, so let it find the right file
1774     if (SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile())
1775       return debug_map->GetSymbolFileByOSOIndex(*file_index);
1776 
1777     // Handle the .dwp file case correctly
1778     if (*file_index == DIERef::k_file_index_mask)
1779       return GetDwpSymbolFile().get(); // DWP case
1780 
1781     // Handle the .dwo file case correctly
1782     return DebugInfo().GetUnitAtIndex(*die_ref.file_index())
1783         ->GetDwoSymbolFile(); // DWO case
1784   }
1785   return this;
1786 }
1787 
1788 DWARFDIE
GetDIE(const DIERef & die_ref)1789 SymbolFileDWARF::GetDIE(const DIERef &die_ref) {
1790   if (die_ref.die_offset() == DW_INVALID_OFFSET)
1791     return DWARFDIE();
1792 
1793   // This method can be called without going through the symbol vendor so we
1794   // need to lock the module.
1795   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1796   SymbolFileDWARF *symbol_file = GetDIERefSymbolFile(die_ref);
1797   if (symbol_file)
1798     return symbol_file->DebugInfo().GetDIE(die_ref.section(),
1799                                            die_ref.die_offset());
1800   return DWARFDIE();
1801 }
1802 
1803 /// Return the DW_AT_(GNU_)dwo_id.
GetDWOId(DWARFCompileUnit & dwarf_cu,const DWARFDebugInfoEntry & cu_die)1804 static std::optional<uint64_t> GetDWOId(DWARFCompileUnit &dwarf_cu,
1805                                         const DWARFDebugInfoEntry &cu_die) {
1806   std::optional<uint64_t> dwo_id =
1807       cu_die.GetAttributeValueAsOptionalUnsigned(&dwarf_cu, DW_AT_GNU_dwo_id);
1808   if (dwo_id)
1809     return dwo_id;
1810   return cu_die.GetAttributeValueAsOptionalUnsigned(&dwarf_cu, DW_AT_dwo_id);
1811 }
1812 
GetDWOId()1813 std::optional<uint64_t> SymbolFileDWARF::GetDWOId() {
1814   if (GetNumCompileUnits() == 1) {
1815     if (auto comp_unit = GetCompileUnitAtIndex(0))
1816       if (DWARFCompileUnit *cu = GetDWARFCompileUnit(comp_unit.get()))
1817         if (DWARFDebugInfoEntry *cu_die = cu->DIE().GetDIE())
1818           return ::GetDWOId(*cu, *cu_die);
1819   }
1820   return {};
1821 }
1822 
GetSkeletonUnit(DWARFUnit * dwo_unit)1823 DWARFUnit *SymbolFileDWARF::GetSkeletonUnit(DWARFUnit *dwo_unit) {
1824   return DebugInfo().GetSkeletonUnit(dwo_unit);
1825 }
1826 
1827 std::shared_ptr<SymbolFileDWARFDwo>
GetDwoSymbolFileForCompileUnit(DWARFUnit & unit,const DWARFDebugInfoEntry & cu_die)1828 SymbolFileDWARF::GetDwoSymbolFileForCompileUnit(
1829     DWARFUnit &unit, const DWARFDebugInfoEntry &cu_die) {
1830   // If this is a Darwin-style debug map (non-.dSYM) symbol file,
1831   // never attempt to load ELF-style DWO files since the -gmodules
1832   // support uses the same DWO mechanism to specify full debug info
1833   // files for modules. This is handled in
1834   // UpdateExternalModuleListIfNeeded().
1835   if (GetDebugMapSymfile())
1836     return nullptr;
1837 
1838   DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit);
1839   // Only compile units can be split into two parts and we should only
1840   // look for a DWO file if there is a valid DWO ID.
1841   if (!dwarf_cu || !dwarf_cu->GetDWOId().has_value())
1842     return nullptr;
1843 
1844   const char *dwo_name = GetDWOName(*dwarf_cu, cu_die);
1845   if (!dwo_name) {
1846     unit.SetDwoError(Status::createWithFormat(
1847         "missing DWO name in skeleton DIE {0:x16}", cu_die.GetOffset()));
1848     return nullptr;
1849   }
1850 
1851   if (std::shared_ptr<SymbolFileDWARFDwo> dwp_sp = GetDwpSymbolFile())
1852     return dwp_sp;
1853 
1854   FileSpec dwo_file(dwo_name);
1855   FileSystem::Instance().Resolve(dwo_file);
1856   bool found = false;
1857 
1858   const FileSpecList &debug_file_search_paths =
1859       Target::GetDefaultDebugFileSearchPaths();
1860   size_t num_search_paths = debug_file_search_paths.GetSize();
1861 
1862   // It's relative, e.g. "foo.dwo", but we just to happen to be right next to
1863   // it. Or it's absolute.
1864   found = FileSystem::Instance().Exists(dwo_file);
1865 
1866   const char *comp_dir =
1867       cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_comp_dir, nullptr);
1868   if (!found) {
1869     // It could be a relative path that also uses DW_AT_COMP_DIR.
1870     if (comp_dir) {
1871       dwo_file.SetFile(comp_dir, FileSpec::Style::native);
1872       if (!dwo_file.IsRelative()) {
1873         FileSystem::Instance().Resolve(dwo_file);
1874         dwo_file.AppendPathComponent(dwo_name);
1875         found = FileSystem::Instance().Exists(dwo_file);
1876       } else {
1877         FileSpecList dwo_paths;
1878 
1879         // if DW_AT_comp_dir is relative, it should be relative to the location
1880         // of the executable, not to the location from which the debugger was
1881         // launched.
1882         FileSpec relative_to_binary = dwo_file;
1883         relative_to_binary.PrependPathComponent(
1884             m_objfile_sp->GetFileSpec().GetDirectory().GetStringRef());
1885         FileSystem::Instance().Resolve(relative_to_binary);
1886         relative_to_binary.AppendPathComponent(dwo_name);
1887         dwo_paths.Append(relative_to_binary);
1888 
1889         // Or it's relative to one of the user specified debug directories.
1890         for (size_t idx = 0; idx < num_search_paths; ++idx) {
1891           FileSpec dirspec = debug_file_search_paths.GetFileSpecAtIndex(idx);
1892           dirspec.AppendPathComponent(comp_dir);
1893           FileSystem::Instance().Resolve(dirspec);
1894           if (!FileSystem::Instance().IsDirectory(dirspec))
1895             continue;
1896 
1897           dirspec.AppendPathComponent(dwo_name);
1898           dwo_paths.Append(dirspec);
1899         }
1900 
1901         size_t num_possible = dwo_paths.GetSize();
1902         for (size_t idx = 0; idx < num_possible && !found; ++idx) {
1903           FileSpec dwo_spec = dwo_paths.GetFileSpecAtIndex(idx);
1904           if (FileSystem::Instance().Exists(dwo_spec)) {
1905             dwo_file = dwo_spec;
1906             found = true;
1907           }
1908         }
1909       }
1910     } else {
1911       Log *log = GetLog(LLDBLog::Symbols);
1912       LLDB_LOGF(log,
1913                 "unable to locate relative .dwo debug file \"%s\" for "
1914                 "skeleton DIE 0x%016" PRIx64 " without valid DW_AT_comp_dir "
1915                 "attribute",
1916                 dwo_name, cu_die.GetOffset());
1917     }
1918   }
1919 
1920   if (!found) {
1921     // Try adding the DW_AT_dwo_name ( e.g. "c/d/main-main.dwo"), and just the
1922     // filename ("main-main.dwo") to binary dir and search paths.
1923     FileSpecList dwo_paths;
1924     FileSpec dwo_name_spec(dwo_name);
1925     llvm::StringRef filename_only = dwo_name_spec.GetFilename();
1926 
1927     FileSpec binary_directory(
1928         m_objfile_sp->GetFileSpec().GetDirectory().GetStringRef());
1929     FileSystem::Instance().Resolve(binary_directory);
1930 
1931     if (dwo_name_spec.IsRelative()) {
1932       FileSpec dwo_name_binary_directory(binary_directory);
1933       dwo_name_binary_directory.AppendPathComponent(dwo_name);
1934       dwo_paths.Append(dwo_name_binary_directory);
1935     }
1936 
1937     FileSpec filename_binary_directory(binary_directory);
1938     filename_binary_directory.AppendPathComponent(filename_only);
1939     dwo_paths.Append(filename_binary_directory);
1940 
1941     for (size_t idx = 0; idx < num_search_paths; ++idx) {
1942       FileSpec dirspec = debug_file_search_paths.GetFileSpecAtIndex(idx);
1943       FileSystem::Instance().Resolve(dirspec);
1944       if (!FileSystem::Instance().IsDirectory(dirspec))
1945         continue;
1946 
1947       FileSpec dwo_name_dirspec(dirspec);
1948       dwo_name_dirspec.AppendPathComponent(dwo_name);
1949       dwo_paths.Append(dwo_name_dirspec);
1950 
1951       FileSpec filename_dirspec(dirspec);
1952       filename_dirspec.AppendPathComponent(filename_only);
1953       dwo_paths.Append(filename_dirspec);
1954     }
1955 
1956     size_t num_possible = dwo_paths.GetSize();
1957     for (size_t idx = 0; idx < num_possible && !found; ++idx) {
1958       FileSpec dwo_spec = dwo_paths.GetFileSpecAtIndex(idx);
1959       if (FileSystem::Instance().Exists(dwo_spec)) {
1960         dwo_file = dwo_spec;
1961         found = true;
1962       }
1963     }
1964   }
1965 
1966   if (!found) {
1967     FileSpec error_dwo_path(dwo_name);
1968     FileSystem::Instance().Resolve(error_dwo_path);
1969     if (error_dwo_path.IsRelative() && comp_dir != nullptr) {
1970       error_dwo_path.PrependPathComponent(comp_dir);
1971       FileSystem::Instance().Resolve(error_dwo_path);
1972     }
1973     unit.SetDwoError(Status::createWithFormat(
1974         "unable to locate .dwo debug file \"{0}\" for skeleton DIE "
1975         "{1:x16}",
1976         error_dwo_path.GetPath().c_str(), cu_die.GetOffset()));
1977 
1978     if (m_dwo_warning_issued.test_and_set(std::memory_order_relaxed) == false) {
1979       GetObjectFile()->GetModule()->ReportWarning(
1980           "unable to locate separate debug file (dwo, dwp). Debugging will be "
1981           "degraded.");
1982     }
1983     return nullptr;
1984   }
1985 
1986   const lldb::offset_t file_offset = 0;
1987   DataBufferSP dwo_file_data_sp;
1988   lldb::offset_t dwo_file_data_offset = 0;
1989   ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin(
1990       GetObjectFile()->GetModule(), &dwo_file, file_offset,
1991       FileSystem::Instance().GetByteSize(dwo_file), dwo_file_data_sp,
1992       dwo_file_data_offset);
1993   if (dwo_obj_file == nullptr) {
1994     unit.SetDwoError(Status::createWithFormat(
1995         "unable to load object file for .dwo debug file \"{0}\" for "
1996         "unit DIE {1:x16}",
1997         dwo_name, cu_die.GetOffset()));
1998     return nullptr;
1999   }
2000 
2001   return std::make_shared<SymbolFileDWARFDwo>(*this, dwo_obj_file,
2002                                               dwarf_cu->GetID());
2003 }
2004 
UpdateExternalModuleListIfNeeded()2005 void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() {
2006   if (m_fetched_external_modules)
2007     return;
2008   m_fetched_external_modules = true;
2009   DWARFDebugInfo &debug_info = DebugInfo();
2010 
2011   // Follow DWO skeleton unit breadcrumbs.
2012   const uint32_t num_compile_units = GetNumCompileUnits();
2013   for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2014     auto *dwarf_cu =
2015         llvm::dyn_cast<DWARFCompileUnit>(debug_info.GetUnitAtIndex(cu_idx));
2016     if (!dwarf_cu)
2017       continue;
2018 
2019     const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
2020     if (!die || die.HasChildren() || !die.GetDIE())
2021       continue;
2022 
2023     const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
2024     if (!name)
2025       continue;
2026 
2027     ConstString const_name(name);
2028     ModuleSP &module_sp = m_external_type_modules[const_name];
2029     if (module_sp)
2030       continue;
2031 
2032     const char *dwo_path = GetDWOName(*dwarf_cu, *die.GetDIE());
2033     if (!dwo_path)
2034       continue;
2035 
2036     ModuleSpec dwo_module_spec;
2037     dwo_module_spec.GetFileSpec().SetFile(dwo_path, FileSpec::Style::native);
2038     if (dwo_module_spec.GetFileSpec().IsRelative()) {
2039       const char *comp_dir =
2040           die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr);
2041       if (comp_dir) {
2042         dwo_module_spec.GetFileSpec().SetFile(comp_dir,
2043                                               FileSpec::Style::native);
2044         FileSystem::Instance().Resolve(dwo_module_spec.GetFileSpec());
2045         dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path);
2046       }
2047     }
2048     dwo_module_spec.GetArchitecture() =
2049         m_objfile_sp->GetModule()->GetArchitecture();
2050 
2051     // When LLDB loads "external" modules it looks at the presence of
2052     // DW_AT_dwo_name. However, when the already created module
2053     // (corresponding to .dwo itself) is being processed, it will see
2054     // the presence of DW_AT_dwo_name (which contains the name of dwo
2055     // file) and will try to call ModuleList::GetSharedModule
2056     // again. In some cases (i.e., for empty files) Clang 4.0
2057     // generates a *.dwo file which has DW_AT_dwo_name, but no
2058     // DW_AT_comp_dir. In this case the method
2059     // ModuleList::GetSharedModule will fail and the warning will be
2060     // printed. However, as one can notice in this case we don't
2061     // actually need to try to load the already loaded module
2062     // (corresponding to .dwo) so we simply skip it.
2063     if (m_objfile_sp->GetFileSpec().GetFileNameExtension() == ".dwo" &&
2064         llvm::StringRef(m_objfile_sp->GetFileSpec().GetPath())
2065             .ends_with(dwo_module_spec.GetFileSpec().GetPath())) {
2066       continue;
2067     }
2068 
2069     Status error = ModuleList::GetSharedModule(dwo_module_spec, module_sp,
2070                                                nullptr, nullptr, nullptr);
2071     if (!module_sp) {
2072       GetObjectFile()->GetModule()->ReportWarning(
2073           "{0:x16}: unable to locate module needed for external types: "
2074           "{1}\nerror: {2}\nDebugging will be degraded due to missing "
2075           "types. Rebuilding the project will regenerate the needed "
2076           "module files.",
2077           die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str(),
2078           error.AsCString("unknown error"));
2079       continue;
2080     }
2081 
2082     // Verify the DWO hash.
2083     // FIXME: Technically "0" is a valid hash.
2084     std::optional<uint64_t> dwo_id = ::GetDWOId(*dwarf_cu, *die.GetDIE());
2085     if (!dwo_id)
2086       continue;
2087 
2088     auto *dwo_symfile =
2089         llvm::dyn_cast_or_null<SymbolFileDWARF>(module_sp->GetSymbolFile());
2090     if (!dwo_symfile)
2091       continue;
2092     std::optional<uint64_t> dwo_dwo_id = dwo_symfile->GetDWOId();
2093     if (!dwo_dwo_id)
2094       continue;
2095 
2096     if (dwo_id != dwo_dwo_id) {
2097       GetObjectFile()->GetModule()->ReportWarning(
2098           "{0:x16}: Module {1} is out-of-date (hash mismatch). Type "
2099           "information "
2100           "from this module may be incomplete or inconsistent with the rest of "
2101           "the program. Rebuilding the project will regenerate the needed "
2102           "module files.",
2103           die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str());
2104     }
2105   }
2106 }
2107 
GetGlobalAranges()2108 SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() {
2109   if (!m_global_aranges_up) {
2110     m_global_aranges_up = std::make_unique<GlobalVariableMap>();
2111 
2112     ModuleSP module_sp = GetObjectFile()->GetModule();
2113     if (module_sp) {
2114       const size_t num_cus = module_sp->GetNumCompileUnits();
2115       for (size_t i = 0; i < num_cus; ++i) {
2116         CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
2117         if (cu_sp) {
2118           VariableListSP globals_sp = cu_sp->GetVariableList(true);
2119           if (globals_sp) {
2120             const size_t num_globals = globals_sp->GetSize();
2121             for (size_t g = 0; g < num_globals; ++g) {
2122               VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
2123               if (var_sp && !var_sp->GetLocationIsConstantValueData()) {
2124                 const DWARFExpressionList &location =
2125                     var_sp->LocationExpressionList();
2126                 ExecutionContext exe_ctx;
2127                 llvm::Expected<Value> location_result = location.Evaluate(
2128                     &exe_ctx, nullptr, LLDB_INVALID_ADDRESS, nullptr, nullptr);
2129                 if (location_result) {
2130                   if (location_result->GetValueType() ==
2131                       Value::ValueType::FileAddress) {
2132                     lldb::addr_t file_addr =
2133                         location_result->GetScalar().ULongLong();
2134                     lldb::addr_t byte_size = 1;
2135                     if (var_sp->GetType())
2136                       byte_size =
2137                           var_sp->GetType()->GetByteSize(nullptr).value_or(0);
2138                     m_global_aranges_up->Append(GlobalVariableMap::Entry(
2139                         file_addr, byte_size, var_sp.get()));
2140                   }
2141                 } else {
2142                   LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols),
2143                                  location_result.takeError(),
2144                                  "location expression failed to execute: {0}");
2145                 }
2146               }
2147             }
2148           }
2149         }
2150       }
2151     }
2152     m_global_aranges_up->Sort();
2153   }
2154   return *m_global_aranges_up;
2155 }
2156 
ResolveFunctionAndBlock(lldb::addr_t file_vm_addr,bool lookup_block,SymbolContext & sc)2157 void SymbolFileDWARF::ResolveFunctionAndBlock(lldb::addr_t file_vm_addr,
2158                                               bool lookup_block,
2159                                               SymbolContext &sc) {
2160   assert(sc.comp_unit);
2161   DWARFCompileUnit &cu =
2162       GetDWARFCompileUnit(sc.comp_unit)->GetNonSkeletonUnit();
2163   DWARFDIE function_die = cu.LookupAddress(file_vm_addr);
2164   DWARFDIE block_die;
2165   if (function_die) {
2166     sc.function = sc.comp_unit->FindFunctionByUID(function_die.GetID()).get();
2167     if (sc.function == nullptr)
2168       sc.function = ParseFunction(*sc.comp_unit, function_die);
2169 
2170     if (sc.function && lookup_block)
2171       block_die = function_die.LookupDeepestBlock(file_vm_addr);
2172   }
2173 
2174   if (!sc.function || !lookup_block)
2175     return;
2176 
2177   Block &block = sc.function->GetBlock(true);
2178   if (block_die)
2179     sc.block = block.FindBlockByID(block_die.GetID());
2180   else
2181     sc.block = block.FindBlockByID(function_die.GetID());
2182 }
2183 
ResolveSymbolContext(const Address & so_addr,SymbolContextItem resolve_scope,SymbolContext & sc)2184 uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr,
2185                                                SymbolContextItem resolve_scope,
2186                                                SymbolContext &sc) {
2187   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2188   LLDB_SCOPED_TIMERF("SymbolFileDWARF::"
2189                      "ResolveSymbolContext (so_addr = { "
2190                      "section = %p, offset = 0x%" PRIx64
2191                      " }, resolve_scope = 0x%8.8x)",
2192                      static_cast<void *>(so_addr.GetSection().get()),
2193                      so_addr.GetOffset(), resolve_scope);
2194   uint32_t resolved = 0;
2195   if (resolve_scope &
2196       (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock |
2197        eSymbolContextLineEntry | eSymbolContextVariable)) {
2198     lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
2199 
2200     DWARFDebugInfo &debug_info = DebugInfo();
2201     const DWARFDebugAranges &aranges = debug_info.GetCompileUnitAranges();
2202     const dw_offset_t cu_offset = aranges.FindAddress(file_vm_addr);
2203     if (cu_offset == DW_INVALID_OFFSET) {
2204       // Global variables are not in the compile unit address ranges. The only
2205       // way to currently find global variables is to iterate over the
2206       // .debug_pubnames or the __apple_names table and find all items in there
2207       // that point to DW_TAG_variable DIEs and then find the address that
2208       // matches.
2209       if (resolve_scope & eSymbolContextVariable) {
2210         GlobalVariableMap &map = GetGlobalAranges();
2211         const GlobalVariableMap::Entry *entry =
2212             map.FindEntryThatContains(file_vm_addr);
2213         if (entry && entry->data) {
2214           Variable *variable = entry->data;
2215           SymbolContextScope *scc = variable->GetSymbolContextScope();
2216           if (scc) {
2217             scc->CalculateSymbolContext(&sc);
2218             sc.variable = variable;
2219           }
2220           return sc.GetResolvedMask();
2221         }
2222       }
2223     } else {
2224       uint32_t cu_idx = DW_INVALID_INDEX;
2225       if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(
2226               debug_info.GetUnitAtOffset(DIERef::Section::DebugInfo, cu_offset,
2227                                          &cu_idx))) {
2228         sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2229         if (sc.comp_unit) {
2230           resolved |= eSymbolContextCompUnit;
2231 
2232           bool force_check_line_table = false;
2233           if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {
2234             ResolveFunctionAndBlock(file_vm_addr,
2235                                     resolve_scope & eSymbolContextBlock, sc);
2236             if (sc.function)
2237               resolved |= eSymbolContextFunction;
2238             else {
2239               // We might have had a compile unit that had discontiguous address
2240               // ranges where the gaps are symbols that don't have any debug
2241               // info. Discontiguous compile unit address ranges should only
2242               // happen when there aren't other functions from other compile
2243               // units in these gaps. This helps keep the size of the aranges
2244               // down.
2245               force_check_line_table = true;
2246             }
2247             if (sc.block)
2248               resolved |= eSymbolContextBlock;
2249           }
2250 
2251           if ((resolve_scope & eSymbolContextLineEntry) ||
2252               force_check_line_table) {
2253             LineTable *line_table = sc.comp_unit->GetLineTable();
2254             if (line_table != nullptr) {
2255               // And address that makes it into this function should be in terms
2256               // of this debug file if there is no debug map, or it will be an
2257               // address in the .o file which needs to be fixed up to be in
2258               // terms of the debug map executable. Either way, calling
2259               // FixupAddress() will work for us.
2260               Address exe_so_addr(so_addr);
2261               if (FixupAddress(exe_so_addr)) {
2262                 if (line_table->FindLineEntryByAddress(exe_so_addr,
2263                                                        sc.line_entry)) {
2264                   resolved |= eSymbolContextLineEntry;
2265                 }
2266               }
2267             }
2268           }
2269 
2270           if (force_check_line_table && !(resolved & eSymbolContextLineEntry)) {
2271             // We might have had a compile unit that had discontiguous address
2272             // ranges where the gaps are symbols that don't have any debug info.
2273             // Discontiguous compile unit address ranges should only happen when
2274             // there aren't other functions from other compile units in these
2275             // gaps. This helps keep the size of the aranges down.
2276             sc.comp_unit = nullptr;
2277             resolved &= ~eSymbolContextCompUnit;
2278           }
2279         } else {
2280           GetObjectFile()->GetModule()->ReportWarning(
2281               "{0:x16}: compile unit {1} failed to create a valid "
2282               "lldb_private::CompileUnit class.",
2283               cu_offset, cu_idx);
2284         }
2285       }
2286     }
2287   }
2288   return resolved;
2289 }
2290 
ResolveSymbolContext(const SourceLocationSpec & src_location_spec,SymbolContextItem resolve_scope,SymbolContextList & sc_list)2291 uint32_t SymbolFileDWARF::ResolveSymbolContext(
2292     const SourceLocationSpec &src_location_spec,
2293     SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
2294   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2295   const bool check_inlines = src_location_spec.GetCheckInlines();
2296   const uint32_t prev_size = sc_list.GetSize();
2297   if (resolve_scope & eSymbolContextCompUnit) {
2298     for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
2299          ++cu_idx) {
2300       CompileUnit *dc_cu = ParseCompileUnitAtIndex(cu_idx).get();
2301       if (!dc_cu)
2302         continue;
2303 
2304       bool file_spec_matches_cu_file_spec = FileSpec::Match(
2305           src_location_spec.GetFileSpec(), dc_cu->GetPrimaryFile());
2306       if (check_inlines || file_spec_matches_cu_file_spec) {
2307         dc_cu->ResolveSymbolContext(src_location_spec, resolve_scope, sc_list);
2308         if (!check_inlines)
2309           break;
2310       }
2311     }
2312   }
2313   return sc_list.GetSize() - prev_size;
2314 }
2315 
PreloadSymbols()2316 void SymbolFileDWARF::PreloadSymbols() {
2317   // Get the symbol table for the symbol file prior to taking the module lock
2318   // so that it is available without needing to take the module lock. The DWARF
2319   // indexing might end up needing to relocate items when DWARF sections are
2320   // loaded as they might end up getting the section contents which can call
2321   // ObjectFileELF::RelocateSection() which in turn will ask for the symbol
2322   // table and can cause deadlocks.
2323   GetSymtab();
2324   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2325   m_index->Preload();
2326 }
2327 
GetModuleMutex() const2328 std::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const {
2329   lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
2330   if (module_sp)
2331     return module_sp->GetMutex();
2332   return GetObjectFile()->GetModule()->GetMutex();
2333 }
2334 
DeclContextMatchesThisSymbolFile(const lldb_private::CompilerDeclContext & decl_ctx)2335 bool SymbolFileDWARF::DeclContextMatchesThisSymbolFile(
2336     const lldb_private::CompilerDeclContext &decl_ctx) {
2337   if (!decl_ctx.IsValid()) {
2338     // Invalid namespace decl which means we aren't matching only things in
2339     // this symbol file, so return true to indicate it matches this symbol
2340     // file.
2341     return true;
2342   }
2343 
2344   TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem();
2345   auto type_system_or_err = GetTypeSystemForLanguage(
2346       decl_ctx_type_system->GetMinimumLanguage(nullptr));
2347   if (auto err = type_system_or_err.takeError()) {
2348     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2349                    "Unable to match namespace decl using TypeSystem: {0}");
2350     return false;
2351   }
2352 
2353   if (decl_ctx_type_system == type_system_or_err->get())
2354     return true; // The type systems match, return true
2355 
2356   // The namespace AST was valid, and it does not match...
2357   Log *log = GetLog(DWARFLog::Lookups);
2358 
2359   if (log)
2360     GetObjectFile()->GetModule()->LogMessage(
2361         log, "Valid namespace does not match symbol file");
2362 
2363   return false;
2364 }
2365 
FindGlobalVariables(ConstString name,const CompilerDeclContext & parent_decl_ctx,uint32_t max_matches,VariableList & variables)2366 void SymbolFileDWARF::FindGlobalVariables(
2367     ConstString name, const CompilerDeclContext &parent_decl_ctx,
2368     uint32_t max_matches, VariableList &variables) {
2369   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2370   Log *log = GetLog(DWARFLog::Lookups);
2371 
2372   if (log)
2373     GetObjectFile()->GetModule()->LogMessage(
2374         log,
2375         "SymbolFileDWARF::FindGlobalVariables (name=\"{0}\", "
2376         "parent_decl_ctx={1:p}, max_matches={2}, variables)",
2377         name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2378         max_matches);
2379 
2380   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2381     return;
2382 
2383   // Remember how many variables are in the list before we search.
2384   const uint32_t original_size = variables.GetSize();
2385 
2386   llvm::StringRef basename;
2387   llvm::StringRef context;
2388   bool name_is_mangled = Mangled::GetManglingScheme(name.GetStringRef()) !=
2389                          Mangled::eManglingSchemeNone;
2390 
2391   if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(),
2392                                                       context, basename))
2393     basename = name.GetStringRef();
2394 
2395   // Loop invariant: Variables up to this index have been checked for context
2396   // matches.
2397   uint32_t pruned_idx = original_size;
2398 
2399   SymbolContext sc;
2400   m_index->GetGlobalVariables(ConstString(basename), [&](DWARFDIE die) {
2401     if (!sc.module_sp)
2402       sc.module_sp = m_objfile_sp->GetModule();
2403     assert(sc.module_sp);
2404 
2405     if (die.Tag() != DW_TAG_variable)
2406       return true;
2407 
2408     auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2409     if (!dwarf_cu)
2410       return true;
2411     sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2412 
2413     if (parent_decl_ctx) {
2414       if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) {
2415         CompilerDeclContext actual_parent_decl_ctx =
2416             dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2417 
2418         /// If the actual namespace is inline (i.e., had a DW_AT_export_symbols)
2419         /// and a child (possibly through other layers of inline namespaces)
2420         /// of the namespace referred to by 'basename', allow the lookup to
2421         /// succeed.
2422         if (!actual_parent_decl_ctx ||
2423             (actual_parent_decl_ctx != parent_decl_ctx &&
2424              !parent_decl_ctx.IsContainedInLookup(actual_parent_decl_ctx)))
2425           return true;
2426       }
2427     }
2428 
2429     ParseAndAppendGlobalVariable(sc, die, variables);
2430     while (pruned_idx < variables.GetSize()) {
2431       VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx);
2432       if (name_is_mangled ||
2433           var_sp->GetName().GetStringRef().contains(name.GetStringRef()))
2434         ++pruned_idx;
2435       else
2436         variables.RemoveVariableAtIndex(pruned_idx);
2437     }
2438 
2439     return variables.GetSize() - original_size < max_matches;
2440   });
2441 
2442   // Return the number of variable that were appended to the list
2443   const uint32_t num_matches = variables.GetSize() - original_size;
2444   if (log && num_matches > 0) {
2445     GetObjectFile()->GetModule()->LogMessage(
2446         log,
2447         "SymbolFileDWARF::FindGlobalVariables (name=\"{0}\", "
2448         "parent_decl_ctx={1:p}, max_matches={2}, variables) => {3}",
2449         name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2450         max_matches, num_matches);
2451   }
2452 }
2453 
FindGlobalVariables(const RegularExpression & regex,uint32_t max_matches,VariableList & variables)2454 void SymbolFileDWARF::FindGlobalVariables(const RegularExpression &regex,
2455                                           uint32_t max_matches,
2456                                           VariableList &variables) {
2457   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2458   Log *log = GetLog(DWARFLog::Lookups);
2459 
2460   if (log) {
2461     GetObjectFile()->GetModule()->LogMessage(
2462         log,
2463         "SymbolFileDWARF::FindGlobalVariables (regex=\"{0}\", "
2464         "max_matches={1}, variables)",
2465         regex.GetText().str().c_str(), max_matches);
2466   }
2467 
2468   // Remember how many variables are in the list before we search.
2469   const uint32_t original_size = variables.GetSize();
2470 
2471   SymbolContext sc;
2472   m_index->GetGlobalVariables(regex, [&](DWARFDIE die) {
2473     if (!sc.module_sp)
2474       sc.module_sp = m_objfile_sp->GetModule();
2475     assert(sc.module_sp);
2476 
2477     DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2478     if (!dwarf_cu)
2479       return true;
2480     sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2481 
2482     ParseAndAppendGlobalVariable(sc, die, variables);
2483 
2484     return variables.GetSize() - original_size < max_matches;
2485   });
2486 }
2487 
ResolveFunction(const DWARFDIE & orig_die,bool include_inlines,SymbolContextList & sc_list)2488 bool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die,
2489                                       bool include_inlines,
2490                                       SymbolContextList &sc_list) {
2491   SymbolContext sc;
2492 
2493   if (!orig_die)
2494     return false;
2495 
2496   // If we were passed a die that is not a function, just return false...
2497   if (!(orig_die.Tag() == DW_TAG_subprogram ||
2498         (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2499     return false;
2500 
2501   DWARFDIE die = orig_die;
2502   DWARFDIE inlined_die;
2503   if (die.Tag() == DW_TAG_inlined_subroutine) {
2504     inlined_die = die;
2505 
2506     while (true) {
2507       die = die.GetParent();
2508 
2509       if (die) {
2510         if (die.Tag() == DW_TAG_subprogram)
2511           break;
2512       } else
2513         break;
2514     }
2515   }
2516   assert(die && die.Tag() == DW_TAG_subprogram);
2517   if (GetFunction(die, sc)) {
2518     Address addr;
2519     // Parse all blocks if needed
2520     if (inlined_die) {
2521       Block &function_block = sc.function->GetBlock(true);
2522       sc.block = function_block.FindBlockByID(inlined_die.GetID());
2523       if (sc.block == nullptr)
2524         sc.block = function_block.FindBlockByID(inlined_die.GetOffset());
2525       if (sc.block == nullptr || !sc.block->GetStartAddress(addr))
2526         addr.Clear();
2527     } else {
2528       sc.block = nullptr;
2529       addr = sc.function->GetAddressRange().GetBaseAddress();
2530     }
2531 
2532     sc_list.Append(sc);
2533     return true;
2534   }
2535 
2536   return false;
2537 }
2538 
DIEInDeclContext(const CompilerDeclContext & decl_ctx,const DWARFDIE & die,bool only_root_namespaces)2539 bool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext &decl_ctx,
2540                                        const DWARFDIE &die,
2541                                        bool only_root_namespaces) {
2542   // If we have no parent decl context to match this DIE matches, and if the
2543   // parent decl context isn't valid, we aren't trying to look for any
2544   // particular decl context so any die matches.
2545   if (!decl_ctx.IsValid()) {
2546     // ...But if we are only checking root decl contexts, confirm that the
2547     // 'die' is a top-level context.
2548     if (only_root_namespaces)
2549       return die.GetParent().Tag() == llvm::dwarf::DW_TAG_compile_unit;
2550 
2551     return true;
2552   }
2553 
2554   if (die) {
2555     if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) {
2556       if (CompilerDeclContext actual_decl_ctx =
2557               dwarf_ast->GetDeclContextContainingUIDFromDWARF(die))
2558         return decl_ctx.IsContainedInLookup(actual_decl_ctx);
2559     }
2560   }
2561   return false;
2562 }
2563 
FindFunctions(const Module::LookupInfo & lookup_info,const CompilerDeclContext & parent_decl_ctx,bool include_inlines,SymbolContextList & sc_list)2564 void SymbolFileDWARF::FindFunctions(const Module::LookupInfo &lookup_info,
2565                                     const CompilerDeclContext &parent_decl_ctx,
2566                                     bool include_inlines,
2567                                     SymbolContextList &sc_list) {
2568   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2569   ConstString name = lookup_info.GetLookupName();
2570   FunctionNameType name_type_mask = lookup_info.GetNameTypeMask();
2571 
2572   // eFunctionNameTypeAuto should be pre-resolved by a call to
2573   // Module::LookupInfo::LookupInfo()
2574   assert((name_type_mask & eFunctionNameTypeAuto) == 0);
2575 
2576   Log *log = GetLog(DWARFLog::Lookups);
2577 
2578   if (log) {
2579     GetObjectFile()->GetModule()->LogMessage(
2580         log,
2581         "SymbolFileDWARF::FindFunctions (name=\"{0}\", name_type_mask={1:x}, "
2582         "sc_list)",
2583         name.GetCString(), name_type_mask);
2584   }
2585 
2586   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2587     return;
2588 
2589   // If name is empty then we won't find anything.
2590   if (name.IsEmpty())
2591     return;
2592 
2593   // Remember how many sc_list are in the list before we search in case we are
2594   // appending the results to a variable list.
2595 
2596   const uint32_t original_size = sc_list.GetSize();
2597 
2598   llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2599 
2600   m_index->GetFunctions(lookup_info, *this, parent_decl_ctx, [&](DWARFDIE die) {
2601     if (resolved_dies.insert(die.GetDIE()).second)
2602       ResolveFunction(die, include_inlines, sc_list);
2603     return true;
2604   });
2605   // With -gsimple-template-names, a templated type's DW_AT_name will not
2606   // contain the template parameters. Try again stripping '<' and anything
2607   // after, filtering out entries with template parameters that don't match.
2608   {
2609     const llvm::StringRef name_ref = name.GetStringRef();
2610     auto it = name_ref.find('<');
2611     if (it != llvm::StringRef::npos) {
2612       const llvm::StringRef name_no_template_params = name_ref.slice(0, it);
2613 
2614       Module::LookupInfo no_tp_lookup_info(lookup_info);
2615       no_tp_lookup_info.SetLookupName(ConstString(name_no_template_params));
2616       m_index->GetFunctions(no_tp_lookup_info, *this, parent_decl_ctx,
2617                             [&](DWARFDIE die) {
2618                               if (resolved_dies.insert(die.GetDIE()).second)
2619                                 ResolveFunction(die, include_inlines, sc_list);
2620                               return true;
2621                             });
2622     }
2623   }
2624 
2625   // Return the number of variable that were appended to the list
2626   const uint32_t num_matches = sc_list.GetSize() - original_size;
2627 
2628   if (log && num_matches > 0) {
2629     GetObjectFile()->GetModule()->LogMessage(
2630         log,
2631         "SymbolFileDWARF::FindFunctions (name=\"{0}\", "
2632         "name_type_mask={1:x}, include_inlines={2:d}, sc_list) => {3}",
2633         name.GetCString(), name_type_mask, include_inlines, num_matches);
2634   }
2635 }
2636 
FindFunctions(const RegularExpression & regex,bool include_inlines,SymbolContextList & sc_list)2637 void SymbolFileDWARF::FindFunctions(const RegularExpression &regex,
2638                                     bool include_inlines,
2639                                     SymbolContextList &sc_list) {
2640   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2641   LLDB_SCOPED_TIMERF("SymbolFileDWARF::FindFunctions (regex = '%s')",
2642                      regex.GetText().str().c_str());
2643 
2644   Log *log = GetLog(DWARFLog::Lookups);
2645 
2646   if (log) {
2647     GetObjectFile()->GetModule()->LogMessage(
2648         log, "SymbolFileDWARF::FindFunctions (regex=\"{0}\", sc_list)",
2649         regex.GetText().str().c_str());
2650   }
2651 
2652   llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2653   m_index->GetFunctions(regex, [&](DWARFDIE die) {
2654     if (resolved_dies.insert(die.GetDIE()).second)
2655       ResolveFunction(die, include_inlines, sc_list);
2656     return true;
2657   });
2658 }
2659 
GetMangledNamesForFunction(const std::string & scope_qualified_name,std::vector<ConstString> & mangled_names)2660 void SymbolFileDWARF::GetMangledNamesForFunction(
2661     const std::string &scope_qualified_name,
2662     std::vector<ConstString> &mangled_names) {
2663   DWARFDebugInfo &info = DebugInfo();
2664   uint32_t num_comp_units = info.GetNumUnits();
2665   for (uint32_t i = 0; i < num_comp_units; i++) {
2666     DWARFUnit *cu = info.GetUnitAtIndex(i);
2667     if (cu == nullptr)
2668       continue;
2669 
2670     SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
2671     if (dwo)
2672       dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
2673   }
2674 
2675   for (DIERef die_ref :
2676        m_function_scope_qualified_name_map.lookup(scope_qualified_name)) {
2677     DWARFDIE die = GetDIE(die_ref);
2678     mangled_names.push_back(ConstString(die.GetMangledName()));
2679   }
2680 }
2681 
2682 /// Split a name up into a basename and template parameters.
SplitTemplateParams(llvm::StringRef fullname,llvm::StringRef & basename,llvm::StringRef & template_params)2683 static bool SplitTemplateParams(llvm::StringRef fullname,
2684                                 llvm::StringRef &basename,
2685                                 llvm::StringRef &template_params) {
2686   auto it = fullname.find('<');
2687   if (it == llvm::StringRef::npos) {
2688     basename = fullname;
2689     template_params = llvm::StringRef();
2690     return false;
2691   }
2692   basename = fullname.slice(0, it);
2693   template_params = fullname.slice(it, fullname.size());
2694   return true;
2695 }
2696 
UpdateCompilerContextForSimpleTemplateNames(TypeQuery & match)2697 static bool UpdateCompilerContextForSimpleTemplateNames(TypeQuery &match) {
2698   // We need to find any names in the context that have template parameters
2699   // and strip them so the context can be matched when -gsimple-template-names
2700   // is being used. Returns true if any of the context items were updated.
2701   bool any_context_updated = false;
2702   for (auto &context : match.GetContextRef()) {
2703     llvm::StringRef basename, params;
2704     if (SplitTemplateParams(context.name.GetStringRef(), basename, params)) {
2705       context.name = ConstString(basename);
2706       any_context_updated = true;
2707     }
2708   }
2709   return any_context_updated;
2710 }
2711 
GetDebugInfoSize(bool load_all_debug_info)2712 uint64_t SymbolFileDWARF::GetDebugInfoSize(bool load_all_debug_info) {
2713   DWARFDebugInfo &info = DebugInfo();
2714   uint32_t num_comp_units = info.GetNumUnits();
2715 
2716   uint64_t debug_info_size = SymbolFileCommon::GetDebugInfoSize();
2717   // In dwp scenario, debug info == skeleton debug info + dwp debug info.
2718   if (std::shared_ptr<SymbolFileDWARFDwo> dwp_sp = GetDwpSymbolFile())
2719     return debug_info_size + dwp_sp->GetDebugInfoSize();
2720 
2721   // In dwo scenario, debug info == skeleton debug info + all dwo debug info.
2722   for (uint32_t i = 0; i < num_comp_units; i++) {
2723     DWARFUnit *cu = info.GetUnitAtIndex(i);
2724     if (cu == nullptr)
2725       continue;
2726 
2727     SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile(load_all_debug_info);
2728     if (dwo)
2729       debug_info_size += dwo->GetDebugInfoSize();
2730   }
2731   return debug_info_size;
2732 }
2733 
FindTypes(const TypeQuery & query,TypeResults & results)2734 void SymbolFileDWARF::FindTypes(const TypeQuery &query, TypeResults &results) {
2735 
2736   // Make sure we haven't already searched this SymbolFile before.
2737   if (results.AlreadySearched(this))
2738     return;
2739 
2740   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2741 
2742   bool have_index_match = false;
2743   m_index->GetTypes(query.GetTypeBasename(), [&](DWARFDIE die) {
2744     // Check the language, but only if we have a language filter.
2745     if (query.HasLanguage()) {
2746       if (!query.LanguageMatches(GetLanguageFamily(*die.GetCU())))
2747         return true; // Keep iterating over index types, language mismatch.
2748     }
2749 
2750     // Check the context matches
2751     std::vector<lldb_private::CompilerContext> die_context;
2752     if (query.GetModuleSearch())
2753       die_context = die.GetDeclContext();
2754     else
2755       die_context = die.GetTypeLookupContext();
2756     assert(!die_context.empty());
2757     if (!query.ContextMatches(die_context))
2758       return true; // Keep iterating over index types, context mismatch.
2759 
2760     // Try to resolve the type.
2761     if (Type *matching_type = ResolveType(die, true, true)) {
2762       if (matching_type->IsTemplateType()) {
2763         // We have to watch out for case where we lookup a type by basename and
2764         // it matches a template with simple template names. Like looking up
2765         // "Foo" and if we have simple template names then we will match
2766         // "Foo<int>" and "Foo<double>" because all the DWARF has is "Foo" in
2767         // the accelerator tables. The main case we see this in is when the
2768         // expression parser is trying to parse "Foo<int>" and it will first do
2769         // a lookup on just "Foo". We verify the type basename matches before
2770         // inserting the type in the results.
2771         auto CompilerTypeBasename =
2772             matching_type->GetForwardCompilerType().GetTypeName(true);
2773         if (CompilerTypeBasename != query.GetTypeBasename())
2774           return true; // Keep iterating over index types, basename mismatch.
2775       }
2776       have_index_match = true;
2777       results.InsertUnique(matching_type->shared_from_this());
2778     }
2779     return !results.Done(query); // Keep iterating if we aren't done.
2780   });
2781 
2782   if (results.Done(query))
2783     return;
2784 
2785   // With -gsimple-template-names, a templated type's DW_AT_name will not
2786   // contain the template parameters. Try again stripping '<' and anything
2787   // after, filtering out entries with template parameters that don't match.
2788   if (!have_index_match) {
2789     // Create a type matcher with a compiler context that is tuned for
2790     // -gsimple-template-names. We will use this for the index lookup and the
2791     // context matching, but will use the original "match" to insert matches
2792     // into if things match. The "match_simple" has a compiler context with
2793     // all template parameters removed to allow the names and context to match.
2794     // The UpdateCompilerContextForSimpleTemplateNames(...) will return true if
2795     // it trims any context items down by removing template parameter names.
2796     TypeQuery query_simple(query);
2797     if (UpdateCompilerContextForSimpleTemplateNames(query_simple)) {
2798 
2799       // Copy our match's context and update the basename we are looking for
2800       // so we can use this only to compare the context correctly.
2801       m_index->GetTypes(query_simple.GetTypeBasename(), [&](DWARFDIE die) {
2802         // Check the language, but only if we have a language filter.
2803         if (query.HasLanguage()) {
2804           if (!query.LanguageMatches(GetLanguageFamily(*die.GetCU())))
2805             return true; // Keep iterating over index types, language mismatch.
2806         }
2807 
2808         // Check the context matches
2809         std::vector<lldb_private::CompilerContext> die_context;
2810         if (query.GetModuleSearch())
2811           die_context = die.GetDeclContext();
2812         else
2813           die_context = die.GetTypeLookupContext();
2814         assert(!die_context.empty());
2815         if (!query_simple.ContextMatches(die_context))
2816           return true; // Keep iterating over index types, context mismatch.
2817 
2818         // Try to resolve the type.
2819         if (Type *matching_type = ResolveType(die, true, true)) {
2820           ConstString name = matching_type->GetQualifiedName();
2821           // We have found a type that still might not match due to template
2822           // parameters. If we create a new TypeQuery that uses the new type's
2823           // fully qualified name, we can find out if this type matches at all
2824           // context levels. We can't use just the "match_simple" context
2825           // because all template parameters were stripped off. The fully
2826           // qualified name of the type will have the template parameters and
2827           // will allow us to make sure it matches correctly.
2828           TypeQuery die_query(name.GetStringRef(),
2829                               TypeQueryOptions::e_exact_match);
2830           if (!query.ContextMatches(die_query.GetContextRef()))
2831             return true; // Keep iterating over index types, context mismatch.
2832 
2833           results.InsertUnique(matching_type->shared_from_this());
2834         }
2835         return !results.Done(query); // Keep iterating if we aren't done.
2836       });
2837       if (results.Done(query))
2838         return;
2839     }
2840   }
2841 
2842   // Next search through the reachable Clang modules. This only applies for
2843   // DWARF objects compiled with -gmodules that haven't been processed by
2844   // dsymutil.
2845   UpdateExternalModuleListIfNeeded();
2846 
2847   for (const auto &pair : m_external_type_modules) {
2848     if (ModuleSP external_module_sp = pair.second) {
2849       external_module_sp->FindTypes(query, results);
2850       if (results.Done(query))
2851         return;
2852     }
2853   }
2854 }
2855 
2856 CompilerDeclContext
FindNamespace(ConstString name,const CompilerDeclContext & parent_decl_ctx,bool only_root_namespaces)2857 SymbolFileDWARF::FindNamespace(ConstString name,
2858                                const CompilerDeclContext &parent_decl_ctx,
2859                                bool only_root_namespaces) {
2860   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2861   Log *log = GetLog(DWARFLog::Lookups);
2862 
2863   if (log) {
2864     GetObjectFile()->GetModule()->LogMessage(
2865         log, "SymbolFileDWARF::FindNamespace (sc, name=\"{0}\")",
2866         name.GetCString());
2867   }
2868 
2869   CompilerDeclContext namespace_decl_ctx;
2870 
2871   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2872     return namespace_decl_ctx;
2873 
2874   m_index->GetNamespaces(name, [&](DWARFDIE die) {
2875     if (!DIEInDeclContext(parent_decl_ctx, die, only_root_namespaces))
2876       return true; // The containing decl contexts don't match
2877 
2878     DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU());
2879     if (!dwarf_ast)
2880       return true;
2881 
2882     namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
2883     return !namespace_decl_ctx.IsValid();
2884   });
2885 
2886   if (log && namespace_decl_ctx) {
2887     GetObjectFile()->GetModule()->LogMessage(
2888         log,
2889         "SymbolFileDWARF::FindNamespace (sc, name=\"{0}\") => "
2890         "CompilerDeclContext({1:p}/{2:p}) \"{3}\"",
2891         name.GetCString(),
2892         static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
2893         static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
2894         namespace_decl_ctx.GetName().AsCString("<NULL>"));
2895   }
2896 
2897   return namespace_decl_ctx;
2898 }
2899 
GetTypeForDIE(const DWARFDIE & die,bool resolve_function_context)2900 TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
2901                                       bool resolve_function_context) {
2902   TypeSP type_sp;
2903   if (die) {
2904     Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
2905     if (type_ptr == nullptr) {
2906       SymbolContextScope *scope;
2907       if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()))
2908         scope = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2909       else
2910         scope = GetObjectFile()->GetModule().get();
2911       assert(scope);
2912       SymbolContext sc(scope);
2913       const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
2914       while (parent_die != nullptr) {
2915         if (parent_die->Tag() == DW_TAG_subprogram)
2916           break;
2917         parent_die = parent_die->GetParent();
2918       }
2919       SymbolContext sc_backup = sc;
2920       if (resolve_function_context && parent_die != nullptr &&
2921           !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
2922         sc = sc_backup;
2923 
2924       type_sp = ParseType(sc, die, nullptr);
2925     } else if (type_ptr != DIE_IS_BEING_PARSED) {
2926       // Get the original shared pointer for this type
2927       type_sp = type_ptr->shared_from_this();
2928     }
2929   }
2930   return type_sp;
2931 }
2932 
2933 DWARFDIE
GetDeclContextDIEContainingDIE(const DWARFDIE & orig_die)2934 SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
2935   if (orig_die) {
2936     DWARFDIE die = orig_die;
2937 
2938     while (die) {
2939       // If this is the original DIE that we are searching for a declaration
2940       // for, then don't look in the cache as we don't want our own decl
2941       // context to be our decl context...
2942       if (orig_die != die) {
2943         switch (die.Tag()) {
2944         case DW_TAG_compile_unit:
2945         case DW_TAG_partial_unit:
2946         case DW_TAG_namespace:
2947         case DW_TAG_structure_type:
2948         case DW_TAG_union_type:
2949         case DW_TAG_class_type:
2950         case DW_TAG_lexical_block:
2951         case DW_TAG_subprogram:
2952           return die;
2953         case DW_TAG_inlined_subroutine: {
2954           DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2955           if (abs_die) {
2956             return abs_die;
2957           }
2958           break;
2959         }
2960         default:
2961           break;
2962         }
2963       }
2964 
2965       DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
2966       if (spec_die) {
2967         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
2968         if (decl_ctx_die)
2969           return decl_ctx_die;
2970       }
2971 
2972       DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2973       if (abs_die) {
2974         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
2975         if (decl_ctx_die)
2976           return decl_ctx_die;
2977       }
2978 
2979       die = die.GetParent();
2980     }
2981   }
2982   return DWARFDIE();
2983 }
2984 
GetObjCClassSymbol(ConstString objc_class_name)2985 Symbol *SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) {
2986   Symbol *objc_class_symbol = nullptr;
2987   if (m_objfile_sp) {
2988     Symtab *symtab = m_objfile_sp->GetSymtab();
2989     if (symtab) {
2990       objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
2991           objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
2992           Symtab::eVisibilityAny);
2993     }
2994   }
2995   return objc_class_symbol;
2996 }
2997 
2998 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If
2999 // they don't then we can end up looking through all class types for a complete
3000 // type and never find the full definition. We need to know if this attribute
3001 // is supported, so we determine this here and cache th result. We also need to
3002 // worry about the debug map
3003 // DWARF file
3004 // if we are doing darwin DWARF in .o file debugging.
Supports_DW_AT_APPLE_objc_complete_type(DWARFUnit * cu)3005 bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(DWARFUnit *cu) {
3006   if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) {
3007     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
3008     if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
3009       m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
3010     else {
3011       DWARFDebugInfo &debug_info = DebugInfo();
3012       const uint32_t num_compile_units = GetNumCompileUnits();
3013       for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
3014         DWARFUnit *dwarf_cu = debug_info.GetUnitAtIndex(cu_idx);
3015         if (dwarf_cu != cu &&
3016             dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) {
3017           m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
3018           break;
3019         }
3020       }
3021     }
3022     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo &&
3023         GetDebugMapSymfile())
3024       return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this);
3025   }
3026   return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
3027 }
3028 
3029 // This function can be used when a DIE is found that is a forward declaration
3030 // DIE and we want to try and find a type that has the complete definition.
FindCompleteObjCDefinitionTypeForDIE(const DWARFDIE & die,ConstString type_name,bool must_be_implementation)3031 TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE(
3032     const DWARFDIE &die, ConstString type_name, bool must_be_implementation) {
3033 
3034   TypeSP type_sp;
3035 
3036   if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
3037     return type_sp;
3038 
3039   m_index->GetCompleteObjCClass(
3040       type_name, must_be_implementation, [&](DWARFDIE type_die) {
3041         // Don't try and resolve the DIE we are looking for with the DIE
3042         // itself!
3043         if (type_die == die || !IsStructOrClassTag(type_die.Tag()))
3044           return true;
3045 
3046         if (must_be_implementation &&
3047             type_die.Supports_DW_AT_APPLE_objc_complete_type()) {
3048           const bool try_resolving_type = type_die.GetAttributeValueAsUnsigned(
3049               DW_AT_APPLE_objc_complete_type, 0);
3050           if (!try_resolving_type)
3051             return true;
3052         }
3053 
3054         Type *resolved_type = ResolveType(type_die, false, true);
3055         if (!resolved_type || resolved_type == DIE_IS_BEING_PARSED)
3056           return true;
3057 
3058         DEBUG_PRINTF(
3059             "resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
3060             " (cu 0x%8.8" PRIx64 ")\n",
3061             die.GetID(),
3062             m_objfile_sp->GetFileSpec().GetFilename().AsCString("<Unknown>"),
3063             type_die.GetID(), type_cu->GetID());
3064 
3065         if (die)
3066           GetDIEToType()[die.GetDIE()] = resolved_type;
3067         type_sp = resolved_type->shared_from_this();
3068         return false;
3069       });
3070   return type_sp;
3071 }
3072 
3073 DWARFDIE
FindDefinitionDIE(const DWARFDIE & die)3074 SymbolFileDWARF::FindDefinitionDIE(const DWARFDIE &die) {
3075   const char *name = die.GetName();
3076   if (!name)
3077     return {};
3078   if (!die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0))
3079     return die;
3080 
3081   Progress progress(llvm::formatv(
3082       "Searching definition DIE in {0}: '{1}'",
3083       GetObjectFile()->GetFileSpec().GetFilename().GetString(), name));
3084 
3085   const dw_tag_t tag = die.Tag();
3086 
3087   Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups);
3088   if (log) {
3089     GetObjectFile()->GetModule()->LogMessage(
3090         log,
3091         "SymbolFileDWARF::FindDefinitionDIE(tag={0} "
3092         "({1}), name='{2}')",
3093         DW_TAG_value_to_name(tag), tag, name);
3094   }
3095 
3096   // Get the type system that we are looking to find a type for. We will
3097   // use this to ensure any matches we find are in a language that this
3098   // type system supports
3099   const LanguageType language = GetLanguage(*die.GetCU());
3100   TypeSystemSP type_system = nullptr;
3101   if (language != eLanguageTypeUnknown) {
3102     auto type_system_or_err = GetTypeSystemForLanguage(language);
3103     if (auto err = type_system_or_err.takeError()) {
3104       LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
3105                      "Cannot get TypeSystem for language {1}: {0}",
3106                      Language::GetNameForLanguageType(language));
3107     } else {
3108       type_system = *type_system_or_err;
3109     }
3110   }
3111 
3112   // See comments below about -gsimple-template-names for why we attempt to
3113   // compute missing template parameter names.
3114   std::vector<std::string> template_params;
3115   DWARFDeclContext die_dwarf_decl_ctx;
3116   DWARFASTParser *dwarf_ast =
3117       type_system ? type_system->GetDWARFParser() : nullptr;
3118   for (DWARFDIE ctx_die = die; ctx_die && !isUnitType(ctx_die.Tag());
3119        ctx_die = ctx_die.GetParentDeclContextDIE()) {
3120     die_dwarf_decl_ctx.AppendDeclContext(ctx_die.Tag(), ctx_die.GetName());
3121     template_params.push_back(
3122         (ctx_die.IsStructUnionOrClass() && dwarf_ast)
3123             ? dwarf_ast->GetDIEClassTemplateParams(ctx_die)
3124             : "");
3125   }
3126   const bool any_template_params = llvm::any_of(
3127       template_params, [](llvm::StringRef p) { return !p.empty(); });
3128 
3129   auto die_matches = [&](DWARFDIE type_die) {
3130     // Resolve the type if both have the same tag or {class, struct} tags.
3131     const bool tag_matches =
3132         type_die.Tag() == tag ||
3133         (IsStructOrClassTag(type_die.Tag()) && IsStructOrClassTag(tag));
3134     if (!tag_matches)
3135       return false;
3136     if (any_template_params) {
3137       size_t pos = 0;
3138       for (DWARFDIE ctx_die = type_die; ctx_die && !isUnitType(ctx_die.Tag()) &&
3139                                         pos < template_params.size();
3140            ctx_die = ctx_die.GetParentDeclContextDIE(), ++pos) {
3141         if (template_params[pos].empty())
3142           continue;
3143         if (template_params[pos] !=
3144             dwarf_ast->GetDIEClassTemplateParams(ctx_die))
3145           return false;
3146       }
3147       if (pos != template_params.size())
3148         return false;
3149     }
3150     return true;
3151   };
3152   DWARFDIE result;
3153   m_index->GetFullyQualifiedType(die_dwarf_decl_ctx, [&](DWARFDIE type_die) {
3154     // Make sure type_die's language matches the type system we are
3155     // looking for. We don't want to find a "Foo" type from Java if we
3156     // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
3157     if (type_system &&
3158         !type_system->SupportsLanguage(GetLanguage(*type_die.GetCU())))
3159       return true;
3160 
3161     if (!die_matches(type_die)) {
3162       if (log) {
3163         GetObjectFile()->GetModule()->LogMessage(
3164             log,
3165             "SymbolFileDWARF::FindDefinitionDIE(tag={0} ({1}), "
3166             "name='{2}') ignoring die={3:x16} ({4})",
3167             DW_TAG_value_to_name(tag), tag, name, type_die.GetOffset(),
3168             type_die.GetName());
3169       }
3170       return true;
3171     }
3172 
3173     if (log) {
3174       DWARFDeclContext type_dwarf_decl_ctx = type_die.GetDWARFDeclContext();
3175       GetObjectFile()->GetModule()->LogMessage(
3176           log,
3177           "SymbolFileDWARF::FindDefinitionTypeDIE(tag={0} ({1}), name='{2}') "
3178           "trying die={3:x16} ({4})",
3179           DW_TAG_value_to_name(tag), tag, name, type_die.GetOffset(),
3180           type_dwarf_decl_ctx.GetQualifiedName());
3181     }
3182 
3183     result = type_die;
3184     return false;
3185   });
3186   return result;
3187 }
3188 
ParseType(const SymbolContext & sc,const DWARFDIE & die,bool * type_is_new_ptr)3189 TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die,
3190                                   bool *type_is_new_ptr) {
3191   if (!die)
3192     return {};
3193 
3194   auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU()));
3195   if (auto err = type_system_or_err.takeError()) {
3196     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
3197                    "Unable to parse type: {0}");
3198     return {};
3199   }
3200   auto ts = *type_system_or_err;
3201   if (!ts)
3202     return {};
3203 
3204   DWARFASTParser *dwarf_ast = ts->GetDWARFParser();
3205   if (!dwarf_ast)
3206     return {};
3207 
3208   TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, type_is_new_ptr);
3209   if (type_sp) {
3210     if (die.Tag() == DW_TAG_subprogram) {
3211       std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
3212                                            .GetScopeQualifiedName()
3213                                            .AsCString(""));
3214       if (scope_qualified_name.size()) {
3215         m_function_scope_qualified_name_map[scope_qualified_name].insert(
3216             *die.GetDIERef());
3217       }
3218     }
3219   }
3220 
3221   return type_sp;
3222 }
3223 
ParseTypes(const SymbolContext & sc,const DWARFDIE & orig_die,bool parse_siblings,bool parse_children)3224 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc,
3225                                    const DWARFDIE &orig_die,
3226                                    bool parse_siblings, bool parse_children) {
3227   size_t types_added = 0;
3228   DWARFDIE die = orig_die;
3229 
3230   while (die) {
3231     const dw_tag_t tag = die.Tag();
3232     bool type_is_new = false;
3233 
3234     Tag dwarf_tag = static_cast<Tag>(tag);
3235 
3236     // TODO: Currently ParseTypeFromDWARF(...) which is called by ParseType(...)
3237     // does not handle DW_TAG_subrange_type. It is not clear if this is a bug or
3238     // not.
3239     if (isType(dwarf_tag) && tag != DW_TAG_subrange_type)
3240       ParseType(sc, die, &type_is_new);
3241 
3242     if (type_is_new)
3243       ++types_added;
3244 
3245     if (parse_children && die.HasChildren()) {
3246       if (die.Tag() == DW_TAG_subprogram) {
3247         SymbolContext child_sc(sc);
3248         child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3249         types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3250       } else
3251         types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3252     }
3253 
3254     if (parse_siblings)
3255       die = die.GetSibling();
3256     else
3257       die.Clear();
3258   }
3259   return types_added;
3260 }
3261 
ParseBlocksRecursive(Function & func)3262 size_t SymbolFileDWARF::ParseBlocksRecursive(Function &func) {
3263   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3264   CompileUnit *comp_unit = func.GetCompileUnit();
3265   lldbassert(comp_unit);
3266 
3267   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit);
3268   if (!dwarf_cu)
3269     return 0;
3270 
3271   size_t functions_added = 0;
3272   const dw_offset_t function_die_offset = DIERef(func.GetID()).die_offset();
3273   DWARFDIE function_die =
3274       dwarf_cu->GetNonSkeletonUnit().GetDIE(function_die_offset);
3275   if (function_die) {
3276     ParseBlocksRecursive(*comp_unit, &func.GetBlock(false), function_die,
3277                          LLDB_INVALID_ADDRESS, 0);
3278   }
3279 
3280   return functions_added;
3281 }
3282 
ParseTypes(CompileUnit & comp_unit)3283 size_t SymbolFileDWARF::ParseTypes(CompileUnit &comp_unit) {
3284   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3285   size_t types_added = 0;
3286   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
3287   if (dwarf_cu) {
3288     DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3289     if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3290       SymbolContext sc;
3291       sc.comp_unit = &comp_unit;
3292       types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3293     }
3294   }
3295 
3296   return types_added;
3297 }
3298 
ParseVariablesForContext(const SymbolContext & sc)3299 size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) {
3300   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3301   if (sc.comp_unit != nullptr) {
3302     if (sc.function) {
3303       DWARFDIE function_die = GetDIE(sc.function->GetID());
3304 
3305       dw_addr_t func_lo_pc = LLDB_INVALID_ADDRESS;
3306       DWARFRangeList ranges = function_die.GetDIE()->GetAttributeAddressRanges(
3307           function_die.GetCU(), /*check_hi_lo_pc=*/true);
3308       if (!ranges.IsEmpty())
3309         func_lo_pc = ranges.GetMinRangeBase(0);
3310       if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3311         const size_t num_variables =
3312             ParseVariablesInFunctionContext(sc, function_die, func_lo_pc);
3313 
3314         // Let all blocks know they have parse all their variables
3315         sc.function->GetBlock(false).SetDidParseVariables(true, true);
3316         return num_variables;
3317       }
3318     } else if (sc.comp_unit) {
3319       DWARFUnit *dwarf_cu = DebugInfo().GetUnitAtIndex(sc.comp_unit->GetID());
3320 
3321       if (dwarf_cu == nullptr)
3322         return 0;
3323 
3324       uint32_t vars_added = 0;
3325       VariableListSP variables(sc.comp_unit->GetVariableList(false));
3326 
3327       if (variables.get() == nullptr) {
3328         variables = std::make_shared<VariableList>();
3329         sc.comp_unit->SetVariableList(variables);
3330 
3331         m_index->GetGlobalVariables(*dwarf_cu, [&](DWARFDIE die) {
3332           VariableSP var_sp(ParseVariableDIECached(sc, die));
3333           if (var_sp) {
3334             variables->AddVariableIfUnique(var_sp);
3335             ++vars_added;
3336           }
3337           return true;
3338         });
3339       }
3340       return vars_added;
3341     }
3342   }
3343   return 0;
3344 }
3345 
ParseVariableDIECached(const SymbolContext & sc,const DWARFDIE & die)3346 VariableSP SymbolFileDWARF::ParseVariableDIECached(const SymbolContext &sc,
3347                                                    const DWARFDIE &die) {
3348   if (!die)
3349     return nullptr;
3350 
3351   DIEToVariableSP &die_to_variable = die.GetDWARF()->GetDIEToVariable();
3352 
3353   VariableSP var_sp = die_to_variable[die.GetDIE()];
3354   if (var_sp)
3355     return var_sp;
3356 
3357   var_sp = ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS);
3358   if (var_sp) {
3359     die_to_variable[die.GetDIE()] = var_sp;
3360     if (DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification))
3361       die_to_variable[spec_die.GetDIE()] = var_sp;
3362   }
3363   return var_sp;
3364 }
3365 
3366 /// Creates a DWARFExpressionList from an DW_AT_location form_value.
GetExprListFromAtLocation(DWARFFormValue form_value,ModuleSP module,const DWARFDIE & die,const addr_t func_low_pc)3367 static DWARFExpressionList GetExprListFromAtLocation(DWARFFormValue form_value,
3368                                                      ModuleSP module,
3369                                                      const DWARFDIE &die,
3370                                                      const addr_t func_low_pc) {
3371   if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3372     const DWARFDataExtractor &data = die.GetData();
3373 
3374     uint64_t block_offset = form_value.BlockData() - data.GetDataStart();
3375     uint64_t block_length = form_value.Unsigned();
3376     return DWARFExpressionList(
3377         module, DataExtractor(data, block_offset, block_length), die.GetCU());
3378   }
3379 
3380   DWARFExpressionList location_list(module, DWARFExpression(), die.GetCU());
3381   DataExtractor data = die.GetCU()->GetLocationData();
3382   dw_offset_t offset = form_value.Unsigned();
3383   if (form_value.Form() == DW_FORM_loclistx)
3384     offset = die.GetCU()->GetLoclistOffset(offset).value_or(-1);
3385   if (data.ValidOffset(offset)) {
3386     data = DataExtractor(data, offset, data.GetByteSize() - offset);
3387     const DWARFUnit *dwarf_cu = form_value.GetUnit();
3388     if (DWARFExpression::ParseDWARFLocationList(dwarf_cu, data, &location_list))
3389       location_list.SetFuncFileAddress(func_low_pc);
3390   }
3391 
3392   return location_list;
3393 }
3394 
3395 /// Creates a DWARFExpressionList from an DW_AT_const_value. This is either a
3396 /// block form, or a string, or a data form. For data forms, this returns an
3397 /// empty list, as we cannot initialize it properly without a SymbolFileType.
3398 static DWARFExpressionList
GetExprListFromAtConstValue(DWARFFormValue form_value,ModuleSP module,const DWARFDIE & die)3399 GetExprListFromAtConstValue(DWARFFormValue form_value, ModuleSP module,
3400                             const DWARFDIE &die) {
3401   const DWARFDataExtractor &debug_info_data = die.GetData();
3402   if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3403     // Retrieve the value as a block expression.
3404     uint64_t block_offset =
3405         form_value.BlockData() - debug_info_data.GetDataStart();
3406     uint64_t block_length = form_value.Unsigned();
3407     return DWARFExpressionList(
3408         module, DataExtractor(debug_info_data, block_offset, block_length),
3409         die.GetCU());
3410   }
3411   if (const char *str = form_value.AsCString())
3412     return DWARFExpressionList(module,
3413                                DataExtractor(str, strlen(str) + 1,
3414                                              die.GetCU()->GetByteOrder(),
3415                                              die.GetCU()->GetAddressByteSize()),
3416                                die.GetCU());
3417   return DWARFExpressionList(module, DWARFExpression(), die.GetCU());
3418 }
3419 
3420 /// Global variables that are not initialized may have their address set to
3421 /// zero. Since multiple variables may have this address, we cannot apply the
3422 /// OSO relink address approach we normally use.
3423 /// However, the executable will have a matching symbol with a good address;
3424 /// this function attempts to find the correct address by looking into the
3425 /// executable's symbol table. If it succeeds, the expr_list is updated with
3426 /// the new address and the executable's symbol is returned.
fixupExternalAddrZeroVariable(SymbolFileDWARFDebugMap & debug_map_symfile,llvm::StringRef name,DWARFExpressionList & expr_list,const DWARFDIE & die)3427 static Symbol *fixupExternalAddrZeroVariable(
3428     SymbolFileDWARFDebugMap &debug_map_symfile, llvm::StringRef name,
3429     DWARFExpressionList &expr_list, const DWARFDIE &die) {
3430   ObjectFile *debug_map_objfile = debug_map_symfile.GetObjectFile();
3431   if (!debug_map_objfile)
3432     return nullptr;
3433 
3434   Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3435   if (!debug_map_symtab)
3436     return nullptr;
3437   Symbol *exe_symbol = debug_map_symtab->FindFirstSymbolWithNameAndType(
3438       ConstString(name), eSymbolTypeData, Symtab::eDebugYes,
3439       Symtab::eVisibilityExtern);
3440   if (!exe_symbol || !exe_symbol->ValueIsAddress())
3441     return nullptr;
3442   const addr_t exe_file_addr = exe_symbol->GetAddressRef().GetFileAddress();
3443   if (exe_file_addr == LLDB_INVALID_ADDRESS)
3444     return nullptr;
3445 
3446   DWARFExpression *location = expr_list.GetMutableExpressionAtAddress();
3447   if (location->Update_DW_OP_addr(die.GetCU(), exe_file_addr))
3448     return exe_symbol;
3449   return nullptr;
3450 }
3451 
ParseVariableDIE(const SymbolContext & sc,const DWARFDIE & die,const lldb::addr_t func_low_pc)3452 VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc,
3453                                              const DWARFDIE &die,
3454                                              const lldb::addr_t func_low_pc) {
3455   if (die.GetDWARF() != this)
3456     return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3457 
3458   if (!die)
3459     return nullptr;
3460 
3461   const dw_tag_t tag = die.Tag();
3462   ModuleSP module = GetObjectFile()->GetModule();
3463 
3464   if (tag != DW_TAG_variable && tag != DW_TAG_constant &&
3465       (tag != DW_TAG_formal_parameter || !sc.function))
3466     return nullptr;
3467 
3468   DWARFAttributes attributes = die.GetAttributes();
3469   const char *name = nullptr;
3470   const char *mangled = nullptr;
3471   Declaration decl;
3472   DWARFFormValue type_die_form;
3473   bool is_external = false;
3474   bool is_artificial = false;
3475   DWARFFormValue const_value_form, location_form;
3476   Variable::RangeList scope_ranges;
3477 
3478   for (size_t i = 0; i < attributes.Size(); ++i) {
3479     dw_attr_t attr = attributes.AttributeAtIndex(i);
3480     DWARFFormValue form_value;
3481 
3482     if (!attributes.ExtractFormValueAtIndex(i, form_value))
3483       continue;
3484     switch (attr) {
3485     case DW_AT_decl_file:
3486       decl.SetFile(
3487           attributes.CompileUnitAtIndex(i)->GetFile(form_value.Unsigned()));
3488       break;
3489     case DW_AT_decl_line:
3490       decl.SetLine(form_value.Unsigned());
3491       break;
3492     case DW_AT_decl_column:
3493       decl.SetColumn(form_value.Unsigned());
3494       break;
3495     case DW_AT_name:
3496       name = form_value.AsCString();
3497       break;
3498     case DW_AT_linkage_name:
3499     case DW_AT_MIPS_linkage_name:
3500       mangled = form_value.AsCString();
3501       break;
3502     case DW_AT_type:
3503       type_die_form = form_value;
3504       break;
3505     case DW_AT_external:
3506       is_external = form_value.Boolean();
3507       break;
3508     case DW_AT_const_value:
3509       const_value_form = form_value;
3510       break;
3511     case DW_AT_location:
3512       location_form = form_value;
3513       break;
3514     case DW_AT_start_scope:
3515       // TODO: Implement this.
3516       break;
3517     case DW_AT_artificial:
3518       is_artificial = form_value.Boolean();
3519       break;
3520     case DW_AT_declaration:
3521     case DW_AT_description:
3522     case DW_AT_endianity:
3523     case DW_AT_segment:
3524     case DW_AT_specification:
3525     case DW_AT_visibility:
3526     default:
3527     case DW_AT_abstract_origin:
3528     case DW_AT_sibling:
3529       break;
3530     }
3531   }
3532 
3533   // Prefer DW_AT_location over DW_AT_const_value. Both can be emitted e.g.
3534   // for static constexpr member variables -- DW_AT_const_value and
3535   // DW_AT_location will both be present in the DIE defining the member.
3536   bool location_is_const_value_data =
3537       const_value_form.IsValid() && !location_form.IsValid();
3538 
3539   DWARFExpressionList location_list = [&] {
3540     if (location_form.IsValid())
3541       return GetExprListFromAtLocation(location_form, module, die, func_low_pc);
3542     if (const_value_form.IsValid())
3543       return GetExprListFromAtConstValue(const_value_form, module, die);
3544     return DWARFExpressionList(module, DWARFExpression(), die.GetCU());
3545   }();
3546 
3547   const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3548   const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3549   const dw_tag_t parent_tag = sc_parent_die.Tag();
3550   bool is_static_member = (parent_tag == DW_TAG_compile_unit ||
3551                            parent_tag == DW_TAG_partial_unit) &&
3552                           (parent_context_die.Tag() == DW_TAG_class_type ||
3553                            parent_context_die.Tag() == DW_TAG_structure_type);
3554 
3555   ValueType scope = eValueTypeInvalid;
3556   SymbolContextScope *symbol_context_scope = nullptr;
3557 
3558   bool has_explicit_mangled = mangled != nullptr;
3559   if (!mangled) {
3560     // LLDB relies on the mangled name (DW_TAG_linkage_name or
3561     // DW_AT_MIPS_linkage_name) to generate fully qualified names
3562     // of global variables with commands like "frame var j". For
3563     // example, if j were an int variable holding a value 4 and
3564     // declared in a namespace B which in turn is contained in a
3565     // namespace A, the command "frame var j" returns
3566     //   "(int) A::B::j = 4".
3567     // If the compiler does not emit a linkage name, we should be
3568     // able to generate a fully qualified name from the
3569     // declaration context.
3570     if ((parent_tag == DW_TAG_compile_unit ||
3571          parent_tag == DW_TAG_partial_unit) &&
3572         Language::LanguageIsCPlusPlus(GetLanguage(*die.GetCU())))
3573       mangled = die.GetDWARFDeclContext()
3574                     .GetQualifiedNameAsConstString()
3575                     .GetCString();
3576   }
3577 
3578   if (tag == DW_TAG_formal_parameter)
3579     scope = eValueTypeVariableArgument;
3580   else {
3581     // DWARF doesn't specify if a DW_TAG_variable is a local, global
3582     // or static variable, so we have to do a little digging:
3583     // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3584     // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3585     // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3586     // Clang likes to combine small global variables into the same symbol
3587     // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3588     // so we need to look through the whole expression.
3589     bool has_explicit_location = location_form.IsValid();
3590     bool is_static_lifetime =
3591         has_explicit_mangled ||
3592         (has_explicit_location && !location_list.IsValid());
3593     // Check if the location has a DW_OP_addr with any address value...
3594     lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3595     if (!location_is_const_value_data) {
3596       bool op_error = false;
3597       const DWARFExpression* location = location_list.GetAlwaysValidExpr();
3598       if (location)
3599         location_DW_OP_addr =
3600             location->GetLocation_DW_OP_addr(location_form.GetUnit(), op_error);
3601       if (op_error) {
3602         StreamString strm;
3603         location->DumpLocation(&strm, eDescriptionLevelFull, nullptr);
3604         GetObjectFile()->GetModule()->ReportError(
3605             "{0:x16}: {1} ({2}) has an invalid location: {3}", die.GetOffset(),
3606             DW_TAG_value_to_name(die.Tag()), die.Tag(), strm.GetData());
3607       }
3608       if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
3609         is_static_lifetime = true;
3610     }
3611     SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
3612     if (debug_map_symfile)
3613       // Set the module of the expression to the linked module
3614       // instead of the object file so the relocated address can be
3615       // found there.
3616       location_list.SetModule(debug_map_symfile->GetObjectFile()->GetModule());
3617 
3618     if (is_static_lifetime) {
3619       if (is_external)
3620         scope = eValueTypeVariableGlobal;
3621       else
3622         scope = eValueTypeVariableStatic;
3623 
3624       if (debug_map_symfile) {
3625         bool linked_oso_file_addr = false;
3626 
3627         if (is_external && location_DW_OP_addr == 0) {
3628           if (Symbol *exe_symbol = fixupExternalAddrZeroVariable(
3629                   *debug_map_symfile, mangled ? mangled : name, location_list,
3630                   die)) {
3631             linked_oso_file_addr = true;
3632             symbol_context_scope = exe_symbol;
3633           }
3634         }
3635 
3636         if (!linked_oso_file_addr) {
3637           // The DW_OP_addr is not zero, but it contains a .o file address
3638           // which needs to be linked up correctly.
3639           const lldb::addr_t exe_file_addr =
3640               debug_map_symfile->LinkOSOFileAddress(this, location_DW_OP_addr);
3641           if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3642             // Update the file address for this variable
3643             DWARFExpression *location =
3644                 location_list.GetMutableExpressionAtAddress();
3645             location->Update_DW_OP_addr(die.GetCU(), exe_file_addr);
3646           } else {
3647             // Variable didn't make it into the final executable
3648             return nullptr;
3649           }
3650         }
3651       }
3652     } else {
3653       if (location_is_const_value_data &&
3654           die.GetDIE()->IsGlobalOrStaticScopeVariable())
3655         scope = eValueTypeVariableStatic;
3656       else {
3657         scope = eValueTypeVariableLocal;
3658         if (debug_map_symfile) {
3659           // We need to check for TLS addresses that we need to fixup
3660           if (location_list.ContainsThreadLocalStorage()) {
3661             location_list.LinkThreadLocalStorage(
3662                 debug_map_symfile->GetObjectFile()->GetModule(),
3663                 [this, debug_map_symfile](
3664                     lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
3665                   return debug_map_symfile->LinkOSOFileAddress(
3666                       this, unlinked_file_addr);
3667                 });
3668             scope = eValueTypeVariableThreadLocal;
3669           }
3670         }
3671       }
3672     }
3673   }
3674 
3675   if (symbol_context_scope == nullptr) {
3676     switch (parent_tag) {
3677     case DW_TAG_subprogram:
3678     case DW_TAG_inlined_subroutine:
3679     case DW_TAG_lexical_block:
3680       if (sc.function) {
3681         symbol_context_scope =
3682             sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID());
3683         if (symbol_context_scope == nullptr)
3684           symbol_context_scope = sc.function;
3685       }
3686       break;
3687 
3688     default:
3689       symbol_context_scope = sc.comp_unit;
3690       break;
3691     }
3692   }
3693 
3694   if (!symbol_context_scope) {
3695     // Not ready to parse this variable yet. It might be a global or static
3696     // variable that is in a function scope and the function in the symbol
3697     // context wasn't filled in yet
3698     return nullptr;
3699   }
3700 
3701   auto type_sp = std::make_shared<SymbolFileType>(
3702       *this, type_die_form.Reference().GetID());
3703 
3704   bool use_type_size_for_value =
3705       location_is_const_value_data &&
3706       DWARFFormValue::IsDataForm(const_value_form.Form());
3707   if (use_type_size_for_value && type_sp->GetType()) {
3708     DWARFExpression *location = location_list.GetMutableExpressionAtAddress();
3709     location->UpdateValue(const_value_form.Unsigned(),
3710                           type_sp->GetType()->GetByteSize(nullptr).value_or(0),
3711                           die.GetCU()->GetAddressByteSize());
3712   }
3713 
3714   return std::make_shared<Variable>(
3715       die.GetID(), name, mangled, type_sp, scope, symbol_context_scope,
3716       scope_ranges, &decl, location_list, is_external, is_artificial,
3717       location_is_const_value_data, is_static_member);
3718 }
3719 
3720 DWARFDIE
FindBlockContainingSpecification(const DIERef & func_die_ref,dw_offset_t spec_block_die_offset)3721 SymbolFileDWARF::FindBlockContainingSpecification(
3722     const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
3723   // Give the concrete function die specified by "func_die_offset", find the
3724   // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3725   // to "spec_block_die_offset"
3726   return FindBlockContainingSpecification(GetDIE(func_die_ref),
3727                                           spec_block_die_offset);
3728 }
3729 
3730 DWARFDIE
FindBlockContainingSpecification(const DWARFDIE & die,dw_offset_t spec_block_die_offset)3731 SymbolFileDWARF::FindBlockContainingSpecification(
3732     const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
3733   if (die) {
3734     switch (die.Tag()) {
3735     case DW_TAG_subprogram:
3736     case DW_TAG_inlined_subroutine:
3737     case DW_TAG_lexical_block: {
3738       if (die.GetReferencedDIE(DW_AT_specification).GetOffset() ==
3739           spec_block_die_offset)
3740         return die;
3741 
3742       if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() ==
3743           spec_block_die_offset)
3744         return die;
3745     } break;
3746     default:
3747       break;
3748     }
3749 
3750     // Give the concrete function die specified by "func_die_offset", find the
3751     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3752     // to "spec_block_die_offset"
3753     for (DWARFDIE child_die : die.children()) {
3754       DWARFDIE result_die =
3755           FindBlockContainingSpecification(child_die, spec_block_die_offset);
3756       if (result_die)
3757         return result_die;
3758     }
3759   }
3760 
3761   return DWARFDIE();
3762 }
3763 
ParseAndAppendGlobalVariable(const SymbolContext & sc,const DWARFDIE & die,VariableList & cc_variable_list)3764 void SymbolFileDWARF::ParseAndAppendGlobalVariable(
3765     const SymbolContext &sc, const DWARFDIE &die,
3766     VariableList &cc_variable_list) {
3767   if (!die)
3768     return;
3769 
3770   dw_tag_t tag = die.Tag();
3771   if (tag != DW_TAG_variable && tag != DW_TAG_constant)
3772     return;
3773 
3774   // Check to see if we have already parsed this variable or constant?
3775   VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
3776   if (var_sp) {
3777     cc_variable_list.AddVariableIfUnique(var_sp);
3778     return;
3779   }
3780 
3781   // We haven't parsed the variable yet, lets do that now. Also, let us include
3782   // the variable in the relevant compilation unit's variable list, if it
3783   // exists.
3784   VariableListSP variable_list_sp;
3785   DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3786   dw_tag_t parent_tag = sc_parent_die.Tag();
3787   switch (parent_tag) {
3788   case DW_TAG_compile_unit:
3789   case DW_TAG_partial_unit:
3790     if (sc.comp_unit != nullptr) {
3791       variable_list_sp = sc.comp_unit->GetVariableList(false);
3792     } else {
3793       GetObjectFile()->GetModule()->ReportError(
3794           "parent {0:x8} {1} ({2}) with no valid compile unit in "
3795           "symbol context for {3:x8} {4} ({5}).\n",
3796           sc_parent_die.GetID(), DW_TAG_value_to_name(sc_parent_die.Tag()),
3797           sc_parent_die.Tag(), die.GetID(), DW_TAG_value_to_name(die.Tag()),
3798           die.Tag());
3799       return;
3800     }
3801     break;
3802 
3803   default:
3804     GetObjectFile()->GetModule()->ReportError(
3805         "didn't find appropriate parent DIE for variable list for {0:x8} "
3806         "{1} ({2}).\n",
3807         die.GetID(), DW_TAG_value_to_name(die.Tag()), die.Tag());
3808     return;
3809   }
3810 
3811   var_sp = ParseVariableDIECached(sc, die);
3812   if (!var_sp)
3813     return;
3814 
3815   cc_variable_list.AddVariableIfUnique(var_sp);
3816   if (variable_list_sp)
3817     variable_list_sp->AddVariableIfUnique(var_sp);
3818 }
3819 
3820 DIEArray
MergeBlockAbstractParameters(const DWARFDIE & block_die,DIEArray && variable_dies)3821 SymbolFileDWARF::MergeBlockAbstractParameters(const DWARFDIE &block_die,
3822                                               DIEArray &&variable_dies) {
3823   // DW_TAG_inline_subroutine objects may omit DW_TAG_formal_parameter in
3824   // instances of the function when they are unused (i.e., the parameter's
3825   // location list would be empty). The current DW_TAG_inline_subroutine may
3826   // refer to another DW_TAG_subprogram that might actually have the definitions
3827   // of the parameters and we need to include these so they show up in the
3828   // variables for this function (for example, in a stack trace). Let us try to
3829   // find the abstract subprogram that might contain the parameter definitions
3830   // and merge with the concrete parameters.
3831 
3832   // Nothing to merge if the block is not an inlined function.
3833   if (block_die.Tag() != DW_TAG_inlined_subroutine) {
3834     return std::move(variable_dies);
3835   }
3836 
3837   // Nothing to merge if the block does not have abstract parameters.
3838   DWARFDIE abs_die = block_die.GetReferencedDIE(DW_AT_abstract_origin);
3839   if (!abs_die || abs_die.Tag() != DW_TAG_subprogram ||
3840       !abs_die.HasChildren()) {
3841     return std::move(variable_dies);
3842   }
3843 
3844   // For each abstract parameter, if we have its concrete counterpart, insert
3845   // it. Otherwise, insert the abstract parameter.
3846   DIEArray::iterator concrete_it = variable_dies.begin();
3847   DWARFDIE abstract_child = abs_die.GetFirstChild();
3848   DIEArray merged;
3849   bool did_merge_abstract = false;
3850   for (; abstract_child; abstract_child = abstract_child.GetSibling()) {
3851     if (abstract_child.Tag() == DW_TAG_formal_parameter) {
3852       if (concrete_it == variable_dies.end() ||
3853           GetDIE(*concrete_it).Tag() != DW_TAG_formal_parameter) {
3854         // We arrived at the end of the concrete parameter list, so all
3855         // the remaining abstract parameters must have been omitted.
3856         // Let us insert them to the merged list here.
3857         merged.push_back(*abstract_child.GetDIERef());
3858         did_merge_abstract = true;
3859         continue;
3860       }
3861 
3862       DWARFDIE origin_of_concrete =
3863           GetDIE(*concrete_it).GetReferencedDIE(DW_AT_abstract_origin);
3864       if (origin_of_concrete == abstract_child) {
3865         // The current abstract parameter is the origin of the current
3866         // concrete parameter, just push the concrete parameter.
3867         merged.push_back(*concrete_it);
3868         ++concrete_it;
3869       } else {
3870         // Otherwise, the parameter must have been omitted from the concrete
3871         // function, so insert the abstract one.
3872         merged.push_back(*abstract_child.GetDIERef());
3873         did_merge_abstract = true;
3874       }
3875     }
3876   }
3877 
3878   // Shortcut if no merging happened.
3879   if (!did_merge_abstract)
3880     return std::move(variable_dies);
3881 
3882   // We inserted all the abstract parameters (or their concrete counterparts).
3883   // Let us insert all the remaining concrete variables to the merged list.
3884   // During the insertion, let us check there are no remaining concrete
3885   // formal parameters. If that's the case, then just bailout from the merge -
3886   // the variable list is malformed.
3887   for (; concrete_it != variable_dies.end(); ++concrete_it) {
3888     if (GetDIE(*concrete_it).Tag() == DW_TAG_formal_parameter) {
3889       return std::move(variable_dies);
3890     }
3891     merged.push_back(*concrete_it);
3892   }
3893   return merged;
3894 }
3895 
ParseVariablesInFunctionContext(const SymbolContext & sc,const DWARFDIE & die,const lldb::addr_t func_low_pc)3896 size_t SymbolFileDWARF::ParseVariablesInFunctionContext(
3897     const SymbolContext &sc, const DWARFDIE &die,
3898     const lldb::addr_t func_low_pc) {
3899   if (!die || !sc.function)
3900     return 0;
3901 
3902   DIEArray dummy_block_variables; // The recursive call should not add anything
3903                                   // to this vector because |die| should be a
3904                                   // subprogram, so all variables will be added
3905                                   // to the subprogram's list.
3906   return ParseVariablesInFunctionContextRecursive(sc, die, func_low_pc,
3907                                                   dummy_block_variables);
3908 }
3909 
3910 // This method parses all the variables in the blocks in the subtree of |die|,
3911 // and inserts them to the variable list for all the nested blocks.
3912 // The uninserted variables for the current block are accumulated in
3913 // |accumulator|.
ParseVariablesInFunctionContextRecursive(const lldb_private::SymbolContext & sc,const DWARFDIE & die,lldb::addr_t func_low_pc,DIEArray & accumulator)3914 size_t SymbolFileDWARF::ParseVariablesInFunctionContextRecursive(
3915     const lldb_private::SymbolContext &sc, const DWARFDIE &die,
3916     lldb::addr_t func_low_pc, DIEArray &accumulator) {
3917   size_t vars_added = 0;
3918   dw_tag_t tag = die.Tag();
3919 
3920   if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3921       (tag == DW_TAG_formal_parameter)) {
3922     accumulator.push_back(*die.GetDIERef());
3923   }
3924 
3925   switch (tag) {
3926   case DW_TAG_subprogram:
3927   case DW_TAG_inlined_subroutine:
3928   case DW_TAG_lexical_block: {
3929     // If we start a new block, compute a new block variable list and recurse.
3930     Block *block =
3931         sc.function->GetBlock(/*can_create=*/true).FindBlockByID(die.GetID());
3932     if (block == nullptr) {
3933       // This must be a specification or abstract origin with a
3934       // concrete block counterpart in the current function. We need
3935       // to find the concrete block so we can correctly add the
3936       // variable to it.
3937       const DWARFDIE concrete_block_die = FindBlockContainingSpecification(
3938           GetDIE(sc.function->GetID()), die.GetOffset());
3939       if (concrete_block_die)
3940         block = sc.function->GetBlock(/*can_create=*/true)
3941                     .FindBlockByID(concrete_block_die.GetID());
3942     }
3943 
3944     if (block == nullptr)
3945       return 0;
3946 
3947     const bool can_create = false;
3948     VariableListSP block_variable_list_sp =
3949         block->GetBlockVariableList(can_create);
3950     if (block_variable_list_sp.get() == nullptr) {
3951       block_variable_list_sp = std::make_shared<VariableList>();
3952       block->SetVariableList(block_variable_list_sp);
3953     }
3954 
3955     DIEArray block_variables;
3956     for (DWARFDIE child = die.GetFirstChild(); child;
3957          child = child.GetSibling()) {
3958       vars_added += ParseVariablesInFunctionContextRecursive(
3959           sc, child, func_low_pc, block_variables);
3960     }
3961     block_variables =
3962         MergeBlockAbstractParameters(die, std::move(block_variables));
3963     vars_added += PopulateBlockVariableList(*block_variable_list_sp, sc,
3964                                             block_variables, func_low_pc);
3965     break;
3966   }
3967 
3968   default:
3969     // Recurse to children with the same variable accumulator.
3970     for (DWARFDIE child = die.GetFirstChild(); child;
3971          child = child.GetSibling()) {
3972       vars_added += ParseVariablesInFunctionContextRecursive(
3973           sc, child, func_low_pc, accumulator);
3974     }
3975     break;
3976   }
3977 
3978   return vars_added;
3979 }
3980 
PopulateBlockVariableList(VariableList & variable_list,const lldb_private::SymbolContext & sc,llvm::ArrayRef<DIERef> variable_dies,lldb::addr_t func_low_pc)3981 size_t SymbolFileDWARF::PopulateBlockVariableList(
3982     VariableList &variable_list, const lldb_private::SymbolContext &sc,
3983     llvm::ArrayRef<DIERef> variable_dies, lldb::addr_t func_low_pc) {
3984   // Parse the variable DIEs and insert them to the list.
3985   for (auto &die : variable_dies) {
3986     if (VariableSP var_sp = ParseVariableDIE(sc, GetDIE(die), func_low_pc)) {
3987       variable_list.AddVariableIfUnique(var_sp);
3988     }
3989   }
3990   return variable_dies.size();
3991 }
3992 
3993 /// Collect call site parameters in a DW_TAG_call_site DIE.
3994 static CallSiteParameterArray
CollectCallSiteParameters(ModuleSP module,DWARFDIE call_site_die)3995 CollectCallSiteParameters(ModuleSP module, DWARFDIE call_site_die) {
3996   CallSiteParameterArray parameters;
3997   for (DWARFDIE child : call_site_die.children()) {
3998     if (child.Tag() != DW_TAG_call_site_parameter &&
3999         child.Tag() != DW_TAG_GNU_call_site_parameter)
4000       continue;
4001 
4002     std::optional<DWARFExpressionList> LocationInCallee;
4003     std::optional<DWARFExpressionList> LocationInCaller;
4004 
4005     DWARFAttributes attributes = child.GetAttributes();
4006 
4007     // Parse the location at index \p attr_index within this call site parameter
4008     // DIE, or return std::nullopt on failure.
4009     auto parse_simple_location =
4010         [&](int attr_index) -> std::optional<DWARFExpressionList> {
4011       DWARFFormValue form_value;
4012       if (!attributes.ExtractFormValueAtIndex(attr_index, form_value))
4013         return {};
4014       if (!DWARFFormValue::IsBlockForm(form_value.Form()))
4015         return {};
4016       auto data = child.GetData();
4017       uint64_t block_offset = form_value.BlockData() - data.GetDataStart();
4018       uint64_t block_length = form_value.Unsigned();
4019       return DWARFExpressionList(
4020           module, DataExtractor(data, block_offset, block_length),
4021           child.GetCU());
4022     };
4023 
4024     for (size_t i = 0; i < attributes.Size(); ++i) {
4025       dw_attr_t attr = attributes.AttributeAtIndex(i);
4026       if (attr == DW_AT_location)
4027         LocationInCallee = parse_simple_location(i);
4028       if (attr == DW_AT_call_value || attr == DW_AT_GNU_call_site_value)
4029         LocationInCaller = parse_simple_location(i);
4030     }
4031 
4032     if (LocationInCallee && LocationInCaller) {
4033       CallSiteParameter param = {*LocationInCallee, *LocationInCaller};
4034       parameters.push_back(param);
4035     }
4036   }
4037   return parameters;
4038 }
4039 
4040 /// Collect call graph edges present in a function DIE.
4041 std::vector<std::unique_ptr<lldb_private::CallEdge>>
CollectCallEdges(ModuleSP module,DWARFDIE function_die)4042 SymbolFileDWARF::CollectCallEdges(ModuleSP module, DWARFDIE function_die) {
4043   // Check if the function has a supported call site-related attribute.
4044   // TODO: In the future it may be worthwhile to support call_all_source_calls.
4045   bool has_call_edges =
4046       function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0) ||
4047       function_die.GetAttributeValueAsUnsigned(DW_AT_GNU_all_call_sites, 0);
4048   if (!has_call_edges)
4049     return {};
4050 
4051   Log *log = GetLog(LLDBLog::Step);
4052   LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}",
4053            function_die.GetPubname());
4054 
4055   // Scan the DIE for TAG_call_site entries.
4056   // TODO: A recursive scan of all blocks in the subprogram is needed in order
4057   // to be DWARF5-compliant. This may need to be done lazily to be performant.
4058   // For now, assume that all entries are nested directly under the subprogram
4059   // (this is the kind of DWARF LLVM produces) and parse them eagerly.
4060   std::vector<std::unique_ptr<CallEdge>> call_edges;
4061   for (DWARFDIE child : function_die.children()) {
4062     if (child.Tag() != DW_TAG_call_site && child.Tag() != DW_TAG_GNU_call_site)
4063       continue;
4064 
4065     std::optional<DWARFDIE> call_origin;
4066     std::optional<DWARFExpressionList> call_target;
4067     addr_t return_pc = LLDB_INVALID_ADDRESS;
4068     addr_t call_inst_pc = LLDB_INVALID_ADDRESS;
4069     addr_t low_pc = LLDB_INVALID_ADDRESS;
4070     bool tail_call = false;
4071 
4072     // Second DW_AT_low_pc may come from DW_TAG_subprogram referenced by
4073     // DW_TAG_GNU_call_site's DW_AT_abstract_origin overwriting our 'low_pc'.
4074     // So do not inherit attributes from DW_AT_abstract_origin.
4075     DWARFAttributes attributes = child.GetAttributes(DWARFDIE::Recurse::no);
4076     for (size_t i = 0; i < attributes.Size(); ++i) {
4077       DWARFFormValue form_value;
4078       if (!attributes.ExtractFormValueAtIndex(i, form_value)) {
4079         LLDB_LOG(log, "CollectCallEdges: Could not extract TAG_call_site form");
4080         break;
4081       }
4082 
4083       dw_attr_t attr = attributes.AttributeAtIndex(i);
4084 
4085       if (attr == DW_AT_call_tail_call || attr == DW_AT_GNU_tail_call)
4086         tail_call = form_value.Boolean();
4087 
4088       // Extract DW_AT_call_origin (the call target's DIE).
4089       if (attr == DW_AT_call_origin || attr == DW_AT_abstract_origin) {
4090         call_origin = form_value.Reference();
4091         if (!call_origin->IsValid()) {
4092           LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}",
4093                    function_die.GetPubname());
4094           break;
4095         }
4096       }
4097 
4098       if (attr == DW_AT_low_pc)
4099         low_pc = form_value.Address();
4100 
4101       // Extract DW_AT_call_return_pc (the PC the call returns to) if it's
4102       // available. It should only ever be unavailable for tail call edges, in
4103       // which case use LLDB_INVALID_ADDRESS.
4104       if (attr == DW_AT_call_return_pc)
4105         return_pc = form_value.Address();
4106 
4107       // Extract DW_AT_call_pc (the PC at the call/branch instruction). It
4108       // should only ever be unavailable for non-tail calls, in which case use
4109       // LLDB_INVALID_ADDRESS.
4110       if (attr == DW_AT_call_pc)
4111         call_inst_pc = form_value.Address();
4112 
4113       // Extract DW_AT_call_target (the location of the address of the indirect
4114       // call).
4115       if (attr == DW_AT_call_target || attr == DW_AT_GNU_call_site_target) {
4116         if (!DWARFFormValue::IsBlockForm(form_value.Form())) {
4117           LLDB_LOG(log,
4118                    "CollectCallEdges: AT_call_target does not have block form");
4119           break;
4120         }
4121 
4122         auto data = child.GetData();
4123         uint64_t block_offset = form_value.BlockData() - data.GetDataStart();
4124         uint64_t block_length = form_value.Unsigned();
4125         call_target = DWARFExpressionList(
4126             module, DataExtractor(data, block_offset, block_length),
4127             child.GetCU());
4128       }
4129     }
4130     if (!call_origin && !call_target) {
4131       LLDB_LOG(log, "CollectCallEdges: call site without any call target");
4132       continue;
4133     }
4134 
4135     addr_t caller_address;
4136     CallEdge::AddrType caller_address_type;
4137     if (return_pc != LLDB_INVALID_ADDRESS) {
4138       caller_address = return_pc;
4139       caller_address_type = CallEdge::AddrType::AfterCall;
4140     } else if (low_pc != LLDB_INVALID_ADDRESS) {
4141       caller_address = low_pc;
4142       caller_address_type = CallEdge::AddrType::AfterCall;
4143     } else if (call_inst_pc != LLDB_INVALID_ADDRESS) {
4144       caller_address = call_inst_pc;
4145       caller_address_type = CallEdge::AddrType::Call;
4146     } else {
4147       LLDB_LOG(log, "CollectCallEdges: No caller address");
4148       continue;
4149     }
4150     // Adjust any PC forms. It needs to be fixed up if the main executable
4151     // contains a debug map (i.e. pointers to object files), because we need a
4152     // file address relative to the executable's text section.
4153     caller_address = FixupAddress(caller_address);
4154 
4155     // Extract call site parameters.
4156     CallSiteParameterArray parameters =
4157         CollectCallSiteParameters(module, child);
4158 
4159     std::unique_ptr<CallEdge> edge;
4160     if (call_origin) {
4161       LLDB_LOG(log,
4162                "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x}) "
4163                "(call-PC: {2:x})",
4164                call_origin->GetPubname(), return_pc, call_inst_pc);
4165       edge = std::make_unique<DirectCallEdge>(
4166           call_origin->GetMangledName(), caller_address_type, caller_address,
4167           tail_call, std::move(parameters));
4168     } else {
4169       if (log) {
4170         StreamString call_target_desc;
4171         call_target->GetDescription(&call_target_desc, eDescriptionLevelBrief,
4172                                     nullptr);
4173         LLDB_LOG(log, "CollectCallEdges: Found indirect call target: {0}",
4174                  call_target_desc.GetString());
4175       }
4176       edge = std::make_unique<IndirectCallEdge>(
4177           *call_target, caller_address_type, caller_address, tail_call,
4178           std::move(parameters));
4179     }
4180 
4181     if (log && parameters.size()) {
4182       for (const CallSiteParameter &param : parameters) {
4183         StreamString callee_loc_desc, caller_loc_desc;
4184         param.LocationInCallee.GetDescription(&callee_loc_desc,
4185                                               eDescriptionLevelBrief, nullptr);
4186         param.LocationInCaller.GetDescription(&caller_loc_desc,
4187                                               eDescriptionLevelBrief, nullptr);
4188         LLDB_LOG(log, "CollectCallEdges: \tparam: {0} => {1}",
4189                  callee_loc_desc.GetString(), caller_loc_desc.GetString());
4190       }
4191     }
4192 
4193     call_edges.push_back(std::move(edge));
4194   }
4195   return call_edges;
4196 }
4197 
4198 std::vector<std::unique_ptr<lldb_private::CallEdge>>
ParseCallEdgesInFunction(lldb_private::UserID func_id)4199 SymbolFileDWARF::ParseCallEdgesInFunction(lldb_private::UserID func_id) {
4200   // ParseCallEdgesInFunction must be called at the behest of an exclusively
4201   // locked lldb::Function instance. Storage for parsed call edges is owned by
4202   // the lldb::Function instance: locking at the SymbolFile level would be too
4203   // late, because the act of storing results from ParseCallEdgesInFunction
4204   // would be racy.
4205   DWARFDIE func_die = GetDIE(func_id.GetID());
4206   if (func_die.IsValid())
4207     return CollectCallEdges(GetObjectFile()->GetModule(), func_die);
4208   return {};
4209 }
4210 
Dump(lldb_private::Stream & s)4211 void SymbolFileDWARF::Dump(lldb_private::Stream &s) {
4212   SymbolFileCommon::Dump(s);
4213   m_index->Dump(s);
4214 }
4215 
DumpClangAST(Stream & s)4216 void SymbolFileDWARF::DumpClangAST(Stream &s) {
4217   auto ts_or_err = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
4218   if (!ts_or_err)
4219     return;
4220   auto ts = *ts_or_err;
4221   TypeSystemClang *clang = llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
4222   if (!clang)
4223     return;
4224   clang->Dump(s.AsRawOstream());
4225 }
4226 
GetSeparateDebugInfo(StructuredData::Dictionary & d,bool errors_only)4227 bool SymbolFileDWARF::GetSeparateDebugInfo(StructuredData::Dictionary &d,
4228                                            bool errors_only) {
4229   StructuredData::Array separate_debug_info_files;
4230   DWARFDebugInfo &info = DebugInfo();
4231   const size_t num_cus = info.GetNumUnits();
4232   for (size_t cu_idx = 0; cu_idx < num_cus; cu_idx++) {
4233     DWARFUnit *unit = info.GetUnitAtIndex(cu_idx);
4234     DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(unit);
4235     if (dwarf_cu == nullptr)
4236       continue;
4237 
4238     // Check if this is a DWO unit by checking if it has a DWO ID.
4239     // NOTE: it seems that `DWARFUnit::IsDWOUnit` is always false?
4240     if (!dwarf_cu->GetDWOId().has_value())
4241       continue;
4242 
4243     StructuredData::DictionarySP dwo_data =
4244         std::make_shared<StructuredData::Dictionary>();
4245     const uint64_t dwo_id = dwarf_cu->GetDWOId().value();
4246     dwo_data->AddIntegerItem("dwo_id", dwo_id);
4247 
4248     if (const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly()) {
4249       const char *dwo_name = GetDWOName(*dwarf_cu, *die.GetDIE());
4250       if (dwo_name) {
4251         dwo_data->AddStringItem("dwo_name", dwo_name);
4252       } else {
4253         dwo_data->AddStringItem("error", "missing dwo name");
4254       }
4255 
4256       const char *comp_dir = die.GetDIE()->GetAttributeValueAsString(
4257           dwarf_cu, DW_AT_comp_dir, nullptr);
4258       if (comp_dir) {
4259         dwo_data->AddStringItem("comp_dir", comp_dir);
4260       }
4261     } else {
4262       dwo_data->AddStringItem(
4263           "error",
4264           llvm::formatv("unable to get unit DIE for DWARFUnit at {0:x}",
4265                         dwarf_cu->GetOffset())
4266               .str());
4267     }
4268 
4269     // If we have a DWO symbol file, that means we were able to successfully
4270     // load it.
4271     SymbolFile *dwo_symfile = dwarf_cu->GetDwoSymbolFile();
4272     if (dwo_symfile) {
4273       dwo_data->AddStringItem(
4274           "resolved_dwo_path",
4275           dwo_symfile->GetObjectFile()->GetFileSpec().GetPath());
4276     } else {
4277       dwo_data->AddStringItem("error",
4278                               dwarf_cu->GetDwoError().AsCString("unknown"));
4279     }
4280     dwo_data->AddBooleanItem("loaded", dwo_symfile != nullptr);
4281     if (!errors_only || dwo_data->HasKey("error"))
4282       separate_debug_info_files.AddItem(dwo_data);
4283   }
4284 
4285   d.AddStringItem("type", "dwo");
4286   d.AddStringItem("symfile", GetMainObjectFile()->GetFileSpec().GetPath());
4287   d.AddItem("separate-debug-info-files",
4288             std::make_shared<StructuredData::Array>(
4289                 std::move(separate_debug_info_files)));
4290   return true;
4291 }
4292 
GetDebugMapSymfile()4293 SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() {
4294   if (m_debug_map_symfile == nullptr) {
4295     lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
4296     if (module_sp) {
4297       m_debug_map_symfile = llvm::cast<SymbolFileDWARFDebugMap>(
4298           module_sp->GetSymbolFile()->GetBackingSymbolFile());
4299     }
4300   }
4301   return m_debug_map_symfile;
4302 }
4303 
GetDwpSymbolFile()4304 const std::shared_ptr<SymbolFileDWARFDwo> &SymbolFileDWARF::GetDwpSymbolFile() {
4305   llvm::call_once(m_dwp_symfile_once_flag, [this]() {
4306     // Create a list of files to try and append .dwp to.
4307     FileSpecList symfiles;
4308     // Append the module's object file path.
4309     const FileSpec module_fspec = m_objfile_sp->GetModule()->GetFileSpec();
4310     symfiles.Append(module_fspec);
4311     // Append the object file for this SymbolFile only if it is different from
4312     // the module's file path. Our main module could be "a.out", our symbol file
4313     // could be "a.debug" and our ".dwp" file might be "a.debug.dwp" instead of
4314     // "a.out.dwp".
4315     const FileSpec symfile_fspec(m_objfile_sp->GetFileSpec());
4316     if (symfile_fspec != module_fspec) {
4317       symfiles.Append(symfile_fspec);
4318     } else {
4319       // If we don't have a separate debug info file, then try stripping the
4320       // extension. The main module could be "a.debug" and the .dwp file could
4321       // be "a.dwp" instead of "a.debug.dwp".
4322       ConstString filename_no_ext =
4323           module_fspec.GetFileNameStrippingExtension();
4324       if (filename_no_ext != module_fspec.GetFilename()) {
4325         FileSpec module_spec_no_ext(module_fspec);
4326         module_spec_no_ext.SetFilename(filename_no_ext);
4327         symfiles.Append(module_spec_no_ext);
4328       }
4329     }
4330     Log *log = GetLog(DWARFLog::SplitDwarf);
4331     FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths();
4332     ModuleSpec module_spec;
4333     module_spec.GetFileSpec() = m_objfile_sp->GetFileSpec();
4334     for (const auto &symfile : symfiles.files()) {
4335       module_spec.GetSymbolFileSpec() =
4336           FileSpec(symfile.GetPath() + ".dwp", symfile.GetPathStyle());
4337       LLDB_LOG(log, "Searching for DWP using: \"{0}\"",
4338                module_spec.GetSymbolFileSpec());
4339       FileSpec dwp_filespec =
4340           PluginManager::LocateExecutableSymbolFile(module_spec, search_paths);
4341       if (FileSystem::Instance().Exists(dwp_filespec)) {
4342         LLDB_LOG(log, "Found DWP file: \"{0}\"", dwp_filespec);
4343         DataBufferSP dwp_file_data_sp;
4344         lldb::offset_t dwp_file_data_offset = 0;
4345         ObjectFileSP dwp_obj_file = ObjectFile::FindPlugin(
4346             GetObjectFile()->GetModule(), &dwp_filespec, 0,
4347             FileSystem::Instance().GetByteSize(dwp_filespec), dwp_file_data_sp,
4348             dwp_file_data_offset);
4349         if (dwp_obj_file) {
4350           m_dwp_symfile = std::make_shared<SymbolFileDWARFDwo>(
4351               *this, dwp_obj_file, DIERef::k_file_index_mask);
4352           break;
4353         }
4354       }
4355     }
4356     if (!m_dwp_symfile) {
4357       LLDB_LOG(log, "Unable to locate for DWP file for: \"{0}\"",
4358                m_objfile_sp->GetModule()->GetFileSpec());
4359     }
4360   });
4361   return m_dwp_symfile;
4362 }
4363 
4364 llvm::Expected<lldb::TypeSystemSP>
GetTypeSystem(DWARFUnit & unit)4365 SymbolFileDWARF::GetTypeSystem(DWARFUnit &unit) {
4366   return unit.GetSymbolFileDWARF().GetTypeSystemForLanguage(GetLanguage(unit));
4367 }
4368 
GetDWARFParser(DWARFUnit & unit)4369 DWARFASTParser *SymbolFileDWARF::GetDWARFParser(DWARFUnit &unit) {
4370   auto type_system_or_err = GetTypeSystem(unit);
4371   if (auto err = type_system_or_err.takeError()) {
4372     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
4373                    "Unable to get DWARFASTParser: {0}");
4374     return nullptr;
4375   }
4376   if (auto ts = *type_system_or_err)
4377     return ts->GetDWARFParser();
4378   return nullptr;
4379 }
4380 
GetDecl(const DWARFDIE & die)4381 CompilerDecl SymbolFileDWARF::GetDecl(const DWARFDIE &die) {
4382   if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
4383     return dwarf_ast->GetDeclForUIDFromDWARF(die);
4384   return CompilerDecl();
4385 }
4386 
GetDeclContext(const DWARFDIE & die)4387 CompilerDeclContext SymbolFileDWARF::GetDeclContext(const DWARFDIE &die) {
4388   if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
4389     return dwarf_ast->GetDeclContextForUIDFromDWARF(die);
4390   return CompilerDeclContext();
4391 }
4392 
4393 CompilerDeclContext
GetContainingDeclContext(const DWARFDIE & die)4394 SymbolFileDWARF::GetContainingDeclContext(const DWARFDIE &die) {
4395   if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
4396     return dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
4397   return CompilerDeclContext();
4398 }
4399 
LanguageTypeFromDWARF(uint64_t val)4400 LanguageType SymbolFileDWARF::LanguageTypeFromDWARF(uint64_t val) {
4401   // Note: user languages between lo_user and hi_user must be handled
4402   // explicitly here.
4403   switch (val) {
4404   case DW_LANG_Mips_Assembler:
4405     return eLanguageTypeMipsAssembler;
4406   default:
4407     return static_cast<LanguageType>(val);
4408   }
4409 }
4410 
GetLanguage(DWARFUnit & unit)4411 LanguageType SymbolFileDWARF::GetLanguage(DWARFUnit &unit) {
4412   return LanguageTypeFromDWARF(unit.GetDWARFLanguageType());
4413 }
4414 
GetLanguageFamily(DWARFUnit & unit)4415 LanguageType SymbolFileDWARF::GetLanguageFamily(DWARFUnit &unit) {
4416   auto lang = (llvm::dwarf::SourceLanguage)unit.GetDWARFLanguageType();
4417   if (llvm::dwarf::isCPlusPlus(lang))
4418     lang = DW_LANG_C_plus_plus;
4419   return LanguageTypeFromDWARF(lang);
4420 }
4421 
GetDebugInfoIndexTime()4422 StatsDuration::Duration SymbolFileDWARF::GetDebugInfoIndexTime() {
4423   if (m_index)
4424     return m_index->GetIndexTime();
4425   return {};
4426 }
4427 
CalculateFrameVariableError(StackFrame & frame)4428 Status SymbolFileDWARF::CalculateFrameVariableError(StackFrame &frame) {
4429   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
4430   CompileUnit *cu = frame.GetSymbolContext(eSymbolContextCompUnit).comp_unit;
4431   if (!cu)
4432     return Status();
4433 
4434   DWARFCompileUnit *dwarf_cu = GetDWARFCompileUnit(cu);
4435   if (!dwarf_cu)
4436     return Status();
4437 
4438   // Check if we have a skeleton compile unit that had issues trying to load
4439   // its .dwo/.dwp file. First pares the Unit DIE to make sure we see any .dwo
4440   // related errors.
4441   dwarf_cu->ExtractUnitDIEIfNeeded();
4442   const Status &dwo_error = dwarf_cu->GetDwoError();
4443   if (dwo_error.Fail())
4444     return dwo_error;
4445 
4446   // Don't return an error for assembly files as they typically don't have
4447   // varaible information.
4448   if (dwarf_cu->GetDWARFLanguageType() == DW_LANG_Mips_Assembler)
4449     return Status();
4450 
4451   // Check if this compile unit has any variable DIEs. If it doesn't then there
4452   // is not variable information for the entire compile unit.
4453   if (dwarf_cu->HasAny({DW_TAG_variable, DW_TAG_formal_parameter}))
4454     return Status();
4455 
4456   return Status("no variable information is available in debug info for this "
4457                 "compile unit");
4458 }
4459 
GetCompileOptions(std::unordered_map<lldb::CompUnitSP,lldb_private::Args> & args)4460 void SymbolFileDWARF::GetCompileOptions(
4461     std::unordered_map<lldb::CompUnitSP, lldb_private::Args> &args) {
4462 
4463   const uint32_t num_compile_units = GetNumCompileUnits();
4464 
4465   for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
4466     lldb::CompUnitSP comp_unit = GetCompileUnitAtIndex(cu_idx);
4467     if (!comp_unit)
4468       continue;
4469 
4470     DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit.get());
4471     if (!dwarf_cu)
4472       continue;
4473 
4474     const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
4475     if (!die)
4476       continue;
4477 
4478     const char *flags = die.GetAttributeValueAsString(DW_AT_APPLE_flags, NULL);
4479 
4480     if (!flags)
4481       continue;
4482     args.insert({comp_unit, Args(flags)});
4483   }
4484 }
4485