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