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