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