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