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