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