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