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