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(llvm::ArrayRef<CompilerContext> pattern,
2488                                   LanguageSet languages, bool append,
2489                                   TypeMap &types) {
2490   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2491   if (!append)
2492     types.Clear();
2493 
2494   if (pattern.empty())
2495     return 0;
2496 
2497   ConstString name = pattern.back().name;
2498 
2499   if (!name)
2500     return 0;
2501 
2502   DIEArray die_offsets;
2503   m_index->GetTypes(name, die_offsets);
2504   const size_t num_die_matches = die_offsets.size();
2505 
2506   size_t num_matches = 0;
2507   for (size_t i = 0; i < num_die_matches; ++i) {
2508     const DIERef &die_ref = die_offsets[i];
2509     DWARFDIE die = GetDIE(die_ref);
2510 
2511     if (die) {
2512       if (!languages[die.GetCU()->GetLanguageType()])
2513         continue;
2514 
2515       llvm::SmallVector<CompilerContext, 4> die_context;
2516       die.GetDeclContext(die_context);
2517       if (!contextMatches(die_context, pattern))
2518         continue;
2519 
2520       Type *matching_type = ResolveType(die, true, true);
2521       if (matching_type) {
2522         // We found a type pointer, now find the shared pointer form our type
2523         // list
2524         types.InsertUnique(matching_type->shared_from_this());
2525         ++num_matches;
2526       }
2527     } else {
2528       m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2529     }
2530   }
2531   return num_matches;
2532 }
2533 
2534 CompilerDeclContext
2535 SymbolFileDWARF::FindNamespace(ConstString name,
2536                                const CompilerDeclContext *parent_decl_ctx) {
2537   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2538   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2539 
2540   if (log) {
2541     GetObjectFile()->GetModule()->LogMessage(
2542         log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
2543         name.GetCString());
2544   }
2545 
2546   CompilerDeclContext namespace_decl_ctx;
2547 
2548   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2549     return namespace_decl_ctx;
2550 
2551   DWARFDebugInfo *info = DebugInfo();
2552   if (info) {
2553     DIEArray die_offsets;
2554     m_index->GetNamespaces(name, die_offsets);
2555     const size_t num_matches = die_offsets.size();
2556     if (num_matches) {
2557       for (size_t i = 0; i < num_matches; ++i) {
2558         const DIERef &die_ref = die_offsets[i];
2559         DWARFDIE die = GetDIE(die_ref);
2560 
2561         if (die) {
2562           if (!DIEInDeclContext(parent_decl_ctx, die))
2563             continue; // The containing decl contexts don't match
2564 
2565           DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2566           if (dwarf_ast) {
2567             namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
2568             if (namespace_decl_ctx)
2569               break;
2570           }
2571         } else {
2572           m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2573         }
2574       }
2575     }
2576   }
2577   if (log && namespace_decl_ctx) {
2578     GetObjectFile()->GetModule()->LogMessage(
2579         log,
2580         "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => "
2581         "CompilerDeclContext(%p/%p) \"%s\"",
2582         name.GetCString(),
2583         static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
2584         static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
2585         namespace_decl_ctx.GetName().AsCString("<NULL>"));
2586   }
2587 
2588   return namespace_decl_ctx;
2589 }
2590 
2591 TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
2592                                       bool resolve_function_context) {
2593   TypeSP type_sp;
2594   if (die) {
2595     Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
2596     if (type_ptr == nullptr) {
2597       SymbolContextScope *scope;
2598       if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()))
2599         scope = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2600       else
2601         scope = GetObjectFile()->GetModule().get();
2602       assert(scope);
2603       SymbolContext sc(scope);
2604       const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
2605       while (parent_die != nullptr) {
2606         if (parent_die->Tag() == DW_TAG_subprogram)
2607           break;
2608         parent_die = parent_die->GetParent();
2609       }
2610       SymbolContext sc_backup = sc;
2611       if (resolve_function_context && parent_die != nullptr &&
2612           !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
2613         sc = sc_backup;
2614 
2615       type_sp = ParseType(sc, die, nullptr);
2616     } else if (type_ptr != DIE_IS_BEING_PARSED) {
2617       // Grab the existing type from the master types lists
2618       type_sp = type_ptr->shared_from_this();
2619     }
2620   }
2621   return type_sp;
2622 }
2623 
2624 DWARFDIE
2625 SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
2626   if (orig_die) {
2627     DWARFDIE die = orig_die;
2628 
2629     while (die) {
2630       // If this is the original DIE that we are searching for a declaration
2631       // for, then don't look in the cache as we don't want our own decl
2632       // context to be our decl context...
2633       if (orig_die != die) {
2634         switch (die.Tag()) {
2635         case DW_TAG_compile_unit:
2636         case DW_TAG_partial_unit:
2637         case DW_TAG_namespace:
2638         case DW_TAG_structure_type:
2639         case DW_TAG_union_type:
2640         case DW_TAG_class_type:
2641         case DW_TAG_lexical_block:
2642         case DW_TAG_subprogram:
2643           return die;
2644         case DW_TAG_inlined_subroutine: {
2645           DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2646           if (abs_die) {
2647             return abs_die;
2648           }
2649           break;
2650         }
2651         default:
2652           break;
2653         }
2654       }
2655 
2656       DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
2657       if (spec_die) {
2658         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
2659         if (decl_ctx_die)
2660           return decl_ctx_die;
2661       }
2662 
2663       DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2664       if (abs_die) {
2665         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
2666         if (decl_ctx_die)
2667           return decl_ctx_die;
2668       }
2669 
2670       die = die.GetParent();
2671     }
2672   }
2673   return DWARFDIE();
2674 }
2675 
2676 Symbol *SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) {
2677   Symbol *objc_class_symbol = nullptr;
2678   if (m_objfile_sp) {
2679     Symtab *symtab = m_objfile_sp->GetSymtab();
2680     if (symtab) {
2681       objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
2682           objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
2683           Symtab::eVisibilityAny);
2684     }
2685   }
2686   return objc_class_symbol;
2687 }
2688 
2689 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If
2690 // they don't then we can end up looking through all class types for a complete
2691 // type and never find the full definition. We need to know if this attribute
2692 // is supported, so we determine this here and cache th result. We also need to
2693 // worry about the debug map
2694 // DWARF file
2695 // if we are doing darwin DWARF in .o file debugging.
2696 bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(DWARFUnit *cu) {
2697   if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) {
2698     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
2699     if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
2700       m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2701     else {
2702       DWARFDebugInfo *debug_info = DebugInfo();
2703       const uint32_t num_compile_units = GetNumCompileUnits();
2704       for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2705         DWARFUnit *dwarf_cu = debug_info->GetUnitAtIndex(cu_idx);
2706         if (dwarf_cu != cu &&
2707             dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) {
2708           m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2709           break;
2710         }
2711       }
2712     }
2713     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo &&
2714         GetDebugMapSymfile())
2715       return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this);
2716   }
2717   return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
2718 }
2719 
2720 // This function can be used when a DIE is found that is a forward declaration
2721 // DIE and we want to try and find a type that has the complete definition.
2722 TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE(
2723     const DWARFDIE &die, ConstString type_name, bool must_be_implementation) {
2724 
2725   TypeSP type_sp;
2726 
2727   if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
2728     return type_sp;
2729 
2730   DIEArray die_offsets;
2731   m_index->GetCompleteObjCClass(type_name, must_be_implementation, die_offsets);
2732 
2733   const size_t num_matches = die_offsets.size();
2734 
2735   if (num_matches) {
2736     for (size_t i = 0; i < num_matches; ++i) {
2737       const DIERef &die_ref = die_offsets[i];
2738       DWARFDIE type_die = GetDIE(die_ref);
2739 
2740       if (type_die) {
2741         bool try_resolving_type = false;
2742 
2743         // Don't try and resolve the DIE we are looking for with the DIE
2744         // itself!
2745         if (type_die != die) {
2746           switch (type_die.Tag()) {
2747           case DW_TAG_class_type:
2748           case DW_TAG_structure_type:
2749             try_resolving_type = true;
2750             break;
2751           default:
2752             break;
2753           }
2754         }
2755 
2756         if (try_resolving_type) {
2757           if (must_be_implementation &&
2758               type_die.Supports_DW_AT_APPLE_objc_complete_type())
2759             try_resolving_type = type_die.GetAttributeValueAsUnsigned(
2760                 DW_AT_APPLE_objc_complete_type, 0);
2761 
2762           if (try_resolving_type) {
2763             Type *resolved_type = ResolveType(type_die, false, true);
2764             if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2765               DEBUG_PRINTF("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
2766                            " (cu 0x%8.8" PRIx64 ")\n",
2767                            die.GetID(),
2768                            m_objfile_sp->GetFileSpec().GetFilename().AsCString(
2769                                "<Unknown>"),
2770                            type_die.GetID(), type_cu->GetID());
2771 
2772               if (die)
2773                 GetDIEToType()[die.GetDIE()] = resolved_type;
2774               type_sp = resolved_type->shared_from_this();
2775               break;
2776             }
2777           }
2778         }
2779       } else {
2780         m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
2781       }
2782     }
2783   }
2784   return type_sp;
2785 }
2786 
2787 // This function helps to ensure that the declaration contexts match for two
2788 // different DIEs. Often times debug information will refer to a forward
2789 // declaration of a type (the equivalent of "struct my_struct;". There will
2790 // often be a declaration of that type elsewhere that has the full definition.
2791 // When we go looking for the full type "my_struct", we will find one or more
2792 // matches in the accelerator tables and we will then need to make sure the
2793 // type was in the same declaration context as the original DIE. This function
2794 // can efficiently compare two DIEs and will return true when the declaration
2795 // context matches, and false when they don't.
2796 bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1,
2797                                            const DWARFDIE &die2) {
2798   if (die1 == die2)
2799     return true;
2800 
2801   std::vector<DWARFDIE> decl_ctx_1;
2802   std::vector<DWARFDIE> decl_ctx_2;
2803   // The declaration DIE stack is a stack of the declaration context DIEs all
2804   // the way back to the compile unit. If a type "T" is declared inside a class
2805   // "B", and class "B" is declared inside a class "A" and class "A" is in a
2806   // namespace "lldb", and the namespace is in a compile unit, there will be a
2807   // stack of DIEs:
2808   //
2809   //   [0] DW_TAG_class_type for "B"
2810   //   [1] DW_TAG_class_type for "A"
2811   //   [2] DW_TAG_namespace  for "lldb"
2812   //   [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file.
2813   //
2814   // We grab both contexts and make sure that everything matches all the way
2815   // back to the compiler unit.
2816 
2817   // First lets grab the decl contexts for both DIEs
2818   decl_ctx_1 = die1.GetDeclContextDIEs();
2819   decl_ctx_2 = die2.GetDeclContextDIEs();
2820   // Make sure the context arrays have the same size, otherwise we are done
2821   const size_t count1 = decl_ctx_1.size();
2822   const size_t count2 = decl_ctx_2.size();
2823   if (count1 != count2)
2824     return false;
2825 
2826   // Make sure the DW_TAG values match all the way back up the compile unit. If
2827   // they don't, then we are done.
2828   DWARFDIE decl_ctx_die1;
2829   DWARFDIE decl_ctx_die2;
2830   size_t i;
2831   for (i = 0; i < count1; i++) {
2832     decl_ctx_die1 = decl_ctx_1[i];
2833     decl_ctx_die2 = decl_ctx_2[i];
2834     if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
2835       return false;
2836   }
2837 #ifndef NDEBUG
2838 
2839   // Make sure the top item in the decl context die array is always
2840   // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then
2841   // something went wrong in the DWARFDIE::GetDeclContextDIEs()
2842   // function.
2843   dw_tag_t cu_tag = decl_ctx_1[count1 - 1].Tag();
2844   UNUSED_IF_ASSERT_DISABLED(cu_tag);
2845   assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit);
2846 
2847 #endif
2848   // Always skip the compile unit when comparing by only iterating up to "count
2849   // - 1". Here we compare the names as we go.
2850   for (i = 0; i < count1 - 1; i++) {
2851     decl_ctx_die1 = decl_ctx_1[i];
2852     decl_ctx_die2 = decl_ctx_2[i];
2853     const char *name1 = decl_ctx_die1.GetName();
2854     const char *name2 = decl_ctx_die2.GetName();
2855     // If the string was from a DW_FORM_strp, then the pointer will often be
2856     // the same!
2857     if (name1 == name2)
2858       continue;
2859 
2860     // Name pointers are not equal, so only compare the strings if both are not
2861     // NULL.
2862     if (name1 && name2) {
2863       // If the strings don't compare, we are done...
2864       if (strcmp(name1, name2) != 0)
2865         return false;
2866     } else {
2867       // One name was NULL while the other wasn't
2868       return false;
2869     }
2870   }
2871   // We made it through all of the checks and the declaration contexts are
2872   // equal.
2873   return true;
2874 }
2875 
2876 TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(
2877     const DWARFDeclContext &dwarf_decl_ctx) {
2878   TypeSP type_sp;
2879 
2880   const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
2881   if (dwarf_decl_ctx_count > 0) {
2882     const ConstString type_name(dwarf_decl_ctx[0].name);
2883     const dw_tag_t tag = dwarf_decl_ctx[0].tag;
2884 
2885     if (type_name) {
2886       Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION |
2887                                             DWARF_LOG_LOOKUPS));
2888       if (log) {
2889         GetObjectFile()->GetModule()->LogMessage(
2890             log,
2891             "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%"
2892             "s, qualified-name='%s')",
2893             DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2894             dwarf_decl_ctx.GetQualifiedName());
2895       }
2896 
2897       DIEArray die_offsets;
2898       m_index->GetTypes(dwarf_decl_ctx, die_offsets);
2899       const size_t num_matches = die_offsets.size();
2900 
2901       // Get the type system that we are looking to find a type for. We will
2902       // use this to ensure any matches we find are in a language that this
2903       // type system supports
2904       const LanguageType language = dwarf_decl_ctx.GetLanguage();
2905       TypeSystem *type_system = nullptr;
2906       if (language != eLanguageTypeUnknown) {
2907         auto type_system_or_err = GetTypeSystemForLanguage(language);
2908         if (auto err = type_system_or_err.takeError()) {
2909           LLDB_LOG_ERROR(
2910               lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
2911               std::move(err), "Cannot get TypeSystem for language {}",
2912               Language::GetNameForLanguageType(language));
2913         } else {
2914           type_system = &type_system_or_err.get();
2915         }
2916       }
2917       if (num_matches) {
2918         for (size_t i = 0; i < num_matches; ++i) {
2919           const DIERef &die_ref = die_offsets[i];
2920           DWARFDIE type_die = GetDIE(die_ref);
2921 
2922           if (type_die) {
2923             // Make sure type_die's langauge matches the type system we are
2924             // looking for. We don't want to find a "Foo" type from Java if we
2925             // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
2926             if (type_system &&
2927                 !type_system->SupportsLanguage(type_die.GetLanguage()))
2928               continue;
2929             bool try_resolving_type = false;
2930 
2931             // Don't try and resolve the DIE we are looking for with the DIE
2932             // itself!
2933             const dw_tag_t type_tag = type_die.Tag();
2934             // Make sure the tags match
2935             if (type_tag == tag) {
2936               // The tags match, lets try resolving this type
2937               try_resolving_type = true;
2938             } else {
2939               // The tags don't match, but we need to watch our for a forward
2940               // declaration for a struct and ("struct foo") ends up being a
2941               // class ("class foo { ... };") or vice versa.
2942               switch (type_tag) {
2943               case DW_TAG_class_type:
2944                 // We had a "class foo", see if we ended up with a "struct foo
2945                 // { ... };"
2946                 try_resolving_type = (tag == DW_TAG_structure_type);
2947                 break;
2948               case DW_TAG_structure_type:
2949                 // We had a "struct foo", see if we ended up with a "class foo
2950                 // { ... };"
2951                 try_resolving_type = (tag == DW_TAG_class_type);
2952                 break;
2953               default:
2954                 // Tags don't match, don't event try to resolve using this type
2955                 // whose name matches....
2956                 break;
2957               }
2958             }
2959 
2960             if (try_resolving_type) {
2961               DWARFDeclContext type_dwarf_decl_ctx;
2962               type_die.GetDWARFDeclContext(type_dwarf_decl_ctx);
2963 
2964               if (log) {
2965                 GetObjectFile()->GetModule()->LogMessage(
2966                     log,
2967                     "SymbolFileDWARF::"
2968                     "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2969                     "qualified-name='%s') trying die=0x%8.8x (%s)",
2970                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2971                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2972                     type_dwarf_decl_ctx.GetQualifiedName());
2973               }
2974 
2975               // Make sure the decl contexts match all the way up
2976               if (dwarf_decl_ctx == type_dwarf_decl_ctx) {
2977                 Type *resolved_type = ResolveType(type_die, false);
2978                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2979                   type_sp = resolved_type->shared_from_this();
2980                   break;
2981                 }
2982               }
2983             } else {
2984               if (log) {
2985                 std::string qualified_name;
2986                 type_die.GetQualifiedName(qualified_name);
2987                 GetObjectFile()->GetModule()->LogMessage(
2988                     log,
2989                     "SymbolFileDWARF::"
2990                     "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2991                     "qualified-name='%s') ignoring die=0x%8.8x (%s)",
2992                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2993                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2994                     qualified_name.c_str());
2995               }
2996             }
2997           } else {
2998             m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
2999           }
3000         }
3001       }
3002     }
3003   }
3004   return type_sp;
3005 }
3006 
3007 TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die,
3008                                   bool *type_is_new_ptr) {
3009   if (!die)
3010     return {};
3011 
3012   auto type_system_or_err =
3013       GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
3014   if (auto err = type_system_or_err.takeError()) {
3015     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
3016                    std::move(err), "Unable to parse type");
3017     return {};
3018   }
3019 
3020   DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser();
3021   if (!dwarf_ast)
3022     return {};
3023 
3024   Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
3025   TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, log, type_is_new_ptr);
3026   if (type_sp) {
3027     GetTypeList().Insert(type_sp);
3028 
3029     if (die.Tag() == DW_TAG_subprogram) {
3030       std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
3031                                            .GetScopeQualifiedName()
3032                                            .AsCString(""));
3033       if (scope_qualified_name.size()) {
3034         m_function_scope_qualified_name_map[scope_qualified_name].insert(
3035             die.GetID());
3036       }
3037     }
3038   }
3039 
3040   return type_sp;
3041 }
3042 
3043 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc,
3044                                    const DWARFDIE &orig_die,
3045                                    bool parse_siblings, bool parse_children) {
3046   size_t types_added = 0;
3047   DWARFDIE die = orig_die;
3048   while (die) {
3049     bool type_is_new = false;
3050     if (ParseType(sc, die, &type_is_new).get()) {
3051       if (type_is_new)
3052         ++types_added;
3053     }
3054 
3055     if (parse_children && die.HasChildren()) {
3056       if (die.Tag() == DW_TAG_subprogram) {
3057         SymbolContext child_sc(sc);
3058         child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3059         types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3060       } else
3061         types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3062     }
3063 
3064     if (parse_siblings)
3065       die = die.GetSibling();
3066     else
3067       die.Clear();
3068   }
3069   return types_added;
3070 }
3071 
3072 size_t SymbolFileDWARF::ParseBlocksRecursive(Function &func) {
3073   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3074   CompileUnit *comp_unit = func.GetCompileUnit();
3075   lldbassert(comp_unit);
3076 
3077   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit);
3078   if (!dwarf_cu)
3079     return 0;
3080 
3081   size_t functions_added = 0;
3082   const dw_offset_t function_die_offset = func.GetID();
3083   DWARFDIE function_die = dwarf_cu->GetDIE(function_die_offset);
3084   if (function_die) {
3085     ParseBlocksRecursive(*comp_unit, &func.GetBlock(false), function_die,
3086                          LLDB_INVALID_ADDRESS, 0);
3087   }
3088 
3089   return functions_added;
3090 }
3091 
3092 size_t SymbolFileDWARF::ParseTypes(CompileUnit &comp_unit) {
3093   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3094   size_t types_added = 0;
3095   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
3096   if (dwarf_cu) {
3097     DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3098     if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3099       SymbolContext sc;
3100       sc.comp_unit = &comp_unit;
3101       types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3102     }
3103   }
3104 
3105   return types_added;
3106 }
3107 
3108 size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) {
3109   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3110   if (sc.comp_unit != nullptr) {
3111     DWARFDebugInfo *info = DebugInfo();
3112     if (info == nullptr)
3113       return 0;
3114 
3115     if (sc.function) {
3116       DWARFDIE function_die = GetDIE(sc.function->GetID());
3117 
3118       const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress(
3119           DW_AT_low_pc, LLDB_INVALID_ADDRESS);
3120       if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3121         const size_t num_variables = ParseVariables(
3122             sc, function_die.GetFirstChild(), func_lo_pc, true, true);
3123 
3124         // Let all blocks know they have parse all their variables
3125         sc.function->GetBlock(false).SetDidParseVariables(true, true);
3126         return num_variables;
3127       }
3128     } else if (sc.comp_unit) {
3129       DWARFUnit *dwarf_cu = info->GetUnitAtIndex(sc.comp_unit->GetID());
3130 
3131       if (dwarf_cu == nullptr)
3132         return 0;
3133 
3134       uint32_t vars_added = 0;
3135       VariableListSP variables(sc.comp_unit->GetVariableList(false));
3136 
3137       if (variables.get() == nullptr) {
3138         variables = std::make_shared<VariableList>();
3139         sc.comp_unit->SetVariableList(variables);
3140 
3141         DIEArray die_offsets;
3142         m_index->GetGlobalVariables(dwarf_cu->GetNonSkeletonUnit(),
3143                                     die_offsets);
3144         const size_t num_matches = die_offsets.size();
3145         if (num_matches) {
3146           for (size_t i = 0; i < num_matches; ++i) {
3147             const DIERef &die_ref = die_offsets[i];
3148             DWARFDIE die = GetDIE(die_ref);
3149             if (die) {
3150               VariableSP var_sp(
3151                   ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS));
3152               if (var_sp) {
3153                 variables->AddVariableIfUnique(var_sp);
3154                 ++vars_added;
3155               }
3156             } else
3157               m_index->ReportInvalidDIERef(die_ref, "");
3158           }
3159         }
3160       }
3161       return vars_added;
3162     }
3163   }
3164   return 0;
3165 }
3166 
3167 VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc,
3168                                              const DWARFDIE &die,
3169                                              const lldb::addr_t func_low_pc) {
3170   if (die.GetDWARF() != this)
3171     return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3172 
3173   VariableSP var_sp;
3174   if (!die)
3175     return var_sp;
3176 
3177   var_sp = GetDIEToVariable()[die.GetDIE()];
3178   if (var_sp)
3179     return var_sp; // Already been parsed!
3180 
3181   const dw_tag_t tag = die.Tag();
3182   ModuleSP module = GetObjectFile()->GetModule();
3183 
3184   if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3185       (tag == DW_TAG_formal_parameter && sc.function)) {
3186     DWARFAttributes attributes;
3187     const size_t num_attributes = die.GetAttributes(attributes);
3188     DWARFDIE spec_die;
3189     if (num_attributes > 0) {
3190       const char *name = nullptr;
3191       const char *mangled = nullptr;
3192       Declaration decl;
3193       uint32_t i;
3194       DWARFFormValue type_die_form;
3195       DWARFExpression location;
3196       bool is_external = false;
3197       bool is_artificial = false;
3198       bool location_is_const_value_data = false;
3199       bool has_explicit_location = false;
3200       DWARFFormValue const_value;
3201       Variable::RangeList scope_ranges;
3202       // AccessType accessibility = eAccessNone;
3203 
3204       for (i = 0; i < num_attributes; ++i) {
3205         dw_attr_t attr = attributes.AttributeAtIndex(i);
3206         DWARFFormValue form_value;
3207 
3208         if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3209           switch (attr) {
3210           case DW_AT_decl_file:
3211             decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3212                 form_value.Unsigned()));
3213             break;
3214           case DW_AT_decl_line:
3215             decl.SetLine(form_value.Unsigned());
3216             break;
3217           case DW_AT_decl_column:
3218             decl.SetColumn(form_value.Unsigned());
3219             break;
3220           case DW_AT_name:
3221             name = form_value.AsCString();
3222             break;
3223           case DW_AT_linkage_name:
3224           case DW_AT_MIPS_linkage_name:
3225             mangled = form_value.AsCString();
3226             break;
3227           case DW_AT_type:
3228             type_die_form = form_value;
3229             break;
3230           case DW_AT_external:
3231             is_external = form_value.Boolean();
3232             break;
3233           case DW_AT_const_value:
3234             // If we have already found a DW_AT_location attribute, ignore this
3235             // attribute.
3236             if (!has_explicit_location) {
3237               location_is_const_value_data = true;
3238               // The constant value will be either a block, a data value or a
3239               // string.
3240               auto debug_info_data = die.GetData();
3241               if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3242                 // Retrieve the value as a block expression.
3243                 uint32_t block_offset =
3244                     form_value.BlockData() - debug_info_data.GetDataStart();
3245                 uint32_t block_length = form_value.Unsigned();
3246                 location = DWARFExpression(
3247                     module,
3248                     DataExtractor(debug_info_data, block_offset, block_length),
3249                     die.GetCU());
3250               } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3251                 // Retrieve the value as a data expression.
3252                 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3253                 if (auto data_length = form_value.GetFixedSize())
3254                   location = DWARFExpression(
3255                       module,
3256                       DataExtractor(debug_info_data, data_offset, *data_length),
3257                       die.GetCU());
3258                 else {
3259                   const uint8_t *data_pointer = form_value.BlockData();
3260                   if (data_pointer) {
3261                     form_value.Unsigned();
3262                   } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3263                     // we need to get the byte size of the type later after we
3264                     // create the variable
3265                     const_value = form_value;
3266                   }
3267                 }
3268               } else {
3269                 // Retrieve the value as a string expression.
3270                 if (form_value.Form() == DW_FORM_strp) {
3271                   uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3272                   if (auto data_length = form_value.GetFixedSize())
3273                     location = DWARFExpression(module,
3274                                                DataExtractor(debug_info_data,
3275                                                              data_offset,
3276                                                              *data_length),
3277                                                die.GetCU());
3278                 } else {
3279                   const char *str = form_value.AsCString();
3280                   uint32_t string_offset =
3281                       str - (const char *)debug_info_data.GetDataStart();
3282                   uint32_t string_length = strlen(str) + 1;
3283                   location = DWARFExpression(module,
3284                                              DataExtractor(debug_info_data,
3285                                                            string_offset,
3286                                                            string_length),
3287                                              die.GetCU());
3288                 }
3289               }
3290             }
3291             break;
3292           case DW_AT_location: {
3293             location_is_const_value_data = false;
3294             has_explicit_location = true;
3295             if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3296               auto data = die.GetData();
3297 
3298               uint32_t block_offset =
3299                   form_value.BlockData() - data.GetDataStart();
3300               uint32_t block_length = form_value.Unsigned();
3301               location = DWARFExpression(
3302                   module, DataExtractor(data, block_offset, block_length),
3303                   die.GetCU());
3304             } else {
3305               DataExtractor data = DebugLocData();
3306               const dw_offset_t offset = form_value.Unsigned();
3307               if (data.ValidOffset(offset)) {
3308                 data = DataExtractor(data, offset, data.GetByteSize() - offset);
3309                 location = DWARFExpression(module, data, die.GetCU());
3310                 assert(func_low_pc != LLDB_INVALID_ADDRESS);
3311                 location.SetLocationListSlide(
3312                     func_low_pc -
3313                     attributes.CompileUnitAtIndex(i)->GetBaseAddress());
3314               }
3315             }
3316           } break;
3317           case DW_AT_specification:
3318             spec_die = form_value.Reference();
3319             break;
3320           case DW_AT_start_scope:
3321             // TODO: Implement this.
3322             break;
3323           case DW_AT_artificial:
3324             is_artificial = form_value.Boolean();
3325             break;
3326           case DW_AT_accessibility:
3327             break; // accessibility =
3328                    // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
3329           case DW_AT_declaration:
3330           case DW_AT_description:
3331           case DW_AT_endianity:
3332           case DW_AT_segment:
3333           case DW_AT_visibility:
3334           default:
3335           case DW_AT_abstract_origin:
3336           case DW_AT_sibling:
3337             break;
3338           }
3339         }
3340       }
3341 
3342       const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3343       const dw_tag_t parent_tag = die.GetParent().Tag();
3344       bool is_static_member =
3345           (parent_tag == DW_TAG_compile_unit ||
3346            parent_tag == DW_TAG_partial_unit) &&
3347           (parent_context_die.Tag() == DW_TAG_class_type ||
3348            parent_context_die.Tag() == DW_TAG_structure_type);
3349 
3350       ValueType scope = eValueTypeInvalid;
3351 
3352       const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3353       SymbolContextScope *symbol_context_scope = nullptr;
3354 
3355       bool has_explicit_mangled = mangled != nullptr;
3356       if (!mangled) {
3357         // LLDB relies on the mangled name (DW_TAG_linkage_name or
3358         // DW_AT_MIPS_linkage_name) to generate fully qualified names
3359         // of global variables with commands like "frame var j". For
3360         // example, if j were an int variable holding a value 4 and
3361         // declared in a namespace B which in turn is contained in a
3362         // namespace A, the command "frame var j" returns
3363         //   "(int) A::B::j = 4".
3364         // If the compiler does not emit a linkage name, we should be
3365         // able to generate a fully qualified name from the
3366         // declaration context.
3367         if ((parent_tag == DW_TAG_compile_unit ||
3368              parent_tag == DW_TAG_partial_unit) &&
3369             Language::LanguageIsCPlusPlus(die.GetLanguage())) {
3370           DWARFDeclContext decl_ctx;
3371 
3372           die.GetDWARFDeclContext(decl_ctx);
3373           mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString();
3374         }
3375       }
3376 
3377       if (tag == DW_TAG_formal_parameter)
3378         scope = eValueTypeVariableArgument;
3379       else {
3380         // DWARF doesn't specify if a DW_TAG_variable is a local, global
3381         // or static variable, so we have to do a little digging:
3382         // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3383         // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3384         // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3385         // Clang likes to combine small global variables into the same symbol
3386         // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3387         // so we need to look through the whole expression.
3388         bool is_static_lifetime =
3389             has_explicit_mangled ||
3390             (has_explicit_location && !location.IsValid());
3391         // Check if the location has a DW_OP_addr with any address value...
3392         lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3393         if (!location_is_const_value_data) {
3394           bool op_error = false;
3395           location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error);
3396           if (op_error) {
3397             StreamString strm;
3398             location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0,
3399                                             nullptr);
3400             GetObjectFile()->GetModule()->ReportError(
3401                 "0x%8.8x: %s has an invalid location: %s", die.GetOffset(),
3402                 die.GetTagAsCString(), strm.GetData());
3403           }
3404           if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
3405             is_static_lifetime = true;
3406         }
3407         SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
3408         if (debug_map_symfile)
3409           // Set the module of the expression to the linked module
3410           // instead of the oject file so the relocated address can be
3411           // found there.
3412           location.SetModule(debug_map_symfile->GetObjectFile()->GetModule());
3413 
3414         if (is_static_lifetime) {
3415           if (is_external)
3416             scope = eValueTypeVariableGlobal;
3417           else
3418             scope = eValueTypeVariableStatic;
3419 
3420           if (debug_map_symfile) {
3421             // When leaving the DWARF in the .o files on darwin, when we have a
3422             // global variable that wasn't initialized, the .o file might not
3423             // have allocated a virtual address for the global variable. In
3424             // this case it will have created a symbol for the global variable
3425             // that is undefined/data and external and the value will be the
3426             // byte size of the variable. When we do the address map in
3427             // SymbolFileDWARFDebugMap we rely on having an address, we need to
3428             // do some magic here so we can get the correct address for our
3429             // global variable. The address for all of these entries will be
3430             // zero, and there will be an undefined symbol in this object file,
3431             // and the executable will have a matching symbol with a good
3432             // address. So here we dig up the correct address and replace it in
3433             // the location for the variable, and set the variable's symbol
3434             // context scope to be that of the main executable so the file
3435             // address will resolve correctly.
3436             bool linked_oso_file_addr = false;
3437             if (is_external && location_DW_OP_addr == 0) {
3438               // we have a possible uninitialized extern global
3439               ConstString const_name(mangled ? mangled : name);
3440               ObjectFile *debug_map_objfile =
3441                   debug_map_symfile->GetObjectFile();
3442               if (debug_map_objfile) {
3443                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3444                 if (debug_map_symtab) {
3445                   Symbol *exe_symbol =
3446                       debug_map_symtab->FindFirstSymbolWithNameAndType(
3447                           const_name, eSymbolTypeData, Symtab::eDebugYes,
3448                           Symtab::eVisibilityExtern);
3449                   if (exe_symbol) {
3450                     if (exe_symbol->ValueIsAddress()) {
3451                       const addr_t exe_file_addr =
3452                           exe_symbol->GetAddressRef().GetFileAddress();
3453                       if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3454                         if (location.Update_DW_OP_addr(exe_file_addr)) {
3455                           linked_oso_file_addr = true;
3456                           symbol_context_scope = exe_symbol;
3457                         }
3458                       }
3459                     }
3460                   }
3461                 }
3462               }
3463             }
3464 
3465             if (!linked_oso_file_addr) {
3466               // The DW_OP_addr is not zero, but it contains a .o file address
3467               // which needs to be linked up correctly.
3468               const lldb::addr_t exe_file_addr =
3469                   debug_map_symfile->LinkOSOFileAddress(this,
3470                                                         location_DW_OP_addr);
3471               if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3472                 // Update the file address for this variable
3473                 location.Update_DW_OP_addr(exe_file_addr);
3474               } else {
3475                 // Variable didn't make it into the final executable
3476                 return var_sp;
3477               }
3478             }
3479           }
3480         } else {
3481           if (location_is_const_value_data)
3482             scope = eValueTypeVariableStatic;
3483           else {
3484             scope = eValueTypeVariableLocal;
3485             if (debug_map_symfile) {
3486               // We need to check for TLS addresses that we need to fixup
3487               if (location.ContainsThreadLocalStorage()) {
3488                 location.LinkThreadLocalStorage(
3489                     debug_map_symfile->GetObjectFile()->GetModule(),
3490                     [this, debug_map_symfile](
3491                         lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
3492                       return debug_map_symfile->LinkOSOFileAddress(
3493                           this, unlinked_file_addr);
3494                     });
3495                 scope = eValueTypeVariableThreadLocal;
3496               }
3497             }
3498           }
3499         }
3500       }
3501 
3502       if (symbol_context_scope == nullptr) {
3503         switch (parent_tag) {
3504         case DW_TAG_subprogram:
3505         case DW_TAG_inlined_subroutine:
3506         case DW_TAG_lexical_block:
3507           if (sc.function) {
3508             symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(
3509                 sc_parent_die.GetID());
3510             if (symbol_context_scope == nullptr)
3511               symbol_context_scope = sc.function;
3512           }
3513           break;
3514 
3515         default:
3516           symbol_context_scope = sc.comp_unit;
3517           break;
3518         }
3519       }
3520 
3521       if (symbol_context_scope) {
3522         SymbolFileTypeSP type_sp(
3523             new SymbolFileType(*this, GetUID(type_die_form.Reference())));
3524 
3525         if (const_value.Form() && type_sp && type_sp->GetType())
3526           location.UpdateValue(const_value.Unsigned(),
3527                                type_sp->GetType()->GetByteSize().getValueOr(0),
3528                                die.GetCU()->GetAddressByteSize());
3529 
3530         var_sp = std::make_shared<Variable>(
3531             die.GetID(), name, mangled, type_sp, scope, symbol_context_scope,
3532             scope_ranges, &decl, location, is_external, is_artificial,
3533             is_static_member);
3534 
3535         var_sp->SetLocationIsConstantValueData(location_is_const_value_data);
3536       } else {
3537         // Not ready to parse this variable yet. It might be a global or static
3538         // variable that is in a function scope and the function in the symbol
3539         // context wasn't filled in yet
3540         return var_sp;
3541       }
3542     }
3543     // Cache var_sp even if NULL (the variable was just a specification or was
3544     // missing vital information to be able to be displayed in the debugger
3545     // (missing location due to optimization, etc)) so we don't re-parse this
3546     // DIE over and over later...
3547     GetDIEToVariable()[die.GetDIE()] = var_sp;
3548     if (spec_die)
3549       GetDIEToVariable()[spec_die.GetDIE()] = var_sp;
3550   }
3551   return var_sp;
3552 }
3553 
3554 DWARFDIE
3555 SymbolFileDWARF::FindBlockContainingSpecification(
3556     const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
3557   // Give the concrete function die specified by "func_die_offset", find the
3558   // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3559   // to "spec_block_die_offset"
3560   return FindBlockContainingSpecification(DebugInfo()->GetDIE(func_die_ref),
3561                                           spec_block_die_offset);
3562 }
3563 
3564 DWARFDIE
3565 SymbolFileDWARF::FindBlockContainingSpecification(
3566     const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
3567   if (die) {
3568     switch (die.Tag()) {
3569     case DW_TAG_subprogram:
3570     case DW_TAG_inlined_subroutine:
3571     case DW_TAG_lexical_block: {
3572       if (die.GetReferencedDIE(DW_AT_specification).GetOffset() ==
3573           spec_block_die_offset)
3574         return die;
3575 
3576       if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() ==
3577           spec_block_die_offset)
3578         return die;
3579     } break;
3580     }
3581 
3582     // Give the concrete function die specified by "func_die_offset", find the
3583     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3584     // to "spec_block_die_offset"
3585     for (DWARFDIE child_die = die.GetFirstChild(); child_die;
3586          child_die = child_die.GetSibling()) {
3587       DWARFDIE result_die =
3588           FindBlockContainingSpecification(child_die, spec_block_die_offset);
3589       if (result_die)
3590         return result_die;
3591     }
3592   }
3593 
3594   return DWARFDIE();
3595 }
3596 
3597 size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc,
3598                                        const DWARFDIE &orig_die,
3599                                        const lldb::addr_t func_low_pc,
3600                                        bool parse_siblings, bool parse_children,
3601                                        VariableList *cc_variable_list) {
3602   if (!orig_die)
3603     return 0;
3604 
3605   VariableListSP variable_list_sp;
3606 
3607   size_t vars_added = 0;
3608   DWARFDIE die = orig_die;
3609   while (die) {
3610     dw_tag_t tag = die.Tag();
3611 
3612     // Check to see if we have already parsed this variable or constant?
3613     VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
3614     if (var_sp) {
3615       if (cc_variable_list)
3616         cc_variable_list->AddVariableIfUnique(var_sp);
3617     } else {
3618       // We haven't already parsed it, lets do that now.
3619       if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3620           (tag == DW_TAG_formal_parameter && sc.function)) {
3621         if (variable_list_sp.get() == nullptr) {
3622           DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die);
3623           dw_tag_t parent_tag = sc_parent_die.Tag();
3624           switch (parent_tag) {
3625           case DW_TAG_compile_unit:
3626           case DW_TAG_partial_unit:
3627             if (sc.comp_unit != nullptr) {
3628               variable_list_sp = sc.comp_unit->GetVariableList(false);
3629               if (variable_list_sp.get() == nullptr) {
3630                 variable_list_sp = std::make_shared<VariableList>();
3631               }
3632             } else {
3633               GetObjectFile()->GetModule()->ReportError(
3634                   "parent 0x%8.8" PRIx64 " %s with no valid compile unit in "
3635                   "symbol context for 0x%8.8" PRIx64 " %s.\n",
3636                   sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(),
3637                   orig_die.GetID(), orig_die.GetTagAsCString());
3638             }
3639             break;
3640 
3641           case DW_TAG_subprogram:
3642           case DW_TAG_inlined_subroutine:
3643           case DW_TAG_lexical_block:
3644             if (sc.function != nullptr) {
3645               // Check to see if we already have parsed the variables for the
3646               // given scope
3647 
3648               Block *block = sc.function->GetBlock(true).FindBlockByID(
3649                   sc_parent_die.GetID());
3650               if (block == nullptr) {
3651                 // This must be a specification or abstract origin with a
3652                 // concrete block counterpart in the current function. We need
3653                 // to find the concrete block so we can correctly add the
3654                 // variable to it
3655                 const DWARFDIE concrete_block_die =
3656                     FindBlockContainingSpecification(
3657                         GetDIE(sc.function->GetID()),
3658                         sc_parent_die.GetOffset());
3659                 if (concrete_block_die)
3660                   block = sc.function->GetBlock(true).FindBlockByID(
3661                       concrete_block_die.GetID());
3662               }
3663 
3664               if (block != nullptr) {
3665                 const bool can_create = false;
3666                 variable_list_sp = block->GetBlockVariableList(can_create);
3667                 if (variable_list_sp.get() == nullptr) {
3668                   variable_list_sp = std::make_shared<VariableList>();
3669                   block->SetVariableList(variable_list_sp);
3670                 }
3671               }
3672             }
3673             break;
3674 
3675           default:
3676             GetObjectFile()->GetModule()->ReportError(
3677                 "didn't find appropriate parent DIE for variable list for "
3678                 "0x%8.8" PRIx64 " %s.\n",
3679                 orig_die.GetID(), orig_die.GetTagAsCString());
3680             break;
3681           }
3682         }
3683 
3684         if (variable_list_sp) {
3685           VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc));
3686           if (var_sp) {
3687             variable_list_sp->AddVariableIfUnique(var_sp);
3688             if (cc_variable_list)
3689               cc_variable_list->AddVariableIfUnique(var_sp);
3690             ++vars_added;
3691           }
3692         }
3693       }
3694     }
3695 
3696     bool skip_children = (sc.function == nullptr && tag == DW_TAG_subprogram);
3697 
3698     if (!skip_children && parse_children && die.HasChildren()) {
3699       vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true,
3700                                    true, cc_variable_list);
3701     }
3702 
3703     if (parse_siblings)
3704       die = die.GetSibling();
3705     else
3706       die.Clear();
3707   }
3708   return vars_added;
3709 }
3710 
3711 /// Collect call graph edges present in a function DIE.
3712 static std::vector<lldb_private::CallEdge>
3713 CollectCallEdges(DWARFDIE function_die) {
3714   // Check if the function has a supported call site-related attribute.
3715   // TODO: In the future it may be worthwhile to support call_all_source_calls.
3716   uint64_t has_call_edges =
3717       function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0);
3718   if (!has_call_edges)
3719     return {};
3720 
3721   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3722   LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}",
3723            function_die.GetPubname());
3724 
3725   // Scan the DIE for TAG_call_site entries.
3726   // TODO: A recursive scan of all blocks in the subprogram is needed in order
3727   // to be DWARF5-compliant. This may need to be done lazily to be performant.
3728   // For now, assume that all entries are nested directly under the subprogram
3729   // (this is the kind of DWARF LLVM produces) and parse them eagerly.
3730   std::vector<CallEdge> call_edges;
3731   for (DWARFDIE child = function_die.GetFirstChild(); child.IsValid();
3732        child = child.GetSibling()) {
3733     if (child.Tag() != DW_TAG_call_site)
3734       continue;
3735 
3736     // Extract DW_AT_call_origin (the call target's DIE).
3737     DWARFDIE call_origin = child.GetReferencedDIE(DW_AT_call_origin);
3738     if (!call_origin.IsValid()) {
3739       LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}",
3740                function_die.GetPubname());
3741       continue;
3742     }
3743 
3744     // Extract DW_AT_call_return_pc (the PC the call returns to) if it's
3745     // available. It should only ever be unavailable for tail call edges, in
3746     // which case use LLDB_INVALID_ADDRESS.
3747     addr_t return_pc = child.GetAttributeValueAsAddress(DW_AT_call_return_pc,
3748                                                         LLDB_INVALID_ADDRESS);
3749 
3750     LLDB_LOG(log, "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x})",
3751              call_origin.GetPubname(), return_pc);
3752     call_edges.emplace_back(call_origin.GetMangledName(), return_pc);
3753   }
3754   return call_edges;
3755 }
3756 
3757 std::vector<lldb_private::CallEdge>
3758 SymbolFileDWARF::ParseCallEdgesInFunction(UserID func_id) {
3759   DWARFDIE func_die = GetDIE(func_id.GetID());
3760   if (func_die.IsValid())
3761     return CollectCallEdges(func_die);
3762   return {};
3763 }
3764 
3765 // PluginInterface protocol
3766 ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); }
3767 
3768 uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; }
3769 
3770 void SymbolFileDWARF::Dump(lldb_private::Stream &s) {
3771   SymbolFile::Dump(s);
3772   m_index->Dump(s);
3773 }
3774 
3775 void SymbolFileDWARF::DumpClangAST(Stream &s) {
3776   auto ts_or_err = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
3777   if (!ts_or_err)
3778     return;
3779   ClangASTContext *clang =
3780       llvm::dyn_cast_or_null<ClangASTContext>(&ts_or_err.get());
3781   if (!clang)
3782     return;
3783   clang->Dump(s);
3784 }
3785 
3786 SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() {
3787   if (m_debug_map_symfile == nullptr && !m_debug_map_module_wp.expired()) {
3788     lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
3789     if (module_sp) {
3790       m_debug_map_symfile =
3791           (SymbolFileDWARFDebugMap *)module_sp->GetSymbolFile();
3792     }
3793   }
3794   return m_debug_map_symfile;
3795 }
3796 
3797 DWARFExpression::LocationListFormat
3798 SymbolFileDWARF::GetLocationListFormat() const {
3799   if (m_data_debug_loclists.m_data.GetByteSize() > 0)
3800     return DWARFExpression::LocLists;
3801   return DWARFExpression::RegularLocationList;
3802 }
3803 
3804 SymbolFileDWARFDwp *SymbolFileDWARF::GetDwpSymbolFile() {
3805   llvm::call_once(m_dwp_symfile_once_flag, [this]() {
3806     ModuleSpec module_spec;
3807     module_spec.GetFileSpec() = m_objfile_sp->GetFileSpec();
3808     module_spec.GetSymbolFileSpec() =
3809         FileSpec(m_objfile_sp->GetFileSpec().GetPath() + ".dwp");
3810 
3811     FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths();
3812     FileSpec dwp_filespec =
3813         Symbols::LocateExecutableSymbolFile(module_spec, search_paths);
3814     if (FileSystem::Instance().Exists(dwp_filespec)) {
3815       m_dwp_symfile = SymbolFileDWARFDwp::Create(GetObjectFile()->GetModule(),
3816                                                  dwp_filespec);
3817     }
3818   });
3819   return m_dwp_symfile.get();
3820 }
3821