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