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