1 //===-- SymbolFileDWARF.cpp ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "SymbolFileDWARF.h"
11 
12 // Other libraries and framework includes
13 #include "llvm/Support/Casting.h"
14 #include "llvm/Support/Threading.h"
15 
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleList.h"
18 #include "lldb/Core/ModuleSpec.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/Scalar.h"
21 #include "lldb/Core/Section.h"
22 #include "lldb/Core/StreamFile.h"
23 #include "lldb/Core/Value.h"
24 #include "lldb/Utility/ArchSpec.h"
25 #include "lldb/Utility/RegularExpression.h"
26 #include "lldb/Utility/StreamString.h"
27 #include "lldb/Utility/Timer.h"
28 
29 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
30 #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 == 3 || version == 4;
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_macro_data() {
649   return GetCachedSectionData(eSectionTypeDWARFDebugMacro, m_data_debug_macro);
650 }
651 
652 const DWARFDataExtractor &SymbolFileDWARF::get_debug_loc_data() {
653   return GetCachedSectionData(eSectionTypeDWARFDebugLoc, m_data_debug_loc);
654 }
655 
656 const DWARFDataExtractor &SymbolFileDWARF::get_debug_ranges_data() {
657   return GetCachedSectionData(eSectionTypeDWARFDebugRanges,
658                               m_data_debug_ranges);
659 }
660 
661 const DWARFDataExtractor &SymbolFileDWARF::get_debug_str_data() {
662   return GetCachedSectionData(eSectionTypeDWARFDebugStr, m_data_debug_str);
663 }
664 
665 const DWARFDataExtractor &SymbolFileDWARF::get_debug_str_offsets_data() {
666   return GetCachedSectionData(eSectionTypeDWARFDebugStrOffsets,
667                               m_data_debug_str_offsets);
668 }
669 
670 const DWARFDataExtractor &SymbolFileDWARF::get_debug_types_data() {
671   return GetCachedSectionData(eSectionTypeDWARFDebugTypes, m_data_debug_types);
672 }
673 
674 const DWARFDataExtractor &SymbolFileDWARF::get_apple_names_data() {
675   return GetCachedSectionData(eSectionTypeDWARFAppleNames, m_data_apple_names);
676 }
677 
678 const DWARFDataExtractor &SymbolFileDWARF::get_apple_types_data() {
679   return GetCachedSectionData(eSectionTypeDWARFAppleTypes, m_data_apple_types);
680 }
681 
682 const DWARFDataExtractor &SymbolFileDWARF::get_apple_namespaces_data() {
683   return GetCachedSectionData(eSectionTypeDWARFAppleNamespaces,
684                               m_data_apple_namespaces);
685 }
686 
687 const DWARFDataExtractor &SymbolFileDWARF::get_apple_objc_data() {
688   return GetCachedSectionData(eSectionTypeDWARFAppleObjC, m_data_apple_objc);
689 }
690 
691 const DWARFDataExtractor &SymbolFileDWARF::get_gnu_debugaltlink() {
692   return GetCachedSectionData(eSectionTypeDWARFGNUDebugAltLink,
693                               m_data_gnu_debugaltlink);
694 }
695 
696 DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() {
697   if (m_abbr.get() == NULL) {
698     const DWARFDataExtractor &debug_abbrev_data = get_debug_abbrev_data();
699     if (debug_abbrev_data.GetByteSize() > 0) {
700       m_abbr.reset(new DWARFDebugAbbrev());
701       if (m_abbr.get())
702         m_abbr->Parse(debug_abbrev_data);
703     }
704   }
705   return m_abbr.get();
706 }
707 
708 const DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() const {
709   return m_abbr.get();
710 }
711 
712 DWARFDebugInfo *SymbolFileDWARF::DebugInfo() {
713   if (m_info.get() == NULL) {
714     static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
715     Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
716                        static_cast<void *>(this));
717     if (get_debug_info_data().GetByteSize() > 0) {
718       m_info.reset(new DWARFDebugInfo());
719       if (m_info.get()) {
720         m_info->SetDwarfData(this);
721       }
722     }
723   }
724   return m_info.get();
725 }
726 
727 const DWARFDebugInfo *SymbolFileDWARF::DebugInfo() const {
728   return m_info.get();
729 }
730 
731 DWARFUnit *
732 SymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit) {
733   if (!comp_unit)
734     return nullptr;
735 
736   DWARFDebugInfo *info = DebugInfo();
737   if (info) {
738     // Just a normal DWARF file whose user ID for the compile unit is the DWARF
739     // offset itself
740 
741     DWARFUnit *dwarf_cu =
742         info->GetCompileUnit((dw_offset_t)comp_unit->GetID());
743     if (dwarf_cu && dwarf_cu->GetUserData() == NULL)
744       dwarf_cu->SetUserData(comp_unit);
745     return dwarf_cu;
746   }
747   return NULL;
748 }
749 
750 DWARFDebugRanges *SymbolFileDWARF::DebugRanges() {
751   if (m_ranges.get() == NULL) {
752     static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
753     Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
754                        static_cast<void *>(this));
755     if (get_debug_ranges_data().GetByteSize() > 0) {
756       m_ranges.reset(new DWARFDebugRanges());
757       if (m_ranges.get())
758         m_ranges->Extract(this);
759     }
760   }
761   return m_ranges.get();
762 }
763 
764 const DWARFDebugRanges *SymbolFileDWARF::DebugRanges() const {
765   return m_ranges.get();
766 }
767 
768 lldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFUnit *dwarf_cu,
769                                                    uint32_t cu_idx) {
770   CompUnitSP cu_sp;
771   if (dwarf_cu) {
772     CompileUnit *comp_unit = (CompileUnit *)dwarf_cu->GetUserData();
773     if (comp_unit) {
774       // We already parsed this compile unit, had out a shared pointer to it
775       cu_sp = comp_unit->shared_from_this();
776     } else {
777       if (dwarf_cu->GetSymbolFileDWARF() != this) {
778         return dwarf_cu->GetSymbolFileDWARF()->ParseCompileUnit(dwarf_cu,
779                                                                 cu_idx);
780       } else if (dwarf_cu->GetOffset() == 0 && GetDebugMapSymfile()) {
781         // Let the debug map create the compile unit
782         cu_sp = m_debug_map_symfile->GetCompileUnit(this);
783         dwarf_cu->SetUserData(cu_sp.get());
784       } else {
785         ModuleSP module_sp(m_obj_file->GetModule());
786         if (module_sp) {
787           const DWARFDIE cu_die = dwarf_cu->DIE();
788           if (cu_die) {
789             FileSpec cu_file_spec{cu_die.GetName(), false};
790             if (cu_file_spec) {
791               // If we have a full path to the compile unit, we don't need to
792               // resolve the file.  This can be expensive e.g. when the source
793               // files are
794               // NFS mounted.
795               if (cu_file_spec.IsRelative()) {
796                 const char *cu_comp_dir{
797                     cu_die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr)};
798                 cu_file_spec.PrependPathComponent(resolveCompDir(cu_comp_dir));
799               }
800 
801               std::string remapped_file;
802               if (module_sp->RemapSourceFile(cu_file_spec.GetPath(),
803                                              remapped_file))
804                 cu_file_spec.SetFile(remapped_file, false);
805             }
806 
807             LanguageType cu_language = DWARFUnit::LanguageTypeFromDWARF(
808                 cu_die.GetAttributeValueAsUnsigned(DW_AT_language, 0));
809 
810             bool is_optimized = dwarf_cu->GetIsOptimized();
811             cu_sp.reset(new CompileUnit(
812                 module_sp, dwarf_cu, cu_file_spec, dwarf_cu->GetID(),
813                 cu_language, is_optimized ? eLazyBoolYes : eLazyBoolNo));
814             if (cu_sp) {
815               // If we just created a compile unit with an invalid file spec,
816               // try and get the first entry in the supports files from the
817               // line table as that should be the compile unit.
818               if (!cu_file_spec) {
819                 cu_file_spec = cu_sp->GetSupportFiles().GetFileSpecAtIndex(1);
820                 if (cu_file_spec) {
821                   (FileSpec &)(*cu_sp) = cu_file_spec;
822                   // Also fix the invalid file spec which was copied from the
823                   // compile unit.
824                   cu_sp->GetSupportFiles().Replace(0, cu_file_spec);
825                 }
826               }
827 
828               dwarf_cu->SetUserData(cu_sp.get());
829 
830               // Figure out the compile unit index if we weren't given one
831               if (cu_idx == UINT32_MAX)
832                 DebugInfo()->GetCompileUnit(dwarf_cu->GetOffset(), &cu_idx);
833 
834               m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(
835                   cu_idx, cu_sp);
836             }
837           }
838         }
839       }
840     }
841   }
842   return cu_sp;
843 }
844 
845 uint32_t SymbolFileDWARF::GetNumCompileUnits() {
846   DWARFDebugInfo *info = DebugInfo();
847   if (info)
848     return info->GetNumCompileUnits();
849   return 0;
850 }
851 
852 CompUnitSP SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx) {
853   CompUnitSP cu_sp;
854   DWARFDebugInfo *info = DebugInfo();
855   if (info) {
856     DWARFUnit *dwarf_cu = info->GetCompileUnitAtIndex(cu_idx);
857     if (dwarf_cu)
858       cu_sp = ParseCompileUnit(dwarf_cu, cu_idx);
859   }
860   return cu_sp;
861 }
862 
863 Function *SymbolFileDWARF::ParseCompileUnitFunction(const SymbolContext &sc,
864                                                     const DWARFDIE &die) {
865   if (die.IsValid()) {
866     TypeSystem *type_system =
867         GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
868 
869     if (type_system) {
870       DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
871       if (dwarf_ast)
872         return dwarf_ast->ParseFunctionFromDWARF(sc, die);
873     }
874   }
875   return nullptr;
876 }
877 
878 bool SymbolFileDWARF::FixupAddress(Address &addr) {
879   SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
880   if (debug_map_symfile) {
881     return debug_map_symfile->LinkOSOAddress(addr);
882   }
883   // This is a normal DWARF file, no address fixups need to happen
884   return true;
885 }
886 lldb::LanguageType
887 SymbolFileDWARF::ParseCompileUnitLanguage(const SymbolContext &sc) {
888   assert(sc.comp_unit);
889   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
890   if (dwarf_cu)
891     return dwarf_cu->GetLanguageType();
892   else
893     return eLanguageTypeUnknown;
894 }
895 
896 size_t SymbolFileDWARF::ParseCompileUnitFunctions(const SymbolContext &sc) {
897   assert(sc.comp_unit);
898   size_t functions_added = 0;
899   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
900   if (dwarf_cu) {
901     DWARFDIECollection function_dies;
902     const size_t num_functions =
903         dwarf_cu->AppendDIEsWithTag(DW_TAG_subprogram, function_dies);
904     size_t func_idx;
905     for (func_idx = 0; func_idx < num_functions; ++func_idx) {
906       DWARFDIE die = function_dies.GetDIEAtIndex(func_idx);
907       if (sc.comp_unit->FindFunctionByUID(die.GetID()).get() == NULL) {
908         if (ParseCompileUnitFunction(sc, die))
909           ++functions_added;
910       }
911     }
912     // FixupTypes();
913   }
914   return functions_added;
915 }
916 
917 bool SymbolFileDWARF::ParseCompileUnitSupportFiles(
918     const SymbolContext &sc, FileSpecList &support_files) {
919   assert(sc.comp_unit);
920   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
921   if (dwarf_cu) {
922     const DWARFBaseDIE cu_die = dwarf_cu->GetUnitDIEOnly();
923 
924     if (cu_die) {
925       FileSpec cu_comp_dir = resolveCompDir(
926           cu_die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr));
927       const dw_offset_t stmt_list = cu_die.GetAttributeValueAsUnsigned(
928           DW_AT_stmt_list, DW_INVALID_OFFSET);
929       if (stmt_list != DW_INVALID_OFFSET) {
930         // All file indexes in DWARF are one based and a file of index zero is
931         // supposed to be the compile unit itself.
932         support_files.Append(*sc.comp_unit);
933         return DWARFDebugLine::ParseSupportFiles(
934             sc.comp_unit->GetModule(), get_debug_line_data(), cu_comp_dir,
935             stmt_list, support_files);
936       }
937     }
938   }
939   return false;
940 }
941 
942 bool SymbolFileDWARF::ParseCompileUnitIsOptimized(
943     const lldb_private::SymbolContext &sc) {
944   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
945   if (dwarf_cu)
946     return dwarf_cu->GetIsOptimized();
947   return false;
948 }
949 
950 bool SymbolFileDWARF::ParseImportedModules(
951     const lldb_private::SymbolContext &sc,
952     std::vector<lldb_private::ConstString> &imported_modules) {
953   assert(sc.comp_unit);
954   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
955   if (dwarf_cu) {
956     if (ClangModulesDeclVendor::LanguageSupportsClangModules(
957             sc.comp_unit->GetLanguage())) {
958       UpdateExternalModuleListIfNeeded();
959 
960       if (sc.comp_unit) {
961         const DWARFDIE die = dwarf_cu->DIE();
962 
963         if (die) {
964           for (DWARFDIE child_die = die.GetFirstChild(); child_die;
965                child_die = child_die.GetSibling()) {
966             if (child_die.Tag() == DW_TAG_imported_declaration) {
967               if (DWARFDIE module_die =
968                       child_die.GetReferencedDIE(DW_AT_import)) {
969                 if (module_die.Tag() == DW_TAG_module) {
970                   if (const char *name = module_die.GetAttributeValueAsString(
971                           DW_AT_name, nullptr)) {
972                     ConstString const_name(name);
973                     imported_modules.push_back(const_name);
974                   }
975                 }
976               }
977             }
978           }
979         }
980       } else {
981         for (const auto &pair : m_external_type_modules) {
982           imported_modules.push_back(pair.first);
983         }
984       }
985     }
986   }
987   return false;
988 }
989 
990 struct ParseDWARFLineTableCallbackInfo {
991   LineTable *line_table;
992   std::unique_ptr<LineSequence> sequence_ap;
993   lldb::addr_t addr_mask;
994 };
995 
996 //----------------------------------------------------------------------
997 // ParseStatementTableCallback
998 //----------------------------------------------------------------------
999 static void ParseDWARFLineTableCallback(dw_offset_t offset,
1000                                         const DWARFDebugLine::State &state,
1001                                         void *userData) {
1002   if (state.row == DWARFDebugLine::State::StartParsingLineTable) {
1003     // Just started parsing the line table
1004   } else if (state.row == DWARFDebugLine::State::DoneParsingLineTable) {
1005     // Done parsing line table, nothing to do for the cleanup
1006   } else {
1007     ParseDWARFLineTableCallbackInfo *info =
1008         (ParseDWARFLineTableCallbackInfo *)userData;
1009     LineTable *line_table = info->line_table;
1010 
1011     // If this is our first time here, we need to create a sequence container.
1012     if (!info->sequence_ap.get()) {
1013       info->sequence_ap.reset(line_table->CreateLineSequenceContainer());
1014       assert(info->sequence_ap.get());
1015     }
1016     line_table->AppendLineEntryToSequence(
1017         info->sequence_ap.get(), state.address & info->addr_mask, state.line,
1018         state.column, state.file, state.is_stmt, state.basic_block,
1019         state.prologue_end, state.epilogue_begin, state.end_sequence);
1020     if (state.end_sequence) {
1021       // First, put the current sequence into the line table.
1022       line_table->InsertSequence(info->sequence_ap.get());
1023       // Then, empty it to prepare for the next sequence.
1024       info->sequence_ap->Clear();
1025     }
1026   }
1027 }
1028 
1029 bool SymbolFileDWARF::ParseCompileUnitLineTable(const SymbolContext &sc) {
1030   assert(sc.comp_unit);
1031   if (sc.comp_unit->GetLineTable() != NULL)
1032     return true;
1033 
1034   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1035   if (dwarf_cu) {
1036     const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
1037     if (dwarf_cu_die) {
1038       const dw_offset_t cu_line_offset =
1039           dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_stmt_list,
1040                                                    DW_INVALID_OFFSET);
1041       if (cu_line_offset != DW_INVALID_OFFSET) {
1042         std::unique_ptr<LineTable> line_table_ap(new LineTable(sc.comp_unit));
1043         if (line_table_ap.get()) {
1044           ParseDWARFLineTableCallbackInfo info;
1045           info.line_table = line_table_ap.get();
1046 
1047           /*
1048            * MIPS:
1049            * The SymbolContext may not have a valid target, thus we may not be
1050            * able
1051            * to call Address::GetOpcodeLoadAddress() which would clear the bit
1052            * #0
1053            * for MIPS. Use ArchSpec to clear the bit #0.
1054           */
1055           ArchSpec arch;
1056           GetObjectFile()->GetArchitecture(arch);
1057           switch (arch.GetMachine()) {
1058           case llvm::Triple::mips:
1059           case llvm::Triple::mipsel:
1060           case llvm::Triple::mips64:
1061           case llvm::Triple::mips64el:
1062             info.addr_mask = ~((lldb::addr_t)1);
1063             break;
1064           default:
1065             info.addr_mask = ~((lldb::addr_t)0);
1066             break;
1067           }
1068 
1069           lldb::offset_t offset = cu_line_offset;
1070           DWARFDebugLine::ParseStatementTable(get_debug_line_data(), &offset,
1071                                               ParseDWARFLineTableCallback,
1072                                               &info);
1073           SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
1074           if (debug_map_symfile) {
1075             // We have an object file that has a line table with addresses that
1076             // are not linked. We need to link the line table and convert the
1077             // addresses that are relative to the .o file into addresses for
1078             // the main executable.
1079             sc.comp_unit->SetLineTable(
1080                 debug_map_symfile->LinkOSOLineTable(this, line_table_ap.get()));
1081           } else {
1082             sc.comp_unit->SetLineTable(line_table_ap.release());
1083             return true;
1084           }
1085         }
1086       }
1087     }
1088   }
1089   return false;
1090 }
1091 
1092 lldb_private::DebugMacrosSP
1093 SymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset) {
1094   auto iter = m_debug_macros_map.find(*offset);
1095   if (iter != m_debug_macros_map.end())
1096     return iter->second;
1097 
1098   const DWARFDataExtractor &debug_macro_data = get_debug_macro_data();
1099   if (debug_macro_data.GetByteSize() == 0)
1100     return DebugMacrosSP();
1101 
1102   lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros());
1103   m_debug_macros_map[*offset] = debug_macros_sp;
1104 
1105   const DWARFDebugMacroHeader &header =
1106       DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset);
1107   DWARFDebugMacroEntry::ReadMacroEntries(debug_macro_data, get_debug_str_data(),
1108                                          header.OffsetIs64Bit(), offset, this,
1109                                          debug_macros_sp);
1110 
1111   return debug_macros_sp;
1112 }
1113 
1114 bool SymbolFileDWARF::ParseCompileUnitDebugMacros(const SymbolContext &sc) {
1115   assert(sc.comp_unit);
1116 
1117   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1118   if (dwarf_cu == nullptr)
1119     return false;
1120 
1121   const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
1122   if (!dwarf_cu_die)
1123     return false;
1124 
1125   lldb::offset_t sect_offset =
1126       dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET);
1127   if (sect_offset == DW_INVALID_OFFSET)
1128     sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros,
1129                                                            DW_INVALID_OFFSET);
1130   if (sect_offset == DW_INVALID_OFFSET)
1131     return false;
1132 
1133   sc.comp_unit->SetDebugMacros(ParseDebugMacros(&sect_offset));
1134 
1135   return true;
1136 }
1137 
1138 size_t SymbolFileDWARF::ParseFunctionBlocks(const SymbolContext &sc,
1139                                             Block *parent_block,
1140                                             const DWARFDIE &orig_die,
1141                                             addr_t subprogram_low_pc,
1142                                             uint32_t depth) {
1143   size_t blocks_added = 0;
1144   DWARFDIE die = orig_die;
1145   while (die) {
1146     dw_tag_t tag = die.Tag();
1147 
1148     switch (tag) {
1149     case DW_TAG_inlined_subroutine:
1150     case DW_TAG_subprogram:
1151     case DW_TAG_lexical_block: {
1152       Block *block = NULL;
1153       if (tag == DW_TAG_subprogram) {
1154         // Skip any DW_TAG_subprogram DIEs that are inside of a normal or
1155         // inlined functions. These will be parsed on their own as separate
1156         // entities.
1157 
1158         if (depth > 0)
1159           break;
1160 
1161         block = parent_block;
1162       } else {
1163         BlockSP block_sp(new Block(die.GetID()));
1164         parent_block->AddChild(block_sp);
1165         block = block_sp.get();
1166       }
1167       DWARFRangeList ranges;
1168       const char *name = NULL;
1169       const char *mangled_name = NULL;
1170 
1171       int decl_file = 0;
1172       int decl_line = 0;
1173       int decl_column = 0;
1174       int call_file = 0;
1175       int call_line = 0;
1176       int call_column = 0;
1177       if (die.GetDIENamesAndRanges(name, mangled_name, ranges, decl_file,
1178                                    decl_line, decl_column, call_file, call_line,
1179                                    call_column, nullptr)) {
1180         if (tag == DW_TAG_subprogram) {
1181           assert(subprogram_low_pc == LLDB_INVALID_ADDRESS);
1182           subprogram_low_pc = ranges.GetMinRangeBase(0);
1183         } else if (tag == DW_TAG_inlined_subroutine) {
1184           // We get called here for inlined subroutines in two ways. The first
1185           // time is when we are making the Function object for this inlined
1186           // concrete instance.  Since we're creating a top level block at
1187           // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS.  So we
1188           // need to adjust the containing address. The second time is when we
1189           // are parsing the blocks inside the function that contains the
1190           // inlined concrete instance.  Since these will be blocks inside the
1191           // containing "real" function the offset will be for that function.
1192           if (subprogram_low_pc == LLDB_INVALID_ADDRESS) {
1193             subprogram_low_pc = ranges.GetMinRangeBase(0);
1194           }
1195         }
1196 
1197         const size_t num_ranges = ranges.GetSize();
1198         for (size_t i = 0; i < num_ranges; ++i) {
1199           const DWARFRangeList::Entry &range = ranges.GetEntryRef(i);
1200           const addr_t range_base = range.GetRangeBase();
1201           if (range_base >= subprogram_low_pc)
1202             block->AddRange(Block::Range(range_base - subprogram_low_pc,
1203                                          range.GetByteSize()));
1204           else {
1205             GetObjectFile()->GetModule()->ReportError(
1206                 "0x%8.8" PRIx64 ": adding range [0x%" PRIx64 "-0x%" PRIx64
1207                 ") which has a base that is less than the function's low PC "
1208                 "0x%" PRIx64 ". Please file a bug and attach the file at the "
1209                              "start of this error message",
1210                 block->GetID(), range_base, range.GetRangeEnd(),
1211                 subprogram_low_pc);
1212           }
1213         }
1214         block->FinalizeRanges();
1215 
1216         if (tag != DW_TAG_subprogram &&
1217             (name != NULL || mangled_name != NULL)) {
1218           std::unique_ptr<Declaration> decl_ap;
1219           if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1220             decl_ap.reset(new Declaration(
1221                 sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),
1222                 decl_line, decl_column));
1223 
1224           std::unique_ptr<Declaration> call_ap;
1225           if (call_file != 0 || call_line != 0 || call_column != 0)
1226             call_ap.reset(new Declaration(
1227                 sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(call_file),
1228                 call_line, call_column));
1229 
1230           block->SetInlinedFunctionInfo(name, mangled_name, decl_ap.get(),
1231                                         call_ap.get());
1232         }
1233 
1234         ++blocks_added;
1235 
1236         if (die.HasChildren()) {
1237           blocks_added += ParseFunctionBlocks(sc, block, die.GetFirstChild(),
1238                                               subprogram_low_pc, depth + 1);
1239         }
1240       }
1241     } break;
1242     default:
1243       break;
1244     }
1245 
1246     // Only parse siblings of the block if we are not at depth zero. A depth of
1247     // zero indicates we are currently parsing the top level DW_TAG_subprogram
1248     // DIE
1249 
1250     if (depth == 0)
1251       die.Clear();
1252     else
1253       die = die.GetSibling();
1254   }
1255   return blocks_added;
1256 }
1257 
1258 bool SymbolFileDWARF::ClassOrStructIsVirtual(const DWARFDIE &parent_die) {
1259   if (parent_die) {
1260     for (DWARFDIE die = parent_die.GetFirstChild(); die;
1261          die = die.GetSibling()) {
1262       dw_tag_t tag = die.Tag();
1263       bool check_virtuality = false;
1264       switch (tag) {
1265       case DW_TAG_inheritance:
1266       case DW_TAG_subprogram:
1267         check_virtuality = true;
1268         break;
1269       default:
1270         break;
1271       }
1272       if (check_virtuality) {
1273         if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0)
1274           return true;
1275       }
1276     }
1277   }
1278   return false;
1279 }
1280 
1281 void SymbolFileDWARF::ParseDeclsForContext(CompilerDeclContext decl_ctx) {
1282   TypeSystem *type_system = decl_ctx.GetTypeSystem();
1283   DWARFASTParser *ast_parser = type_system->GetDWARFParser();
1284   std::vector<DWARFDIE> decl_ctx_die_list =
1285       ast_parser->GetDIEForDeclContext(decl_ctx);
1286 
1287   for (DWARFDIE decl_ctx_die : decl_ctx_die_list)
1288     for (DWARFDIE decl = decl_ctx_die.GetFirstChild(); decl;
1289          decl = decl.GetSibling())
1290       ast_parser->GetDeclForUIDFromDWARF(decl);
1291 }
1292 
1293 SymbolFileDWARF *SymbolFileDWARF::GetDWARFForUID(lldb::user_id_t uid) {
1294   // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we
1295   // must make sure we use the correct DWARF file when resolving things. On
1296   // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1297   // SymbolFileDWARF classes, one for each .o file. We can often end up with
1298   // references to other DWARF objects and we must be ready to receive a
1299   // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1300   // instance.
1301   SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile();
1302   if (debug_map)
1303     return debug_map->GetSymbolFileByOSOIndex(
1304         debug_map->GetOSOIndexFromUserID(uid));
1305   return this;
1306 }
1307 
1308 DWARFDIE
1309 SymbolFileDWARF::GetDIEFromUID(lldb::user_id_t uid) {
1310   // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we
1311   // must make sure we use the correct DWARF file when resolving things. On
1312   // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1313   // SymbolFileDWARF classes, one for each .o file. We can often end up with
1314   // references to other DWARF objects and we must be ready to receive a
1315   // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1316   // instance.
1317   SymbolFileDWARF *dwarf = GetDWARFForUID(uid);
1318   if (dwarf)
1319     return dwarf->GetDIE(DIERef(uid, dwarf));
1320   return DWARFDIE();
1321 }
1322 
1323 CompilerDecl SymbolFileDWARF::GetDeclForUID(lldb::user_id_t type_uid) {
1324   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1325   // SymbolFileDWARF::GetDIEFromUID(). See comments inside the
1326   // SymbolFileDWARF::GetDIEFromUID() for details.
1327   DWARFDIE die = GetDIEFromUID(type_uid);
1328   if (die)
1329     return die.GetDecl();
1330   return CompilerDecl();
1331 }
1332 
1333 CompilerDeclContext
1334 SymbolFileDWARF::GetDeclContextForUID(lldb::user_id_t type_uid) {
1335   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1336   // SymbolFileDWARF::GetDIEFromUID(). See comments inside the
1337   // SymbolFileDWARF::GetDIEFromUID() for details.
1338   DWARFDIE die = GetDIEFromUID(type_uid);
1339   if (die)
1340     return die.GetDeclContext();
1341   return CompilerDeclContext();
1342 }
1343 
1344 CompilerDeclContext
1345 SymbolFileDWARF::GetDeclContextContainingUID(lldb::user_id_t type_uid) {
1346   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1347   // SymbolFileDWARF::GetDIEFromUID(). See comments inside the
1348   // SymbolFileDWARF::GetDIEFromUID() for details.
1349   DWARFDIE die = GetDIEFromUID(type_uid);
1350   if (die)
1351     return die.GetContainingDeclContext();
1352   return CompilerDeclContext();
1353 }
1354 
1355 Type *SymbolFileDWARF::ResolveTypeUID(lldb::user_id_t type_uid) {
1356   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1357   // SymbolFileDWARF::GetDIEFromUID(). See comments inside the
1358   // SymbolFileDWARF::GetDIEFromUID() for details.
1359   DWARFDIE type_die = GetDIEFromUID(type_uid);
1360   if (type_die)
1361     return type_die.ResolveType();
1362   else
1363     return nullptr;
1364 }
1365 
1366 Type *SymbolFileDWARF::ResolveTypeUID(const DIERef &die_ref) {
1367   return ResolveType(GetDIE(die_ref), true);
1368 }
1369 
1370 Type *SymbolFileDWARF::ResolveTypeUID(const DWARFDIE &die,
1371                                       bool assert_not_being_parsed) {
1372   if (die) {
1373     Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
1374     if (log)
1375       GetObjectFile()->GetModule()->LogMessage(
1376           log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
1377           die.GetOffset(), die.GetTagAsCString(), die.GetName());
1378 
1379     // We might be coming in in the middle of a type tree (a class within a
1380     // class, an enum within a class), so parse any needed parent DIEs before
1381     // we get to this one...
1382     DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die);
1383     if (decl_ctx_die) {
1384       if (log) {
1385         switch (decl_ctx_die.Tag()) {
1386         case DW_TAG_structure_type:
1387         case DW_TAG_union_type:
1388         case DW_TAG_class_type: {
1389           // Get the type, which could be a forward declaration
1390           if (log)
1391             GetObjectFile()->GetModule()->LogMessage(
1392                 log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' "
1393                      "resolve parent forward type for 0x%8.8x",
1394                 die.GetOffset(), die.GetTagAsCString(), die.GetName(),
1395                 decl_ctx_die.GetOffset());
1396         } break;
1397 
1398         default:
1399           break;
1400         }
1401       }
1402     }
1403     return ResolveType(die);
1404   }
1405   return NULL;
1406 }
1407 
1408 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
1409 // SymbolFileDWARF objects to detect if this DWARF file is the one that can
1410 // resolve a compiler_type.
1411 bool SymbolFileDWARF::HasForwardDeclForClangType(
1412     const CompilerType &compiler_type) {
1413   CompilerType compiler_type_no_qualifiers =
1414       ClangUtil::RemoveFastQualifiers(compiler_type);
1415   if (GetForwardDeclClangTypeToDie().count(
1416           compiler_type_no_qualifiers.GetOpaqueQualType())) {
1417     return true;
1418   }
1419   TypeSystem *type_system = compiler_type.GetTypeSystem();
1420 
1421   ClangASTContext *clang_type_system =
1422       llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1423   if (!clang_type_system)
1424     return false;
1425   DWARFASTParserClang *ast_parser =
1426       static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1427   return ast_parser->GetClangASTImporter().CanImport(compiler_type);
1428 }
1429 
1430 bool SymbolFileDWARF::CompleteType(CompilerType &compiler_type) {
1431   std::lock_guard<std::recursive_mutex> guard(
1432       GetObjectFile()->GetModule()->GetMutex());
1433 
1434   ClangASTContext *clang_type_system =
1435       llvm::dyn_cast_or_null<ClangASTContext>(compiler_type.GetTypeSystem());
1436   if (clang_type_system) {
1437     DWARFASTParserClang *ast_parser =
1438         static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1439     if (ast_parser &&
1440         ast_parser->GetClangASTImporter().CanImport(compiler_type))
1441       return ast_parser->GetClangASTImporter().CompleteType(compiler_type);
1442   }
1443 
1444   // We have a struct/union/class/enum that needs to be fully resolved.
1445   CompilerType compiler_type_no_qualifiers =
1446       ClangUtil::RemoveFastQualifiers(compiler_type);
1447   auto die_it = GetForwardDeclClangTypeToDie().find(
1448       compiler_type_no_qualifiers.GetOpaqueQualType());
1449   if (die_it == GetForwardDeclClangTypeToDie().end()) {
1450     // We have already resolved this type...
1451     return true;
1452   }
1453 
1454   DWARFDIE dwarf_die = GetDIE(die_it->getSecond());
1455   if (dwarf_die) {
1456     // Once we start resolving this type, remove it from the forward
1457     // declaration map in case anyone child members or other types require this
1458     // type to get resolved. The type will get resolved when all of the calls
1459     // to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition are done.
1460     GetForwardDeclClangTypeToDie().erase(die_it);
1461 
1462     Type *type = GetDIEToType().lookup(dwarf_die.GetDIE());
1463 
1464     Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO |
1465                                           DWARF_LOG_TYPE_COMPLETION));
1466     if (log)
1467       GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
1468           log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
1469           dwarf_die.GetID(), dwarf_die.GetTagAsCString(),
1470           type->GetName().AsCString());
1471     assert(compiler_type);
1472     DWARFASTParser *dwarf_ast = dwarf_die.GetDWARFParser();
1473     if (dwarf_ast)
1474       return dwarf_ast->CompleteTypeFromDWARF(dwarf_die, type, compiler_type);
1475   }
1476   return false;
1477 }
1478 
1479 Type *SymbolFileDWARF::ResolveType(const DWARFDIE &die,
1480                                    bool assert_not_being_parsed,
1481                                    bool resolve_function_context) {
1482   if (die) {
1483     Type *type = GetTypeForDIE(die, resolve_function_context).get();
1484 
1485     if (assert_not_being_parsed) {
1486       if (type != DIE_IS_BEING_PARSED)
1487         return type;
1488 
1489       GetObjectFile()->GetModule()->ReportError(
1490           "Parsing a die that is being parsed die: 0x%8.8x: %s %s",
1491           die.GetOffset(), die.GetTagAsCString(), die.GetName());
1492 
1493     } else
1494       return type;
1495   }
1496   return nullptr;
1497 }
1498 
1499 CompileUnit *
1500 SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFUnit *dwarf_cu,
1501                                              uint32_t cu_idx) {
1502   // Check if the symbol vendor already knows about this compile unit?
1503   if (dwarf_cu->GetUserData() == NULL) {
1504     // The symbol vendor doesn't know about this compile unit, we need to parse
1505     // and add it to the symbol vendor object.
1506     return ParseCompileUnit(dwarf_cu, cu_idx).get();
1507   }
1508   return (CompileUnit *)dwarf_cu->GetUserData();
1509 }
1510 
1511 size_t SymbolFileDWARF::GetObjCMethodDIEOffsets(ConstString class_name,
1512                                                 DIEArray &method_die_offsets) {
1513   method_die_offsets.clear();
1514   m_index->GetObjCMethods(class_name, method_die_offsets);
1515   return method_die_offsets.size();
1516 }
1517 
1518 bool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) {
1519   sc.Clear(false);
1520 
1521   if (die) {
1522     // Check if the symbol vendor already knows about this compile unit?
1523     sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
1524 
1525     sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
1526     if (sc.function == NULL)
1527       sc.function = ParseCompileUnitFunction(sc, die);
1528 
1529     if (sc.function) {
1530       sc.module_sp = sc.function->CalculateSymbolContextModule();
1531       return true;
1532     }
1533   }
1534 
1535   return false;
1536 }
1537 
1538 lldb::ModuleSP SymbolFileDWARF::GetDWOModule(ConstString name) {
1539   UpdateExternalModuleListIfNeeded();
1540   const auto &pos = m_external_type_modules.find(name);
1541   if (pos != m_external_type_modules.end())
1542     return pos->second;
1543   else
1544     return lldb::ModuleSP();
1545 }
1546 
1547 DWARFDIE
1548 SymbolFileDWARF::GetDIE(const DIERef &die_ref) {
1549   DWARFDebugInfo *debug_info = DebugInfo();
1550   if (debug_info)
1551     return debug_info->GetDIE(die_ref);
1552   else
1553     return DWARFDIE();
1554 }
1555 
1556 std::unique_ptr<SymbolFileDWARFDwo>
1557 SymbolFileDWARF::GetDwoSymbolFileForCompileUnit(
1558     DWARFUnit &dwarf_cu, const DWARFDebugInfoEntry &cu_die) {
1559   // If we are using a dSYM file, we never want the standard DWO files since
1560   // the -gmodules support uses the same DWO machanism to specify full debug
1561   // info files for modules.
1562   if (GetDebugMapSymfile())
1563     return nullptr;
1564 
1565   const char *dwo_name = cu_die.GetAttributeValueAsString(
1566       this, &dwarf_cu, DW_AT_GNU_dwo_name, nullptr);
1567   if (!dwo_name)
1568     return nullptr;
1569 
1570   SymbolFileDWARFDwp *dwp_symfile = GetDwpSymbolFile();
1571   if (dwp_symfile) {
1572     uint64_t dwo_id = cu_die.GetAttributeValueAsUnsigned(this, &dwarf_cu,
1573                                                          DW_AT_GNU_dwo_id, 0);
1574     std::unique_ptr<SymbolFileDWARFDwo> dwo_symfile =
1575         dwp_symfile->GetSymbolFileForDwoId(&dwarf_cu, dwo_id);
1576     if (dwo_symfile)
1577       return dwo_symfile;
1578   }
1579 
1580   FileSpec dwo_file(dwo_name, true);
1581   if (dwo_file.IsRelative()) {
1582     const char *comp_dir = cu_die.GetAttributeValueAsString(
1583         this, &dwarf_cu, DW_AT_comp_dir, nullptr);
1584     if (!comp_dir)
1585       return nullptr;
1586 
1587     dwo_file.SetFile(comp_dir, true);
1588     dwo_file.AppendPathComponent(dwo_name);
1589   }
1590 
1591   if (!dwo_file.Exists())
1592     return nullptr;
1593 
1594   const lldb::offset_t file_offset = 0;
1595   DataBufferSP dwo_file_data_sp;
1596   lldb::offset_t dwo_file_data_offset = 0;
1597   ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin(
1598       GetObjectFile()->GetModule(), &dwo_file, file_offset,
1599       dwo_file.GetByteSize(), dwo_file_data_sp, dwo_file_data_offset);
1600   if (dwo_obj_file == nullptr)
1601     return nullptr;
1602 
1603   return llvm::make_unique<SymbolFileDWARFDwo>(dwo_obj_file, &dwarf_cu);
1604 }
1605 
1606 void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() {
1607   if (m_fetched_external_modules)
1608     return;
1609   m_fetched_external_modules = true;
1610 
1611   DWARFDebugInfo *debug_info = DebugInfo();
1612 
1613   const uint32_t num_compile_units = GetNumCompileUnits();
1614   for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
1615     DWARFUnit *dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
1616 
1617     const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
1618     if (die && die.HasChildren() == false) {
1619       const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
1620 
1621       if (name) {
1622         ConstString const_name(name);
1623         if (m_external_type_modules.find(const_name) ==
1624             m_external_type_modules.end()) {
1625           ModuleSP module_sp;
1626           const char *dwo_path =
1627               die.GetAttributeValueAsString(DW_AT_GNU_dwo_name, nullptr);
1628           if (dwo_path) {
1629             ModuleSpec dwo_module_spec;
1630             dwo_module_spec.GetFileSpec().SetFile(dwo_path, false);
1631             if (dwo_module_spec.GetFileSpec().IsRelative()) {
1632               const char *comp_dir =
1633                   die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr);
1634               if (comp_dir) {
1635                 dwo_module_spec.GetFileSpec().SetFile(comp_dir, true);
1636                 dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path);
1637               }
1638             }
1639             dwo_module_spec.GetArchitecture() =
1640                 m_obj_file->GetModule()->GetArchitecture();
1641 
1642             // When LLDB loads "external" modules it looks at the presence of
1643             // DW_AT_GNU_dwo_name. However, when the already created module
1644             // (corresponding to .dwo itself) is being processed, it will see
1645             // the presence of DW_AT_GNU_dwo_name (which contains the name of
1646             // dwo file) and will try to call ModuleList::GetSharedModule
1647             // again. In some cases (i.e. for empty files) Clang 4.0 generates
1648             // a *.dwo file which has DW_AT_GNU_dwo_name, but no
1649             // DW_AT_comp_dir. In this case the method
1650             // ModuleList::GetSharedModule will fail and the warning will be
1651             // printed. However, as one can notice in this case we don't
1652             // actually need to try to load the already loaded module
1653             // (corresponding to .dwo) so we simply skip it.
1654             if (m_obj_file->GetFileSpec()
1655                         .GetFileNameExtension()
1656                         .GetStringRef() == "dwo" &&
1657                 llvm::StringRef(m_obj_file->GetFileSpec().GetPath())
1658                     .endswith(dwo_module_spec.GetFileSpec().GetPath())) {
1659               continue;
1660             }
1661 
1662             Status error = ModuleList::GetSharedModule(
1663                 dwo_module_spec, module_sp, NULL, NULL, NULL);
1664             if (!module_sp) {
1665               GetObjectFile()->GetModule()->ReportWarning(
1666                   "0x%8.8x: unable to locate module needed for external types: "
1667                   "%s\nerror: %s\nDebugging will be degraded due to missing "
1668                   "types. Rebuilding your project will regenerate the needed "
1669                   "module files.",
1670                   die.GetOffset(),
1671                   dwo_module_spec.GetFileSpec().GetPath().c_str(),
1672                   error.AsCString("unknown error"));
1673             }
1674           }
1675           m_external_type_modules[const_name] = module_sp;
1676         }
1677       }
1678     }
1679   }
1680 }
1681 
1682 SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() {
1683   if (!m_global_aranges_ap) {
1684     m_global_aranges_ap.reset(new GlobalVariableMap());
1685 
1686     ModuleSP module_sp = GetObjectFile()->GetModule();
1687     if (module_sp) {
1688       const size_t num_cus = module_sp->GetNumCompileUnits();
1689       for (size_t i = 0; i < num_cus; ++i) {
1690         CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
1691         if (cu_sp) {
1692           VariableListSP globals_sp = cu_sp->GetVariableList(true);
1693           if (globals_sp) {
1694             const size_t num_globals = globals_sp->GetSize();
1695             for (size_t g = 0; g < num_globals; ++g) {
1696               VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
1697               if (var_sp && !var_sp->GetLocationIsConstantValueData()) {
1698                 const DWARFExpression &location = var_sp->LocationExpression();
1699                 Value location_result;
1700                 Status error;
1701                 if (location.Evaluate(nullptr, LLDB_INVALID_ADDRESS, nullptr,
1702                                       nullptr, location_result, &error)) {
1703                   if (location_result.GetValueType() ==
1704                       Value::eValueTypeFileAddress) {
1705                     lldb::addr_t file_addr =
1706                         location_result.GetScalar().ULongLong();
1707                     lldb::addr_t byte_size = 1;
1708                     if (var_sp->GetType())
1709                       byte_size = var_sp->GetType()->GetByteSize();
1710                     m_global_aranges_ap->Append(GlobalVariableMap::Entry(
1711                         file_addr, byte_size, var_sp.get()));
1712                   }
1713                 }
1714               }
1715             }
1716           }
1717         }
1718       }
1719     }
1720     m_global_aranges_ap->Sort();
1721   }
1722   return *m_global_aranges_ap;
1723 }
1724 
1725 uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr,
1726                                                uint32_t resolve_scope,
1727                                                SymbolContext &sc) {
1728   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1729   Timer scoped_timer(func_cat,
1730                      "SymbolFileDWARF::"
1731                      "ResolveSymbolContext (so_addr = { "
1732                      "section = %p, offset = 0x%" PRIx64
1733                      " }, resolve_scope = 0x%8.8x)",
1734                      static_cast<void *>(so_addr.GetSection().get()),
1735                      so_addr.GetOffset(), resolve_scope);
1736   uint32_t resolved = 0;
1737   if (resolve_scope &
1738       (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock |
1739        eSymbolContextLineEntry | eSymbolContextVariable)) {
1740     lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1741 
1742     DWARFDebugInfo *debug_info = DebugInfo();
1743     if (debug_info) {
1744       const dw_offset_t cu_offset =
1745           debug_info->GetCompileUnitAranges().FindAddress(file_vm_addr);
1746       if (cu_offset == DW_INVALID_OFFSET) {
1747         // Global variables are not in the compile unit address ranges. The
1748         // only way to currently find global variables is to iterate over the
1749         // .debug_pubnames or the __apple_names table and find all items in
1750         // there that point to DW_TAG_variable DIEs and then find the address
1751         // that matches.
1752         if (resolve_scope & eSymbolContextVariable) {
1753           GlobalVariableMap &map = GetGlobalAranges();
1754           const GlobalVariableMap::Entry *entry =
1755               map.FindEntryThatContains(file_vm_addr);
1756           if (entry && entry->data) {
1757             Variable *variable = entry->data;
1758             SymbolContextScope *scc = variable->GetSymbolContextScope();
1759             if (scc) {
1760               scc->CalculateSymbolContext(&sc);
1761               sc.variable = variable;
1762             }
1763             return sc.GetResolvedMask();
1764           }
1765         }
1766       } else {
1767         uint32_t cu_idx = DW_INVALID_INDEX;
1768         DWARFUnit *dwarf_cu =
1769             debug_info->GetCompileUnit(cu_offset, &cu_idx);
1770         if (dwarf_cu) {
1771           sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
1772           if (sc.comp_unit) {
1773             resolved |= eSymbolContextCompUnit;
1774 
1775             bool force_check_line_table = false;
1776             if (resolve_scope &
1777                 (eSymbolContextFunction | eSymbolContextBlock)) {
1778               DWARFDIE function_die = dwarf_cu->LookupAddress(file_vm_addr);
1779               DWARFDIE block_die;
1780               if (function_die) {
1781                 sc.function =
1782                     sc.comp_unit->FindFunctionByUID(function_die.GetID()).get();
1783                 if (sc.function == NULL)
1784                   sc.function = ParseCompileUnitFunction(sc, function_die);
1785 
1786                 if (sc.function && (resolve_scope & eSymbolContextBlock))
1787                   block_die = function_die.LookupDeepestBlock(file_vm_addr);
1788               } else {
1789                 // We might have had a compile unit that had discontiguous
1790                 // address ranges where the gaps are symbols that don't have
1791                 // any debug info. Discontiguous compile unit address ranges
1792                 // should only happen when there aren't other functions from
1793                 // other compile units in these gaps. This helps keep the size
1794                 // of the aranges down.
1795                 force_check_line_table = true;
1796               }
1797 
1798               if (sc.function != NULL) {
1799                 resolved |= eSymbolContextFunction;
1800 
1801                 if (resolve_scope & eSymbolContextBlock) {
1802                   Block &block = sc.function->GetBlock(true);
1803 
1804                   if (block_die)
1805                     sc.block = block.FindBlockByID(block_die.GetID());
1806                   else
1807                     sc.block = block.FindBlockByID(function_die.GetID());
1808                   if (sc.block)
1809                     resolved |= eSymbolContextBlock;
1810                 }
1811               }
1812             }
1813 
1814             if ((resolve_scope & eSymbolContextLineEntry) ||
1815                 force_check_line_table) {
1816               LineTable *line_table = sc.comp_unit->GetLineTable();
1817               if (line_table != NULL) {
1818                 // And address that makes it into this function should be in
1819                 // terms of this debug file if there is no debug map, or it
1820                 // will be an address in the .o file which needs to be fixed up
1821                 // to be in terms of the debug map executable. Either way,
1822                 // calling FixupAddress() will work for us.
1823                 Address exe_so_addr(so_addr);
1824                 if (FixupAddress(exe_so_addr)) {
1825                   if (line_table->FindLineEntryByAddress(exe_so_addr,
1826                                                          sc.line_entry)) {
1827                     resolved |= eSymbolContextLineEntry;
1828                   }
1829                 }
1830               }
1831             }
1832 
1833             if (force_check_line_table &&
1834                 !(resolved & eSymbolContextLineEntry)) {
1835               // We might have had a compile unit that had discontiguous
1836               // address ranges where the gaps are symbols that don't have any
1837               // debug info. Discontiguous compile unit address ranges should
1838               // only happen when there aren't other functions from other
1839               // compile units in these gaps. This helps keep the size of the
1840               // aranges down.
1841               sc.comp_unit = NULL;
1842               resolved &= ~eSymbolContextCompUnit;
1843             }
1844           } else {
1845             GetObjectFile()->GetModule()->ReportWarning(
1846                 "0x%8.8x: compile unit %u failed to create a valid "
1847                 "lldb_private::CompileUnit class.",
1848                 cu_offset, cu_idx);
1849           }
1850         }
1851       }
1852     }
1853   }
1854   return resolved;
1855 }
1856 
1857 uint32_t SymbolFileDWARF::ResolveSymbolContext(const FileSpec &file_spec,
1858                                                uint32_t line,
1859                                                bool check_inlines,
1860                                                uint32_t resolve_scope,
1861                                                SymbolContextList &sc_list) {
1862   const uint32_t prev_size = sc_list.GetSize();
1863   if (resolve_scope & eSymbolContextCompUnit) {
1864     DWARFDebugInfo *debug_info = DebugInfo();
1865     if (debug_info) {
1866       uint32_t cu_idx;
1867       DWARFUnit *dwarf_cu = NULL;
1868 
1869       for (cu_idx = 0;
1870            (dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx)) != NULL;
1871            ++cu_idx) {
1872         CompileUnit *dc_cu = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
1873         const bool full_match = (bool)file_spec.GetDirectory();
1874         bool file_spec_matches_cu_file_spec =
1875             dc_cu != NULL && FileSpec::Equal(file_spec, *dc_cu, full_match);
1876         if (check_inlines || file_spec_matches_cu_file_spec) {
1877           SymbolContext sc(m_obj_file->GetModule());
1878           sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
1879           if (sc.comp_unit) {
1880             uint32_t file_idx = UINT32_MAX;
1881 
1882             // If we are looking for inline functions only and we don't find it
1883             // in the support files, we are done.
1884             if (check_inlines) {
1885               file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex(
1886                   1, file_spec, true);
1887               if (file_idx == UINT32_MAX)
1888                 continue;
1889             }
1890 
1891             if (line != 0) {
1892               LineTable *line_table = sc.comp_unit->GetLineTable();
1893 
1894               if (line_table != NULL && line != 0) {
1895                 // We will have already looked up the file index if we are
1896                 // searching for inline entries.
1897                 if (!check_inlines)
1898                   file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex(
1899                       1, file_spec, true);
1900 
1901                 if (file_idx != UINT32_MAX) {
1902                   uint32_t found_line;
1903                   uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex(
1904                       0, file_idx, line, false, &sc.line_entry);
1905                   found_line = sc.line_entry.line;
1906 
1907                   while (line_idx != UINT32_MAX) {
1908                     sc.function = NULL;
1909                     sc.block = NULL;
1910                     if (resolve_scope &
1911                         (eSymbolContextFunction | eSymbolContextBlock)) {
1912                       const lldb::addr_t file_vm_addr =
1913                           sc.line_entry.range.GetBaseAddress().GetFileAddress();
1914                       if (file_vm_addr != LLDB_INVALID_ADDRESS) {
1915                         DWARFDIE function_die =
1916                             dwarf_cu->LookupAddress(file_vm_addr);
1917                         DWARFDIE block_die;
1918                         if (function_die) {
1919                           sc.function =
1920                               sc.comp_unit
1921                                   ->FindFunctionByUID(function_die.GetID())
1922                                   .get();
1923                           if (sc.function == NULL)
1924                             sc.function =
1925                                 ParseCompileUnitFunction(sc, function_die);
1926 
1927                           if (sc.function &&
1928                               (resolve_scope & eSymbolContextBlock))
1929                             block_die =
1930                                 function_die.LookupDeepestBlock(file_vm_addr);
1931                         }
1932 
1933                         if (sc.function != NULL) {
1934                           Block &block = sc.function->GetBlock(true);
1935 
1936                           if (block_die)
1937                             sc.block = block.FindBlockByID(block_die.GetID());
1938                           else if (function_die)
1939                             sc.block =
1940                                 block.FindBlockByID(function_die.GetID());
1941                         }
1942                       }
1943                     }
1944 
1945                     sc_list.Append(sc);
1946                     line_idx = line_table->FindLineEntryIndexByFileIndex(
1947                         line_idx + 1, file_idx, found_line, true,
1948                         &sc.line_entry);
1949                   }
1950                 }
1951               } else if (file_spec_matches_cu_file_spec && !check_inlines) {
1952                 // only append the context if we aren't looking for inline call
1953                 // sites by file and line and if the file spec matches that of
1954                 // the compile unit
1955                 sc_list.Append(sc);
1956               }
1957             } else if (file_spec_matches_cu_file_spec && !check_inlines) {
1958               // only append the context if we aren't looking for inline call
1959               // sites by file and line and if the file spec matches that of
1960               // the compile unit
1961               sc_list.Append(sc);
1962             }
1963 
1964             if (!check_inlines)
1965               break;
1966           }
1967         }
1968       }
1969     }
1970   }
1971   return sc_list.GetSize() - prev_size;
1972 }
1973 
1974 void SymbolFileDWARF::PreloadSymbols() {
1975   std::lock_guard<std::recursive_mutex> guard(
1976       GetObjectFile()->GetModule()->GetMutex());
1977   m_index->Preload();
1978 }
1979 
1980 bool SymbolFileDWARF::DeclContextMatchesThisSymbolFile(
1981     const lldb_private::CompilerDeclContext *decl_ctx) {
1982   if (decl_ctx == nullptr || !decl_ctx->IsValid()) {
1983     // Invalid namespace decl which means we aren't matching only things in
1984     // this symbol file, so return true to indicate it matches this symbol
1985     // file.
1986     return true;
1987   }
1988 
1989   TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
1990   TypeSystem *type_system = GetTypeSystemForLanguage(
1991       decl_ctx_type_system->GetMinimumLanguage(nullptr));
1992   if (decl_ctx_type_system == type_system)
1993     return true; // The type systems match, return true
1994 
1995   // The namespace AST was valid, and it does not match...
1996   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
1997 
1998   if (log)
1999     GetObjectFile()->GetModule()->LogMessage(
2000         log, "Valid namespace does not match symbol file");
2001 
2002   return false;
2003 }
2004 
2005 uint32_t SymbolFileDWARF::FindGlobalVariables(
2006     const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
2007     uint32_t max_matches, VariableList &variables) {
2008   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2009 
2010   if (log)
2011     GetObjectFile()->GetModule()->LogMessage(
2012         log,
2013         "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2014         "parent_decl_ctx=%p, max_matches=%u, variables)",
2015         name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2016         max_matches);
2017 
2018   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2019     return 0;
2020 
2021   DWARFDebugInfo *info = DebugInfo();
2022   if (info == NULL)
2023     return 0;
2024 
2025   // Remember how many variables are in the list before we search.
2026   const uint32_t original_size = variables.GetSize();
2027 
2028   llvm::StringRef basename;
2029   llvm::StringRef context;
2030 
2031   if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(),
2032                                                       context, basename))
2033     basename = name.GetStringRef();
2034 
2035   DIEArray die_offsets;
2036   m_index->GetGlobalVariables(ConstString(basename), die_offsets);
2037   const size_t num_die_matches = die_offsets.size();
2038   if (num_die_matches) {
2039     SymbolContext sc;
2040     sc.module_sp = m_obj_file->GetModule();
2041     assert(sc.module_sp);
2042 
2043     // Loop invariant: Variables up to this index have been checked for context
2044     // matches.
2045     uint32_t pruned_idx = original_size;
2046 
2047     bool done = false;
2048     for (size_t i = 0; i < num_die_matches && !done; ++i) {
2049       const DIERef &die_ref = die_offsets[i];
2050       DWARFDIE die = GetDIE(die_ref);
2051 
2052       if (die) {
2053         switch (die.Tag()) {
2054         default:
2055         case DW_TAG_subprogram:
2056         case DW_TAG_inlined_subroutine:
2057         case DW_TAG_try_block:
2058         case DW_TAG_catch_block:
2059           break;
2060 
2061         case DW_TAG_variable: {
2062           sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
2063 
2064           if (parent_decl_ctx) {
2065             DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2066             if (dwarf_ast) {
2067               CompilerDeclContext actual_parent_decl_ctx =
2068                   dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2069               if (!actual_parent_decl_ctx ||
2070                   actual_parent_decl_ctx != *parent_decl_ctx)
2071                 continue;
2072             }
2073           }
2074 
2075           ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false,
2076                          &variables);
2077           while (pruned_idx < variables.GetSize()) {
2078             VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx);
2079             if (var_sp->GetName().GetStringRef().contains(name.GetStringRef()))
2080               ++pruned_idx;
2081             else
2082               variables.RemoveVariableAtIndex(pruned_idx);
2083           }
2084 
2085           if (variables.GetSize() - original_size >= max_matches)
2086             done = true;
2087         } break;
2088         }
2089       } else {
2090         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2091                                         name.GetStringRef());
2092       }
2093     }
2094   }
2095 
2096   // Return the number of variable that were appended to the list
2097   const uint32_t num_matches = variables.GetSize() - original_size;
2098   if (log && num_matches > 0) {
2099     GetObjectFile()->GetModule()->LogMessage(
2100         log,
2101         "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2102         "parent_decl_ctx=%p, max_matches=%u, variables) => %u",
2103         name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2104         max_matches, num_matches);
2105   }
2106   return num_matches;
2107 }
2108 
2109 uint32_t SymbolFileDWARF::FindGlobalVariables(const RegularExpression &regex,
2110                                               uint32_t max_matches,
2111                                               VariableList &variables) {
2112   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2113 
2114   if (log) {
2115     GetObjectFile()->GetModule()->LogMessage(
2116         log,
2117         "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", "
2118         "max_matches=%u, variables)",
2119         regex.GetText().str().c_str(), max_matches);
2120   }
2121 
2122   DWARFDebugInfo *info = DebugInfo();
2123   if (info == NULL)
2124     return 0;
2125 
2126   // Remember how many variables are in the list before we search.
2127   const uint32_t original_size = variables.GetSize();
2128 
2129   DIEArray die_offsets;
2130   m_index->GetGlobalVariables(regex, die_offsets);
2131 
2132   SymbolContext sc;
2133   sc.module_sp = m_obj_file->GetModule();
2134   assert(sc.module_sp);
2135 
2136   const size_t num_matches = die_offsets.size();
2137   if (num_matches) {
2138     for (size_t i = 0; i < num_matches; ++i) {
2139       const DIERef &die_ref = die_offsets[i];
2140       DWARFDIE die = GetDIE(die_ref);
2141 
2142       if (die) {
2143         sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
2144 
2145         ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2146 
2147         if (variables.GetSize() - original_size >= max_matches)
2148           break;
2149       } else
2150         m_index->ReportInvalidDIEOffset(die_ref.die_offset, regex.GetText());
2151     }
2152   }
2153 
2154   // Return the number of variable that were appended to the list
2155   return variables.GetSize() - original_size;
2156 }
2157 
2158 bool SymbolFileDWARF::ResolveFunction(const DIERef &die_ref,
2159                                       bool include_inlines,
2160                                       SymbolContextList &sc_list) {
2161   DWARFDIE die = DebugInfo()->GetDIE(die_ref);
2162   return ResolveFunction(die, include_inlines, sc_list);
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   for (DIERef ref : offsets)
2339     ResolveFunction(ref, include_inlines, sc_list);
2340 
2341   // Return the number of variable that were appended to the list
2342   return sc_list.GetSize() - original_size;
2343 }
2344 
2345 void SymbolFileDWARF::GetMangledNamesForFunction(
2346     const std::string &scope_qualified_name,
2347     std::vector<ConstString> &mangled_names) {
2348   DWARFDebugInfo *info = DebugInfo();
2349   uint32_t num_comp_units = 0;
2350   if (info)
2351     num_comp_units = info->GetNumCompileUnits();
2352 
2353   for (uint32_t i = 0; i < num_comp_units; i++) {
2354     DWARFUnit *cu = info->GetCompileUnitAtIndex(i);
2355     if (cu == nullptr)
2356       continue;
2357 
2358     SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
2359     if (dwo)
2360       dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
2361   }
2362 
2363   NameToOffsetMap::iterator iter =
2364       m_function_scope_qualified_name_map.find(scope_qualified_name);
2365   if (iter == m_function_scope_qualified_name_map.end())
2366     return;
2367 
2368   DIERefSetSP set_sp = (*iter).second;
2369   std::set<DIERef>::iterator set_iter;
2370   for (set_iter = set_sp->begin(); set_iter != set_sp->end(); set_iter++) {
2371     DWARFDIE die = DebugInfo()->GetDIE(*set_iter);
2372     mangled_names.push_back(ConstString(die.GetMangledName()));
2373   }
2374 }
2375 
2376 uint32_t SymbolFileDWARF::FindTypes(
2377     const SymbolContext &sc, const ConstString &name,
2378     const CompilerDeclContext *parent_decl_ctx, bool append,
2379     uint32_t max_matches,
2380     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
2381     TypeMap &types) {
2382   // If we aren't appending the results to this list, then clear the list
2383   if (!append)
2384     types.Clear();
2385 
2386   // Make sure we haven't already searched this SymbolFile before...
2387   if (searched_symbol_files.count(this))
2388     return 0;
2389   else
2390     searched_symbol_files.insert(this);
2391 
2392   DWARFDebugInfo *info = DebugInfo();
2393   if (info == NULL)
2394     return 0;
2395 
2396   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2397 
2398   if (log) {
2399     if (parent_decl_ctx)
2400       GetObjectFile()->GetModule()->LogMessage(
2401           log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2402                "%p (\"%s\"), append=%u, max_matches=%u, type_list)",
2403           name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2404           parent_decl_ctx->GetName().AsCString("<NULL>"), append, max_matches);
2405     else
2406       GetObjectFile()->GetModule()->LogMessage(
2407           log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2408                "NULL, append=%u, max_matches=%u, type_list)",
2409           name.GetCString(), append, max_matches);
2410   }
2411 
2412   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2413     return 0;
2414 
2415   DIEArray die_offsets;
2416   m_index->GetTypes(name, die_offsets);
2417   const size_t num_die_matches = die_offsets.size();
2418 
2419   if (num_die_matches) {
2420     const uint32_t initial_types_size = types.GetSize();
2421     for (size_t i = 0; i < num_die_matches; ++i) {
2422       const DIERef &die_ref = die_offsets[i];
2423       DWARFDIE die = GetDIE(die_ref);
2424 
2425       if (die) {
2426         if (!DIEInDeclContext(parent_decl_ctx, die))
2427           continue; // The containing decl contexts don't match
2428 
2429         Type *matching_type = ResolveType(die, true, true);
2430         if (matching_type) {
2431           // We found a type pointer, now find the shared pointer form our type
2432           // list
2433           types.InsertUnique(matching_type->shared_from_this());
2434           if (types.GetSize() >= max_matches)
2435             break;
2436         }
2437       } else {
2438         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2439                                         name.GetStringRef());
2440       }
2441     }
2442     const uint32_t num_matches = types.GetSize() - initial_types_size;
2443     if (log && num_matches) {
2444       if (parent_decl_ctx) {
2445         GetObjectFile()->GetModule()->LogMessage(
2446             log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2447                  "= %p (\"%s\"), append=%u, max_matches=%u, type_list) => %u",
2448             name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2449             parent_decl_ctx->GetName().AsCString("<NULL>"), append, max_matches,
2450             num_matches);
2451       } else {
2452         GetObjectFile()->GetModule()->LogMessage(
2453             log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2454                  "= NULL, append=%u, max_matches=%u, type_list) => %u",
2455             name.GetCString(), append, max_matches, num_matches);
2456       }
2457     }
2458     return num_matches;
2459   } else {
2460     UpdateExternalModuleListIfNeeded();
2461 
2462     for (const auto &pair : m_external_type_modules) {
2463       ModuleSP external_module_sp = pair.second;
2464       if (external_module_sp) {
2465         SymbolVendor *sym_vendor = external_module_sp->GetSymbolVendor();
2466         if (sym_vendor) {
2467           const uint32_t num_external_matches =
2468               sym_vendor->FindTypes(sc, name, parent_decl_ctx, append,
2469                                     max_matches, searched_symbol_files, types);
2470           if (num_external_matches)
2471             return num_external_matches;
2472         }
2473       }
2474     }
2475   }
2476 
2477   return 0;
2478 }
2479 
2480 size_t SymbolFileDWARF::FindTypes(const std::vector<CompilerContext> &context,
2481                                   bool append, TypeMap &types) {
2482   if (!append)
2483     types.Clear();
2484 
2485   if (context.empty())
2486     return 0;
2487 
2488   ConstString name = context.back().name;
2489 
2490   if (!name)
2491     return 0;
2492 
2493   DIEArray die_offsets;
2494   m_index->GetTypes(name, die_offsets);
2495   const size_t num_die_matches = die_offsets.size();
2496 
2497   if (num_die_matches) {
2498     size_t num_matches = 0;
2499     for (size_t i = 0; i < num_die_matches; ++i) {
2500       const DIERef &die_ref = die_offsets[i];
2501       DWARFDIE die = GetDIE(die_ref);
2502 
2503       if (die) {
2504         std::vector<CompilerContext> die_context;
2505         die.GetDWOContext(die_context);
2506         if (die_context != context)
2507           continue;
2508 
2509         Type *matching_type = ResolveType(die, true, true);
2510         if (matching_type) {
2511           // We found a type pointer, now find the shared pointer form our type
2512           // list
2513           types.InsertUnique(matching_type->shared_from_this());
2514           ++num_matches;
2515         }
2516       } else {
2517         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2518                                         name.GetStringRef());
2519       }
2520     }
2521     return num_matches;
2522   }
2523   return 0;
2524 }
2525 
2526 CompilerDeclContext
2527 SymbolFileDWARF::FindNamespace(const SymbolContext &sc, const ConstString &name,
2528                                const CompilerDeclContext *parent_decl_ctx) {
2529   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2530 
2531   if (log) {
2532     GetObjectFile()->GetModule()->LogMessage(
2533         log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
2534         name.GetCString());
2535   }
2536 
2537   CompilerDeclContext namespace_decl_ctx;
2538 
2539   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2540     return namespace_decl_ctx;
2541 
2542   DWARFDebugInfo *info = DebugInfo();
2543   if (info) {
2544     DIEArray die_offsets;
2545     m_index->GetNamespaces(name, die_offsets);
2546     const size_t num_matches = die_offsets.size();
2547     if (num_matches) {
2548       for (size_t i = 0; i < num_matches; ++i) {
2549         const DIERef &die_ref = die_offsets[i];
2550         DWARFDIE die = GetDIE(die_ref);
2551 
2552         if (die) {
2553           if (!DIEInDeclContext(parent_decl_ctx, die))
2554             continue; // The containing decl contexts don't match
2555 
2556           DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2557           if (dwarf_ast) {
2558             namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
2559             if (namespace_decl_ctx)
2560               break;
2561           }
2562         } else {
2563           m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2564                                           name.GetStringRef());
2565         }
2566       }
2567     }
2568   }
2569   if (log && namespace_decl_ctx) {
2570     GetObjectFile()->GetModule()->LogMessage(
2571         log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => "
2572              "CompilerDeclContext(%p/%p) \"%s\"",
2573         name.GetCString(),
2574         static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
2575         static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
2576         namespace_decl_ctx.GetName().AsCString("<NULL>"));
2577   }
2578 
2579   return namespace_decl_ctx;
2580 }
2581 
2582 TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
2583                                       bool resolve_function_context) {
2584   TypeSP type_sp;
2585   if (die) {
2586     Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
2587     if (type_ptr == NULL) {
2588       CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(die.GetCU());
2589       assert(lldb_cu);
2590       SymbolContext sc(lldb_cu);
2591       const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
2592       while (parent_die != nullptr) {
2593         if (parent_die->Tag() == DW_TAG_subprogram)
2594           break;
2595         parent_die = parent_die->GetParent();
2596       }
2597       SymbolContext sc_backup = sc;
2598       if (resolve_function_context && parent_die != nullptr &&
2599           !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
2600         sc = sc_backup;
2601 
2602       type_sp = ParseType(sc, die, NULL);
2603     } else if (type_ptr != DIE_IS_BEING_PARSED) {
2604       // Grab the existing type from the master types lists
2605       type_sp = type_ptr->shared_from_this();
2606     }
2607   }
2608   return type_sp;
2609 }
2610 
2611 DWARFDIE
2612 SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
2613   if (orig_die) {
2614     DWARFDIE die = orig_die;
2615 
2616     while (die) {
2617       // If this is the original DIE that we are searching for a declaration
2618       // for, then don't look in the cache as we don't want our own decl
2619       // context to be our decl context...
2620       if (orig_die != die) {
2621         switch (die.Tag()) {
2622         case DW_TAG_compile_unit:
2623         case DW_TAG_partial_unit:
2624         case DW_TAG_namespace:
2625         case DW_TAG_structure_type:
2626         case DW_TAG_union_type:
2627         case DW_TAG_class_type:
2628         case DW_TAG_lexical_block:
2629         case DW_TAG_subprogram:
2630           return die;
2631         case DW_TAG_inlined_subroutine: {
2632           DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2633           if (abs_die) {
2634             return abs_die;
2635           }
2636           break;
2637         }
2638         default:
2639           break;
2640         }
2641       }
2642 
2643       DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
2644       if (spec_die) {
2645         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
2646         if (decl_ctx_die)
2647           return decl_ctx_die;
2648       }
2649 
2650       DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2651       if (abs_die) {
2652         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
2653         if (decl_ctx_die)
2654           return decl_ctx_die;
2655       }
2656 
2657       die = die.GetParent();
2658     }
2659   }
2660   return DWARFDIE();
2661 }
2662 
2663 Symbol *
2664 SymbolFileDWARF::GetObjCClassSymbol(const ConstString &objc_class_name) {
2665   Symbol *objc_class_symbol = NULL;
2666   if (m_obj_file) {
2667     Symtab *symtab = m_obj_file->GetSymtab();
2668     if (symtab) {
2669       objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
2670           objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
2671           Symtab::eVisibilityAny);
2672     }
2673   }
2674   return objc_class_symbol;
2675 }
2676 
2677 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If
2678 // they don't then we can end up looking through all class types for a complete
2679 // type and never find the full definition. We need to know if this attribute
2680 // is supported, so we determine this here and cache th result. We also need to
2681 // worry about the debug map
2682 // DWARF file
2683 // if we are doing darwin DWARF in .o file debugging.
2684 bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(
2685     DWARFUnit *cu) {
2686   if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) {
2687     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
2688     if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
2689       m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2690     else {
2691       DWARFDebugInfo *debug_info = DebugInfo();
2692       const uint32_t num_compile_units = GetNumCompileUnits();
2693       for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2694         DWARFUnit *dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
2695         if (dwarf_cu != cu &&
2696             dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) {
2697           m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2698           break;
2699         }
2700       }
2701     }
2702     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo &&
2703         GetDebugMapSymfile())
2704       return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this);
2705   }
2706   return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
2707 }
2708 
2709 // This function can be used when a DIE is found that is a forward declaration
2710 // DIE and we want to try and find a type that has the complete definition.
2711 TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE(
2712     const DWARFDIE &die, const ConstString &type_name,
2713     bool must_be_implementation) {
2714 
2715   TypeSP type_sp;
2716 
2717   if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
2718     return type_sp;
2719 
2720   DIEArray die_offsets;
2721   m_index->GetCompleteObjCClass(type_name, must_be_implementation, die_offsets);
2722 
2723   const size_t num_matches = die_offsets.size();
2724 
2725   if (num_matches) {
2726     for (size_t i = 0; i < num_matches; ++i) {
2727       const DIERef &die_ref = die_offsets[i];
2728       DWARFDIE type_die = GetDIE(die_ref);
2729 
2730       if (type_die) {
2731         bool try_resolving_type = false;
2732 
2733         // Don't try and resolve the DIE we are looking for with the DIE
2734         // itself!
2735         if (type_die != die) {
2736           switch (type_die.Tag()) {
2737           case DW_TAG_class_type:
2738           case DW_TAG_structure_type:
2739             try_resolving_type = true;
2740             break;
2741           default:
2742             break;
2743           }
2744         }
2745 
2746         if (try_resolving_type) {
2747           if (must_be_implementation &&
2748               type_die.Supports_DW_AT_APPLE_objc_complete_type())
2749             try_resolving_type = type_die.GetAttributeValueAsUnsigned(
2750                 DW_AT_APPLE_objc_complete_type, 0);
2751 
2752           if (try_resolving_type) {
2753             Type *resolved_type = ResolveType(type_die, false, true);
2754             if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2755               DEBUG_PRINTF("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
2756                            " (cu 0x%8.8" PRIx64 ")\n",
2757                            die.GetID(),
2758                            m_obj_file->GetFileSpec().GetFilename().AsCString(
2759                                "<Unknown>"),
2760                            type_die.GetID(), type_cu->GetID());
2761 
2762               if (die)
2763                 GetDIEToType()[die.GetDIE()] = resolved_type;
2764               type_sp = resolved_type->shared_from_this();
2765               break;
2766             }
2767           }
2768         }
2769       } else {
2770         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2771                                         type_name.GetStringRef());
2772       }
2773     }
2774   }
2775   return type_sp;
2776 }
2777 
2778 //----------------------------------------------------------------------
2779 // This function helps to ensure that the declaration contexts match for two
2780 // different DIEs. Often times debug information will refer to a forward
2781 // declaration of a type (the equivalent of "struct my_struct;". There will
2782 // often be a declaration of that type elsewhere that has the full definition.
2783 // When we go looking for the full type "my_struct", we will find one or more
2784 // matches in the accelerator tables and we will then need to make sure the
2785 // type was in the same declaration context as the original DIE. This function
2786 // can efficiently compare two DIEs and will return true when the declaration
2787 // context matches, and false when they don't.
2788 //----------------------------------------------------------------------
2789 bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1,
2790                                            const DWARFDIE &die2) {
2791   if (die1 == die2)
2792     return true;
2793 
2794   DWARFDIECollection decl_ctx_1;
2795   DWARFDIECollection decl_ctx_2;
2796   // The declaration DIE stack is a stack of the declaration context DIEs all
2797   // the way back to the compile unit. If a type "T" is declared inside a class
2798   // "B", and class "B" is declared inside a class "A" and class "A" is in a
2799   // namespace "lldb", and the namespace is in a compile unit, there will be a
2800   // stack of DIEs:
2801   //
2802   //   [0] DW_TAG_class_type for "B"
2803   //   [1] DW_TAG_class_type for "A"
2804   //   [2] DW_TAG_namespace  for "lldb"
2805   //   [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file.
2806   //
2807   // We grab both contexts and make sure that everything matches all the way
2808   // back to the compiler unit.
2809 
2810   // First lets grab the decl contexts for both DIEs
2811   die1.GetDeclContextDIEs(decl_ctx_1);
2812   die2.GetDeclContextDIEs(decl_ctx_2);
2813   // Make sure the context arrays have the same size, otherwise we are done
2814   const size_t count1 = decl_ctx_1.Size();
2815   const size_t count2 = decl_ctx_2.Size();
2816   if (count1 != count2)
2817     return false;
2818 
2819   // Make sure the DW_TAG values match all the way back up the compile unit. If
2820   // they don't, then we are done.
2821   DWARFDIE decl_ctx_die1;
2822   DWARFDIE decl_ctx_die2;
2823   size_t i;
2824   for (i = 0; i < count1; i++) {
2825     decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex(i);
2826     decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex(i);
2827     if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
2828       return false;
2829   }
2830 #if defined LLDB_CONFIGURATION_DEBUG
2831 
2832   // Make sure the top item in the decl context die array is always
2833   // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then
2834   // something went wrong in the DWARFDIE::GetDeclContextDIEs()
2835   // function.
2836   dw_tag_t cu_tag = decl_ctx_1.GetDIEAtIndex(count1 - 1).Tag();
2837   UNUSED_IF_ASSERT_DISABLED(cu_tag);
2838   assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit);
2839 
2840 #endif
2841   // Always skip the compile unit when comparing by only iterating up to "count
2842   // - 1". Here we compare the names as we go.
2843   for (i = 0; i < count1 - 1; i++) {
2844     decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex(i);
2845     decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex(i);
2846     const char *name1 = decl_ctx_die1.GetName();
2847     const char *name2 = decl_ctx_die2.GetName();
2848     // If the string was from a DW_FORM_strp, then the pointer will often be
2849     // the same!
2850     if (name1 == name2)
2851       continue;
2852 
2853     // Name pointers are not equal, so only compare the strings if both are not
2854     // NULL.
2855     if (name1 && name2) {
2856       // If the strings don't compare, we are done...
2857       if (strcmp(name1, name2) != 0)
2858         return false;
2859     } else {
2860       // One name was NULL while the other wasn't
2861       return false;
2862     }
2863   }
2864   // We made it through all of the checks and the declaration contexts are
2865   // equal.
2866   return true;
2867 }
2868 
2869 TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(
2870     const DWARFDeclContext &dwarf_decl_ctx) {
2871   TypeSP type_sp;
2872 
2873   const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
2874   if (dwarf_decl_ctx_count > 0) {
2875     const ConstString type_name(dwarf_decl_ctx[0].name);
2876     const dw_tag_t tag = dwarf_decl_ctx[0].tag;
2877 
2878     if (type_name) {
2879       Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION |
2880                                             DWARF_LOG_LOOKUPS));
2881       if (log) {
2882         GetObjectFile()->GetModule()->LogMessage(
2883             log, "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%"
2884                  "s, qualified-name='%s')",
2885             DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2886             dwarf_decl_ctx.GetQualifiedName());
2887       }
2888 
2889       DIEArray die_offsets;
2890       m_index->GetTypes(dwarf_decl_ctx, die_offsets);
2891       const size_t num_matches = die_offsets.size();
2892 
2893       // Get the type system that we are looking to find a type for. We will
2894       // use this to ensure any matches we find are in a language that this
2895       // type system supports
2896       const LanguageType language = dwarf_decl_ctx.GetLanguage();
2897       TypeSystem *type_system = (language == eLanguageTypeUnknown)
2898                                     ? nullptr
2899                                     : GetTypeSystemForLanguage(language);
2900 
2901       if (num_matches) {
2902         for (size_t i = 0; i < num_matches; ++i) {
2903           const DIERef &die_ref = die_offsets[i];
2904           DWARFDIE type_die = GetDIE(die_ref);
2905 
2906           if (type_die) {
2907             // Make sure type_die's langauge matches the type system we are
2908             // looking for. We don't want to find a "Foo" type from Java if we
2909             // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
2910             if (type_system &&
2911                 !type_system->SupportsLanguage(type_die.GetLanguage()))
2912               continue;
2913             bool try_resolving_type = false;
2914 
2915             // Don't try and resolve the DIE we are looking for with the DIE
2916             // itself!
2917             const dw_tag_t type_tag = type_die.Tag();
2918             // Make sure the tags match
2919             if (type_tag == tag) {
2920               // The tags match, lets try resolving this type
2921               try_resolving_type = true;
2922             } else {
2923               // The tags don't match, but we need to watch our for a forward
2924               // declaration for a struct and ("struct foo") ends up being a
2925               // class ("class foo { ... };") or vice versa.
2926               switch (type_tag) {
2927               case DW_TAG_class_type:
2928                 // We had a "class foo", see if we ended up with a "struct foo
2929                 // { ... };"
2930                 try_resolving_type = (tag == DW_TAG_structure_type);
2931                 break;
2932               case DW_TAG_structure_type:
2933                 // We had a "struct foo", see if we ended up with a "class foo
2934                 // { ... };"
2935                 try_resolving_type = (tag == DW_TAG_class_type);
2936                 break;
2937               default:
2938                 // Tags don't match, don't event try to resolve using this type
2939                 // whose name matches....
2940                 break;
2941               }
2942             }
2943 
2944             if (try_resolving_type) {
2945               DWARFDeclContext type_dwarf_decl_ctx;
2946               type_die.GetDWARFDeclContext(type_dwarf_decl_ctx);
2947 
2948               if (log) {
2949                 GetObjectFile()->GetModule()->LogMessage(
2950                     log, "SymbolFileDWARF::"
2951                          "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2952                          "qualified-name='%s') trying die=0x%8.8x (%s)",
2953                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2954                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2955                     type_dwarf_decl_ctx.GetQualifiedName());
2956               }
2957 
2958               // Make sure the decl contexts match all the way up
2959               if (dwarf_decl_ctx == type_dwarf_decl_ctx) {
2960                 Type *resolved_type = ResolveType(type_die, false);
2961                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2962                   type_sp = resolved_type->shared_from_this();
2963                   break;
2964                 }
2965               }
2966             } else {
2967               if (log) {
2968                 std::string qualified_name;
2969                 type_die.GetQualifiedName(qualified_name);
2970                 GetObjectFile()->GetModule()->LogMessage(
2971                     log, "SymbolFileDWARF::"
2972                          "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2973                          "qualified-name='%s') ignoring die=0x%8.8x (%s)",
2974                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2975                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2976                     qualified_name.c_str());
2977               }
2978             }
2979           } else {
2980             m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2981                                             type_name.GetStringRef());
2982           }
2983         }
2984       }
2985     }
2986   }
2987   return type_sp;
2988 }
2989 
2990 TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die,
2991                                   bool *type_is_new_ptr) {
2992   TypeSP type_sp;
2993 
2994   if (die) {
2995     TypeSystem *type_system =
2996         GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
2997 
2998     if (type_system) {
2999       DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
3000       if (dwarf_ast) {
3001         Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
3002         type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, log, type_is_new_ptr);
3003         if (type_sp) {
3004           TypeList *type_list = GetTypeList();
3005           if (type_list)
3006             type_list->Insert(type_sp);
3007 
3008           if (die.Tag() == DW_TAG_subprogram) {
3009             DIERef die_ref = die.GetDIERef();
3010             std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
3011                                                  .GetScopeQualifiedName()
3012                                                  .AsCString(""));
3013             if (scope_qualified_name.size()) {
3014               NameToOffsetMap::iterator iter =
3015                   m_function_scope_qualified_name_map.find(
3016                       scope_qualified_name);
3017               if (iter != m_function_scope_qualified_name_map.end())
3018                 (*iter).second->insert(die_ref);
3019               else {
3020                 DIERefSetSP new_set(new std::set<DIERef>);
3021                 new_set->insert(die_ref);
3022                 m_function_scope_qualified_name_map.emplace(
3023                     std::make_pair(scope_qualified_name, new_set));
3024               }
3025             }
3026           }
3027         }
3028       }
3029     }
3030   }
3031 
3032   return type_sp;
3033 }
3034 
3035 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc,
3036                                    const DWARFDIE &orig_die,
3037                                    bool parse_siblings, bool parse_children) {
3038   size_t types_added = 0;
3039   DWARFDIE die = orig_die;
3040   while (die) {
3041     bool type_is_new = false;
3042     if (ParseType(sc, die, &type_is_new).get()) {
3043       if (type_is_new)
3044         ++types_added;
3045     }
3046 
3047     if (parse_children && die.HasChildren()) {
3048       if (die.Tag() == DW_TAG_subprogram) {
3049         SymbolContext child_sc(sc);
3050         child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3051         types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3052       } else
3053         types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3054     }
3055 
3056     if (parse_siblings)
3057       die = die.GetSibling();
3058     else
3059       die.Clear();
3060   }
3061   return types_added;
3062 }
3063 
3064 size_t SymbolFileDWARF::ParseFunctionBlocks(const SymbolContext &sc) {
3065   assert(sc.comp_unit && sc.function);
3066   size_t functions_added = 0;
3067   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
3068   if (dwarf_cu) {
3069     const dw_offset_t function_die_offset = sc.function->GetID();
3070     DWARFDIE function_die = dwarf_cu->GetDIE(function_die_offset);
3071     if (function_die) {
3072       ParseFunctionBlocks(sc, &sc.function->GetBlock(false), function_die,
3073                           LLDB_INVALID_ADDRESS, 0);
3074     }
3075   }
3076 
3077   return functions_added;
3078 }
3079 
3080 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc) {
3081   // At least a compile unit must be valid
3082   assert(sc.comp_unit);
3083   size_t types_added = 0;
3084   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
3085   if (dwarf_cu) {
3086     if (sc.function) {
3087       dw_offset_t function_die_offset = sc.function->GetID();
3088       DWARFDIE func_die = dwarf_cu->GetDIE(function_die_offset);
3089       if (func_die && func_die.HasChildren()) {
3090         types_added = ParseTypes(sc, func_die.GetFirstChild(), true, true);
3091       }
3092     } else {
3093       DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3094       if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3095         types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3096       }
3097     }
3098   }
3099 
3100   return types_added;
3101 }
3102 
3103 size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) {
3104   if (sc.comp_unit != NULL) {
3105     DWARFDebugInfo *info = DebugInfo();
3106     if (info == NULL)
3107       return 0;
3108 
3109     if (sc.function) {
3110       DWARFDIE function_die = info->GetDIE(DIERef(sc.function->GetID(), this));
3111 
3112       const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress(
3113           DW_AT_low_pc, LLDB_INVALID_ADDRESS);
3114       if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3115         const size_t num_variables = ParseVariables(
3116             sc, function_die.GetFirstChild(), func_lo_pc, true, true);
3117 
3118         // Let all blocks know they have parse all their variables
3119         sc.function->GetBlock(false).SetDidParseVariables(true, true);
3120         return num_variables;
3121       }
3122     } else if (sc.comp_unit) {
3123       DWARFUnit *dwarf_cu = info->GetCompileUnit(sc.comp_unit->GetID());
3124 
3125       if (dwarf_cu == NULL)
3126         return 0;
3127 
3128       uint32_t vars_added = 0;
3129       VariableListSP variables(sc.comp_unit->GetVariableList(false));
3130 
3131       if (variables.get() == NULL) {
3132         variables.reset(new VariableList());
3133         sc.comp_unit->SetVariableList(variables);
3134 
3135         DIEArray die_offsets;
3136         m_index->GetGlobalVariables(*dwarf_cu, die_offsets);
3137         const size_t num_matches = die_offsets.size();
3138         if (num_matches) {
3139           for (size_t i = 0; i < num_matches; ++i) {
3140             const DIERef &die_ref = die_offsets[i];
3141             DWARFDIE die = GetDIE(die_ref);
3142             if (die) {
3143               VariableSP var_sp(
3144                   ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS));
3145               if (var_sp) {
3146                 variables->AddVariableIfUnique(var_sp);
3147                 ++vars_added;
3148               }
3149             } else
3150               m_index->ReportInvalidDIEOffset(die_ref.die_offset, "");
3151           }
3152         }
3153       }
3154       return vars_added;
3155     }
3156   }
3157   return 0;
3158 }
3159 
3160 VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc,
3161                                              const DWARFDIE &die,
3162                                              const lldb::addr_t func_low_pc) {
3163   if (die.GetDWARF() != this)
3164     return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3165 
3166   VariableSP var_sp;
3167   if (!die)
3168     return var_sp;
3169 
3170   var_sp = GetDIEToVariable()[die.GetDIE()];
3171   if (var_sp)
3172     return var_sp; // Already been parsed!
3173 
3174   const dw_tag_t tag = die.Tag();
3175   ModuleSP module = GetObjectFile()->GetModule();
3176 
3177   if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3178       (tag == DW_TAG_formal_parameter && sc.function)) {
3179     DWARFAttributes attributes;
3180     const size_t num_attributes = die.GetAttributes(attributes);
3181     DWARFDIE spec_die;
3182     if (num_attributes > 0) {
3183       const char *name = NULL;
3184       const char *mangled = NULL;
3185       Declaration decl;
3186       uint32_t i;
3187       DWARFFormValue type_die_form;
3188       DWARFExpression location(die.GetCU());
3189       bool is_external = false;
3190       bool is_artificial = false;
3191       bool location_is_const_value_data = false;
3192       bool has_explicit_location = false;
3193       DWARFFormValue const_value;
3194       Variable::RangeList scope_ranges;
3195       // AccessType accessibility = eAccessNone;
3196 
3197       for (i = 0; i < num_attributes; ++i) {
3198         dw_attr_t attr = attributes.AttributeAtIndex(i);
3199         DWARFFormValue form_value;
3200 
3201         if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3202           switch (attr) {
3203           case DW_AT_decl_file:
3204             decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3205                 form_value.Unsigned()));
3206             break;
3207           case DW_AT_decl_line:
3208             decl.SetLine(form_value.Unsigned());
3209             break;
3210           case DW_AT_decl_column:
3211             decl.SetColumn(form_value.Unsigned());
3212             break;
3213           case DW_AT_name:
3214             name = form_value.AsCString();
3215             break;
3216           case DW_AT_linkage_name:
3217           case DW_AT_MIPS_linkage_name:
3218             mangled = form_value.AsCString();
3219             break;
3220           case DW_AT_type:
3221             type_die_form = form_value;
3222             break;
3223           case DW_AT_external:
3224             is_external = form_value.Boolean();
3225             break;
3226           case DW_AT_const_value:
3227             // If we have already found a DW_AT_location attribute, ignore this
3228             // attribute.
3229             if (!has_explicit_location) {
3230               location_is_const_value_data = true;
3231               // The constant value will be either a block, a data value or a
3232               // string.
3233               auto debug_info_data = die.GetData();
3234               if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3235                 // Retrieve the value as a block expression.
3236                 uint32_t block_offset =
3237                     form_value.BlockData() - debug_info_data.GetDataStart();
3238                 uint32_t block_length = form_value.Unsigned();
3239                 location.CopyOpcodeData(module, debug_info_data, block_offset,
3240                                         block_length);
3241               } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3242                 // Retrieve the value as a data expression.
3243                 DWARFFormValue::FixedFormSizes fixed_form_sizes =
3244                     DWARFFormValue::GetFixedFormSizesForAddressSize(
3245                         attributes.CompileUnitAtIndex(i)->GetAddressByteSize(),
3246                         attributes.CompileUnitAtIndex(i)->IsDWARF64());
3247                 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3248                 uint32_t data_length =
3249                     fixed_form_sizes.GetSize(form_value.Form());
3250                 if (data_length == 0) {
3251                   const uint8_t *data_pointer = form_value.BlockData();
3252                   if (data_pointer) {
3253                     form_value.Unsigned();
3254                   } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3255                     // we need to get the byte size of the type later after we
3256                     // create the variable
3257                     const_value = form_value;
3258                   }
3259                 } else
3260                   location.CopyOpcodeData(module, debug_info_data, data_offset,
3261                                           data_length);
3262               } else {
3263                 // Retrieve the value as a string expression.
3264                 if (form_value.Form() == DW_FORM_strp) {
3265                   DWARFFormValue::FixedFormSizes fixed_form_sizes =
3266                       DWARFFormValue::GetFixedFormSizesForAddressSize(
3267                           attributes.CompileUnitAtIndex(i)
3268                               ->GetAddressByteSize(),
3269                           attributes.CompileUnitAtIndex(i)->IsDWARF64());
3270                   uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3271                   uint32_t data_length =
3272                       fixed_form_sizes.GetSize(form_value.Form());
3273                   location.CopyOpcodeData(module, debug_info_data, data_offset,
3274                                           data_length);
3275                 } else {
3276                   const char *str = form_value.AsCString();
3277                   uint32_t string_offset =
3278                       str - (const char *)debug_info_data.GetDataStart();
3279                   uint32_t string_length = strlen(str) + 1;
3280                   location.CopyOpcodeData(module, debug_info_data,
3281                                           string_offset, string_length);
3282                 }
3283               }
3284             }
3285             break;
3286           case DW_AT_location: {
3287             location_is_const_value_data = false;
3288             has_explicit_location = true;
3289             if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3290               auto data = die.GetData();
3291 
3292               uint32_t block_offset =
3293                   form_value.BlockData() - data.GetDataStart();
3294               uint32_t block_length = form_value.Unsigned();
3295               location.CopyOpcodeData(module, data, block_offset, block_length);
3296             } else {
3297               const DWARFDataExtractor &debug_loc_data = get_debug_loc_data();
3298               const dw_offset_t debug_loc_offset = form_value.Unsigned();
3299 
3300               size_t loc_list_length = DWARFExpression::LocationListSize(
3301                   die.GetCU(), debug_loc_data, debug_loc_offset);
3302               if (loc_list_length > 0) {
3303                 location.CopyOpcodeData(module, debug_loc_data,
3304                                         debug_loc_offset, loc_list_length);
3305                 assert(func_low_pc != LLDB_INVALID_ADDRESS);
3306                 location.SetLocationListSlide(
3307                     func_low_pc -
3308                     attributes.CompileUnitAtIndex(i)->GetBaseAddress());
3309               }
3310             }
3311           } break;
3312           case DW_AT_specification:
3313             spec_die = GetDIE(DIERef(form_value));
3314             break;
3315           case DW_AT_start_scope: {
3316             if (form_value.Form() == DW_FORM_sec_offset) {
3317               DWARFRangeList dwarf_scope_ranges;
3318               const DWARFDebugRanges *debug_ranges = DebugRanges();
3319               debug_ranges->FindRanges(die.GetCU()->GetRangesBase(),
3320                                        form_value.Unsigned(),
3321                                        dwarf_scope_ranges);
3322 
3323               // All DW_AT_start_scope are relative to the base address of the
3324               // compile unit. We add the compile unit base address to make
3325               // sure all the addresses are properly fixed up.
3326               for (size_t i = 0, count = dwarf_scope_ranges.GetSize();
3327                    i < count; ++i) {
3328                 const DWARFRangeList::Entry &range =
3329                     dwarf_scope_ranges.GetEntryRef(i);
3330                 scope_ranges.Append(range.GetRangeBase() +
3331                                         die.GetCU()->GetBaseAddress(),
3332                                     range.GetByteSize());
3333               }
3334             } else {
3335               // TODO: Handle the case when DW_AT_start_scope have form
3336               // constant. The
3337               // dwarf spec is a bit ambiguous about what is the expected
3338               // behavior in case the enclosing block have a non coninious
3339               // address range and the DW_AT_start_scope entry have a form
3340               // constant.
3341               GetObjectFile()->GetModule()->ReportWarning(
3342                   "0x%8.8" PRIx64
3343                   ": DW_AT_start_scope has unsupported form type (0x%x)\n",
3344                   die.GetID(), form_value.Form());
3345             }
3346 
3347             scope_ranges.Sort();
3348             scope_ranges.CombineConsecutiveRanges();
3349           } break;
3350           case DW_AT_artificial:
3351             is_artificial = form_value.Boolean();
3352             break;
3353           case DW_AT_accessibility:
3354             break; // accessibility =
3355                    // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
3356           case DW_AT_declaration:
3357           case DW_AT_description:
3358           case DW_AT_endianity:
3359           case DW_AT_segment:
3360           case DW_AT_visibility:
3361           default:
3362           case DW_AT_abstract_origin:
3363           case DW_AT_sibling:
3364             break;
3365           }
3366         }
3367       }
3368 
3369       const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3370       const dw_tag_t parent_tag = die.GetParent().Tag();
3371       bool is_static_member =
3372           (parent_tag == DW_TAG_compile_unit ||
3373            parent_tag == DW_TAG_partial_unit) &&
3374           (parent_context_die.Tag() == DW_TAG_class_type ||
3375            parent_context_die.Tag() == DW_TAG_structure_type);
3376 
3377       ValueType scope = eValueTypeInvalid;
3378 
3379       const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3380       SymbolContextScope *symbol_context_scope = NULL;
3381 
3382       bool has_explicit_mangled = mangled != nullptr;
3383       if (!mangled) {
3384         // LLDB relies on the mangled name (DW_TAG_linkage_name or
3385         // DW_AT_MIPS_linkage_name) to generate fully qualified names
3386         // of global variables with commands like "frame var j". For
3387         // example, if j were an int variable holding a value 4 and
3388         // declared in a namespace B which in turn is contained in a
3389         // namespace A, the command "frame var j" returns
3390         //   "(int) A::B::j = 4".
3391         // If the compiler does not emit a linkage name, we should be
3392         // able to generate a fully qualified name from the
3393         // declaration context.
3394         if ((parent_tag == DW_TAG_compile_unit ||
3395              parent_tag == DW_TAG_partial_unit) &&
3396             Language::LanguageIsCPlusPlus(die.GetLanguage())) {
3397           DWARFDeclContext decl_ctx;
3398 
3399           die.GetDWARFDeclContext(decl_ctx);
3400           mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString();
3401         }
3402       }
3403 
3404       if (tag == DW_TAG_formal_parameter)
3405         scope = eValueTypeVariableArgument;
3406       else {
3407         // DWARF doesn't specify if a DW_TAG_variable is a local, global
3408         // or static variable, so we have to do a little digging:
3409         // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3410         // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3411         // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3412         // Clang likes to combine small global variables into the same symbol
3413         // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3414         // so we need to look through the whole expression.
3415         bool is_static_lifetime =
3416             has_explicit_mangled ||
3417             (has_explicit_location && !location.IsValid());
3418         // Check if the location has a DW_OP_addr with any address value...
3419         lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3420         if (!location_is_const_value_data) {
3421           bool op_error = false;
3422           location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error);
3423           if (op_error) {
3424             StreamString strm;
3425             location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0,
3426                                             NULL);
3427             GetObjectFile()->GetModule()->ReportError(
3428                 "0x%8.8x: %s has an invalid location: %s", die.GetOffset(),
3429                 die.GetTagAsCString(), strm.GetData());
3430           }
3431           if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
3432             is_static_lifetime = true;
3433         }
3434         SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
3435 
3436         if (is_static_lifetime) {
3437           if (is_external)
3438             scope = eValueTypeVariableGlobal;
3439           else
3440             scope = eValueTypeVariableStatic;
3441 
3442           if (debug_map_symfile) {
3443             // When leaving the DWARF in the .o files on darwin, when we have a
3444             // global variable that wasn't initialized, the .o file might not
3445             // have allocated a virtual address for the global variable. In
3446             // this case it will have created a symbol for the global variable
3447             // that is undefined/data and external and the value will be the
3448             // byte size of the variable. When we do the address map in
3449             // SymbolFileDWARFDebugMap we rely on having an address, we need to
3450             // do some magic here so we can get the correct address for our
3451             // global variable. The address for all of these entries will be
3452             // zero, and there will be an undefined symbol in this object file,
3453             // and the executable will have a matching symbol with a good
3454             // address. So here we dig up the correct address and replace it in
3455             // the location for the variable, and set the variable's symbol
3456             // context scope to be that of the main executable so the file
3457             // address will resolve correctly.
3458             bool linked_oso_file_addr = false;
3459             if (is_external && location_DW_OP_addr == 0) {
3460               // we have a possible uninitialized extern global
3461               ConstString const_name(mangled ? mangled : name);
3462               ObjectFile *debug_map_objfile =
3463                   debug_map_symfile->GetObjectFile();
3464               if (debug_map_objfile) {
3465                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3466                 if (debug_map_symtab) {
3467                   Symbol *exe_symbol =
3468                       debug_map_symtab->FindFirstSymbolWithNameAndType(
3469                           const_name, eSymbolTypeData, Symtab::eDebugYes,
3470                           Symtab::eVisibilityExtern);
3471                   if (exe_symbol) {
3472                     if (exe_symbol->ValueIsAddress()) {
3473                       const addr_t exe_file_addr =
3474                           exe_symbol->GetAddressRef().GetFileAddress();
3475                       if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3476                         if (location.Update_DW_OP_addr(exe_file_addr)) {
3477                           linked_oso_file_addr = true;
3478                           symbol_context_scope = exe_symbol;
3479                         }
3480                       }
3481                     }
3482                   }
3483                 }
3484               }
3485             }
3486 
3487             if (!linked_oso_file_addr) {
3488               // The DW_OP_addr is not zero, but it contains a .o file address
3489               // which needs to be linked up correctly.
3490               const lldb::addr_t exe_file_addr =
3491                   debug_map_symfile->LinkOSOFileAddress(this,
3492                                                         location_DW_OP_addr);
3493               if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3494                 // Update the file address for this variable
3495                 location.Update_DW_OP_addr(exe_file_addr);
3496               } else {
3497                 // Variable didn't make it into the final executable
3498                 return var_sp;
3499               }
3500             }
3501           }
3502         } else {
3503           if (location_is_const_value_data)
3504             scope = eValueTypeVariableStatic;
3505           else {
3506             scope = eValueTypeVariableLocal;
3507             if (debug_map_symfile) {
3508               // We need to check for TLS addresses that we need to fixup
3509               if (location.ContainsThreadLocalStorage()) {
3510                 location.LinkThreadLocalStorage(
3511                     debug_map_symfile->GetObjectFile()->GetModule(),
3512                     [this, debug_map_symfile](
3513                         lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
3514                       return debug_map_symfile->LinkOSOFileAddress(
3515                           this, unlinked_file_addr);
3516                     });
3517                 scope = eValueTypeVariableThreadLocal;
3518               }
3519             }
3520           }
3521         }
3522       }
3523 
3524       if (symbol_context_scope == NULL) {
3525         switch (parent_tag) {
3526         case DW_TAG_subprogram:
3527         case DW_TAG_inlined_subroutine:
3528         case DW_TAG_lexical_block:
3529           if (sc.function) {
3530             symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(
3531                 sc_parent_die.GetID());
3532             if (symbol_context_scope == NULL)
3533               symbol_context_scope = sc.function;
3534           }
3535           break;
3536 
3537         default:
3538           symbol_context_scope = sc.comp_unit;
3539           break;
3540         }
3541       }
3542 
3543       if (symbol_context_scope) {
3544         SymbolFileTypeSP type_sp(
3545             new SymbolFileType(*this, DIERef(type_die_form).GetUID(this)));
3546 
3547         if (const_value.Form() && type_sp && type_sp->GetType())
3548           location.CopyOpcodeData(const_value.Unsigned(),
3549                                   type_sp->GetType()->GetByteSize(),
3550                                   die.GetCU()->GetAddressByteSize());
3551 
3552         var_sp.reset(new Variable(die.GetID(), name, mangled, type_sp, scope,
3553                                   symbol_context_scope, scope_ranges, &decl,
3554                                   location, is_external, is_artificial,
3555                                   is_static_member));
3556 
3557         var_sp->SetLocationIsConstantValueData(location_is_const_value_data);
3558       } else {
3559         // Not ready to parse this variable yet. It might be a global or static
3560         // variable that is in a function scope and the function in the symbol
3561         // context wasn't filled in yet
3562         return var_sp;
3563       }
3564     }
3565     // Cache var_sp even if NULL (the variable was just a specification or was
3566     // missing vital information to be able to be displayed in the debugger
3567     // (missing location due to optimization, etc)) so we don't re-parse this
3568     // DIE over and over later...
3569     GetDIEToVariable()[die.GetDIE()] = var_sp;
3570     if (spec_die)
3571       GetDIEToVariable()[spec_die.GetDIE()] = var_sp;
3572   }
3573   return var_sp;
3574 }
3575 
3576 DWARFDIE
3577 SymbolFileDWARF::FindBlockContainingSpecification(
3578     const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
3579   // Give the concrete function die specified by "func_die_offset", find the
3580   // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3581   // to "spec_block_die_offset"
3582   return FindBlockContainingSpecification(DebugInfo()->GetDIE(func_die_ref),
3583                                           spec_block_die_offset);
3584 }
3585 
3586 DWARFDIE
3587 SymbolFileDWARF::FindBlockContainingSpecification(
3588     const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
3589   if (die) {
3590     switch (die.Tag()) {
3591     case DW_TAG_subprogram:
3592     case DW_TAG_inlined_subroutine:
3593     case DW_TAG_lexical_block: {
3594       if (die.GetAttributeValueAsReference(
3595               DW_AT_specification, DW_INVALID_OFFSET) == spec_block_die_offset)
3596         return die;
3597 
3598       if (die.GetAttributeValueAsReference(DW_AT_abstract_origin,
3599                                            DW_INVALID_OFFSET) ==
3600           spec_block_die_offset)
3601         return die;
3602     } break;
3603     }
3604 
3605     // Give the concrete function die specified by "func_die_offset", find the
3606     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3607     // to "spec_block_die_offset"
3608     for (DWARFDIE child_die = die.GetFirstChild(); child_die;
3609          child_die = child_die.GetSibling()) {
3610       DWARFDIE result_die =
3611           FindBlockContainingSpecification(child_die, spec_block_die_offset);
3612       if (result_die)
3613         return result_die;
3614     }
3615   }
3616 
3617   return DWARFDIE();
3618 }
3619 
3620 size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc,
3621                                        const DWARFDIE &orig_die,
3622                                        const lldb::addr_t func_low_pc,
3623                                        bool parse_siblings, bool parse_children,
3624                                        VariableList *cc_variable_list) {
3625   if (!orig_die)
3626     return 0;
3627 
3628   VariableListSP variable_list_sp;
3629 
3630   size_t vars_added = 0;
3631   DWARFDIE die = orig_die;
3632   while (die) {
3633     dw_tag_t tag = die.Tag();
3634 
3635     // Check to see if we have already parsed this variable or constant?
3636     VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
3637     if (var_sp) {
3638       if (cc_variable_list)
3639         cc_variable_list->AddVariableIfUnique(var_sp);
3640     } else {
3641       // We haven't already parsed it, lets do that now.
3642       if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3643           (tag == DW_TAG_formal_parameter && sc.function)) {
3644         if (variable_list_sp.get() == NULL) {
3645           DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die);
3646           dw_tag_t parent_tag = sc_parent_die.Tag();
3647           switch (parent_tag) {
3648           case DW_TAG_compile_unit:
3649           case DW_TAG_partial_unit:
3650             if (sc.comp_unit != NULL) {
3651               variable_list_sp = sc.comp_unit->GetVariableList(false);
3652               if (variable_list_sp.get() == NULL) {
3653                 variable_list_sp.reset(new VariableList());
3654               }
3655             } else {
3656               GetObjectFile()->GetModule()->ReportError(
3657                   "parent 0x%8.8" PRIx64 " %s with no valid compile unit in "
3658                                          "symbol context for 0x%8.8" PRIx64
3659                   " %s.\n",
3660                   sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(),
3661                   orig_die.GetID(), orig_die.GetTagAsCString());
3662             }
3663             break;
3664 
3665           case DW_TAG_subprogram:
3666           case DW_TAG_inlined_subroutine:
3667           case DW_TAG_lexical_block:
3668             if (sc.function != NULL) {
3669               // Check to see if we already have parsed the variables for the
3670               // given scope
3671 
3672               Block *block = sc.function->GetBlock(true).FindBlockByID(
3673                   sc_parent_die.GetID());
3674               if (block == NULL) {
3675                 // This must be a specification or abstract origin with a
3676                 // concrete block counterpart in the current function. We need
3677                 // to find the concrete block so we can correctly add the
3678                 // variable to it
3679                 const DWARFDIE concrete_block_die =
3680                     FindBlockContainingSpecification(
3681                         DIERef(sc.function->GetID(), this),
3682                         sc_parent_die.GetOffset());
3683                 if (concrete_block_die)
3684                   block = sc.function->GetBlock(true).FindBlockByID(
3685                       concrete_block_die.GetID());
3686               }
3687 
3688               if (block != NULL) {
3689                 const bool can_create = false;
3690                 variable_list_sp = block->GetBlockVariableList(can_create);
3691                 if (variable_list_sp.get() == NULL) {
3692                   variable_list_sp.reset(new VariableList());
3693                   block->SetVariableList(variable_list_sp);
3694                 }
3695               }
3696             }
3697             break;
3698 
3699           default:
3700             GetObjectFile()->GetModule()->ReportError(
3701                 "didn't find appropriate parent DIE for variable list for "
3702                 "0x%8.8" PRIx64 " %s.\n",
3703                 orig_die.GetID(), orig_die.GetTagAsCString());
3704             break;
3705           }
3706         }
3707 
3708         if (variable_list_sp) {
3709           VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc));
3710           if (var_sp) {
3711             variable_list_sp->AddVariableIfUnique(var_sp);
3712             if (cc_variable_list)
3713               cc_variable_list->AddVariableIfUnique(var_sp);
3714             ++vars_added;
3715           }
3716         }
3717       }
3718     }
3719 
3720     bool skip_children = (sc.function == NULL && tag == DW_TAG_subprogram);
3721 
3722     if (!skip_children && parse_children && die.HasChildren()) {
3723       vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true,
3724                                    true, cc_variable_list);
3725     }
3726 
3727     if (parse_siblings)
3728       die = die.GetSibling();
3729     else
3730       die.Clear();
3731   }
3732   return vars_added;
3733 }
3734 
3735 //------------------------------------------------------------------
3736 // PluginInterface protocol
3737 //------------------------------------------------------------------
3738 ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); }
3739 
3740 uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; }
3741 
3742 void SymbolFileDWARF::Dump(lldb_private::Stream &s) { m_index->Dump(s); }
3743 
3744 SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() {
3745   if (m_debug_map_symfile == NULL && !m_debug_map_module_wp.expired()) {
3746     lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
3747     if (module_sp) {
3748       SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
3749       if (sym_vendor)
3750         m_debug_map_symfile =
3751             (SymbolFileDWARFDebugMap *)sym_vendor->GetSymbolFile();
3752     }
3753   }
3754   return m_debug_map_symfile;
3755 }
3756 
3757 DWARFExpression::LocationListFormat
3758 SymbolFileDWARF::GetLocationListFormat() const {
3759   return DWARFExpression::RegularLocationList;
3760 }
3761 
3762 SymbolFileDWARFDwp *SymbolFileDWARF::GetDwpSymbolFile() {
3763   llvm::call_once(m_dwp_symfile_once_flag, [this]() {
3764     ModuleSpec module_spec;
3765     module_spec.GetFileSpec() = m_obj_file->GetFileSpec();
3766     module_spec.GetSymbolFileSpec() =
3767         FileSpec(m_obj_file->GetFileSpec().GetPath() + ".dwp", false);
3768     FileSpec dwp_filespec = Symbols::LocateExecutableSymbolFile(module_spec);
3769     if (dwp_filespec.Exists()) {
3770       m_dwp_symfile = SymbolFileDWARFDwp::Create(GetObjectFile()->GetModule(),
3771                                                  dwp_filespec);
3772     }
3773   });
3774   return m_dwp_symfile.get();
3775 }
3776