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