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