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