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