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