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