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