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