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