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