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