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