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