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