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