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