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