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