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