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