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