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