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