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