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