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