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     bool append, uint32_t max_matches, VariableList &variables) {
1972   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
1973 
1974   if (log)
1975     GetObjectFile()->GetModule()->LogMessage(
1976         log, "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
1977              "parent_decl_ctx=%p, append=%u, max_matches=%u, variables)",
1978         name.GetCString(), static_cast<const void *>(parent_decl_ctx), append,
1979         max_matches);
1980 
1981   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1982     return 0;
1983 
1984   DWARFDebugInfo *info = DebugInfo();
1985   if (info == NULL)
1986     return 0;
1987 
1988   // If we aren't appending the results to this list, then clear the list
1989   if (!append)
1990     variables.Clear();
1991 
1992   // Remember how many variables are in the list before we search in case we
1993   // are appending the results to a variable list.
1994   const uint32_t original_size = variables.GetSize();
1995 
1996   DIEArray die_offsets;
1997   m_index->GetGlobalVariables(name, die_offsets);
1998   const size_t num_die_matches = die_offsets.size();
1999   if (num_die_matches) {
2000     SymbolContext sc;
2001     sc.module_sp = m_obj_file->GetModule();
2002     assert(sc.module_sp);
2003 
2004     bool done = false;
2005     for (size_t i = 0; i < num_die_matches && !done; ++i) {
2006       const DIERef &die_ref = die_offsets[i];
2007       DWARFDIE die = GetDIE(die_ref);
2008 
2009       if (die) {
2010         switch (die.Tag()) {
2011         default:
2012         case DW_TAG_subprogram:
2013         case DW_TAG_inlined_subroutine:
2014         case DW_TAG_try_block:
2015         case DW_TAG_catch_block:
2016           break;
2017 
2018         case DW_TAG_variable: {
2019           sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
2020 
2021           if (parent_decl_ctx) {
2022             DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2023             if (dwarf_ast) {
2024               CompilerDeclContext actual_parent_decl_ctx =
2025                   dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2026               if (!actual_parent_decl_ctx ||
2027                   actual_parent_decl_ctx != *parent_decl_ctx)
2028                 continue;
2029             }
2030           }
2031 
2032           ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false,
2033                          &variables);
2034 
2035           if (variables.GetSize() - original_size >= max_matches)
2036             done = true;
2037         } break;
2038         }
2039       } else {
2040         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2041                                         name.GetStringRef());
2042       }
2043     }
2044   }
2045 
2046   // Return the number of variable that were appended to the list
2047   const uint32_t num_matches = variables.GetSize() - original_size;
2048   if (log && num_matches > 0) {
2049     GetObjectFile()->GetModule()->LogMessage(
2050         log, "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2051              "parent_decl_ctx=%p, append=%u, max_matches=%u, variables) => %u",
2052         name.GetCString(), static_cast<const void *>(parent_decl_ctx), append,
2053         max_matches, num_matches);
2054   }
2055   return num_matches;
2056 }
2057 
2058 uint32_t SymbolFileDWARF::FindGlobalVariables(const RegularExpression &regex,
2059                                               bool append, uint32_t max_matches,
2060                                               VariableList &variables) {
2061   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2062 
2063   if (log) {
2064     GetObjectFile()->GetModule()->LogMessage(
2065         log, "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", append=%u, "
2066              "max_matches=%u, variables)",
2067         regex.GetText().str().c_str(), append, max_matches);
2068   }
2069 
2070   DWARFDebugInfo *info = DebugInfo();
2071   if (info == NULL)
2072     return 0;
2073 
2074   // If we aren't appending the results to this list, then clear the list
2075   if (!append)
2076     variables.Clear();
2077 
2078   // Remember how many variables are in the list before we search in case we
2079   // are appending the results to a variable list.
2080   const uint32_t original_size = variables.GetSize();
2081 
2082   DIEArray die_offsets;
2083   m_index->GetGlobalVariables(regex, die_offsets);
2084 
2085   SymbolContext sc;
2086   sc.module_sp = m_obj_file->GetModule();
2087   assert(sc.module_sp);
2088 
2089   const size_t num_matches = die_offsets.size();
2090   if (num_matches) {
2091     for (size_t i = 0; i < num_matches; ++i) {
2092       const DIERef &die_ref = die_offsets[i];
2093       DWARFDIE die = GetDIE(die_ref);
2094 
2095       if (die) {
2096         sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
2097 
2098         ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2099 
2100         if (variables.GetSize() - original_size >= max_matches)
2101           break;
2102       } else
2103         m_index->ReportInvalidDIEOffset(die_ref.die_offset, regex.GetText());
2104     }
2105   }
2106 
2107   // Return the number of variable that were appended to the list
2108   return variables.GetSize() - original_size;
2109 }
2110 
2111 bool SymbolFileDWARF::ResolveFunction(const DIERef &die_ref,
2112                                       bool include_inlines,
2113                                       SymbolContextList &sc_list) {
2114   DWARFDIE die = DebugInfo()->GetDIE(die_ref);
2115   return ResolveFunction(die, include_inlines, sc_list);
2116 }
2117 
2118 bool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die,
2119                                       bool include_inlines,
2120                                       SymbolContextList &sc_list) {
2121   SymbolContext sc;
2122 
2123   if (!orig_die)
2124     return false;
2125 
2126   // If we were passed a die that is not a function, just return false...
2127   if (!(orig_die.Tag() == DW_TAG_subprogram ||
2128         (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2129     return false;
2130 
2131   DWARFDIE die = orig_die;
2132   DWARFDIE inlined_die;
2133   if (die.Tag() == DW_TAG_inlined_subroutine) {
2134     inlined_die = die;
2135 
2136     while (1) {
2137       die = die.GetParent();
2138 
2139       if (die) {
2140         if (die.Tag() == DW_TAG_subprogram)
2141           break;
2142       } else
2143         break;
2144     }
2145   }
2146   assert(die && die.Tag() == DW_TAG_subprogram);
2147   if (GetFunction(die, sc)) {
2148     Address addr;
2149     // Parse all blocks if needed
2150     if (inlined_die) {
2151       Block &function_block = sc.function->GetBlock(true);
2152       sc.block = function_block.FindBlockByID(inlined_die.GetID());
2153       if (sc.block == NULL)
2154         sc.block = function_block.FindBlockByID(inlined_die.GetOffset());
2155       if (sc.block == NULL || sc.block->GetStartAddress(addr) == false)
2156         addr.Clear();
2157     } else {
2158       sc.block = NULL;
2159       addr = sc.function->GetAddressRange().GetBaseAddress();
2160     }
2161 
2162     if (addr.IsValid()) {
2163       sc_list.Append(sc);
2164       return true;
2165     }
2166   }
2167 
2168   return false;
2169 }
2170 
2171 bool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext *decl_ctx,
2172                                        const DWARFDIE &die) {
2173   // If we have no parent decl context to match this DIE matches, and if the
2174   // parent decl context isn't valid, we aren't trying to look for any
2175   // particular decl context so any die matches.
2176   if (decl_ctx == nullptr || !decl_ctx->IsValid())
2177     return true;
2178 
2179   if (die) {
2180     DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2181     if (dwarf_ast) {
2182       CompilerDeclContext actual_decl_ctx =
2183           dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2184       if (actual_decl_ctx)
2185         return actual_decl_ctx == *decl_ctx;
2186     }
2187   }
2188   return false;
2189 }
2190 
2191 uint32_t
2192 SymbolFileDWARF::FindFunctions(const ConstString &name,
2193                                const CompilerDeclContext *parent_decl_ctx,
2194                                uint32_t name_type_mask, bool include_inlines,
2195                                bool append, SymbolContextList &sc_list) {
2196   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2197   Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (name = '%s')",
2198                      name.AsCString());
2199 
2200   // eFunctionNameTypeAuto should be pre-resolved by a call to
2201   // Module::LookupInfo::LookupInfo()
2202   assert((name_type_mask & eFunctionNameTypeAuto) == 0);
2203 
2204   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2205 
2206   if (log) {
2207     GetObjectFile()->GetModule()->LogMessage(
2208         log, "SymbolFileDWARF::FindFunctions (name=\"%s\", "
2209              "name_type_mask=0x%x, append=%u, sc_list)",
2210         name.GetCString(), name_type_mask, append);
2211   }
2212 
2213   // If we aren't appending the results to this list, then clear the list
2214   if (!append)
2215     sc_list.Clear();
2216 
2217   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2218     return 0;
2219 
2220   // If name is empty then we won't find anything.
2221   if (name.IsEmpty())
2222     return 0;
2223 
2224   // Remember how many sc_list are in the list before we search in case we are
2225   // appending the results to a variable list.
2226 
2227   const uint32_t original_size = sc_list.GetSize();
2228 
2229   DWARFDebugInfo *info = DebugInfo();
2230   if (info == NULL)
2231     return 0;
2232 
2233   m_index->GetFunctions(name, *info,
2234                         [this](const DWARFDIE &die, bool include_inlines,
2235                                lldb_private::SymbolContextList &sc_list) {
2236                           return ResolveFunction(die, include_inlines, sc_list);
2237                         },
2238                         [this](lldb::user_id_t type_uid) {
2239                           return GetDeclContextContainingUID(type_uid);
2240                         },
2241                         parent_decl_ctx, name_type_mask, include_inlines,
2242                         sc_list);
2243 
2244   // Return the number of variable that were appended to the list
2245   const uint32_t num_matches = sc_list.GetSize() - original_size;
2246 
2247   if (log && num_matches > 0) {
2248     GetObjectFile()->GetModule()->LogMessage(
2249         log, "SymbolFileDWARF::FindFunctions (name=\"%s\", "
2250              "name_type_mask=0x%x, include_inlines=%d, append=%u, sc_list) => "
2251              "%u",
2252         name.GetCString(), name_type_mask, include_inlines, append,
2253         num_matches);
2254   }
2255   return num_matches;
2256 }
2257 
2258 uint32_t SymbolFileDWARF::FindFunctions(const RegularExpression &regex,
2259                                         bool include_inlines, bool append,
2260                                         SymbolContextList &sc_list) {
2261   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2262   Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (regex = '%s')",
2263                      regex.GetText().str().c_str());
2264 
2265   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2266 
2267   if (log) {
2268     GetObjectFile()->GetModule()->LogMessage(
2269         log,
2270         "SymbolFileDWARF::FindFunctions (regex=\"%s\", append=%u, sc_list)",
2271         regex.GetText().str().c_str(), append);
2272   }
2273 
2274   // If we aren't appending the results to this list, then clear the list
2275   if (!append)
2276     sc_list.Clear();
2277 
2278   DWARFDebugInfo *info = DebugInfo();
2279   if (!info)
2280     return 0;
2281 
2282   // Remember how many sc_list are in the list before we search in case we are
2283   // appending the results to a variable list.
2284   uint32_t original_size = sc_list.GetSize();
2285 
2286   m_index->GetFunctions(regex, *info,
2287                         [this](const DWARFDIE &die, bool include_inlines,
2288                                lldb_private::SymbolContextList &sc_list) {
2289                           return ResolveFunction(die, include_inlines, sc_list);
2290                         },
2291                         include_inlines, sc_list);
2292 
2293   // Return the number of variable that were appended to the list
2294   return sc_list.GetSize() - original_size;
2295 }
2296 
2297 void SymbolFileDWARF::GetMangledNamesForFunction(
2298     const std::string &scope_qualified_name,
2299     std::vector<ConstString> &mangled_names) {
2300   DWARFDebugInfo *info = DebugInfo();
2301   uint32_t num_comp_units = 0;
2302   if (info)
2303     num_comp_units = info->GetNumCompileUnits();
2304 
2305   for (uint32_t i = 0; i < num_comp_units; i++) {
2306     DWARFUnit *cu = info->GetCompileUnitAtIndex(i);
2307     if (cu == nullptr)
2308       continue;
2309 
2310     SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
2311     if (dwo)
2312       dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
2313   }
2314 
2315   NameToOffsetMap::iterator iter =
2316       m_function_scope_qualified_name_map.find(scope_qualified_name);
2317   if (iter == m_function_scope_qualified_name_map.end())
2318     return;
2319 
2320   DIERefSetSP set_sp = (*iter).second;
2321   std::set<DIERef>::iterator set_iter;
2322   for (set_iter = set_sp->begin(); set_iter != set_sp->end(); set_iter++) {
2323     DWARFDIE die = DebugInfo()->GetDIE(*set_iter);
2324     mangled_names.push_back(ConstString(die.GetMangledName()));
2325   }
2326 }
2327 
2328 uint32_t SymbolFileDWARF::FindTypes(
2329     const SymbolContext &sc, const ConstString &name,
2330     const CompilerDeclContext *parent_decl_ctx, bool append,
2331     uint32_t max_matches,
2332     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
2333     TypeMap &types) {
2334   // If we aren't appending the results to this list, then clear the list
2335   if (!append)
2336     types.Clear();
2337 
2338   // Make sure we haven't already searched this SymbolFile before...
2339   if (searched_symbol_files.count(this))
2340     return 0;
2341   else
2342     searched_symbol_files.insert(this);
2343 
2344   DWARFDebugInfo *info = DebugInfo();
2345   if (info == NULL)
2346     return 0;
2347 
2348   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2349 
2350   if (log) {
2351     if (parent_decl_ctx)
2352       GetObjectFile()->GetModule()->LogMessage(
2353           log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2354                "%p (\"%s\"), append=%u, max_matches=%u, type_list)",
2355           name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2356           parent_decl_ctx->GetName().AsCString("<NULL>"), append, max_matches);
2357     else
2358       GetObjectFile()->GetModule()->LogMessage(
2359           log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2360                "NULL, append=%u, max_matches=%u, type_list)",
2361           name.GetCString(), append, max_matches);
2362   }
2363 
2364   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2365     return 0;
2366 
2367   DIEArray die_offsets;
2368   m_index->GetTypes(name, die_offsets);
2369   const size_t num_die_matches = die_offsets.size();
2370 
2371   if (num_die_matches) {
2372     const uint32_t initial_types_size = types.GetSize();
2373     for (size_t i = 0; i < num_die_matches; ++i) {
2374       const DIERef &die_ref = die_offsets[i];
2375       DWARFDIE die = GetDIE(die_ref);
2376 
2377       if (die) {
2378         if (!DIEInDeclContext(parent_decl_ctx, die))
2379           continue; // The containing decl contexts don't match
2380 
2381         Type *matching_type = ResolveType(die, true, true);
2382         if (matching_type) {
2383           // We found a type pointer, now find the shared pointer form our type
2384           // list
2385           types.InsertUnique(matching_type->shared_from_this());
2386           if (types.GetSize() >= max_matches)
2387             break;
2388         }
2389       } else {
2390         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2391                                         name.GetStringRef());
2392       }
2393     }
2394     const uint32_t num_matches = types.GetSize() - initial_types_size;
2395     if (log && num_matches) {
2396       if (parent_decl_ctx) {
2397         GetObjectFile()->GetModule()->LogMessage(
2398             log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2399                  "= %p (\"%s\"), append=%u, max_matches=%u, type_list) => %u",
2400             name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2401             parent_decl_ctx->GetName().AsCString("<NULL>"), append, max_matches,
2402             num_matches);
2403       } else {
2404         GetObjectFile()->GetModule()->LogMessage(
2405             log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2406                  "= NULL, append=%u, max_matches=%u, type_list) => %u",
2407             name.GetCString(), append, max_matches, num_matches);
2408       }
2409     }
2410     return num_matches;
2411   } else {
2412     UpdateExternalModuleListIfNeeded();
2413 
2414     for (const auto &pair : m_external_type_modules) {
2415       ModuleSP external_module_sp = pair.second;
2416       if (external_module_sp) {
2417         SymbolVendor *sym_vendor = external_module_sp->GetSymbolVendor();
2418         if (sym_vendor) {
2419           const uint32_t num_external_matches =
2420               sym_vendor->FindTypes(sc, name, parent_decl_ctx, append,
2421                                     max_matches, searched_symbol_files, types);
2422           if (num_external_matches)
2423             return num_external_matches;
2424         }
2425       }
2426     }
2427   }
2428 
2429   return 0;
2430 }
2431 
2432 size_t SymbolFileDWARF::FindTypes(const std::vector<CompilerContext> &context,
2433                                   bool append, TypeMap &types) {
2434   if (!append)
2435     types.Clear();
2436 
2437   if (context.empty())
2438     return 0;
2439 
2440   ConstString name = context.back().name;
2441 
2442   if (!name)
2443     return 0;
2444 
2445   DIEArray die_offsets;
2446   m_index->GetTypes(name, die_offsets);
2447   const size_t num_die_matches = die_offsets.size();
2448 
2449   if (num_die_matches) {
2450     size_t num_matches = 0;
2451     for (size_t i = 0; i < num_die_matches; ++i) {
2452       const DIERef &die_ref = die_offsets[i];
2453       DWARFDIE die = GetDIE(die_ref);
2454 
2455       if (die) {
2456         std::vector<CompilerContext> die_context;
2457         die.GetDWOContext(die_context);
2458         if (die_context != context)
2459           continue;
2460 
2461         Type *matching_type = ResolveType(die, true, true);
2462         if (matching_type) {
2463           // We found a type pointer, now find the shared pointer form our type
2464           // list
2465           types.InsertUnique(matching_type->shared_from_this());
2466           ++num_matches;
2467         }
2468       } else {
2469         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2470                                         name.GetStringRef());
2471       }
2472     }
2473     return num_matches;
2474   }
2475   return 0;
2476 }
2477 
2478 CompilerDeclContext
2479 SymbolFileDWARF::FindNamespace(const SymbolContext &sc, const ConstString &name,
2480                                const CompilerDeclContext *parent_decl_ctx) {
2481   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2482 
2483   if (log) {
2484     GetObjectFile()->GetModule()->LogMessage(
2485         log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
2486         name.GetCString());
2487   }
2488 
2489   CompilerDeclContext namespace_decl_ctx;
2490 
2491   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2492     return namespace_decl_ctx;
2493 
2494   DWARFDebugInfo *info = DebugInfo();
2495   if (info) {
2496     DIEArray die_offsets;
2497     m_index->GetNamespaces(name, die_offsets);
2498     const size_t num_matches = die_offsets.size();
2499     if (num_matches) {
2500       for (size_t i = 0; i < num_matches; ++i) {
2501         const DIERef &die_ref = die_offsets[i];
2502         DWARFDIE die = GetDIE(die_ref);
2503 
2504         if (die) {
2505           if (!DIEInDeclContext(parent_decl_ctx, die))
2506             continue; // The containing decl contexts don't match
2507 
2508           DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2509           if (dwarf_ast) {
2510             namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
2511             if (namespace_decl_ctx)
2512               break;
2513           }
2514         } else {
2515           m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2516                                           name.GetStringRef());
2517         }
2518       }
2519     }
2520   }
2521   if (log && namespace_decl_ctx) {
2522     GetObjectFile()->GetModule()->LogMessage(
2523         log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => "
2524              "CompilerDeclContext(%p/%p) \"%s\"",
2525         name.GetCString(),
2526         static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
2527         static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
2528         namespace_decl_ctx.GetName().AsCString("<NULL>"));
2529   }
2530 
2531   return namespace_decl_ctx;
2532 }
2533 
2534 TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
2535                                       bool resolve_function_context) {
2536   TypeSP type_sp;
2537   if (die) {
2538     Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
2539     if (type_ptr == NULL) {
2540       CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(die.GetCU());
2541       assert(lldb_cu);
2542       SymbolContext sc(lldb_cu);
2543       const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
2544       while (parent_die != nullptr) {
2545         if (parent_die->Tag() == DW_TAG_subprogram)
2546           break;
2547         parent_die = parent_die->GetParent();
2548       }
2549       SymbolContext sc_backup = sc;
2550       if (resolve_function_context && parent_die != nullptr &&
2551           !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
2552         sc = sc_backup;
2553 
2554       type_sp = ParseType(sc, die, NULL);
2555     } else if (type_ptr != DIE_IS_BEING_PARSED) {
2556       // Grab the existing type from the master types lists
2557       type_sp = type_ptr->shared_from_this();
2558     }
2559   }
2560   return type_sp;
2561 }
2562 
2563 DWARFDIE
2564 SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
2565   if (orig_die) {
2566     DWARFDIE die = orig_die;
2567 
2568     while (die) {
2569       // If this is the original DIE that we are searching for a declaration
2570       // for, then don't look in the cache as we don't want our own decl
2571       // context to be our decl context...
2572       if (orig_die != die) {
2573         switch (die.Tag()) {
2574         case DW_TAG_compile_unit:
2575         case DW_TAG_partial_unit:
2576         case DW_TAG_namespace:
2577         case DW_TAG_structure_type:
2578         case DW_TAG_union_type:
2579         case DW_TAG_class_type:
2580         case DW_TAG_lexical_block:
2581         case DW_TAG_subprogram:
2582           return die;
2583         case DW_TAG_inlined_subroutine: {
2584           DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2585           if (abs_die) {
2586             return abs_die;
2587           }
2588           break;
2589         }
2590         default:
2591           break;
2592         }
2593       }
2594 
2595       DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
2596       if (spec_die) {
2597         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
2598         if (decl_ctx_die)
2599           return decl_ctx_die;
2600       }
2601 
2602       DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2603       if (abs_die) {
2604         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
2605         if (decl_ctx_die)
2606           return decl_ctx_die;
2607       }
2608 
2609       die = die.GetParent();
2610     }
2611   }
2612   return DWARFDIE();
2613 }
2614 
2615 Symbol *
2616 SymbolFileDWARF::GetObjCClassSymbol(const ConstString &objc_class_name) {
2617   Symbol *objc_class_symbol = NULL;
2618   if (m_obj_file) {
2619     Symtab *symtab = m_obj_file->GetSymtab();
2620     if (symtab) {
2621       objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
2622           objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
2623           Symtab::eVisibilityAny);
2624     }
2625   }
2626   return objc_class_symbol;
2627 }
2628 
2629 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If
2630 // they don't then we can end up looking through all class types for a complete
2631 // type and never find the full definition. We need to know if this attribute
2632 // is supported, so we determine this here and cache th result. We also need to
2633 // worry about the debug map
2634 // DWARF file
2635 // if we are doing darwin DWARF in .o file debugging.
2636 bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(
2637     DWARFUnit *cu) {
2638   if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) {
2639     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
2640     if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
2641       m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2642     else {
2643       DWARFDebugInfo *debug_info = DebugInfo();
2644       const uint32_t num_compile_units = GetNumCompileUnits();
2645       for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2646         DWARFUnit *dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
2647         if (dwarf_cu != cu &&
2648             dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) {
2649           m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2650           break;
2651         }
2652       }
2653     }
2654     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo &&
2655         GetDebugMapSymfile())
2656       return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this);
2657   }
2658   return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
2659 }
2660 
2661 // This function can be used when a DIE is found that is a forward declaration
2662 // DIE and we want to try and find a type that has the complete definition.
2663 TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE(
2664     const DWARFDIE &die, const ConstString &type_name,
2665     bool must_be_implementation) {
2666 
2667   TypeSP type_sp;
2668 
2669   if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
2670     return type_sp;
2671 
2672   DIEArray die_offsets;
2673   m_index->GetCompleteObjCClass(type_name, must_be_implementation, die_offsets);
2674 
2675   const size_t num_matches = die_offsets.size();
2676 
2677   if (num_matches) {
2678     for (size_t i = 0; i < num_matches; ++i) {
2679       const DIERef &die_ref = die_offsets[i];
2680       DWARFDIE type_die = GetDIE(die_ref);
2681 
2682       if (type_die) {
2683         bool try_resolving_type = false;
2684 
2685         // Don't try and resolve the DIE we are looking for with the DIE
2686         // itself!
2687         if (type_die != die) {
2688           switch (type_die.Tag()) {
2689           case DW_TAG_class_type:
2690           case DW_TAG_structure_type:
2691             try_resolving_type = true;
2692             break;
2693           default:
2694             break;
2695           }
2696         }
2697 
2698         if (try_resolving_type) {
2699           if (must_be_implementation &&
2700               type_die.Supports_DW_AT_APPLE_objc_complete_type())
2701             try_resolving_type = type_die.GetAttributeValueAsUnsigned(
2702                 DW_AT_APPLE_objc_complete_type, 0);
2703 
2704           if (try_resolving_type) {
2705             Type *resolved_type = ResolveType(type_die, false, true);
2706             if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2707               DEBUG_PRINTF("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
2708                            " (cu 0x%8.8" PRIx64 ")\n",
2709                            die.GetID(),
2710                            m_obj_file->GetFileSpec().GetFilename().AsCString(
2711                                "<Unknown>"),
2712                            type_die.GetID(), type_cu->GetID());
2713 
2714               if (die)
2715                 GetDIEToType()[die.GetDIE()] = resolved_type;
2716               type_sp = resolved_type->shared_from_this();
2717               break;
2718             }
2719           }
2720         }
2721       } else {
2722         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2723                                         type_name.GetStringRef());
2724       }
2725     }
2726   }
2727   return type_sp;
2728 }
2729 
2730 //----------------------------------------------------------------------
2731 // This function helps to ensure that the declaration contexts match for two
2732 // different DIEs. Often times debug information will refer to a forward
2733 // declaration of a type (the equivalent of "struct my_struct;". There will
2734 // often be a declaration of that type elsewhere that has the full definition.
2735 // When we go looking for the full type "my_struct", we will find one or more
2736 // matches in the accelerator tables and we will then need to make sure the
2737 // type was in the same declaration context as the original DIE. This function
2738 // can efficiently compare two DIEs and will return true when the declaration
2739 // context matches, and false when they don't.
2740 //----------------------------------------------------------------------
2741 bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1,
2742                                            const DWARFDIE &die2) {
2743   if (die1 == die2)
2744     return true;
2745 
2746   DWARFDIECollection decl_ctx_1;
2747   DWARFDIECollection decl_ctx_2;
2748   // The declaration DIE stack is a stack of the declaration context DIEs all
2749   // the way back to the compile unit. If a type "T" is declared inside a class
2750   // "B", and class "B" is declared inside a class "A" and class "A" is in a
2751   // namespace "lldb", and the namespace is in a compile unit, there will be a
2752   // stack of DIEs:
2753   //
2754   //   [0] DW_TAG_class_type for "B"
2755   //   [1] DW_TAG_class_type for "A"
2756   //   [2] DW_TAG_namespace  for "lldb"
2757   //   [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file.
2758   //
2759   // We grab both contexts and make sure that everything matches all the way
2760   // back to the compiler unit.
2761 
2762   // First lets grab the decl contexts for both DIEs
2763   die1.GetDeclContextDIEs(decl_ctx_1);
2764   die2.GetDeclContextDIEs(decl_ctx_2);
2765   // Make sure the context arrays have the same size, otherwise we are done
2766   const size_t count1 = decl_ctx_1.Size();
2767   const size_t count2 = decl_ctx_2.Size();
2768   if (count1 != count2)
2769     return false;
2770 
2771   // Make sure the DW_TAG values match all the way back up the compile unit. If
2772   // they don't, then we are done.
2773   DWARFDIE decl_ctx_die1;
2774   DWARFDIE decl_ctx_die2;
2775   size_t i;
2776   for (i = 0; i < count1; i++) {
2777     decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex(i);
2778     decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex(i);
2779     if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
2780       return false;
2781   }
2782 #if defined LLDB_CONFIGURATION_DEBUG
2783 
2784   // Make sure the top item in the decl context die array is always
2785   // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then
2786   // something went wrong in the DWARFDIE::GetDeclContextDIEs()
2787   // function.
2788   dw_tag_t cu_tag = decl_ctx_1.GetDIEAtIndex(count1 - 1).Tag();
2789   UNUSED_IF_ASSERT_DISABLED(cu_tag);
2790   assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit);
2791 
2792 #endif
2793   // Always skip the compile unit when comparing by only iterating up to "count
2794   // - 1". Here we compare the names as we go.
2795   for (i = 0; i < count1 - 1; i++) {
2796     decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex(i);
2797     decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex(i);
2798     const char *name1 = decl_ctx_die1.GetName();
2799     const char *name2 = decl_ctx_die2.GetName();
2800     // If the string was from a DW_FORM_strp, then the pointer will often be
2801     // the same!
2802     if (name1 == name2)
2803       continue;
2804 
2805     // Name pointers are not equal, so only compare the strings if both are not
2806     // NULL.
2807     if (name1 && name2) {
2808       // If the strings don't compare, we are done...
2809       if (strcmp(name1, name2) != 0)
2810         return false;
2811     } else {
2812       // One name was NULL while the other wasn't
2813       return false;
2814     }
2815   }
2816   // We made it through all of the checks and the declaration contexts are
2817   // equal.
2818   return true;
2819 }
2820 
2821 TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(
2822     const DWARFDeclContext &dwarf_decl_ctx) {
2823   TypeSP type_sp;
2824 
2825   const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
2826   if (dwarf_decl_ctx_count > 0) {
2827     const ConstString type_name(dwarf_decl_ctx[0].name);
2828     const dw_tag_t tag = dwarf_decl_ctx[0].tag;
2829 
2830     if (type_name) {
2831       Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION |
2832                                             DWARF_LOG_LOOKUPS));
2833       if (log) {
2834         GetObjectFile()->GetModule()->LogMessage(
2835             log, "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%"
2836                  "s, qualified-name='%s')",
2837             DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2838             dwarf_decl_ctx.GetQualifiedName());
2839       }
2840 
2841       DIEArray die_offsets;
2842       m_index->GetTypes(dwarf_decl_ctx, die_offsets);
2843       const size_t num_matches = die_offsets.size();
2844 
2845       // Get the type system that we are looking to find a type for. We will
2846       // use this to ensure any matches we find are in a language that this
2847       // type system supports
2848       const LanguageType language = dwarf_decl_ctx.GetLanguage();
2849       TypeSystem *type_system = (language == eLanguageTypeUnknown)
2850                                     ? nullptr
2851                                     : GetTypeSystemForLanguage(language);
2852 
2853       if (num_matches) {
2854         for (size_t i = 0; i < num_matches; ++i) {
2855           const DIERef &die_ref = die_offsets[i];
2856           DWARFDIE type_die = GetDIE(die_ref);
2857 
2858           if (type_die) {
2859             // Make sure type_die's langauge matches the type system we are
2860             // looking for. We don't want to find a "Foo" type from Java if we
2861             // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
2862             if (type_system &&
2863                 !type_system->SupportsLanguage(type_die.GetLanguage()))
2864               continue;
2865             bool try_resolving_type = false;
2866 
2867             // Don't try and resolve the DIE we are looking for with the DIE
2868             // itself!
2869             const dw_tag_t type_tag = type_die.Tag();
2870             // Make sure the tags match
2871             if (type_tag == tag) {
2872               // The tags match, lets try resolving this type
2873               try_resolving_type = true;
2874             } else {
2875               // The tags don't match, but we need to watch our for a forward
2876               // declaration for a struct and ("struct foo") ends up being a
2877               // class ("class foo { ... };") or vice versa.
2878               switch (type_tag) {
2879               case DW_TAG_class_type:
2880                 // We had a "class foo", see if we ended up with a "struct foo
2881                 // { ... };"
2882                 try_resolving_type = (tag == DW_TAG_structure_type);
2883                 break;
2884               case DW_TAG_structure_type:
2885                 // We had a "struct foo", see if we ended up with a "class foo
2886                 // { ... };"
2887                 try_resolving_type = (tag == DW_TAG_class_type);
2888                 break;
2889               default:
2890                 // Tags don't match, don't event try to resolve using this type
2891                 // whose name matches....
2892                 break;
2893               }
2894             }
2895 
2896             if (try_resolving_type) {
2897               DWARFDeclContext type_dwarf_decl_ctx;
2898               type_die.GetDWARFDeclContext(type_dwarf_decl_ctx);
2899 
2900               if (log) {
2901                 GetObjectFile()->GetModule()->LogMessage(
2902                     log, "SymbolFileDWARF::"
2903                          "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2904                          "qualified-name='%s') trying die=0x%8.8x (%s)",
2905                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2906                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2907                     type_dwarf_decl_ctx.GetQualifiedName());
2908               }
2909 
2910               // Make sure the decl contexts match all the way up
2911               if (dwarf_decl_ctx == type_dwarf_decl_ctx) {
2912                 Type *resolved_type = ResolveType(type_die, false);
2913                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2914                   type_sp = resolved_type->shared_from_this();
2915                   break;
2916                 }
2917               }
2918             } else {
2919               if (log) {
2920                 std::string qualified_name;
2921                 type_die.GetQualifiedName(qualified_name);
2922                 GetObjectFile()->GetModule()->LogMessage(
2923                     log, "SymbolFileDWARF::"
2924                          "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2925                          "qualified-name='%s') ignoring die=0x%8.8x (%s)",
2926                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2927                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2928                     qualified_name.c_str());
2929               }
2930             }
2931           } else {
2932             m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2933                                             type_name.GetStringRef());
2934           }
2935         }
2936       }
2937     }
2938   }
2939   return type_sp;
2940 }
2941 
2942 TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die,
2943                                   bool *type_is_new_ptr) {
2944   TypeSP type_sp;
2945 
2946   if (die) {
2947     TypeSystem *type_system =
2948         GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
2949 
2950     if (type_system) {
2951       DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
2952       if (dwarf_ast) {
2953         Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
2954         type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, log, type_is_new_ptr);
2955         if (type_sp) {
2956           TypeList *type_list = GetTypeList();
2957           if (type_list)
2958             type_list->Insert(type_sp);
2959 
2960           if (die.Tag() == DW_TAG_subprogram) {
2961             DIERef die_ref = die.GetDIERef();
2962             std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
2963                                                  .GetScopeQualifiedName()
2964                                                  .AsCString(""));
2965             if (scope_qualified_name.size()) {
2966               NameToOffsetMap::iterator iter =
2967                   m_function_scope_qualified_name_map.find(
2968                       scope_qualified_name);
2969               if (iter != m_function_scope_qualified_name_map.end())
2970                 (*iter).second->insert(die_ref);
2971               else {
2972                 DIERefSetSP new_set(new std::set<DIERef>);
2973                 new_set->insert(die_ref);
2974                 m_function_scope_qualified_name_map.emplace(
2975                     std::make_pair(scope_qualified_name, new_set));
2976               }
2977             }
2978           }
2979         }
2980       }
2981     }
2982   }
2983 
2984   return type_sp;
2985 }
2986 
2987 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc,
2988                                    const DWARFDIE &orig_die,
2989                                    bool parse_siblings, bool parse_children) {
2990   size_t types_added = 0;
2991   DWARFDIE die = orig_die;
2992   while (die) {
2993     bool type_is_new = false;
2994     if (ParseType(sc, die, &type_is_new).get()) {
2995       if (type_is_new)
2996         ++types_added;
2997     }
2998 
2999     if (parse_children && die.HasChildren()) {
3000       if (die.Tag() == DW_TAG_subprogram) {
3001         SymbolContext child_sc(sc);
3002         child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3003         types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3004       } else
3005         types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3006     }
3007 
3008     if (parse_siblings)
3009       die = die.GetSibling();
3010     else
3011       die.Clear();
3012   }
3013   return types_added;
3014 }
3015 
3016 size_t SymbolFileDWARF::ParseFunctionBlocks(const SymbolContext &sc) {
3017   assert(sc.comp_unit && sc.function);
3018   size_t functions_added = 0;
3019   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
3020   if (dwarf_cu) {
3021     const dw_offset_t function_die_offset = sc.function->GetID();
3022     DWARFDIE function_die = dwarf_cu->GetDIE(function_die_offset);
3023     if (function_die) {
3024       ParseFunctionBlocks(sc, &sc.function->GetBlock(false), function_die,
3025                           LLDB_INVALID_ADDRESS, 0);
3026     }
3027   }
3028 
3029   return functions_added;
3030 }
3031 
3032 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc) {
3033   // At least a compile unit must be valid
3034   assert(sc.comp_unit);
3035   size_t types_added = 0;
3036   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
3037   if (dwarf_cu) {
3038     if (sc.function) {
3039       dw_offset_t function_die_offset = sc.function->GetID();
3040       DWARFDIE func_die = dwarf_cu->GetDIE(function_die_offset);
3041       if (func_die && func_die.HasChildren()) {
3042         types_added = ParseTypes(sc, func_die.GetFirstChild(), true, true);
3043       }
3044     } else {
3045       DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3046       if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3047         types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3048       }
3049     }
3050   }
3051 
3052   return types_added;
3053 }
3054 
3055 size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) {
3056   if (sc.comp_unit != NULL) {
3057     DWARFDebugInfo *info = DebugInfo();
3058     if (info == NULL)
3059       return 0;
3060 
3061     if (sc.function) {
3062       DWARFDIE function_die = info->GetDIE(DIERef(sc.function->GetID(), this));
3063 
3064       const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress(
3065           DW_AT_low_pc, LLDB_INVALID_ADDRESS);
3066       if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3067         const size_t num_variables = ParseVariables(
3068             sc, function_die.GetFirstChild(), func_lo_pc, true, true);
3069 
3070         // Let all blocks know they have parse all their variables
3071         sc.function->GetBlock(false).SetDidParseVariables(true, true);
3072         return num_variables;
3073       }
3074     } else if (sc.comp_unit) {
3075       DWARFUnit *dwarf_cu = info->GetCompileUnit(sc.comp_unit->GetID());
3076 
3077       if (dwarf_cu == NULL)
3078         return 0;
3079 
3080       uint32_t vars_added = 0;
3081       VariableListSP variables(sc.comp_unit->GetVariableList(false));
3082 
3083       if (variables.get() == NULL) {
3084         variables.reset(new VariableList());
3085         sc.comp_unit->SetVariableList(variables);
3086 
3087         DIEArray die_offsets;
3088         m_index->GetGlobalVariables(*dwarf_cu, die_offsets);
3089         const size_t num_matches = die_offsets.size();
3090         if (num_matches) {
3091           for (size_t i = 0; i < num_matches; ++i) {
3092             const DIERef &die_ref = die_offsets[i];
3093             DWARFDIE die = GetDIE(die_ref);
3094             if (die) {
3095               VariableSP var_sp(
3096                   ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS));
3097               if (var_sp) {
3098                 variables->AddVariableIfUnique(var_sp);
3099                 ++vars_added;
3100               }
3101             } else
3102               m_index->ReportInvalidDIEOffset(die_ref.die_offset, "");
3103           }
3104         }
3105       }
3106       return vars_added;
3107     }
3108   }
3109   return 0;
3110 }
3111 
3112 VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc,
3113                                              const DWARFDIE &die,
3114                                              const lldb::addr_t func_low_pc) {
3115   if (die.GetDWARF() != this)
3116     return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3117 
3118   VariableSP var_sp;
3119   if (!die)
3120     return var_sp;
3121 
3122   var_sp = GetDIEToVariable()[die.GetDIE()];
3123   if (var_sp)
3124     return var_sp; // Already been parsed!
3125 
3126   const dw_tag_t tag = die.Tag();
3127   ModuleSP module = GetObjectFile()->GetModule();
3128 
3129   if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3130       (tag == DW_TAG_formal_parameter && sc.function)) {
3131     DWARFAttributes attributes;
3132     const size_t num_attributes = die.GetAttributes(attributes);
3133     DWARFDIE spec_die;
3134     if (num_attributes > 0) {
3135       const char *name = NULL;
3136       const char *mangled = NULL;
3137       Declaration decl;
3138       uint32_t i;
3139       DWARFFormValue type_die_form;
3140       DWARFExpression location(die.GetCU());
3141       bool is_external = false;
3142       bool is_artificial = false;
3143       bool location_is_const_value_data = false;
3144       bool has_explicit_location = false;
3145       DWARFFormValue const_value;
3146       Variable::RangeList scope_ranges;
3147       // AccessType accessibility = eAccessNone;
3148 
3149       for (i = 0; i < num_attributes; ++i) {
3150         dw_attr_t attr = attributes.AttributeAtIndex(i);
3151         DWARFFormValue form_value;
3152 
3153         if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3154           switch (attr) {
3155           case DW_AT_decl_file:
3156             decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3157                 form_value.Unsigned()));
3158             break;
3159           case DW_AT_decl_line:
3160             decl.SetLine(form_value.Unsigned());
3161             break;
3162           case DW_AT_decl_column:
3163             decl.SetColumn(form_value.Unsigned());
3164             break;
3165           case DW_AT_name:
3166             name = form_value.AsCString();
3167             break;
3168           case DW_AT_linkage_name:
3169           case DW_AT_MIPS_linkage_name:
3170             mangled = form_value.AsCString();
3171             break;
3172           case DW_AT_type:
3173             type_die_form = form_value;
3174             break;
3175           case DW_AT_external:
3176             is_external = form_value.Boolean();
3177             break;
3178           case DW_AT_const_value:
3179             // If we have already found a DW_AT_location attribute, ignore this
3180             // attribute.
3181             if (!has_explicit_location) {
3182               location_is_const_value_data = true;
3183               // The constant value will be either a block, a data value or a
3184               // string.
3185               auto debug_info_data = die.GetData();
3186               if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3187                 // Retrieve the value as a block expression.
3188                 uint32_t block_offset =
3189                     form_value.BlockData() - debug_info_data.GetDataStart();
3190                 uint32_t block_length = form_value.Unsigned();
3191                 location.CopyOpcodeData(module, debug_info_data, block_offset,
3192                                         block_length);
3193               } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3194                 // Retrieve the value as a data expression.
3195                 DWARFFormValue::FixedFormSizes fixed_form_sizes =
3196                     DWARFFormValue::GetFixedFormSizesForAddressSize(
3197                         attributes.CompileUnitAtIndex(i)->GetAddressByteSize(),
3198                         attributes.CompileUnitAtIndex(i)->IsDWARF64());
3199                 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3200                 uint32_t data_length =
3201                     fixed_form_sizes.GetSize(form_value.Form());
3202                 if (data_length == 0) {
3203                   const uint8_t *data_pointer = form_value.BlockData();
3204                   if (data_pointer) {
3205                     form_value.Unsigned();
3206                   } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3207                     // we need to get the byte size of the type later after we
3208                     // create the variable
3209                     const_value = form_value;
3210                   }
3211                 } else
3212                   location.CopyOpcodeData(module, debug_info_data, data_offset,
3213                                           data_length);
3214               } else {
3215                 // Retrieve the value as a string expression.
3216                 if (form_value.Form() == DW_FORM_strp) {
3217                   DWARFFormValue::FixedFormSizes fixed_form_sizes =
3218                       DWARFFormValue::GetFixedFormSizesForAddressSize(
3219                           attributes.CompileUnitAtIndex(i)
3220                               ->GetAddressByteSize(),
3221                           attributes.CompileUnitAtIndex(i)->IsDWARF64());
3222                   uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3223                   uint32_t data_length =
3224                       fixed_form_sizes.GetSize(form_value.Form());
3225                   location.CopyOpcodeData(module, debug_info_data, data_offset,
3226                                           data_length);
3227                 } else {
3228                   const char *str = form_value.AsCString();
3229                   uint32_t string_offset =
3230                       str - (const char *)debug_info_data.GetDataStart();
3231                   uint32_t string_length = strlen(str) + 1;
3232                   location.CopyOpcodeData(module, debug_info_data,
3233                                           string_offset, string_length);
3234                 }
3235               }
3236             }
3237             break;
3238           case DW_AT_location: {
3239             location_is_const_value_data = false;
3240             has_explicit_location = true;
3241             if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3242               auto data = die.GetData();
3243 
3244               uint32_t block_offset =
3245                   form_value.BlockData() - data.GetDataStart();
3246               uint32_t block_length = form_value.Unsigned();
3247               location.CopyOpcodeData(module, data, block_offset, block_length);
3248             } else {
3249               const DWARFDataExtractor &debug_loc_data = get_debug_loc_data();
3250               const dw_offset_t debug_loc_offset = form_value.Unsigned();
3251 
3252               size_t loc_list_length = DWARFExpression::LocationListSize(
3253                   die.GetCU(), debug_loc_data, debug_loc_offset);
3254               if (loc_list_length > 0) {
3255                 location.CopyOpcodeData(module, debug_loc_data,
3256                                         debug_loc_offset, loc_list_length);
3257                 assert(func_low_pc != LLDB_INVALID_ADDRESS);
3258                 location.SetLocationListSlide(
3259                     func_low_pc -
3260                     attributes.CompileUnitAtIndex(i)->GetBaseAddress());
3261               }
3262             }
3263           } break;
3264           case DW_AT_specification:
3265             spec_die = GetDIE(DIERef(form_value));
3266             break;
3267           case DW_AT_start_scope: {
3268             if (form_value.Form() == DW_FORM_sec_offset) {
3269               DWARFRangeList dwarf_scope_ranges;
3270               const DWARFDebugRanges *debug_ranges = DebugRanges();
3271               debug_ranges->FindRanges(die.GetCU()->GetRangesBase(),
3272                                        form_value.Unsigned(),
3273                                        dwarf_scope_ranges);
3274 
3275               // All DW_AT_start_scope are relative to the base address of the
3276               // compile unit. We add the compile unit base address to make
3277               // sure all the addresses are properly fixed up.
3278               for (size_t i = 0, count = dwarf_scope_ranges.GetSize();
3279                    i < count; ++i) {
3280                 const DWARFRangeList::Entry &range =
3281                     dwarf_scope_ranges.GetEntryRef(i);
3282                 scope_ranges.Append(range.GetRangeBase() +
3283                                         die.GetCU()->GetBaseAddress(),
3284                                     range.GetByteSize());
3285               }
3286             } else {
3287               // TODO: Handle the case when DW_AT_start_scope have form
3288               // constant. The
3289               // dwarf spec is a bit ambiguous about what is the expected
3290               // behavior in case the enclosing block have a non coninious
3291               // address range and the DW_AT_start_scope entry have a form
3292               // constant.
3293               GetObjectFile()->GetModule()->ReportWarning(
3294                   "0x%8.8" PRIx64
3295                   ": DW_AT_start_scope has unsupported form type (0x%x)\n",
3296                   die.GetID(), form_value.Form());
3297             }
3298 
3299             scope_ranges.Sort();
3300             scope_ranges.CombineConsecutiveRanges();
3301           } break;
3302           case DW_AT_artificial:
3303             is_artificial = form_value.Boolean();
3304             break;
3305           case DW_AT_accessibility:
3306             break; // accessibility =
3307                    // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
3308           case DW_AT_declaration:
3309           case DW_AT_description:
3310           case DW_AT_endianity:
3311           case DW_AT_segment:
3312           case DW_AT_visibility:
3313           default:
3314           case DW_AT_abstract_origin:
3315           case DW_AT_sibling:
3316             break;
3317           }
3318         }
3319       }
3320 
3321       const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3322       const dw_tag_t parent_tag = die.GetParent().Tag();
3323       bool is_static_member =
3324           (parent_tag == DW_TAG_compile_unit ||
3325            parent_tag == DW_TAG_partial_unit) &&
3326           (parent_context_die.Tag() == DW_TAG_class_type ||
3327            parent_context_die.Tag() == DW_TAG_structure_type);
3328 
3329       ValueType scope = eValueTypeInvalid;
3330 
3331       const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3332       SymbolContextScope *symbol_context_scope = NULL;
3333 
3334       bool has_explicit_mangled = mangled != nullptr;
3335       if (!mangled) {
3336         // LLDB relies on the mangled name (DW_TAG_linkage_name or
3337         // DW_AT_MIPS_linkage_name) to generate fully qualified names
3338         // of global variables with commands like "frame var j". For
3339         // example, if j were an int variable holding a value 4 and
3340         // declared in a namespace B which in turn is contained in a
3341         // namespace A, the command "frame var j" returns
3342         //   "(int) A::B::j = 4".
3343         // If the compiler does not emit a linkage name, we should be
3344         // able to generate a fully qualified name from the
3345         // declaration context.
3346         if ((parent_tag == DW_TAG_compile_unit ||
3347              parent_tag == DW_TAG_partial_unit) &&
3348             Language::LanguageIsCPlusPlus(die.GetLanguage())) {
3349           DWARFDeclContext decl_ctx;
3350 
3351           die.GetDWARFDeclContext(decl_ctx);
3352           mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString();
3353         }
3354       }
3355 
3356       if (tag == DW_TAG_formal_parameter)
3357         scope = eValueTypeVariableArgument;
3358       else {
3359         // DWARF doesn't specify if a DW_TAG_variable is a local, global
3360         // or static variable, so we have to do a little digging:
3361         // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3362         // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3363         // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3364         // Clang likes to combine small global variables into the same symbol
3365         // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3366         // so we need to look through the whole expression.
3367         bool is_static_lifetime =
3368             has_explicit_mangled ||
3369             (has_explicit_location && !location.IsValid());
3370         // Check if the location has a DW_OP_addr with any address value...
3371         lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3372         if (!location_is_const_value_data) {
3373           bool op_error = false;
3374           location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error);
3375           if (op_error) {
3376             StreamString strm;
3377             location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0,
3378                                             NULL);
3379             GetObjectFile()->GetModule()->ReportError(
3380                 "0x%8.8x: %s has an invalid location: %s", die.GetOffset(),
3381                 die.GetTagAsCString(), strm.GetData());
3382           }
3383           if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
3384             is_static_lifetime = true;
3385         }
3386         SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
3387 
3388         if (is_static_lifetime) {
3389           if (is_external)
3390             scope = eValueTypeVariableGlobal;
3391           else
3392             scope = eValueTypeVariableStatic;
3393 
3394           if (debug_map_symfile) {
3395             // When leaving the DWARF in the .o files on darwin, when we have a
3396             // global variable that wasn't initialized, the .o file might not
3397             // have allocated a virtual address for the global variable. In
3398             // this case it will have created a symbol for the global variable
3399             // that is undefined/data and external and the value will be the
3400             // byte size of the variable. When we do the address map in
3401             // SymbolFileDWARFDebugMap we rely on having an address, we need to
3402             // do some magic here so we can get the correct address for our
3403             // global variable. The address for all of these entries will be
3404             // zero, and there will be an undefined symbol in this object file,
3405             // and the executable will have a matching symbol with a good
3406             // address. So here we dig up the correct address and replace it in
3407             // the location for the variable, and set the variable's symbol
3408             // context scope to be that of the main executable so the file
3409             // address will resolve correctly.
3410             bool linked_oso_file_addr = false;
3411             if (is_external && location_DW_OP_addr == 0) {
3412               // we have a possible uninitialized extern global
3413               ConstString const_name(mangled ? mangled : name);
3414               ObjectFile *debug_map_objfile =
3415                   debug_map_symfile->GetObjectFile();
3416               if (debug_map_objfile) {
3417                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3418                 if (debug_map_symtab) {
3419                   Symbol *exe_symbol =
3420                       debug_map_symtab->FindFirstSymbolWithNameAndType(
3421                           const_name, eSymbolTypeData, Symtab::eDebugYes,
3422                           Symtab::eVisibilityExtern);
3423                   if (exe_symbol) {
3424                     if (exe_symbol->ValueIsAddress()) {
3425                       const addr_t exe_file_addr =
3426                           exe_symbol->GetAddressRef().GetFileAddress();
3427                       if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3428                         if (location.Update_DW_OP_addr(exe_file_addr)) {
3429                           linked_oso_file_addr = true;
3430                           symbol_context_scope = exe_symbol;
3431                         }
3432                       }
3433                     }
3434                   }
3435                 }
3436               }
3437             }
3438 
3439             if (!linked_oso_file_addr) {
3440               // The DW_OP_addr is not zero, but it contains a .o file address
3441               // which needs to be linked up correctly.
3442               const lldb::addr_t exe_file_addr =
3443                   debug_map_symfile->LinkOSOFileAddress(this,
3444                                                         location_DW_OP_addr);
3445               if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3446                 // Update the file address for this variable
3447                 location.Update_DW_OP_addr(exe_file_addr);
3448               } else {
3449                 // Variable didn't make it into the final executable
3450                 return var_sp;
3451               }
3452             }
3453           }
3454         } else {
3455           if (location_is_const_value_data)
3456             scope = eValueTypeVariableStatic;
3457           else {
3458             scope = eValueTypeVariableLocal;
3459             if (debug_map_symfile) {
3460               // We need to check for TLS addresses that we need to fixup
3461               if (location.ContainsThreadLocalStorage()) {
3462                 location.LinkThreadLocalStorage(
3463                     debug_map_symfile->GetObjectFile()->GetModule(),
3464                     [this, debug_map_symfile](
3465                         lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
3466                       return debug_map_symfile->LinkOSOFileAddress(
3467                           this, unlinked_file_addr);
3468                     });
3469                 scope = eValueTypeVariableThreadLocal;
3470               }
3471             }
3472           }
3473         }
3474       }
3475 
3476       if (symbol_context_scope == NULL) {
3477         switch (parent_tag) {
3478         case DW_TAG_subprogram:
3479         case DW_TAG_inlined_subroutine:
3480         case DW_TAG_lexical_block:
3481           if (sc.function) {
3482             symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(
3483                 sc_parent_die.GetID());
3484             if (symbol_context_scope == NULL)
3485               symbol_context_scope = sc.function;
3486           }
3487           break;
3488 
3489         default:
3490           symbol_context_scope = sc.comp_unit;
3491           break;
3492         }
3493       }
3494 
3495       if (symbol_context_scope) {
3496         SymbolFileTypeSP type_sp(
3497             new SymbolFileType(*this, DIERef(type_die_form).GetUID(this)));
3498 
3499         if (const_value.Form() && type_sp && type_sp->GetType())
3500           location.CopyOpcodeData(const_value.Unsigned(),
3501                                   type_sp->GetType()->GetByteSize(),
3502                                   die.GetCU()->GetAddressByteSize());
3503 
3504         var_sp.reset(new Variable(die.GetID(), name, mangled, type_sp, scope,
3505                                   symbol_context_scope, scope_ranges, &decl,
3506                                   location, is_external, is_artificial,
3507                                   is_static_member));
3508 
3509         var_sp->SetLocationIsConstantValueData(location_is_const_value_data);
3510       } else {
3511         // Not ready to parse this variable yet. It might be a global or static
3512         // variable that is in a function scope and the function in the symbol
3513         // context wasn't filled in yet
3514         return var_sp;
3515       }
3516     }
3517     // Cache var_sp even if NULL (the variable was just a specification or was
3518     // missing vital information to be able to be displayed in the debugger
3519     // (missing location due to optimization, etc)) so we don't re-parse this
3520     // DIE over and over later...
3521     GetDIEToVariable()[die.GetDIE()] = var_sp;
3522     if (spec_die)
3523       GetDIEToVariable()[spec_die.GetDIE()] = var_sp;
3524   }
3525   return var_sp;
3526 }
3527 
3528 DWARFDIE
3529 SymbolFileDWARF::FindBlockContainingSpecification(
3530     const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
3531   // Give the concrete function die specified by "func_die_offset", find the
3532   // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3533   // to "spec_block_die_offset"
3534   return FindBlockContainingSpecification(DebugInfo()->GetDIE(func_die_ref),
3535                                           spec_block_die_offset);
3536 }
3537 
3538 DWARFDIE
3539 SymbolFileDWARF::FindBlockContainingSpecification(
3540     const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
3541   if (die) {
3542     switch (die.Tag()) {
3543     case DW_TAG_subprogram:
3544     case DW_TAG_inlined_subroutine:
3545     case DW_TAG_lexical_block: {
3546       if (die.GetAttributeValueAsReference(
3547               DW_AT_specification, DW_INVALID_OFFSET) == spec_block_die_offset)
3548         return die;
3549 
3550       if (die.GetAttributeValueAsReference(DW_AT_abstract_origin,
3551                                            DW_INVALID_OFFSET) ==
3552           spec_block_die_offset)
3553         return die;
3554     } break;
3555     }
3556 
3557     // Give the concrete function die specified by "func_die_offset", find the
3558     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3559     // to "spec_block_die_offset"
3560     for (DWARFDIE child_die = die.GetFirstChild(); child_die;
3561          child_die = child_die.GetSibling()) {
3562       DWARFDIE result_die =
3563           FindBlockContainingSpecification(child_die, spec_block_die_offset);
3564       if (result_die)
3565         return result_die;
3566     }
3567   }
3568 
3569   return DWARFDIE();
3570 }
3571 
3572 size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc,
3573                                        const DWARFDIE &orig_die,
3574                                        const lldb::addr_t func_low_pc,
3575                                        bool parse_siblings, bool parse_children,
3576                                        VariableList *cc_variable_list) {
3577   if (!orig_die)
3578     return 0;
3579 
3580   VariableListSP variable_list_sp;
3581 
3582   size_t vars_added = 0;
3583   DWARFDIE die = orig_die;
3584   while (die) {
3585     dw_tag_t tag = die.Tag();
3586 
3587     // Check to see if we have already parsed this variable or constant?
3588     VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
3589     if (var_sp) {
3590       if (cc_variable_list)
3591         cc_variable_list->AddVariableIfUnique(var_sp);
3592     } else {
3593       // We haven't already parsed it, lets do that now.
3594       if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3595           (tag == DW_TAG_formal_parameter && sc.function)) {
3596         if (variable_list_sp.get() == NULL) {
3597           DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die);
3598           dw_tag_t parent_tag = sc_parent_die.Tag();
3599           switch (parent_tag) {
3600           case DW_TAG_compile_unit:
3601           case DW_TAG_partial_unit:
3602             if (sc.comp_unit != NULL) {
3603               variable_list_sp = sc.comp_unit->GetVariableList(false);
3604               if (variable_list_sp.get() == NULL) {
3605                 variable_list_sp.reset(new VariableList());
3606               }
3607             } else {
3608               GetObjectFile()->GetModule()->ReportError(
3609                   "parent 0x%8.8" PRIx64 " %s with no valid compile unit in "
3610                                          "symbol context for 0x%8.8" PRIx64
3611                   " %s.\n",
3612                   sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(),
3613                   orig_die.GetID(), orig_die.GetTagAsCString());
3614             }
3615             break;
3616 
3617           case DW_TAG_subprogram:
3618           case DW_TAG_inlined_subroutine:
3619           case DW_TAG_lexical_block:
3620             if (sc.function != NULL) {
3621               // Check to see if we already have parsed the variables for the
3622               // given scope
3623 
3624               Block *block = sc.function->GetBlock(true).FindBlockByID(
3625                   sc_parent_die.GetID());
3626               if (block == NULL) {
3627                 // This must be a specification or abstract origin with a
3628                 // concrete block counterpart in the current function. We need
3629                 // to find the concrete block so we can correctly add the
3630                 // variable to it
3631                 const DWARFDIE concrete_block_die =
3632                     FindBlockContainingSpecification(
3633                         DIERef(sc.function->GetID(), this),
3634                         sc_parent_die.GetOffset());
3635                 if (concrete_block_die)
3636                   block = sc.function->GetBlock(true).FindBlockByID(
3637                       concrete_block_die.GetID());
3638               }
3639 
3640               if (block != NULL) {
3641                 const bool can_create = false;
3642                 variable_list_sp = block->GetBlockVariableList(can_create);
3643                 if (variable_list_sp.get() == NULL) {
3644                   variable_list_sp.reset(new VariableList());
3645                   block->SetVariableList(variable_list_sp);
3646                 }
3647               }
3648             }
3649             break;
3650 
3651           default:
3652             GetObjectFile()->GetModule()->ReportError(
3653                 "didn't find appropriate parent DIE for variable list for "
3654                 "0x%8.8" PRIx64 " %s.\n",
3655                 orig_die.GetID(), orig_die.GetTagAsCString());
3656             break;
3657           }
3658         }
3659 
3660         if (variable_list_sp) {
3661           VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc));
3662           if (var_sp) {
3663             variable_list_sp->AddVariableIfUnique(var_sp);
3664             if (cc_variable_list)
3665               cc_variable_list->AddVariableIfUnique(var_sp);
3666             ++vars_added;
3667           }
3668         }
3669       }
3670     }
3671 
3672     bool skip_children = (sc.function == NULL && tag == DW_TAG_subprogram);
3673 
3674     if (!skip_children && parse_children && die.HasChildren()) {
3675       vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true,
3676                                    true, cc_variable_list);
3677     }
3678 
3679     if (parse_siblings)
3680       die = die.GetSibling();
3681     else
3682       die.Clear();
3683   }
3684   return vars_added;
3685 }
3686 
3687 //------------------------------------------------------------------
3688 // PluginInterface protocol
3689 //------------------------------------------------------------------
3690 ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); }
3691 
3692 uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; }
3693 
3694 void SymbolFileDWARF::DumpIndexes() {
3695   StreamFile s(stdout, false);
3696   m_index->Dump(s);
3697 }
3698 
3699 SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() {
3700   if (m_debug_map_symfile == NULL && !m_debug_map_module_wp.expired()) {
3701     lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
3702     if (module_sp) {
3703       SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
3704       if (sym_vendor)
3705         m_debug_map_symfile =
3706             (SymbolFileDWARFDebugMap *)sym_vendor->GetSymbolFile();
3707     }
3708   }
3709   return m_debug_map_symfile;
3710 }
3711 
3712 DWARFExpression::LocationListFormat
3713 SymbolFileDWARF::GetLocationListFormat() const {
3714   return DWARFExpression::RegularLocationList;
3715 }
3716 
3717 SymbolFileDWARFDwp *SymbolFileDWARF::GetDwpSymbolFile() {
3718   llvm::call_once(m_dwp_symfile_once_flag, [this]() {
3719     ModuleSpec module_spec;
3720     module_spec.GetFileSpec() = m_obj_file->GetFileSpec();
3721     module_spec.GetSymbolFileSpec() =
3722         FileSpec(m_obj_file->GetFileSpec().GetPath() + ".dwp", false);
3723     FileSpec dwp_filespec = Symbols::LocateExecutableSymbolFile(module_spec);
3724     if (dwp_filespec.Exists()) {
3725       m_dwp_symfile = SymbolFileDWARFDwp::Create(GetObjectFile()->GetModule(),
3726                                                  dwp_filespec);
3727     }
3728   });
3729   return m_dwp_symfile.get();
3730 }
3731