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