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