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