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 Type *SymbolFileDWARF::ResolveTypeUID(const DIERef &die_ref) {
1419   return ResolveType(GetDIE(die_ref), true);
1420 }
1421 
1422 Type *SymbolFileDWARF::ResolveTypeUID(const DWARFDIE &die,
1423                                       bool assert_not_being_parsed) {
1424   if (die) {
1425     Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
1426     if (log)
1427       GetObjectFile()->GetModule()->LogMessage(
1428           log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
1429           die.GetOffset(), die.GetTagAsCString(), die.GetName());
1430 
1431     // We might be coming in in the middle of a type tree (a class within a
1432     // class, an enum within a class), so parse any needed parent DIEs before
1433     // we get to this one...
1434     DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die);
1435     if (decl_ctx_die) {
1436       if (log) {
1437         switch (decl_ctx_die.Tag()) {
1438         case DW_TAG_structure_type:
1439         case DW_TAG_union_type:
1440         case DW_TAG_class_type: {
1441           // Get the type, which could be a forward declaration
1442           if (log)
1443             GetObjectFile()->GetModule()->LogMessage(
1444                 log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' "
1445                      "resolve parent forward type for 0x%8.8x",
1446                 die.GetOffset(), die.GetTagAsCString(), die.GetName(),
1447                 decl_ctx_die.GetOffset());
1448         } break;
1449 
1450         default:
1451           break;
1452         }
1453       }
1454     }
1455     return ResolveType(die);
1456   }
1457   return NULL;
1458 }
1459 
1460 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
1461 // SymbolFileDWARF objects to detect if this DWARF file is the one that can
1462 // resolve a compiler_type.
1463 bool SymbolFileDWARF::HasForwardDeclForClangType(
1464     const CompilerType &compiler_type) {
1465   CompilerType compiler_type_no_qualifiers =
1466       ClangUtil::RemoveFastQualifiers(compiler_type);
1467   if (GetForwardDeclClangTypeToDie().count(
1468           compiler_type_no_qualifiers.GetOpaqueQualType())) {
1469     return true;
1470   }
1471   TypeSystem *type_system = compiler_type.GetTypeSystem();
1472 
1473   ClangASTContext *clang_type_system =
1474       llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1475   if (!clang_type_system)
1476     return false;
1477   DWARFASTParserClang *ast_parser =
1478       static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1479   return ast_parser->GetClangASTImporter().CanImport(compiler_type);
1480 }
1481 
1482 bool SymbolFileDWARF::CompleteType(CompilerType &compiler_type) {
1483   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1484 
1485   ClangASTContext *clang_type_system =
1486       llvm::dyn_cast_or_null<ClangASTContext>(compiler_type.GetTypeSystem());
1487   if (clang_type_system) {
1488     DWARFASTParserClang *ast_parser =
1489         static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1490     if (ast_parser &&
1491         ast_parser->GetClangASTImporter().CanImport(compiler_type))
1492       return ast_parser->GetClangASTImporter().CompleteType(compiler_type);
1493   }
1494 
1495   // We have a struct/union/class/enum that needs to be fully resolved.
1496   CompilerType compiler_type_no_qualifiers =
1497       ClangUtil::RemoveFastQualifiers(compiler_type);
1498   auto die_it = GetForwardDeclClangTypeToDie().find(
1499       compiler_type_no_qualifiers.GetOpaqueQualType());
1500   if (die_it == GetForwardDeclClangTypeToDie().end()) {
1501     // We have already resolved this type...
1502     return true;
1503   }
1504 
1505   DWARFDIE dwarf_die = GetDIE(die_it->getSecond());
1506   if (dwarf_die) {
1507     // Once we start resolving this type, remove it from the forward
1508     // declaration map in case anyone child members or other types require this
1509     // type to get resolved. The type will get resolved when all of the calls
1510     // to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition are done.
1511     GetForwardDeclClangTypeToDie().erase(die_it);
1512 
1513     Type *type = GetDIEToType().lookup(dwarf_die.GetDIE());
1514 
1515     Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO |
1516                                           DWARF_LOG_TYPE_COMPLETION));
1517     if (log)
1518       GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
1519           log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
1520           dwarf_die.GetID(), dwarf_die.GetTagAsCString(),
1521           type->GetName().AsCString());
1522     assert(compiler_type);
1523     DWARFASTParser *dwarf_ast = dwarf_die.GetDWARFParser();
1524     if (dwarf_ast)
1525       return dwarf_ast->CompleteTypeFromDWARF(dwarf_die, type, compiler_type);
1526   }
1527   return false;
1528 }
1529 
1530 Type *SymbolFileDWARF::ResolveType(const DWARFDIE &die,
1531                                    bool assert_not_being_parsed,
1532                                    bool resolve_function_context) {
1533   if (die) {
1534     Type *type = GetTypeForDIE(die, resolve_function_context).get();
1535 
1536     if (assert_not_being_parsed) {
1537       if (type != DIE_IS_BEING_PARSED)
1538         return type;
1539 
1540       GetObjectFile()->GetModule()->ReportError(
1541           "Parsing a die that is being parsed die: 0x%8.8x: %s %s",
1542           die.GetOffset(), die.GetTagAsCString(), die.GetName());
1543 
1544     } else
1545       return type;
1546   }
1547   return nullptr;
1548 }
1549 
1550 CompileUnit *
1551 SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFUnit *dwarf_cu,
1552                                              uint32_t cu_idx) {
1553   // Check if the symbol vendor already knows about this compile unit?
1554   if (dwarf_cu->GetUserData() == NULL) {
1555     // The symbol vendor doesn't know about this compile unit, we need to parse
1556     // and add it to the symbol vendor object.
1557     return ParseCompileUnit(dwarf_cu, cu_idx).get();
1558   }
1559   return (CompileUnit *)dwarf_cu->GetUserData();
1560 }
1561 
1562 size_t SymbolFileDWARF::GetObjCMethodDIEOffsets(ConstString class_name,
1563                                                 DIEArray &method_die_offsets) {
1564   method_die_offsets.clear();
1565   m_index->GetObjCMethods(class_name, method_die_offsets);
1566   return method_die_offsets.size();
1567 }
1568 
1569 bool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) {
1570   sc.Clear(false);
1571 
1572   if (die) {
1573     // Check if the symbol vendor already knows about this compile unit?
1574     sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
1575 
1576     sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
1577     if (sc.function == NULL)
1578       sc.function = ParseCompileUnitFunction(sc, die);
1579 
1580     if (sc.function) {
1581       sc.module_sp = sc.function->CalculateSymbolContextModule();
1582       return true;
1583     }
1584   }
1585 
1586   return false;
1587 }
1588 
1589 lldb::ModuleSP SymbolFileDWARF::GetDWOModule(ConstString name) {
1590   UpdateExternalModuleListIfNeeded();
1591   const auto &pos = m_external_type_modules.find(name);
1592   if (pos != m_external_type_modules.end())
1593     return pos->second;
1594   else
1595     return lldb::ModuleSP();
1596 }
1597 
1598 DWARFDIE
1599 SymbolFileDWARF::GetDIE(const DIERef &die_ref) {
1600   DWARFDebugInfo *debug_info = DebugInfo();
1601   if (debug_info)
1602     return debug_info->GetDIE(die_ref);
1603   else
1604     return DWARFDIE();
1605 }
1606 
1607 std::unique_ptr<SymbolFileDWARFDwo>
1608 SymbolFileDWARF::GetDwoSymbolFileForCompileUnit(
1609     DWARFUnit &dwarf_cu, const DWARFDebugInfoEntry &cu_die) {
1610   // If we are using a dSYM file, we never want the standard DWO files since
1611   // the -gmodules support uses the same DWO machanism to specify full debug
1612   // info files for modules.
1613   if (GetDebugMapSymfile())
1614     return nullptr;
1615 
1616   const char *dwo_name = cu_die.GetAttributeValueAsString(
1617       this, &dwarf_cu, DW_AT_GNU_dwo_name, nullptr);
1618   if (!dwo_name)
1619     return nullptr;
1620 
1621   SymbolFileDWARFDwp *dwp_symfile = GetDwpSymbolFile();
1622   if (dwp_symfile) {
1623     uint64_t dwo_id = cu_die.GetAttributeValueAsUnsigned(this, &dwarf_cu,
1624                                                          DW_AT_GNU_dwo_id, 0);
1625     std::unique_ptr<SymbolFileDWARFDwo> dwo_symfile =
1626         dwp_symfile->GetSymbolFileForDwoId(&dwarf_cu, dwo_id);
1627     if (dwo_symfile)
1628       return dwo_symfile;
1629   }
1630 
1631   FileSpec dwo_file(dwo_name);
1632   FileSystem::Instance().Resolve(dwo_file);
1633   if (dwo_file.IsRelative()) {
1634     const char *comp_dir = cu_die.GetAttributeValueAsString(
1635         this, &dwarf_cu, DW_AT_comp_dir, nullptr);
1636     if (!comp_dir)
1637       return nullptr;
1638 
1639     dwo_file.SetFile(comp_dir, FileSpec::Style::native);
1640     FileSystem::Instance().Resolve(dwo_file);
1641     dwo_file.AppendPathComponent(dwo_name);
1642   }
1643 
1644   if (!FileSystem::Instance().Exists(dwo_file))
1645     return nullptr;
1646 
1647   const lldb::offset_t file_offset = 0;
1648   DataBufferSP dwo_file_data_sp;
1649   lldb::offset_t dwo_file_data_offset = 0;
1650   ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin(
1651       GetObjectFile()->GetModule(), &dwo_file, file_offset,
1652       FileSystem::Instance().GetByteSize(dwo_file), dwo_file_data_sp,
1653       dwo_file_data_offset);
1654   if (dwo_obj_file == nullptr)
1655     return nullptr;
1656 
1657   return llvm::make_unique<SymbolFileDWARFDwo>(dwo_obj_file, &dwarf_cu);
1658 }
1659 
1660 void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() {
1661   if (m_fetched_external_modules)
1662     return;
1663   m_fetched_external_modules = true;
1664 
1665   DWARFDebugInfo *debug_info = DebugInfo();
1666 
1667   const uint32_t num_compile_units = GetNumCompileUnits();
1668   for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
1669     DWARFUnit *dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
1670 
1671     const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
1672     if (die && die.HasChildren() == false) {
1673       const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
1674 
1675       if (name) {
1676         ConstString const_name(name);
1677         if (m_external_type_modules.find(const_name) ==
1678             m_external_type_modules.end()) {
1679           ModuleSP module_sp;
1680           const char *dwo_path =
1681               die.GetAttributeValueAsString(DW_AT_GNU_dwo_name, nullptr);
1682           if (dwo_path) {
1683             ModuleSpec dwo_module_spec;
1684             dwo_module_spec.GetFileSpec().SetFile(dwo_path,
1685                                                   FileSpec::Style::native);
1686             if (dwo_module_spec.GetFileSpec().IsRelative()) {
1687               const char *comp_dir =
1688                   die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr);
1689               if (comp_dir) {
1690                 dwo_module_spec.GetFileSpec().SetFile(comp_dir,
1691                                                       FileSpec::Style::native);
1692                 FileSystem::Instance().Resolve(dwo_module_spec.GetFileSpec());
1693                 dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path);
1694               }
1695             }
1696             dwo_module_spec.GetArchitecture() =
1697                 m_obj_file->GetModule()->GetArchitecture();
1698 
1699             // When LLDB loads "external" modules it looks at the presence of
1700             // DW_AT_GNU_dwo_name. However, when the already created module
1701             // (corresponding to .dwo itself) is being processed, it will see
1702             // the presence of DW_AT_GNU_dwo_name (which contains the name of
1703             // dwo file) and will try to call ModuleList::GetSharedModule
1704             // again. In some cases (i.e. for empty files) Clang 4.0 generates
1705             // a *.dwo file which has DW_AT_GNU_dwo_name, but no
1706             // DW_AT_comp_dir. In this case the method
1707             // ModuleList::GetSharedModule will fail and the warning will be
1708             // printed. However, as one can notice in this case we don't
1709             // actually need to try to load the already loaded module
1710             // (corresponding to .dwo) so we simply skip it.
1711             if (m_obj_file->GetFileSpec()
1712                         .GetFileNameExtension()
1713                         .GetStringRef() == ".dwo" &&
1714                 llvm::StringRef(m_obj_file->GetFileSpec().GetPath())
1715                     .endswith(dwo_module_spec.GetFileSpec().GetPath())) {
1716               continue;
1717             }
1718 
1719             Status error = ModuleList::GetSharedModule(
1720                 dwo_module_spec, module_sp, NULL, NULL, NULL);
1721             if (!module_sp) {
1722               GetObjectFile()->GetModule()->ReportWarning(
1723                   "0x%8.8x: unable to locate module needed for external types: "
1724                   "%s\nerror: %s\nDebugging will be degraded due to missing "
1725                   "types. Rebuilding your project will regenerate the needed "
1726                   "module files.",
1727                   die.GetOffset(),
1728                   dwo_module_spec.GetFileSpec().GetPath().c_str(),
1729                   error.AsCString("unknown error"));
1730             }
1731           }
1732           m_external_type_modules[const_name] = module_sp;
1733         }
1734       }
1735     }
1736   }
1737 }
1738 
1739 SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() {
1740   if (!m_global_aranges_ap) {
1741     m_global_aranges_ap.reset(new GlobalVariableMap());
1742 
1743     ModuleSP module_sp = GetObjectFile()->GetModule();
1744     if (module_sp) {
1745       const size_t num_cus = module_sp->GetNumCompileUnits();
1746       for (size_t i = 0; i < num_cus; ++i) {
1747         CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
1748         if (cu_sp) {
1749           VariableListSP globals_sp = cu_sp->GetVariableList(true);
1750           if (globals_sp) {
1751             const size_t num_globals = globals_sp->GetSize();
1752             for (size_t g = 0; g < num_globals; ++g) {
1753               VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
1754               if (var_sp && !var_sp->GetLocationIsConstantValueData()) {
1755                 const DWARFExpression &location = var_sp->LocationExpression();
1756                 Value location_result;
1757                 Status error;
1758                 if (location.Evaluate(nullptr, LLDB_INVALID_ADDRESS, nullptr,
1759                                       nullptr, location_result, &error)) {
1760                   if (location_result.GetValueType() ==
1761                       Value::eValueTypeFileAddress) {
1762                     lldb::addr_t file_addr =
1763                         location_result.GetScalar().ULongLong();
1764                     lldb::addr_t byte_size = 1;
1765                     if (var_sp->GetType())
1766                       byte_size = var_sp->GetType()->GetByteSize();
1767                     m_global_aranges_ap->Append(GlobalVariableMap::Entry(
1768                         file_addr, byte_size, var_sp.get()));
1769                   }
1770                 }
1771               }
1772             }
1773           }
1774         }
1775       }
1776     }
1777     m_global_aranges_ap->Sort();
1778   }
1779   return *m_global_aranges_ap;
1780 }
1781 
1782 uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr,
1783                                                SymbolContextItem resolve_scope,
1784                                                SymbolContext &sc) {
1785   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1786   Timer scoped_timer(func_cat,
1787                      "SymbolFileDWARF::"
1788                      "ResolveSymbolContext (so_addr = { "
1789                      "section = %p, offset = 0x%" PRIx64
1790                      " }, resolve_scope = 0x%8.8x)",
1791                      static_cast<void *>(so_addr.GetSection().get()),
1792                      so_addr.GetOffset(), resolve_scope);
1793   uint32_t resolved = 0;
1794   if (resolve_scope &
1795       (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock |
1796        eSymbolContextLineEntry | eSymbolContextVariable)) {
1797     lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1798 
1799     DWARFDebugInfo *debug_info = DebugInfo();
1800     if (debug_info) {
1801       const dw_offset_t cu_offset =
1802           debug_info->GetCompileUnitAranges().FindAddress(file_vm_addr);
1803       if (cu_offset == DW_INVALID_OFFSET) {
1804         // Global variables are not in the compile unit address ranges. The
1805         // only way to currently find global variables is to iterate over the
1806         // .debug_pubnames or the __apple_names table and find all items in
1807         // there that point to DW_TAG_variable DIEs and then find the address
1808         // that matches.
1809         if (resolve_scope & eSymbolContextVariable) {
1810           GlobalVariableMap &map = GetGlobalAranges();
1811           const GlobalVariableMap::Entry *entry =
1812               map.FindEntryThatContains(file_vm_addr);
1813           if (entry && entry->data) {
1814             Variable *variable = entry->data;
1815             SymbolContextScope *scc = variable->GetSymbolContextScope();
1816             if (scc) {
1817               scc->CalculateSymbolContext(&sc);
1818               sc.variable = variable;
1819             }
1820             return sc.GetResolvedMask();
1821           }
1822         }
1823       } else {
1824         uint32_t cu_idx = DW_INVALID_INDEX;
1825         DWARFUnit *dwarf_cu =
1826             debug_info->GetCompileUnit(cu_offset, &cu_idx);
1827         if (dwarf_cu) {
1828           sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
1829           if (sc.comp_unit) {
1830             resolved |= eSymbolContextCompUnit;
1831 
1832             bool force_check_line_table = false;
1833             if (resolve_scope &
1834                 (eSymbolContextFunction | eSymbolContextBlock)) {
1835               DWARFDIE function_die = dwarf_cu->LookupAddress(file_vm_addr);
1836               DWARFDIE block_die;
1837               if (function_die) {
1838                 sc.function =
1839                     sc.comp_unit->FindFunctionByUID(function_die.GetID()).get();
1840                 if (sc.function == NULL)
1841                   sc.function = ParseCompileUnitFunction(sc, function_die);
1842 
1843                 if (sc.function && (resolve_scope & eSymbolContextBlock))
1844                   block_die = function_die.LookupDeepestBlock(file_vm_addr);
1845               } else {
1846                 // We might have had a compile unit that had discontiguous
1847                 // address ranges where the gaps are symbols that don't have
1848                 // any debug info. Discontiguous compile unit address ranges
1849                 // should only happen when there aren't other functions from
1850                 // other compile units in these gaps. This helps keep the size
1851                 // of the aranges down.
1852                 force_check_line_table = true;
1853               }
1854 
1855               if (sc.function != NULL) {
1856                 resolved |= eSymbolContextFunction;
1857 
1858                 if (resolve_scope & eSymbolContextBlock) {
1859                   Block &block = sc.function->GetBlock(true);
1860 
1861                   if (block_die)
1862                     sc.block = block.FindBlockByID(block_die.GetID());
1863                   else
1864                     sc.block = block.FindBlockByID(function_die.GetID());
1865                   if (sc.block)
1866                     resolved |= eSymbolContextBlock;
1867                 }
1868               }
1869             }
1870 
1871             if ((resolve_scope & eSymbolContextLineEntry) ||
1872                 force_check_line_table) {
1873               LineTable *line_table = sc.comp_unit->GetLineTable();
1874               if (line_table != NULL) {
1875                 // And address that makes it into this function should be in
1876                 // terms of this debug file if there is no debug map, or it
1877                 // will be an address in the .o file which needs to be fixed up
1878                 // to be in terms of the debug map executable. Either way,
1879                 // calling FixupAddress() will work for us.
1880                 Address exe_so_addr(so_addr);
1881                 if (FixupAddress(exe_so_addr)) {
1882                   if (line_table->FindLineEntryByAddress(exe_so_addr,
1883                                                          sc.line_entry)) {
1884                     resolved |= eSymbolContextLineEntry;
1885                   }
1886                 }
1887               }
1888             }
1889 
1890             if (force_check_line_table &&
1891                 !(resolved & eSymbolContextLineEntry)) {
1892               // We might have had a compile unit that had discontiguous
1893               // address ranges where the gaps are symbols that don't have any
1894               // debug info. Discontiguous compile unit address ranges should
1895               // only happen when there aren't other functions from other
1896               // compile units in these gaps. This helps keep the size of the
1897               // aranges down.
1898               sc.comp_unit = NULL;
1899               resolved &= ~eSymbolContextCompUnit;
1900             }
1901           } else {
1902             GetObjectFile()->GetModule()->ReportWarning(
1903                 "0x%8.8x: compile unit %u failed to create a valid "
1904                 "lldb_private::CompileUnit class.",
1905                 cu_offset, cu_idx);
1906           }
1907         }
1908       }
1909     }
1910   }
1911   return resolved;
1912 }
1913 
1914 uint32_t SymbolFileDWARF::ResolveSymbolContext(const FileSpec &file_spec,
1915                                                uint32_t line,
1916                                                bool check_inlines,
1917                                                SymbolContextItem resolve_scope,
1918                                                SymbolContextList &sc_list) {
1919   const uint32_t prev_size = sc_list.GetSize();
1920   if (resolve_scope & eSymbolContextCompUnit) {
1921     DWARFDebugInfo *debug_info = DebugInfo();
1922     if (debug_info) {
1923       uint32_t cu_idx;
1924       DWARFUnit *dwarf_cu = NULL;
1925 
1926       for (cu_idx = 0;
1927            (dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx)) != NULL;
1928            ++cu_idx) {
1929         CompileUnit *dc_cu = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
1930         const bool full_match = (bool)file_spec.GetDirectory();
1931         bool file_spec_matches_cu_file_spec =
1932             dc_cu != NULL && FileSpec::Equal(file_spec, *dc_cu, full_match);
1933         if (check_inlines || file_spec_matches_cu_file_spec) {
1934           SymbolContext sc(m_obj_file->GetModule());
1935           sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
1936           if (sc.comp_unit) {
1937             uint32_t file_idx = UINT32_MAX;
1938 
1939             // If we are looking for inline functions only and we don't find it
1940             // in the support files, we are done.
1941             if (check_inlines) {
1942               file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex(
1943                   1, file_spec, true);
1944               if (file_idx == UINT32_MAX)
1945                 continue;
1946             }
1947 
1948             if (line != 0) {
1949               LineTable *line_table = sc.comp_unit->GetLineTable();
1950 
1951               if (line_table != NULL && line != 0) {
1952                 // We will have already looked up the file index if we are
1953                 // searching for inline entries.
1954                 if (!check_inlines)
1955                   file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex(
1956                       1, file_spec, true);
1957 
1958                 if (file_idx != UINT32_MAX) {
1959                   uint32_t found_line;
1960                   uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex(
1961                       0, file_idx, line, false, &sc.line_entry);
1962                   found_line = sc.line_entry.line;
1963 
1964                   while (line_idx != UINT32_MAX) {
1965                     sc.function = NULL;
1966                     sc.block = NULL;
1967                     if (resolve_scope &
1968                         (eSymbolContextFunction | eSymbolContextBlock)) {
1969                       const lldb::addr_t file_vm_addr =
1970                           sc.line_entry.range.GetBaseAddress().GetFileAddress();
1971                       if (file_vm_addr != LLDB_INVALID_ADDRESS) {
1972                         DWARFDIE function_die =
1973                             dwarf_cu->LookupAddress(file_vm_addr);
1974                         DWARFDIE block_die;
1975                         if (function_die) {
1976                           sc.function =
1977                               sc.comp_unit
1978                                   ->FindFunctionByUID(function_die.GetID())
1979                                   .get();
1980                           if (sc.function == NULL)
1981                             sc.function =
1982                                 ParseCompileUnitFunction(sc, function_die);
1983 
1984                           if (sc.function &&
1985                               (resolve_scope & eSymbolContextBlock))
1986                             block_die =
1987                                 function_die.LookupDeepestBlock(file_vm_addr);
1988                         }
1989 
1990                         if (sc.function != NULL) {
1991                           Block &block = sc.function->GetBlock(true);
1992 
1993                           if (block_die)
1994                             sc.block = block.FindBlockByID(block_die.GetID());
1995                           else if (function_die)
1996                             sc.block =
1997                                 block.FindBlockByID(function_die.GetID());
1998                         }
1999                       }
2000                     }
2001 
2002                     sc_list.Append(sc);
2003                     line_idx = line_table->FindLineEntryIndexByFileIndex(
2004                         line_idx + 1, file_idx, found_line, true,
2005                         &sc.line_entry);
2006                   }
2007                 }
2008               } else if (file_spec_matches_cu_file_spec && !check_inlines) {
2009                 // only append the context if we aren't looking for inline call
2010                 // sites by file and line and if the file spec matches that of
2011                 // the compile unit
2012                 sc_list.Append(sc);
2013               }
2014             } else if (file_spec_matches_cu_file_spec && !check_inlines) {
2015               // only append the context if we aren't looking for inline call
2016               // sites by file and line and if the file spec matches that of
2017               // the compile unit
2018               sc_list.Append(sc);
2019             }
2020 
2021             if (!check_inlines)
2022               break;
2023           }
2024         }
2025       }
2026     }
2027   }
2028   return sc_list.GetSize() - prev_size;
2029 }
2030 
2031 void SymbolFileDWARF::PreloadSymbols() {
2032   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2033   m_index->Preload();
2034 }
2035 
2036 std::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const {
2037   lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
2038   if (module_sp)
2039     return module_sp->GetMutex();
2040   return GetObjectFile()->GetModule()->GetMutex();
2041 }
2042 
2043 bool SymbolFileDWARF::DeclContextMatchesThisSymbolFile(
2044     const lldb_private::CompilerDeclContext *decl_ctx) {
2045   if (decl_ctx == nullptr || !decl_ctx->IsValid()) {
2046     // Invalid namespace decl which means we aren't matching only things in
2047     // this symbol file, so return true to indicate it matches this symbol
2048     // file.
2049     return true;
2050   }
2051 
2052   TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
2053   TypeSystem *type_system = GetTypeSystemForLanguage(
2054       decl_ctx_type_system->GetMinimumLanguage(nullptr));
2055   if (decl_ctx_type_system == type_system)
2056     return true; // The type systems match, return true
2057 
2058   // The namespace AST was valid, and it does not match...
2059   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2060 
2061   if (log)
2062     GetObjectFile()->GetModule()->LogMessage(
2063         log, "Valid namespace does not match symbol file");
2064 
2065   return false;
2066 }
2067 
2068 uint32_t SymbolFileDWARF::FindGlobalVariables(
2069     const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
2070     uint32_t max_matches, VariableList &variables) {
2071   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2072 
2073   if (log)
2074     GetObjectFile()->GetModule()->LogMessage(
2075         log,
2076         "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2077         "parent_decl_ctx=%p, max_matches=%u, variables)",
2078         name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2079         max_matches);
2080 
2081   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2082     return 0;
2083 
2084   DWARFDebugInfo *info = DebugInfo();
2085   if (info == NULL)
2086     return 0;
2087 
2088   // Remember how many variables are in the list before we search.
2089   const uint32_t original_size = variables.GetSize();
2090 
2091   llvm::StringRef basename;
2092   llvm::StringRef context;
2093 
2094   if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(),
2095                                                       context, basename))
2096     basename = name.GetStringRef();
2097 
2098   DIEArray die_offsets;
2099   m_index->GetGlobalVariables(ConstString(basename), die_offsets);
2100   const size_t num_die_matches = die_offsets.size();
2101   if (num_die_matches) {
2102     SymbolContext sc;
2103     sc.module_sp = m_obj_file->GetModule();
2104     assert(sc.module_sp);
2105 
2106     // Loop invariant: Variables up to this index have been checked for context
2107     // matches.
2108     uint32_t pruned_idx = original_size;
2109 
2110     bool done = false;
2111     for (size_t i = 0; i < num_die_matches && !done; ++i) {
2112       const DIERef &die_ref = die_offsets[i];
2113       DWARFDIE die = GetDIE(die_ref);
2114 
2115       if (die) {
2116         switch (die.Tag()) {
2117         default:
2118         case DW_TAG_subprogram:
2119         case DW_TAG_inlined_subroutine:
2120         case DW_TAG_try_block:
2121         case DW_TAG_catch_block:
2122           break;
2123 
2124         case DW_TAG_variable: {
2125           sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
2126 
2127           if (parent_decl_ctx) {
2128             DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2129             if (dwarf_ast) {
2130               CompilerDeclContext actual_parent_decl_ctx =
2131                   dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2132               if (!actual_parent_decl_ctx ||
2133                   actual_parent_decl_ctx != *parent_decl_ctx)
2134                 continue;
2135             }
2136           }
2137 
2138           ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false,
2139                          &variables);
2140           while (pruned_idx < variables.GetSize()) {
2141             VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx);
2142             if (var_sp->GetName().GetStringRef().contains(name.GetStringRef()))
2143               ++pruned_idx;
2144             else
2145               variables.RemoveVariableAtIndex(pruned_idx);
2146           }
2147 
2148           if (variables.GetSize() - original_size >= max_matches)
2149             done = true;
2150         } break;
2151         }
2152       } else {
2153         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2154                                         name.GetStringRef());
2155       }
2156     }
2157   }
2158 
2159   // Return the number of variable that were appended to the list
2160   const uint32_t num_matches = variables.GetSize() - original_size;
2161   if (log && num_matches > 0) {
2162     GetObjectFile()->GetModule()->LogMessage(
2163         log,
2164         "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2165         "parent_decl_ctx=%p, max_matches=%u, variables) => %u",
2166         name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2167         max_matches, num_matches);
2168   }
2169   return num_matches;
2170 }
2171 
2172 uint32_t SymbolFileDWARF::FindGlobalVariables(const RegularExpression &regex,
2173                                               uint32_t max_matches,
2174                                               VariableList &variables) {
2175   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2176 
2177   if (log) {
2178     GetObjectFile()->GetModule()->LogMessage(
2179         log,
2180         "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", "
2181         "max_matches=%u, variables)",
2182         regex.GetText().str().c_str(), max_matches);
2183   }
2184 
2185   DWARFDebugInfo *info = DebugInfo();
2186   if (info == NULL)
2187     return 0;
2188 
2189   // Remember how many variables are in the list before we search.
2190   const uint32_t original_size = variables.GetSize();
2191 
2192   DIEArray die_offsets;
2193   m_index->GetGlobalVariables(regex, die_offsets);
2194 
2195   SymbolContext sc;
2196   sc.module_sp = m_obj_file->GetModule();
2197   assert(sc.module_sp);
2198 
2199   const size_t num_matches = die_offsets.size();
2200   if (num_matches) {
2201     for (size_t i = 0; i < num_matches; ++i) {
2202       const DIERef &die_ref = die_offsets[i];
2203       DWARFDIE die = GetDIE(die_ref);
2204 
2205       if (die) {
2206         sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
2207 
2208         ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2209 
2210         if (variables.GetSize() - original_size >= max_matches)
2211           break;
2212       } else
2213         m_index->ReportInvalidDIEOffset(die_ref.die_offset, regex.GetText());
2214     }
2215   }
2216 
2217   // Return the number of variable that were appended to the list
2218   return variables.GetSize() - original_size;
2219 }
2220 
2221 bool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die,
2222                                       bool include_inlines,
2223                                       SymbolContextList &sc_list) {
2224   SymbolContext sc;
2225 
2226   if (!orig_die)
2227     return false;
2228 
2229   // If we were passed a die that is not a function, just return false...
2230   if (!(orig_die.Tag() == DW_TAG_subprogram ||
2231         (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2232     return false;
2233 
2234   DWARFDIE die = orig_die;
2235   DWARFDIE inlined_die;
2236   if (die.Tag() == DW_TAG_inlined_subroutine) {
2237     inlined_die = die;
2238 
2239     while (1) {
2240       die = die.GetParent();
2241 
2242       if (die) {
2243         if (die.Tag() == DW_TAG_subprogram)
2244           break;
2245       } else
2246         break;
2247     }
2248   }
2249   assert(die && die.Tag() == DW_TAG_subprogram);
2250   if (GetFunction(die, sc)) {
2251     Address addr;
2252     // Parse all blocks if needed
2253     if (inlined_die) {
2254       Block &function_block = sc.function->GetBlock(true);
2255       sc.block = function_block.FindBlockByID(inlined_die.GetID());
2256       if (sc.block == NULL)
2257         sc.block = function_block.FindBlockByID(inlined_die.GetOffset());
2258       if (sc.block == NULL || sc.block->GetStartAddress(addr) == false)
2259         addr.Clear();
2260     } else {
2261       sc.block = NULL;
2262       addr = sc.function->GetAddressRange().GetBaseAddress();
2263     }
2264 
2265     if (addr.IsValid()) {
2266       sc_list.Append(sc);
2267       return true;
2268     }
2269   }
2270 
2271   return false;
2272 }
2273 
2274 bool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext *decl_ctx,
2275                                        const DWARFDIE &die) {
2276   // If we have no parent decl context to match this DIE matches, and if the
2277   // parent decl context isn't valid, we aren't trying to look for any
2278   // particular decl context so any die matches.
2279   if (decl_ctx == nullptr || !decl_ctx->IsValid())
2280     return true;
2281 
2282   if (die) {
2283     DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2284     if (dwarf_ast) {
2285       CompilerDeclContext actual_decl_ctx =
2286           dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2287       if (actual_decl_ctx)
2288         return actual_decl_ctx == *decl_ctx;
2289     }
2290   }
2291   return false;
2292 }
2293 
2294 uint32_t SymbolFileDWARF::FindFunctions(
2295     const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
2296     FunctionNameType name_type_mask, bool include_inlines, bool append,
2297     SymbolContextList &sc_list) {
2298   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2299   Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (name = '%s')",
2300                      name.AsCString());
2301 
2302   // eFunctionNameTypeAuto should be pre-resolved by a call to
2303   // Module::LookupInfo::LookupInfo()
2304   assert((name_type_mask & eFunctionNameTypeAuto) == 0);
2305 
2306   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2307 
2308   if (log) {
2309     GetObjectFile()->GetModule()->LogMessage(
2310         log, "SymbolFileDWARF::FindFunctions (name=\"%s\", "
2311              "name_type_mask=0x%x, append=%u, sc_list)",
2312         name.GetCString(), name_type_mask, append);
2313   }
2314 
2315   // If we aren't appending the results to this list, then clear the list
2316   if (!append)
2317     sc_list.Clear();
2318 
2319   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2320     return 0;
2321 
2322   // If name is empty then we won't find anything.
2323   if (name.IsEmpty())
2324     return 0;
2325 
2326   // Remember how many sc_list are in the list before we search in case we are
2327   // appending the results to a variable list.
2328 
2329   const uint32_t original_size = sc_list.GetSize();
2330 
2331   DWARFDebugInfo *info = DebugInfo();
2332   if (info == NULL)
2333     return 0;
2334 
2335   llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2336   DIEArray offsets;
2337   CompilerDeclContext empty_decl_ctx;
2338   if (!parent_decl_ctx)
2339     parent_decl_ctx = &empty_decl_ctx;
2340 
2341   std::vector<DWARFDIE> dies;
2342   m_index->GetFunctions(name, *info, *parent_decl_ctx, name_type_mask, dies);
2343   for (const DWARFDIE &die: dies) {
2344     if (resolved_dies.insert(die.GetDIE()).second)
2345       ResolveFunction(die, include_inlines, sc_list);
2346   }
2347 
2348   // Return the number of variable that were appended to the list
2349   const uint32_t num_matches = sc_list.GetSize() - original_size;
2350 
2351   if (log && num_matches > 0) {
2352     GetObjectFile()->GetModule()->LogMessage(
2353         log, "SymbolFileDWARF::FindFunctions (name=\"%s\", "
2354              "name_type_mask=0x%x, include_inlines=%d, append=%u, sc_list) => "
2355              "%u",
2356         name.GetCString(), name_type_mask, include_inlines, append,
2357         num_matches);
2358   }
2359   return num_matches;
2360 }
2361 
2362 uint32_t SymbolFileDWARF::FindFunctions(const RegularExpression &regex,
2363                                         bool include_inlines, bool append,
2364                                         SymbolContextList &sc_list) {
2365   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2366   Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (regex = '%s')",
2367                      regex.GetText().str().c_str());
2368 
2369   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2370 
2371   if (log) {
2372     GetObjectFile()->GetModule()->LogMessage(
2373         log,
2374         "SymbolFileDWARF::FindFunctions (regex=\"%s\", append=%u, sc_list)",
2375         regex.GetText().str().c_str(), append);
2376   }
2377 
2378   // If we aren't appending the results to this list, then clear the list
2379   if (!append)
2380     sc_list.Clear();
2381 
2382   DWARFDebugInfo *info = DebugInfo();
2383   if (!info)
2384     return 0;
2385 
2386   // Remember how many sc_list are in the list before we search in case we are
2387   // appending the results to a variable list.
2388   uint32_t original_size = sc_list.GetSize();
2389 
2390   DIEArray offsets;
2391   m_index->GetFunctions(regex, offsets);
2392 
2393   llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2394   for (DIERef ref : offsets) {
2395     DWARFDIE die = info->GetDIE(ref);
2396     if (!die) {
2397       m_index->ReportInvalidDIEOffset(ref.die_offset, regex.GetText());
2398       continue;
2399     }
2400     if (resolved_dies.insert(die.GetDIE()).second)
2401       ResolveFunction(die, include_inlines, sc_list);
2402   }
2403 
2404   // Return the number of variable that were appended to the list
2405   return sc_list.GetSize() - original_size;
2406 }
2407 
2408 void SymbolFileDWARF::GetMangledNamesForFunction(
2409     const std::string &scope_qualified_name,
2410     std::vector<ConstString> &mangled_names) {
2411   DWARFDebugInfo *info = DebugInfo();
2412   uint32_t num_comp_units = 0;
2413   if (info)
2414     num_comp_units = info->GetNumCompileUnits();
2415 
2416   for (uint32_t i = 0; i < num_comp_units; i++) {
2417     DWARFUnit *cu = info->GetCompileUnitAtIndex(i);
2418     if (cu == nullptr)
2419       continue;
2420 
2421     SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
2422     if (dwo)
2423       dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
2424   }
2425 
2426   NameToOffsetMap::iterator iter =
2427       m_function_scope_qualified_name_map.find(scope_qualified_name);
2428   if (iter == m_function_scope_qualified_name_map.end())
2429     return;
2430 
2431   DIERefSetSP set_sp = (*iter).second;
2432   std::set<DIERef>::iterator set_iter;
2433   for (set_iter = set_sp->begin(); set_iter != set_sp->end(); set_iter++) {
2434     DWARFDIE die = DebugInfo()->GetDIE(*set_iter);
2435     mangled_names.push_back(ConstString(die.GetMangledName()));
2436   }
2437 }
2438 
2439 uint32_t SymbolFileDWARF::FindTypes(
2440     const SymbolContext &sc, const ConstString &name,
2441     const CompilerDeclContext *parent_decl_ctx, bool append,
2442     uint32_t max_matches,
2443     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
2444     TypeMap &types) {
2445   // If we aren't appending the results to this list, then clear the list
2446   if (!append)
2447     types.Clear();
2448 
2449   // Make sure we haven't already searched this SymbolFile before...
2450   if (searched_symbol_files.count(this))
2451     return 0;
2452   else
2453     searched_symbol_files.insert(this);
2454 
2455   DWARFDebugInfo *info = DebugInfo();
2456   if (info == NULL)
2457     return 0;
2458 
2459   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2460 
2461   if (log) {
2462     if (parent_decl_ctx)
2463       GetObjectFile()->GetModule()->LogMessage(
2464           log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2465                "%p (\"%s\"), append=%u, max_matches=%u, type_list)",
2466           name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2467           parent_decl_ctx->GetName().AsCString("<NULL>"), append, max_matches);
2468     else
2469       GetObjectFile()->GetModule()->LogMessage(
2470           log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2471                "NULL, append=%u, max_matches=%u, type_list)",
2472           name.GetCString(), append, max_matches);
2473   }
2474 
2475   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2476     return 0;
2477 
2478   DIEArray die_offsets;
2479   m_index->GetTypes(name, die_offsets);
2480   const size_t num_die_matches = die_offsets.size();
2481 
2482   if (num_die_matches) {
2483     const uint32_t initial_types_size = types.GetSize();
2484     for (size_t i = 0; i < num_die_matches; ++i) {
2485       const DIERef &die_ref = die_offsets[i];
2486       DWARFDIE die = GetDIE(die_ref);
2487 
2488       if (die) {
2489         if (!DIEInDeclContext(parent_decl_ctx, die))
2490           continue; // The containing decl contexts don't match
2491 
2492         Type *matching_type = ResolveType(die, true, true);
2493         if (matching_type) {
2494           // We found a type pointer, now find the shared pointer form our type
2495           // list
2496           types.InsertUnique(matching_type->shared_from_this());
2497           if (types.GetSize() >= max_matches)
2498             break;
2499         }
2500       } else {
2501         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2502                                         name.GetStringRef());
2503       }
2504     }
2505     const uint32_t num_matches = types.GetSize() - initial_types_size;
2506     if (log && num_matches) {
2507       if (parent_decl_ctx) {
2508         GetObjectFile()->GetModule()->LogMessage(
2509             log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2510                  "= %p (\"%s\"), append=%u, max_matches=%u, type_list) => %u",
2511             name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2512             parent_decl_ctx->GetName().AsCString("<NULL>"), append, max_matches,
2513             num_matches);
2514       } else {
2515         GetObjectFile()->GetModule()->LogMessage(
2516             log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2517                  "= NULL, append=%u, max_matches=%u, type_list) => %u",
2518             name.GetCString(), append, max_matches, num_matches);
2519       }
2520     }
2521     return num_matches;
2522   } else {
2523     UpdateExternalModuleListIfNeeded();
2524 
2525     for (const auto &pair : m_external_type_modules) {
2526       ModuleSP external_module_sp = pair.second;
2527       if (external_module_sp) {
2528         SymbolVendor *sym_vendor = external_module_sp->GetSymbolVendor();
2529         if (sym_vendor) {
2530           const uint32_t num_external_matches =
2531               sym_vendor->FindTypes(sc, name, parent_decl_ctx, append,
2532                                     max_matches, searched_symbol_files, types);
2533           if (num_external_matches)
2534             return num_external_matches;
2535         }
2536       }
2537     }
2538   }
2539 
2540   return 0;
2541 }
2542 
2543 size_t SymbolFileDWARF::FindTypes(const std::vector<CompilerContext> &context,
2544                                   bool append, TypeMap &types) {
2545   if (!append)
2546     types.Clear();
2547 
2548   if (context.empty())
2549     return 0;
2550 
2551   ConstString name = context.back().name;
2552 
2553   if (!name)
2554     return 0;
2555 
2556   DIEArray die_offsets;
2557   m_index->GetTypes(name, die_offsets);
2558   const size_t num_die_matches = die_offsets.size();
2559 
2560   if (num_die_matches) {
2561     size_t num_matches = 0;
2562     for (size_t i = 0; i < num_die_matches; ++i) {
2563       const DIERef &die_ref = die_offsets[i];
2564       DWARFDIE die = GetDIE(die_ref);
2565 
2566       if (die) {
2567         std::vector<CompilerContext> die_context;
2568         die.GetDWOContext(die_context);
2569         if (die_context != context)
2570           continue;
2571 
2572         Type *matching_type = ResolveType(die, true, true);
2573         if (matching_type) {
2574           // We found a type pointer, now find the shared pointer form our type
2575           // list
2576           types.InsertUnique(matching_type->shared_from_this());
2577           ++num_matches;
2578         }
2579       } else {
2580         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2581                                         name.GetStringRef());
2582       }
2583     }
2584     return num_matches;
2585   }
2586   return 0;
2587 }
2588 
2589 CompilerDeclContext
2590 SymbolFileDWARF::FindNamespace(const SymbolContext &sc, const ConstString &name,
2591                                const CompilerDeclContext *parent_decl_ctx) {
2592   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2593 
2594   if (log) {
2595     GetObjectFile()->GetModule()->LogMessage(
2596         log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
2597         name.GetCString());
2598   }
2599 
2600   CompilerDeclContext namespace_decl_ctx;
2601 
2602   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2603     return namespace_decl_ctx;
2604 
2605   DWARFDebugInfo *info = DebugInfo();
2606   if (info) {
2607     DIEArray die_offsets;
2608     m_index->GetNamespaces(name, die_offsets);
2609     const size_t num_matches = die_offsets.size();
2610     if (num_matches) {
2611       for (size_t i = 0; i < num_matches; ++i) {
2612         const DIERef &die_ref = die_offsets[i];
2613         DWARFDIE die = GetDIE(die_ref);
2614 
2615         if (die) {
2616           if (!DIEInDeclContext(parent_decl_ctx, die))
2617             continue; // The containing decl contexts don't match
2618 
2619           DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2620           if (dwarf_ast) {
2621             namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
2622             if (namespace_decl_ctx)
2623               break;
2624           }
2625         } else {
2626           m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2627                                           name.GetStringRef());
2628         }
2629       }
2630     }
2631   }
2632   if (log && namespace_decl_ctx) {
2633     GetObjectFile()->GetModule()->LogMessage(
2634         log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => "
2635              "CompilerDeclContext(%p/%p) \"%s\"",
2636         name.GetCString(),
2637         static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
2638         static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
2639         namespace_decl_ctx.GetName().AsCString("<NULL>"));
2640   }
2641 
2642   return namespace_decl_ctx;
2643 }
2644 
2645 TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
2646                                       bool resolve_function_context) {
2647   TypeSP type_sp;
2648   if (die) {
2649     Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
2650     if (type_ptr == NULL) {
2651       CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(die.GetCU());
2652       assert(lldb_cu);
2653       SymbolContext sc(lldb_cu);
2654       const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
2655       while (parent_die != nullptr) {
2656         if (parent_die->Tag() == DW_TAG_subprogram)
2657           break;
2658         parent_die = parent_die->GetParent();
2659       }
2660       SymbolContext sc_backup = sc;
2661       if (resolve_function_context && parent_die != nullptr &&
2662           !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
2663         sc = sc_backup;
2664 
2665       type_sp = ParseType(sc, die, NULL);
2666     } else if (type_ptr != DIE_IS_BEING_PARSED) {
2667       // Grab the existing type from the master types lists
2668       type_sp = type_ptr->shared_from_this();
2669     }
2670   }
2671   return type_sp;
2672 }
2673 
2674 DWARFDIE
2675 SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
2676   if (orig_die) {
2677     DWARFDIE die = orig_die;
2678 
2679     while (die) {
2680       // If this is the original DIE that we are searching for a declaration
2681       // for, then don't look in the cache as we don't want our own decl
2682       // context to be our decl context...
2683       if (orig_die != die) {
2684         switch (die.Tag()) {
2685         case DW_TAG_compile_unit:
2686         case DW_TAG_partial_unit:
2687         case DW_TAG_namespace:
2688         case DW_TAG_structure_type:
2689         case DW_TAG_union_type:
2690         case DW_TAG_class_type:
2691         case DW_TAG_lexical_block:
2692         case DW_TAG_subprogram:
2693           return die;
2694         case DW_TAG_inlined_subroutine: {
2695           DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2696           if (abs_die) {
2697             return abs_die;
2698           }
2699           break;
2700         }
2701         default:
2702           break;
2703         }
2704       }
2705 
2706       DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
2707       if (spec_die) {
2708         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
2709         if (decl_ctx_die)
2710           return decl_ctx_die;
2711       }
2712 
2713       DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2714       if (abs_die) {
2715         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
2716         if (decl_ctx_die)
2717           return decl_ctx_die;
2718       }
2719 
2720       die = die.GetParent();
2721     }
2722   }
2723   return DWARFDIE();
2724 }
2725 
2726 Symbol *
2727 SymbolFileDWARF::GetObjCClassSymbol(const ConstString &objc_class_name) {
2728   Symbol *objc_class_symbol = NULL;
2729   if (m_obj_file) {
2730     Symtab *symtab = m_obj_file->GetSymtab();
2731     if (symtab) {
2732       objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
2733           objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
2734           Symtab::eVisibilityAny);
2735     }
2736   }
2737   return objc_class_symbol;
2738 }
2739 
2740 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If
2741 // they don't then we can end up looking through all class types for a complete
2742 // type and never find the full definition. We need to know if this attribute
2743 // is supported, so we determine this here and cache th result. We also need to
2744 // worry about the debug map
2745 // DWARF file
2746 // if we are doing darwin DWARF in .o file debugging.
2747 bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(
2748     DWARFUnit *cu) {
2749   if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) {
2750     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
2751     if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
2752       m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2753     else {
2754       DWARFDebugInfo *debug_info = DebugInfo();
2755       const uint32_t num_compile_units = GetNumCompileUnits();
2756       for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2757         DWARFUnit *dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
2758         if (dwarf_cu != cu &&
2759             dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) {
2760           m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2761           break;
2762         }
2763       }
2764     }
2765     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo &&
2766         GetDebugMapSymfile())
2767       return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this);
2768   }
2769   return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
2770 }
2771 
2772 // This function can be used when a DIE is found that is a forward declaration
2773 // DIE and we want to try and find a type that has the complete definition.
2774 TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE(
2775     const DWARFDIE &die, const ConstString &type_name,
2776     bool must_be_implementation) {
2777 
2778   TypeSP type_sp;
2779 
2780   if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
2781     return type_sp;
2782 
2783   DIEArray die_offsets;
2784   m_index->GetCompleteObjCClass(type_name, must_be_implementation, die_offsets);
2785 
2786   const size_t num_matches = die_offsets.size();
2787 
2788   if (num_matches) {
2789     for (size_t i = 0; i < num_matches; ++i) {
2790       const DIERef &die_ref = die_offsets[i];
2791       DWARFDIE type_die = GetDIE(die_ref);
2792 
2793       if (type_die) {
2794         bool try_resolving_type = false;
2795 
2796         // Don't try and resolve the DIE we are looking for with the DIE
2797         // itself!
2798         if (type_die != die) {
2799           switch (type_die.Tag()) {
2800           case DW_TAG_class_type:
2801           case DW_TAG_structure_type:
2802             try_resolving_type = true;
2803             break;
2804           default:
2805             break;
2806           }
2807         }
2808 
2809         if (try_resolving_type) {
2810           if (must_be_implementation &&
2811               type_die.Supports_DW_AT_APPLE_objc_complete_type())
2812             try_resolving_type = type_die.GetAttributeValueAsUnsigned(
2813                 DW_AT_APPLE_objc_complete_type, 0);
2814 
2815           if (try_resolving_type) {
2816             Type *resolved_type = ResolveType(type_die, false, true);
2817             if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2818               DEBUG_PRINTF("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
2819                            " (cu 0x%8.8" PRIx64 ")\n",
2820                            die.GetID(),
2821                            m_obj_file->GetFileSpec().GetFilename().AsCString(
2822                                "<Unknown>"),
2823                            type_die.GetID(), type_cu->GetID());
2824 
2825               if (die)
2826                 GetDIEToType()[die.GetDIE()] = resolved_type;
2827               type_sp = resolved_type->shared_from_this();
2828               break;
2829             }
2830           }
2831         }
2832       } else {
2833         m_index->ReportInvalidDIEOffset(die_ref.die_offset,
2834                                         type_name.GetStringRef());
2835       }
2836     }
2837   }
2838   return type_sp;
2839 }
2840 
2841 //----------------------------------------------------------------------
2842 // This function helps to ensure that the declaration contexts match for two
2843 // different DIEs. Often times debug information will refer to a forward
2844 // declaration of a type (the equivalent of "struct my_struct;". There will
2845 // often be a declaration of that type elsewhere that has the full definition.
2846 // When we go looking for the full type "my_struct", we will find one or more
2847 // matches in the accelerator tables and we will then need to make sure the
2848 // type was in the same declaration context as the original DIE. This function
2849 // can efficiently compare two DIEs and will return true when the declaration
2850 // context matches, and false when they don't.
2851 //----------------------------------------------------------------------
2852 bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1,
2853                                            const DWARFDIE &die2) {
2854   if (die1 == die2)
2855     return true;
2856 
2857   DWARFDIECollection decl_ctx_1;
2858   DWARFDIECollection decl_ctx_2;
2859   // The declaration DIE stack is a stack of the declaration context DIEs all
2860   // the way back to the compile unit. If a type "T" is declared inside a class
2861   // "B", and class "B" is declared inside a class "A" and class "A" is in a
2862   // namespace "lldb", and the namespace is in a compile unit, there will be a
2863   // stack of DIEs:
2864   //
2865   //   [0] DW_TAG_class_type for "B"
2866   //   [1] DW_TAG_class_type for "A"
2867   //   [2] DW_TAG_namespace  for "lldb"
2868   //   [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file.
2869   //
2870   // We grab both contexts and make sure that everything matches all the way
2871   // back to the compiler unit.
2872 
2873   // First lets grab the decl contexts for both DIEs
2874   die1.GetDeclContextDIEs(decl_ctx_1);
2875   die2.GetDeclContextDIEs(decl_ctx_2);
2876   // Make sure the context arrays have the same size, otherwise we are done
2877   const size_t count1 = decl_ctx_1.Size();
2878   const size_t count2 = decl_ctx_2.Size();
2879   if (count1 != count2)
2880     return false;
2881 
2882   // Make sure the DW_TAG values match all the way back up the compile unit. If
2883   // they don't, then we are done.
2884   DWARFDIE decl_ctx_die1;
2885   DWARFDIE decl_ctx_die2;
2886   size_t i;
2887   for (i = 0; i < count1; i++) {
2888     decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex(i);
2889     decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex(i);
2890     if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
2891       return false;
2892   }
2893 #if defined LLDB_CONFIGURATION_DEBUG
2894 
2895   // Make sure the top item in the decl context die array is always
2896   // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then
2897   // something went wrong in the DWARFDIE::GetDeclContextDIEs()
2898   // function.
2899   dw_tag_t cu_tag = decl_ctx_1.GetDIEAtIndex(count1 - 1).Tag();
2900   UNUSED_IF_ASSERT_DISABLED(cu_tag);
2901   assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit);
2902 
2903 #endif
2904   // Always skip the compile unit when comparing by only iterating up to "count
2905   // - 1". Here we compare the names as we go.
2906   for (i = 0; i < count1 - 1; i++) {
2907     decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex(i);
2908     decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex(i);
2909     const char *name1 = decl_ctx_die1.GetName();
2910     const char *name2 = decl_ctx_die2.GetName();
2911     // If the string was from a DW_FORM_strp, then the pointer will often be
2912     // the same!
2913     if (name1 == name2)
2914       continue;
2915 
2916     // Name pointers are not equal, so only compare the strings if both are not
2917     // NULL.
2918     if (name1 && name2) {
2919       // If the strings don't compare, we are done...
2920       if (strcmp(name1, name2) != 0)
2921         return false;
2922     } else {
2923       // One name was NULL while the other wasn't
2924       return false;
2925     }
2926   }
2927   // We made it through all of the checks and the declaration contexts are
2928   // equal.
2929   return true;
2930 }
2931 
2932 TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(
2933     const DWARFDeclContext &dwarf_decl_ctx) {
2934   TypeSP type_sp;
2935 
2936   const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
2937   if (dwarf_decl_ctx_count > 0) {
2938     const ConstString type_name(dwarf_decl_ctx[0].name);
2939     const dw_tag_t tag = dwarf_decl_ctx[0].tag;
2940 
2941     if (type_name) {
2942       Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION |
2943                                             DWARF_LOG_LOOKUPS));
2944       if (log) {
2945         GetObjectFile()->GetModule()->LogMessage(
2946             log, "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%"
2947                  "s, qualified-name='%s')",
2948             DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2949             dwarf_decl_ctx.GetQualifiedName());
2950       }
2951 
2952       DIEArray die_offsets;
2953       m_index->GetTypes(dwarf_decl_ctx, die_offsets);
2954       const size_t num_matches = die_offsets.size();
2955 
2956       // Get the type system that we are looking to find a type for. We will
2957       // use this to ensure any matches we find are in a language that this
2958       // type system supports
2959       const LanguageType language = dwarf_decl_ctx.GetLanguage();
2960       TypeSystem *type_system = (language == eLanguageTypeUnknown)
2961                                     ? nullptr
2962                                     : GetTypeSystemForLanguage(language);
2963 
2964       if (num_matches) {
2965         for (size_t i = 0; i < num_matches; ++i) {
2966           const DIERef &die_ref = die_offsets[i];
2967           DWARFDIE type_die = GetDIE(die_ref);
2968 
2969           if (type_die) {
2970             // Make sure type_die's langauge matches the type system we are
2971             // looking for. We don't want to find a "Foo" type from Java if we
2972             // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
2973             if (type_system &&
2974                 !type_system->SupportsLanguage(type_die.GetLanguage()))
2975               continue;
2976             bool try_resolving_type = false;
2977 
2978             // Don't try and resolve the DIE we are looking for with the DIE
2979             // itself!
2980             const dw_tag_t type_tag = type_die.Tag();
2981             // Make sure the tags match
2982             if (type_tag == tag) {
2983               // The tags match, lets try resolving this type
2984               try_resolving_type = true;
2985             } else {
2986               // The tags don't match, but we need to watch our for a forward
2987               // declaration for a struct and ("struct foo") ends up being a
2988               // class ("class foo { ... };") or vice versa.
2989               switch (type_tag) {
2990               case DW_TAG_class_type:
2991                 // We had a "class foo", see if we ended up with a "struct foo
2992                 // { ... };"
2993                 try_resolving_type = (tag == DW_TAG_structure_type);
2994                 break;
2995               case DW_TAG_structure_type:
2996                 // We had a "struct foo", see if we ended up with a "class foo
2997                 // { ... };"
2998                 try_resolving_type = (tag == DW_TAG_class_type);
2999                 break;
3000               default:
3001                 // Tags don't match, don't event try to resolve using this type
3002                 // whose name matches....
3003                 break;
3004               }
3005             }
3006 
3007             if (try_resolving_type) {
3008               DWARFDeclContext type_dwarf_decl_ctx;
3009               type_die.GetDWARFDeclContext(type_dwarf_decl_ctx);
3010 
3011               if (log) {
3012                 GetObjectFile()->GetModule()->LogMessage(
3013                     log, "SymbolFileDWARF::"
3014                          "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
3015                          "qualified-name='%s') trying die=0x%8.8x (%s)",
3016                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3017                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
3018                     type_dwarf_decl_ctx.GetQualifiedName());
3019               }
3020 
3021               // Make sure the decl contexts match all the way up
3022               if (dwarf_decl_ctx == type_dwarf_decl_ctx) {
3023                 Type *resolved_type = ResolveType(type_die, false);
3024                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
3025                   type_sp = resolved_type->shared_from_this();
3026                   break;
3027                 }
3028               }
3029             } else {
3030               if (log) {
3031                 std::string qualified_name;
3032                 type_die.GetQualifiedName(qualified_name);
3033                 GetObjectFile()->GetModule()->LogMessage(
3034                     log, "SymbolFileDWARF::"
3035                          "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
3036                          "qualified-name='%s') ignoring die=0x%8.8x (%s)",
3037                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3038                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
3039                     qualified_name.c_str());
3040               }
3041             }
3042           } else {
3043             m_index->ReportInvalidDIEOffset(die_ref.die_offset,
3044                                             type_name.GetStringRef());
3045           }
3046         }
3047       }
3048     }
3049   }
3050   return type_sp;
3051 }
3052 
3053 TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die,
3054                                   bool *type_is_new_ptr) {
3055   TypeSP type_sp;
3056 
3057   if (die) {
3058     TypeSystem *type_system =
3059         GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
3060 
3061     if (type_system) {
3062       DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
3063       if (dwarf_ast) {
3064         Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
3065         type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, log, type_is_new_ptr);
3066         if (type_sp) {
3067           TypeList *type_list = GetTypeList();
3068           if (type_list)
3069             type_list->Insert(type_sp);
3070 
3071           if (die.Tag() == DW_TAG_subprogram) {
3072             DIERef die_ref = die.GetDIERef();
3073             std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
3074                                                  .GetScopeQualifiedName()
3075                                                  .AsCString(""));
3076             if (scope_qualified_name.size()) {
3077               NameToOffsetMap::iterator iter =
3078                   m_function_scope_qualified_name_map.find(
3079                       scope_qualified_name);
3080               if (iter != m_function_scope_qualified_name_map.end())
3081                 (*iter).second->insert(die_ref);
3082               else {
3083                 DIERefSetSP new_set(new std::set<DIERef>);
3084                 new_set->insert(die_ref);
3085                 m_function_scope_qualified_name_map.emplace(
3086                     std::make_pair(scope_qualified_name, new_set));
3087               }
3088             }
3089           }
3090         }
3091       }
3092     }
3093   }
3094 
3095   return type_sp;
3096 }
3097 
3098 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc,
3099                                    const DWARFDIE &orig_die,
3100                                    bool parse_siblings, bool parse_children) {
3101   size_t types_added = 0;
3102   DWARFDIE die = orig_die;
3103   while (die) {
3104     bool type_is_new = false;
3105     if (ParseType(sc, die, &type_is_new).get()) {
3106       if (type_is_new)
3107         ++types_added;
3108     }
3109 
3110     if (parse_children && die.HasChildren()) {
3111       if (die.Tag() == DW_TAG_subprogram) {
3112         SymbolContext child_sc(sc);
3113         child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3114         types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3115       } else
3116         types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3117     }
3118 
3119     if (parse_siblings)
3120       die = die.GetSibling();
3121     else
3122       die.Clear();
3123   }
3124   return types_added;
3125 }
3126 
3127 size_t SymbolFileDWARF::ParseFunctionBlocks(const SymbolContext &sc) {
3128   ASSERT_MODULE_LOCK(this);
3129   assert(sc.comp_unit && sc.function);
3130   size_t functions_added = 0;
3131   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
3132   if (dwarf_cu) {
3133     const dw_offset_t function_die_offset = sc.function->GetID();
3134     DWARFDIE function_die = dwarf_cu->GetDIE(function_die_offset);
3135     if (function_die) {
3136       ParseFunctionBlocks(sc, &sc.function->GetBlock(false), function_die,
3137                           LLDB_INVALID_ADDRESS, 0);
3138     }
3139   }
3140 
3141   return functions_added;
3142 }
3143 
3144 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc) {
3145   ASSERT_MODULE_LOCK(this);
3146   // At least a compile unit must be valid
3147   assert(sc.comp_unit);
3148   size_t types_added = 0;
3149   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
3150   if (dwarf_cu) {
3151     if (sc.function) {
3152       dw_offset_t function_die_offset = sc.function->GetID();
3153       DWARFDIE func_die = dwarf_cu->GetDIE(function_die_offset);
3154       if (func_die && func_die.HasChildren()) {
3155         types_added = ParseTypes(sc, func_die.GetFirstChild(), true, true);
3156       }
3157     } else {
3158       DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3159       if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3160         types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3161       }
3162     }
3163   }
3164 
3165   return types_added;
3166 }
3167 
3168 size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) {
3169   ASSERT_MODULE_LOCK(this);
3170   if (sc.comp_unit != NULL) {
3171     DWARFDebugInfo *info = DebugInfo();
3172     if (info == NULL)
3173       return 0;
3174 
3175     if (sc.function) {
3176       DWARFDIE function_die = info->GetDIE(DIERef(sc.function->GetID(), this));
3177 
3178       const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress(
3179           DW_AT_low_pc, LLDB_INVALID_ADDRESS);
3180       if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3181         const size_t num_variables = ParseVariables(
3182             sc, function_die.GetFirstChild(), func_lo_pc, true, true);
3183 
3184         // Let all blocks know they have parse all their variables
3185         sc.function->GetBlock(false).SetDidParseVariables(true, true);
3186         return num_variables;
3187       }
3188     } else if (sc.comp_unit) {
3189       DWARFUnit *dwarf_cu = info->GetCompileUnit(sc.comp_unit->GetID());
3190 
3191       if (dwarf_cu == NULL)
3192         return 0;
3193 
3194       uint32_t vars_added = 0;
3195       VariableListSP variables(sc.comp_unit->GetVariableList(false));
3196 
3197       if (variables.get() == NULL) {
3198         variables.reset(new VariableList());
3199         sc.comp_unit->SetVariableList(variables);
3200 
3201         DIEArray die_offsets;
3202         m_index->GetGlobalVariables(*dwarf_cu, die_offsets);
3203         const size_t num_matches = die_offsets.size();
3204         if (num_matches) {
3205           for (size_t i = 0; i < num_matches; ++i) {
3206             const DIERef &die_ref = die_offsets[i];
3207             DWARFDIE die = GetDIE(die_ref);
3208             if (die) {
3209               VariableSP var_sp(
3210                   ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS));
3211               if (var_sp) {
3212                 variables->AddVariableIfUnique(var_sp);
3213                 ++vars_added;
3214               }
3215             } else
3216               m_index->ReportInvalidDIEOffset(die_ref.die_offset, "");
3217           }
3218         }
3219       }
3220       return vars_added;
3221     }
3222   }
3223   return 0;
3224 }
3225 
3226 VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc,
3227                                              const DWARFDIE &die,
3228                                              const lldb::addr_t func_low_pc) {
3229   if (die.GetDWARF() != this)
3230     return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3231 
3232   VariableSP var_sp;
3233   if (!die)
3234     return var_sp;
3235 
3236   var_sp = GetDIEToVariable()[die.GetDIE()];
3237   if (var_sp)
3238     return var_sp; // Already been parsed!
3239 
3240   const dw_tag_t tag = die.Tag();
3241   ModuleSP module = GetObjectFile()->GetModule();
3242 
3243   if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3244       (tag == DW_TAG_formal_parameter && sc.function)) {
3245     DWARFAttributes attributes;
3246     const size_t num_attributes = die.GetAttributes(attributes);
3247     DWARFDIE spec_die;
3248     if (num_attributes > 0) {
3249       const char *name = NULL;
3250       const char *mangled = NULL;
3251       Declaration decl;
3252       uint32_t i;
3253       DWARFFormValue type_die_form;
3254       DWARFExpression location(die.GetCU());
3255       bool is_external = false;
3256       bool is_artificial = false;
3257       bool location_is_const_value_data = false;
3258       bool has_explicit_location = false;
3259       DWARFFormValue const_value;
3260       Variable::RangeList scope_ranges;
3261       // AccessType accessibility = eAccessNone;
3262 
3263       for (i = 0; i < num_attributes; ++i) {
3264         dw_attr_t attr = attributes.AttributeAtIndex(i);
3265         DWARFFormValue form_value;
3266 
3267         if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3268           switch (attr) {
3269           case DW_AT_decl_file:
3270             decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3271                 form_value.Unsigned()));
3272             break;
3273           case DW_AT_decl_line:
3274             decl.SetLine(form_value.Unsigned());
3275             break;
3276           case DW_AT_decl_column:
3277             decl.SetColumn(form_value.Unsigned());
3278             break;
3279           case DW_AT_name:
3280             name = form_value.AsCString();
3281             break;
3282           case DW_AT_linkage_name:
3283           case DW_AT_MIPS_linkage_name:
3284             mangled = form_value.AsCString();
3285             break;
3286           case DW_AT_type:
3287             type_die_form = form_value;
3288             break;
3289           case DW_AT_external:
3290             is_external = form_value.Boolean();
3291             break;
3292           case DW_AT_const_value:
3293             // If we have already found a DW_AT_location attribute, ignore this
3294             // attribute.
3295             if (!has_explicit_location) {
3296               location_is_const_value_data = true;
3297               // The constant value will be either a block, a data value or a
3298               // string.
3299               auto debug_info_data = die.GetData();
3300               if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3301                 // Retrieve the value as a block expression.
3302                 uint32_t block_offset =
3303                     form_value.BlockData() - debug_info_data.GetDataStart();
3304                 uint32_t block_length = form_value.Unsigned();
3305                 location.CopyOpcodeData(module, debug_info_data, block_offset,
3306                                         block_length);
3307               } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3308                 // Retrieve the value as a data expression.
3309                 DWARFFormValue::FixedFormSizes fixed_form_sizes =
3310                     DWARFFormValue::GetFixedFormSizesForAddressSize(
3311                         attributes.CompileUnitAtIndex(i)->GetAddressByteSize(),
3312                         attributes.CompileUnitAtIndex(i)->IsDWARF64());
3313                 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3314                 uint32_t data_length =
3315                     fixed_form_sizes.GetSize(form_value.Form());
3316                 if (data_length == 0) {
3317                   const uint8_t *data_pointer = form_value.BlockData();
3318                   if (data_pointer) {
3319                     form_value.Unsigned();
3320                   } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3321                     // we need to get the byte size of the type later after we
3322                     // create the variable
3323                     const_value = form_value;
3324                   }
3325                 } else
3326                   location.CopyOpcodeData(module, debug_info_data, data_offset,
3327                                           data_length);
3328               } else {
3329                 // Retrieve the value as a string expression.
3330                 if (form_value.Form() == DW_FORM_strp) {
3331                   DWARFFormValue::FixedFormSizes fixed_form_sizes =
3332                       DWARFFormValue::GetFixedFormSizesForAddressSize(
3333                           attributes.CompileUnitAtIndex(i)
3334                               ->GetAddressByteSize(),
3335                           attributes.CompileUnitAtIndex(i)->IsDWARF64());
3336                   uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3337                   uint32_t data_length =
3338                       fixed_form_sizes.GetSize(form_value.Form());
3339                   location.CopyOpcodeData(module, debug_info_data, data_offset,
3340                                           data_length);
3341                 } else {
3342                   const char *str = form_value.AsCString();
3343                   uint32_t string_offset =
3344                       str - (const char *)debug_info_data.GetDataStart();
3345                   uint32_t string_length = strlen(str) + 1;
3346                   location.CopyOpcodeData(module, debug_info_data,
3347                                           string_offset, string_length);
3348                 }
3349               }
3350             }
3351             break;
3352           case DW_AT_location: {
3353             location_is_const_value_data = false;
3354             has_explicit_location = true;
3355             if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3356               auto data = die.GetData();
3357 
3358               uint32_t block_offset =
3359                   form_value.BlockData() - data.GetDataStart();
3360               uint32_t block_length = form_value.Unsigned();
3361               location.CopyOpcodeData(module, data, block_offset, block_length);
3362             } else {
3363               const DWARFDataExtractor &debug_loc_data = DebugLocData();
3364               const dw_offset_t debug_loc_offset = form_value.Unsigned();
3365 
3366               size_t loc_list_length = DWARFExpression::LocationListSize(
3367                   die.GetCU(), debug_loc_data, debug_loc_offset);
3368               if (loc_list_length > 0) {
3369                 location.CopyOpcodeData(module, debug_loc_data,
3370                                         debug_loc_offset, loc_list_length);
3371                 assert(func_low_pc != LLDB_INVALID_ADDRESS);
3372                 location.SetLocationListSlide(
3373                     func_low_pc -
3374                     attributes.CompileUnitAtIndex(i)->GetBaseAddress());
3375               }
3376             }
3377           } break;
3378           case DW_AT_specification:
3379             spec_die = GetDIE(DIERef(form_value));
3380             break;
3381           case DW_AT_start_scope: {
3382             if (form_value.Form() == DW_FORM_sec_offset) {
3383               DWARFRangeList dwarf_scope_ranges;
3384               const DWARFDebugRangesBase *debug_ranges = DebugRanges();
3385               debug_ranges->FindRanges(die.GetCU(),
3386                                        form_value.Unsigned(),
3387                                        dwarf_scope_ranges);
3388             } else {
3389               // TODO: Handle the case when DW_AT_start_scope have form
3390               // constant. The
3391               // dwarf spec is a bit ambiguous about what is the expected
3392               // behavior in case the enclosing block have a non coninious
3393               // address range and the DW_AT_start_scope entry have a form
3394               // constant.
3395               GetObjectFile()->GetModule()->ReportWarning(
3396                   "0x%8.8" PRIx64
3397                   ": DW_AT_start_scope has unsupported form type (0x%x)\n",
3398                   die.GetID(), form_value.Form());
3399             }
3400 
3401             scope_ranges.Sort();
3402             scope_ranges.CombineConsecutiveRanges();
3403           } break;
3404           case DW_AT_artificial:
3405             is_artificial = form_value.Boolean();
3406             break;
3407           case DW_AT_accessibility:
3408             break; // accessibility =
3409                    // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
3410           case DW_AT_declaration:
3411           case DW_AT_description:
3412           case DW_AT_endianity:
3413           case DW_AT_segment:
3414           case DW_AT_visibility:
3415           default:
3416           case DW_AT_abstract_origin:
3417           case DW_AT_sibling:
3418             break;
3419           }
3420         }
3421       }
3422 
3423       const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3424       const dw_tag_t parent_tag = die.GetParent().Tag();
3425       bool is_static_member =
3426           (parent_tag == DW_TAG_compile_unit ||
3427            parent_tag == DW_TAG_partial_unit) &&
3428           (parent_context_die.Tag() == DW_TAG_class_type ||
3429            parent_context_die.Tag() == DW_TAG_structure_type);
3430 
3431       ValueType scope = eValueTypeInvalid;
3432 
3433       const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3434       SymbolContextScope *symbol_context_scope = NULL;
3435 
3436       bool has_explicit_mangled = mangled != nullptr;
3437       if (!mangled) {
3438         // LLDB relies on the mangled name (DW_TAG_linkage_name or
3439         // DW_AT_MIPS_linkage_name) to generate fully qualified names
3440         // of global variables with commands like "frame var j". For
3441         // example, if j were an int variable holding a value 4 and
3442         // declared in a namespace B which in turn is contained in a
3443         // namespace A, the command "frame var j" returns
3444         //   "(int) A::B::j = 4".
3445         // If the compiler does not emit a linkage name, we should be
3446         // able to generate a fully qualified name from the
3447         // declaration context.
3448         if ((parent_tag == DW_TAG_compile_unit ||
3449              parent_tag == DW_TAG_partial_unit) &&
3450             Language::LanguageIsCPlusPlus(die.GetLanguage())) {
3451           DWARFDeclContext decl_ctx;
3452 
3453           die.GetDWARFDeclContext(decl_ctx);
3454           mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString();
3455         }
3456       }
3457 
3458       if (tag == DW_TAG_formal_parameter)
3459         scope = eValueTypeVariableArgument;
3460       else {
3461         // DWARF doesn't specify if a DW_TAG_variable is a local, global
3462         // or static variable, so we have to do a little digging:
3463         // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3464         // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3465         // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3466         // Clang likes to combine small global variables into the same symbol
3467         // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3468         // so we need to look through the whole expression.
3469         bool is_static_lifetime =
3470             has_explicit_mangled ||
3471             (has_explicit_location && !location.IsValid());
3472         // Check if the location has a DW_OP_addr with any address value...
3473         lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3474         if (!location_is_const_value_data) {
3475           bool op_error = false;
3476           location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error);
3477           if (op_error) {
3478             StreamString strm;
3479             location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0,
3480                                             NULL);
3481             GetObjectFile()->GetModule()->ReportError(
3482                 "0x%8.8x: %s has an invalid location: %s", die.GetOffset(),
3483                 die.GetTagAsCString(), strm.GetData());
3484           }
3485           if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
3486             is_static_lifetime = true;
3487         }
3488         SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
3489         if (debug_map_symfile)
3490           // Set the module of the expression to the linked module
3491           // instead of the oject file so the relocated address can be
3492           // found there.
3493           location.SetModule(debug_map_symfile->GetObjectFile()->GetModule());
3494 
3495         if (is_static_lifetime) {
3496           if (is_external)
3497             scope = eValueTypeVariableGlobal;
3498           else
3499             scope = eValueTypeVariableStatic;
3500 
3501           if (debug_map_symfile) {
3502             // When leaving the DWARF in the .o files on darwin, when we have a
3503             // global variable that wasn't initialized, the .o file might not
3504             // have allocated a virtual address for the global variable. In
3505             // this case it will have created a symbol for the global variable
3506             // that is undefined/data and external and the value will be the
3507             // byte size of the variable. When we do the address map in
3508             // SymbolFileDWARFDebugMap we rely on having an address, we need to
3509             // do some magic here so we can get the correct address for our
3510             // global variable. The address for all of these entries will be
3511             // zero, and there will be an undefined symbol in this object file,
3512             // and the executable will have a matching symbol with a good
3513             // address. So here we dig up the correct address and replace it in
3514             // the location for the variable, and set the variable's symbol
3515             // context scope to be that of the main executable so the file
3516             // address will resolve correctly.
3517             bool linked_oso_file_addr = false;
3518             if (is_external && location_DW_OP_addr == 0) {
3519               // we have a possible uninitialized extern global
3520               ConstString const_name(mangled ? mangled : name);
3521               ObjectFile *debug_map_objfile =
3522                   debug_map_symfile->GetObjectFile();
3523               if (debug_map_objfile) {
3524                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3525                 if (debug_map_symtab) {
3526                   Symbol *exe_symbol =
3527                       debug_map_symtab->FindFirstSymbolWithNameAndType(
3528                           const_name, eSymbolTypeData, Symtab::eDebugYes,
3529                           Symtab::eVisibilityExtern);
3530                   if (exe_symbol) {
3531                     if (exe_symbol->ValueIsAddress()) {
3532                       const addr_t exe_file_addr =
3533                           exe_symbol->GetAddressRef().GetFileAddress();
3534                       if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3535                         if (location.Update_DW_OP_addr(exe_file_addr)) {
3536                           linked_oso_file_addr = true;
3537                           symbol_context_scope = exe_symbol;
3538                         }
3539                       }
3540                     }
3541                   }
3542                 }
3543               }
3544             }
3545 
3546             if (!linked_oso_file_addr) {
3547               // The DW_OP_addr is not zero, but it contains a .o file address
3548               // which needs to be linked up correctly.
3549               const lldb::addr_t exe_file_addr =
3550                   debug_map_symfile->LinkOSOFileAddress(this,
3551                                                         location_DW_OP_addr);
3552               if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3553                 // Update the file address for this variable
3554                 location.Update_DW_OP_addr(exe_file_addr);
3555               } else {
3556                 // Variable didn't make it into the final executable
3557                 return var_sp;
3558               }
3559             }
3560           }
3561         } else {
3562           if (location_is_const_value_data)
3563             scope = eValueTypeVariableStatic;
3564           else {
3565             scope = eValueTypeVariableLocal;
3566             if (debug_map_symfile) {
3567               // We need to check for TLS addresses that we need to fixup
3568               if (location.ContainsThreadLocalStorage()) {
3569                 location.LinkThreadLocalStorage(
3570                     debug_map_symfile->GetObjectFile()->GetModule(),
3571                     [this, debug_map_symfile](
3572                         lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
3573                       return debug_map_symfile->LinkOSOFileAddress(
3574                           this, unlinked_file_addr);
3575                     });
3576                 scope = eValueTypeVariableThreadLocal;
3577               }
3578             }
3579           }
3580         }
3581       }
3582 
3583       if (symbol_context_scope == NULL) {
3584         switch (parent_tag) {
3585         case DW_TAG_subprogram:
3586         case DW_TAG_inlined_subroutine:
3587         case DW_TAG_lexical_block:
3588           if (sc.function) {
3589             symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(
3590                 sc_parent_die.GetID());
3591             if (symbol_context_scope == NULL)
3592               symbol_context_scope = sc.function;
3593           }
3594           break;
3595 
3596         default:
3597           symbol_context_scope = sc.comp_unit;
3598           break;
3599         }
3600       }
3601 
3602       if (symbol_context_scope) {
3603         SymbolFileTypeSP type_sp(
3604             new SymbolFileType(*this, DIERef(type_die_form).GetUID(this)));
3605 
3606         if (const_value.Form() && type_sp && type_sp->GetType())
3607           location.CopyOpcodeData(const_value.Unsigned(),
3608                                   type_sp->GetType()->GetByteSize(),
3609                                   die.GetCU()->GetAddressByteSize());
3610 
3611         var_sp.reset(new Variable(die.GetID(), name, mangled, type_sp, scope,
3612                                   symbol_context_scope, scope_ranges, &decl,
3613                                   location, is_external, is_artificial,
3614                                   is_static_member));
3615 
3616         var_sp->SetLocationIsConstantValueData(location_is_const_value_data);
3617       } else {
3618         // Not ready to parse this variable yet. It might be a global or static
3619         // variable that is in a function scope and the function in the symbol
3620         // context wasn't filled in yet
3621         return var_sp;
3622       }
3623     }
3624     // Cache var_sp even if NULL (the variable was just a specification or was
3625     // missing vital information to be able to be displayed in the debugger
3626     // (missing location due to optimization, etc)) so we don't re-parse this
3627     // DIE over and over later...
3628     GetDIEToVariable()[die.GetDIE()] = var_sp;
3629     if (spec_die)
3630       GetDIEToVariable()[spec_die.GetDIE()] = var_sp;
3631   }
3632   return var_sp;
3633 }
3634 
3635 DWARFDIE
3636 SymbolFileDWARF::FindBlockContainingSpecification(
3637     const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
3638   // Give the concrete function die specified by "func_die_offset", find the
3639   // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3640   // to "spec_block_die_offset"
3641   return FindBlockContainingSpecification(DebugInfo()->GetDIE(func_die_ref),
3642                                           spec_block_die_offset);
3643 }
3644 
3645 DWARFDIE
3646 SymbolFileDWARF::FindBlockContainingSpecification(
3647     const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
3648   if (die) {
3649     switch (die.Tag()) {
3650     case DW_TAG_subprogram:
3651     case DW_TAG_inlined_subroutine:
3652     case DW_TAG_lexical_block: {
3653       if (die.GetAttributeValueAsReference(
3654               DW_AT_specification, DW_INVALID_OFFSET) == spec_block_die_offset)
3655         return die;
3656 
3657       if (die.GetAttributeValueAsReference(DW_AT_abstract_origin,
3658                                            DW_INVALID_OFFSET) ==
3659           spec_block_die_offset)
3660         return die;
3661     } break;
3662     }
3663 
3664     // Give the concrete function die specified by "func_die_offset", find the
3665     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3666     // to "spec_block_die_offset"
3667     for (DWARFDIE child_die = die.GetFirstChild(); child_die;
3668          child_die = child_die.GetSibling()) {
3669       DWARFDIE result_die =
3670           FindBlockContainingSpecification(child_die, spec_block_die_offset);
3671       if (result_die)
3672         return result_die;
3673     }
3674   }
3675 
3676   return DWARFDIE();
3677 }
3678 
3679 size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc,
3680                                        const DWARFDIE &orig_die,
3681                                        const lldb::addr_t func_low_pc,
3682                                        bool parse_siblings, bool parse_children,
3683                                        VariableList *cc_variable_list) {
3684   if (!orig_die)
3685     return 0;
3686 
3687   VariableListSP variable_list_sp;
3688 
3689   size_t vars_added = 0;
3690   DWARFDIE die = orig_die;
3691   while (die) {
3692     dw_tag_t tag = die.Tag();
3693 
3694     // Check to see if we have already parsed this variable or constant?
3695     VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
3696     if (var_sp) {
3697       if (cc_variable_list)
3698         cc_variable_list->AddVariableIfUnique(var_sp);
3699     } else {
3700       // We haven't already parsed it, lets do that now.
3701       if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3702           (tag == DW_TAG_formal_parameter && sc.function)) {
3703         if (variable_list_sp.get() == NULL) {
3704           DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die);
3705           dw_tag_t parent_tag = sc_parent_die.Tag();
3706           switch (parent_tag) {
3707           case DW_TAG_compile_unit:
3708           case DW_TAG_partial_unit:
3709             if (sc.comp_unit != NULL) {
3710               variable_list_sp = sc.comp_unit->GetVariableList(false);
3711               if (variable_list_sp.get() == NULL) {
3712                 variable_list_sp.reset(new VariableList());
3713               }
3714             } else {
3715               GetObjectFile()->GetModule()->ReportError(
3716                   "parent 0x%8.8" PRIx64 " %s with no valid compile unit in "
3717                                          "symbol context for 0x%8.8" PRIx64
3718                   " %s.\n",
3719                   sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(),
3720                   orig_die.GetID(), orig_die.GetTagAsCString());
3721             }
3722             break;
3723 
3724           case DW_TAG_subprogram:
3725           case DW_TAG_inlined_subroutine:
3726           case DW_TAG_lexical_block:
3727             if (sc.function != NULL) {
3728               // Check to see if we already have parsed the variables for the
3729               // given scope
3730 
3731               Block *block = sc.function->GetBlock(true).FindBlockByID(
3732                   sc_parent_die.GetID());
3733               if (block == NULL) {
3734                 // This must be a specification or abstract origin with a
3735                 // concrete block counterpart in the current function. We need
3736                 // to find the concrete block so we can correctly add the
3737                 // variable to it
3738                 const DWARFDIE concrete_block_die =
3739                     FindBlockContainingSpecification(
3740                         DIERef(sc.function->GetID(), this),
3741                         sc_parent_die.GetOffset());
3742                 if (concrete_block_die)
3743                   block = sc.function->GetBlock(true).FindBlockByID(
3744                       concrete_block_die.GetID());
3745               }
3746 
3747               if (block != NULL) {
3748                 const bool can_create = false;
3749                 variable_list_sp = block->GetBlockVariableList(can_create);
3750                 if (variable_list_sp.get() == NULL) {
3751                   variable_list_sp.reset(new VariableList());
3752                   block->SetVariableList(variable_list_sp);
3753                 }
3754               }
3755             }
3756             break;
3757 
3758           default:
3759             GetObjectFile()->GetModule()->ReportError(
3760                 "didn't find appropriate parent DIE for variable list for "
3761                 "0x%8.8" PRIx64 " %s.\n",
3762                 orig_die.GetID(), orig_die.GetTagAsCString());
3763             break;
3764           }
3765         }
3766 
3767         if (variable_list_sp) {
3768           VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc));
3769           if (var_sp) {
3770             variable_list_sp->AddVariableIfUnique(var_sp);
3771             if (cc_variable_list)
3772               cc_variable_list->AddVariableIfUnique(var_sp);
3773             ++vars_added;
3774           }
3775         }
3776       }
3777     }
3778 
3779     bool skip_children = (sc.function == NULL && tag == DW_TAG_subprogram);
3780 
3781     if (!skip_children && parse_children && die.HasChildren()) {
3782       vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true,
3783                                    true, cc_variable_list);
3784     }
3785 
3786     if (parse_siblings)
3787       die = die.GetSibling();
3788     else
3789       die.Clear();
3790   }
3791   return vars_added;
3792 }
3793 
3794 /// Collect call graph edges present in a function DIE.
3795 static std::vector<lldb_private::CallEdge>
3796 CollectCallEdges(DWARFDIE function_die) {
3797   // Check if the function has a supported call site-related attribute.
3798   // TODO: In the future it may be worthwhile to support call_all_source_calls.
3799   uint64_t has_call_edges =
3800       function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0);
3801   if (!has_call_edges)
3802     return {};
3803 
3804   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3805   LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}",
3806            function_die.GetPubname());
3807 
3808   // Scan the DIE for TAG_call_site entries.
3809   // TODO: A recursive scan of all blocks in the subprogram is needed in order
3810   // to be DWARF5-compliant. This may need to be done lazily to be performant.
3811   // For now, assume that all entries are nested directly under the subprogram
3812   // (this is the kind of DWARF LLVM produces) and parse them eagerly.
3813   std::vector<CallEdge> call_edges;
3814   for (DWARFDIE child = function_die.GetFirstChild(); child.IsValid();
3815        child = child.GetSibling()) {
3816     if (child.Tag() != DW_TAG_call_site)
3817       continue;
3818 
3819     // Extract DW_AT_call_origin (the call target's DIE).
3820     DWARFDIE call_origin = child.GetReferencedDIE(DW_AT_call_origin);
3821     if (!call_origin.IsValid()) {
3822       LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}",
3823                function_die.GetPubname());
3824       continue;
3825     }
3826 
3827     // Extract DW_AT_call_return_pc (the PC the call returns to) if it's
3828     // available. It should only ever be unavailable for tail call edges, in
3829     // which case use LLDB_INVALID_ADDRESS.
3830     addr_t return_pc = child.GetAttributeValueAsAddress(DW_AT_call_return_pc,
3831                                                         LLDB_INVALID_ADDRESS);
3832 
3833     LLDB_LOG(log, "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x})",
3834              call_origin.GetPubname(), return_pc);
3835     call_edges.emplace_back(call_origin.GetMangledName(), return_pc);
3836   }
3837   return call_edges;
3838 }
3839 
3840 std::vector<lldb_private::CallEdge>
3841 SymbolFileDWARF::ParseCallEdgesInFunction(UserID func_id) {
3842   DWARFDIE func_die = GetDIEFromUID(func_id.GetID());
3843   if (func_die.IsValid())
3844     return CollectCallEdges(func_die);
3845   return {};
3846 }
3847 
3848 //------------------------------------------------------------------
3849 // PluginInterface protocol
3850 //------------------------------------------------------------------
3851 ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); }
3852 
3853 uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; }
3854 
3855 void SymbolFileDWARF::Dump(lldb_private::Stream &s) { m_index->Dump(s); }
3856 
3857 SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() {
3858   if (m_debug_map_symfile == NULL && !m_debug_map_module_wp.expired()) {
3859     lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
3860     if (module_sp) {
3861       SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
3862       if (sym_vendor)
3863         m_debug_map_symfile =
3864             (SymbolFileDWARFDebugMap *)sym_vendor->GetSymbolFile();
3865     }
3866   }
3867   return m_debug_map_symfile;
3868 }
3869 
3870 DWARFExpression::LocationListFormat
3871 SymbolFileDWARF::GetLocationListFormat() const {
3872   if (m_data_debug_loclists.m_data.GetByteSize() > 0)
3873     return DWARFExpression::LocLists;
3874   return DWARFExpression::RegularLocationList;
3875 }
3876 
3877 SymbolFileDWARFDwp *SymbolFileDWARF::GetDwpSymbolFile() {
3878   llvm::call_once(m_dwp_symfile_once_flag, [this]() {
3879     ModuleSpec module_spec;
3880     module_spec.GetFileSpec() = m_obj_file->GetFileSpec();
3881     module_spec.GetSymbolFileSpec() =
3882         FileSpec(m_obj_file->GetFileSpec().GetPath() + ".dwp");
3883     FileSpec dwp_filespec = Symbols::LocateExecutableSymbolFile(module_spec);
3884     if (FileSystem::Instance().Exists(dwp_filespec)) {
3885       m_dwp_symfile = SymbolFileDWARFDwp::Create(GetObjectFile()->GetModule(),
3886                                                  dwp_filespec);
3887     }
3888   });
3889   return m_dwp_symfile.get();
3890 }
3891