1 //===-- SymbolFileDWARF.cpp ------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "SymbolFileDWARF.h"
11 #include "llvm/ADT/Optional.h"
12 #include "llvm/Support/Casting.h"
13 #include "llvm/Support/Threading.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleList.h"
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Core/Section.h"
20 #include "lldb/Core/StreamFile.h"
21 #include "lldb/Core/Value.h"
22 #include "lldb/Utility/ArchSpec.h"
23 #include "lldb/Utility/RegularExpression.h"
24 #include "lldb/Utility/Scalar.h"
25 #include "lldb/Utility/StreamString.h"
26 #include "lldb/Utility/Timer.h"
28 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
29 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
31 #include "lldb/Host/FileSystem.h"
32 #include "lldb/Host/Host.h"
34 #include "lldb/Interpreter/OptionValueFileSpecList.h"
35 #include "lldb/Interpreter/OptionValueProperties.h"
37 #include "lldb/Symbol/Block.h"
38 #include "lldb/Symbol/ClangASTContext.h"
39 #include "lldb/Symbol/ClangUtil.h"
40 #include "lldb/Symbol/CompileUnit.h"
41 #include "lldb/Symbol/CompilerDecl.h"
42 #include "lldb/Symbol/CompilerDeclContext.h"
43 #include "lldb/Symbol/DebugMacros.h"
44 #include "lldb/Symbol/LineTable.h"
45 #include "lldb/Symbol/LocateSymbolFile.h"
46 #include "lldb/Symbol/ObjectFile.h"
47 #include "lldb/Symbol/SymbolFile.h"
48 #include "lldb/Symbol/TypeMap.h"
49 #include "lldb/Symbol/TypeSystem.h"
50 #include "lldb/Symbol/VariableList.h"
52 #include "lldb/Target/Language.h"
53 #include "lldb/Target/Target.h"
55 #include "AppleDWARFIndex.h"
56 #include "DWARFASTParser.h"
57 #include "DWARFASTParserClang.h"
58 #include "DWARFCompileUnit.h"
59 #include "DWARFDebugAbbrev.h"
60 #include "DWARFDebugAranges.h"
61 #include "DWARFDebugInfo.h"
62 #include "DWARFDebugMacro.h"
63 #include "DWARFDebugRanges.h"
64 #include "DWARFDeclContext.h"
65 #include "DWARFFormValue.h"
66 #include "DWARFTypeUnit.h"
67 #include "DWARFUnit.h"
68 #include "DebugNamesDWARFIndex.h"
69 #include "LogChannelDWARF.h"
70 #include "ManualDWARFIndex.h"
71 #include "SymbolFileDWARFDebugMap.h"
72 #include "SymbolFileDWARFDwo.h"
73 #include "SymbolFileDWARFDwp.h"
75 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
76 #include "llvm/Support/FileSystem.h"
85 //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
87 #ifdef ENABLE_DEBUG_PRINTF
89 #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
91 #define DEBUG_PRINTF(fmt, ...)
95 using namespace lldb_private;
97 char SymbolFileDWARF::ID;
100 // child_requires_parent_class_union_or_struct_to_be_completed (dw_tag_t tag)
106 // case DW_TAG_subprogram:
107 // case DW_TAG_inlined_subroutine:
108 // case DW_TAG_class_type:
109 // case DW_TAG_structure_type:
110 // case DW_TAG_union_type:
119 #define LLDB_PROPERTIES_symbolfiledwarf
120 #include "SymbolFileDWARFProperties.inc"
123 #define LLDB_PROPERTIES_symbolfiledwarf
124 #include "SymbolFileDWARFPropertiesEnum.inc"
127 class PluginProperties : public Properties {
129 static ConstString GetSettingName() {
130 return SymbolFileDWARF::GetPluginNameStatic();
134 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
135 m_collection_sp->Initialize(g_symbolfiledwarf_properties);
138 FileSpecList GetSymLinkPaths() {
139 const OptionValueFileSpecList *option_value =
140 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(
141 nullptr, true, ePropertySymLinkPaths);
142 assert(option_value);
143 return option_value->GetCurrentValue();
146 bool IgnoreFileIndexes() const {
147 return m_collection_sp->GetPropertyAtIndexAsBoolean(
148 nullptr, ePropertyIgnoreIndexes, false);
152 typedef std::shared_ptr<PluginProperties> SymbolFileDWARFPropertiesSP;
154 static const SymbolFileDWARFPropertiesSP &GetGlobalPluginProperties() {
155 static const auto g_settings_sp(std::make_shared<PluginProperties>());
156 return g_settings_sp;
161 static const llvm::DWARFDebugLine::LineTable *
162 ParseLLVMLineTable(lldb_private::DWARFContext &context,
163 llvm::DWARFDebugLine &line, dw_offset_t line_offset,
164 dw_offset_t unit_offset) {
165 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
167 llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVM();
168 llvm::DWARFContext &ctx = context.GetAsLLVM();
169 llvm::Expected<const llvm::DWARFDebugLine::LineTable *> line_table =
170 line.getOrParseLineTable(
171 data, line_offset, ctx, nullptr, [&](llvm::Error e) {
172 LLDB_LOG_ERROR(log, std::move(e),
173 "SymbolFileDWARF::ParseLineTable failed to parse");
177 LLDB_LOG_ERROR(log, line_table.takeError(),
178 "SymbolFileDWARF::ParseLineTable failed to parse");
184 static llvm::Optional<std::string>
185 GetFileByIndex(const llvm::DWARFDebugLine::Prologue &prologue, size_t idx,
186 llvm::StringRef compile_dir, FileSpec::Style style) {
187 // Try to get an absolute path first.
188 std::string abs_path;
189 auto absolute = llvm::DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath;
190 if (prologue.getFileNameByIndex(idx, compile_dir, absolute, abs_path, style))
191 return std::move(abs_path);
193 // Otherwise ask for a relative path.
194 std::string rel_path;
195 auto relative = llvm::DILineInfoSpecifier::FileLineInfoKind::Default;
196 if (!prologue.getFileNameByIndex(idx, compile_dir, relative, rel_path, style))
198 return std::move(rel_path);
202 ParseSupportFilesFromPrologue(const lldb::ModuleSP &module,
203 const llvm::DWARFDebugLine::Prologue &prologue,
204 FileSpec::Style style,
205 llvm::StringRef compile_dir = {}) {
206 FileSpecList support_files;
207 size_t first_file = 0;
208 if (prologue.getVersion() <= 4) {
209 // File index 0 is not valid before DWARF v5. Add a dummy entry to ensure
210 // support file list indices match those we get from the debug info and line
212 support_files.Append(FileSpec());
216 const size_t number_of_files = prologue.FileNames.size();
217 for (size_t idx = first_file; idx <= number_of_files; ++idx) {
218 std::string remapped_file;
219 if (auto file_path = GetFileByIndex(prologue, idx, compile_dir, style))
220 if (!module->RemapSourceFile(llvm::StringRef(*file_path), remapped_file))
221 remapped_file = std::move(*file_path);
223 // Unconditionally add an entry, so the indices match up.
224 support_files.EmplaceBack(remapped_file, style);
227 return support_files;
230 FileSpecList SymbolFileDWARF::GetSymlinkPaths() {
231 return GetGlobalPluginProperties()->GetSymLinkPaths();
234 void SymbolFileDWARF::Initialize() {
235 LogChannelDWARF::Initialize();
236 PluginManager::RegisterPlugin(GetPluginNameStatic(),
237 GetPluginDescriptionStatic(), CreateInstance,
241 void SymbolFileDWARF::DebuggerInitialize(Debugger &debugger) {
242 if (!PluginManager::GetSettingForSymbolFilePlugin(
243 debugger, PluginProperties::GetSettingName())) {
244 const bool is_global_setting = true;
245 PluginManager::CreateSettingForSymbolFilePlugin(
246 debugger, GetGlobalPluginProperties()->GetValueProperties(),
247 ConstString("Properties for the dwarf symbol-file plug-in."),
252 void SymbolFileDWARF::Terminate() {
253 PluginManager::UnregisterPlugin(CreateInstance);
254 LogChannelDWARF::Terminate();
257 lldb_private::ConstString SymbolFileDWARF::GetPluginNameStatic() {
258 static ConstString g_name("dwarf");
262 const char *SymbolFileDWARF::GetPluginDescriptionStatic() {
263 return "DWARF and DWARF3 debug symbol file reader.";
266 SymbolFile *SymbolFileDWARF::CreateInstance(ObjectFileSP objfile_sp) {
267 return new SymbolFileDWARF(std::move(objfile_sp),
268 /*dwo_section_list*/ nullptr);
271 TypeList &SymbolFileDWARF::GetTypeList() {
272 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
273 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
274 return debug_map_symfile->GetTypeList();
275 return SymbolFile::GetTypeList();
277 void SymbolFileDWARF::GetTypes(const DWARFDIE &die, dw_offset_t min_die_offset,
278 dw_offset_t max_die_offset, uint32_t type_mask,
281 const dw_offset_t die_offset = die.GetOffset();
283 if (die_offset >= max_die_offset)
286 if (die_offset >= min_die_offset) {
287 const dw_tag_t tag = die.Tag();
289 bool add_type = false;
292 case DW_TAG_array_type:
293 add_type = (type_mask & eTypeClassArray) != 0;
295 case DW_TAG_unspecified_type:
296 case DW_TAG_base_type:
297 add_type = (type_mask & eTypeClassBuiltin) != 0;
299 case DW_TAG_class_type:
300 add_type = (type_mask & eTypeClassClass) != 0;
302 case DW_TAG_structure_type:
303 add_type = (type_mask & eTypeClassStruct) != 0;
305 case DW_TAG_union_type:
306 add_type = (type_mask & eTypeClassUnion) != 0;
308 case DW_TAG_enumeration_type:
309 add_type = (type_mask & eTypeClassEnumeration) != 0;
311 case DW_TAG_subroutine_type:
312 case DW_TAG_subprogram:
313 case DW_TAG_inlined_subroutine:
314 add_type = (type_mask & eTypeClassFunction) != 0;
316 case DW_TAG_pointer_type:
317 add_type = (type_mask & eTypeClassPointer) != 0;
319 case DW_TAG_rvalue_reference_type:
320 case DW_TAG_reference_type:
321 add_type = (type_mask & eTypeClassReference) != 0;
324 add_type = (type_mask & eTypeClassTypedef) != 0;
326 case DW_TAG_ptr_to_member_type:
327 add_type = (type_mask & eTypeClassMemberPointer) != 0;
334 const bool assert_not_being_parsed = true;
335 Type *type = ResolveTypeUID(die, assert_not_being_parsed);
337 if (type_set.find(type) == type_set.end())
338 type_set.insert(type);
343 for (DWARFDIE child_die = die.GetFirstChild(); child_die.IsValid();
344 child_die = child_die.GetSibling()) {
345 GetTypes(child_die, min_die_offset, max_die_offset, type_mask, type_set);
350 void SymbolFileDWARF::GetTypes(SymbolContextScope *sc_scope,
351 TypeClass type_mask, TypeList &type_list)
354 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
357 CompileUnit *comp_unit = nullptr;
358 DWARFUnit *dwarf_cu = nullptr;
360 comp_unit = sc_scope->CalculateSymbolContextCompileUnit();
363 dwarf_cu = GetDWARFCompileUnit(comp_unit);
366 GetTypes(dwarf_cu->DIE(), dwarf_cu->GetOffset(),
367 dwarf_cu->GetNextUnitOffset(), type_mask, type_set);
369 DWARFDebugInfo *info = DebugInfo();
371 const size_t num_cus = info->GetNumUnits();
372 for (size_t cu_idx = 0; cu_idx < num_cus; ++cu_idx) {
373 dwarf_cu = info->GetUnitAtIndex(cu_idx);
375 GetTypes(dwarf_cu->DIE(), 0, UINT32_MAX, type_mask, type_set);
381 std::set<CompilerType> compiler_type_set;
382 for (Type *type : type_set) {
383 CompilerType compiler_type = type->GetForwardCompilerType();
384 if (compiler_type_set.find(compiler_type) == compiler_type_set.end()) {
385 compiler_type_set.insert(compiler_type);
386 type_list.Insert(type->shared_from_this());
391 // Gets the first parent that is a lexical block, function or inlined
392 // subroutine, or compile unit.
394 SymbolFileDWARF::GetParentSymbolContextDIE(const DWARFDIE &child_die) {
396 for (die = child_die.GetParent(); die; die = die.GetParent()) {
397 dw_tag_t tag = die.Tag();
400 case DW_TAG_compile_unit:
401 case DW_TAG_partial_unit:
402 case DW_TAG_subprogram:
403 case DW_TAG_inlined_subroutine:
404 case DW_TAG_lexical_block:
413 SymbolFileDWARF::SymbolFileDWARF(ObjectFileSP objfile_sp,
414 SectionList *dwo_section_list)
415 : SymbolFile(std::move(objfile_sp)),
416 UserID(0x7fffffff00000000), // Used by SymbolFileDWARFDebugMap to
417 // when this class parses .o files to
418 // contain the .o file index/ID
419 m_debug_map_module_wp(), m_debug_map_symfile(nullptr),
420 m_context(m_objfile_sp->GetModule()->GetSectionList(), dwo_section_list),
421 m_data_debug_loc(), m_abbr(), m_info(), m_fetched_external_modules(false),
422 m_supports_DW_AT_APPLE_objc_complete_type(eLazyBoolCalculate),
423 m_unique_ast_type_map() {}
425 SymbolFileDWARF::~SymbolFileDWARF() {}
427 static ConstString GetDWARFMachOSegmentName() {
428 static ConstString g_dwarf_section_name("__DWARF");
429 return g_dwarf_section_name;
432 UniqueDWARFASTTypeMap &SymbolFileDWARF::GetUniqueDWARFASTTypeMap() {
433 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
434 if (debug_map_symfile)
435 return debug_map_symfile->GetUniqueDWARFASTTypeMap();
437 return m_unique_ast_type_map;
440 llvm::Expected<TypeSystem &>
441 SymbolFileDWARF::GetTypeSystemForLanguage(LanguageType language) {
442 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
443 return debug_map_symfile->GetTypeSystemForLanguage(language);
445 auto type_system_or_err =
446 m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
447 if (type_system_or_err) {
448 type_system_or_err->SetSymbolFile(this);
450 return type_system_or_err;
453 void SymbolFileDWARF::InitializeObject() {
454 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
456 if (!GetGlobalPluginProperties()->IgnoreFileIndexes()) {
457 DWARFDataExtractor apple_names, apple_namespaces, apple_types, apple_objc;
458 LoadSectionData(eSectionTypeDWARFAppleNames, apple_names);
459 LoadSectionData(eSectionTypeDWARFAppleNamespaces, apple_namespaces);
460 LoadSectionData(eSectionTypeDWARFAppleTypes, apple_types);
461 LoadSectionData(eSectionTypeDWARFAppleObjC, apple_objc);
463 m_index = AppleDWARFIndex::Create(
464 *GetObjectFile()->GetModule(), apple_names, apple_namespaces,
465 apple_types, apple_objc, m_context.getOrLoadStrData());
470 DWARFDataExtractor debug_names;
471 LoadSectionData(eSectionTypeDWARFDebugNames, debug_names);
472 if (debug_names.GetByteSize() > 0) {
473 llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> index_or =
474 DebugNamesDWARFIndex::Create(
475 *GetObjectFile()->GetModule(), debug_names,
476 m_context.getOrLoadStrData(), DebugInfo());
478 m_index = std::move(*index_or);
481 LLDB_LOG_ERROR(log, index_or.takeError(),
482 "Unable to read .debug_names data: {0}");
486 m_index = std::make_unique<ManualDWARFIndex>(*GetObjectFile()->GetModule(),
490 bool SymbolFileDWARF::SupportedVersion(uint16_t version) {
491 return version >= 2 && version <= 5;
494 uint32_t SymbolFileDWARF::CalculateAbilities() {
495 uint32_t abilities = 0;
496 if (m_objfile_sp != nullptr) {
497 const Section *section = nullptr;
498 const SectionList *section_list = m_objfile_sp->GetSectionList();
499 if (section_list == nullptr)
502 uint64_t debug_abbrev_file_size = 0;
503 uint64_t debug_info_file_size = 0;
504 uint64_t debug_line_file_size = 0;
506 section = section_list->FindSectionByName(GetDWARFMachOSegmentName()).get();
509 section_list = §ion->GetChildren();
512 section_list->FindSectionByType(eSectionTypeDWARFDebugInfo, true).get();
513 if (section != nullptr) {
514 debug_info_file_size = section->GetFileSize();
517 section_list->FindSectionByType(eSectionTypeDWARFDebugAbbrev, true)
520 debug_abbrev_file_size = section->GetFileSize();
522 DWARFDebugAbbrev *abbrev = DebugAbbrev();
524 std::set<dw_form_t> invalid_forms;
525 abbrev->GetUnsupportedForms(invalid_forms);
526 if (!invalid_forms.empty()) {
528 error.Printf("unsupported DW_FORM value%s:",
529 invalid_forms.size() > 1 ? "s" : "");
530 for (auto form : invalid_forms)
531 error.Printf(" %#x", form);
532 m_objfile_sp->GetModule()->ReportWarning(
533 "%s", error.GetString().str().c_str());
539 section_list->FindSectionByType(eSectionTypeDWARFDebugLine, true)
542 debug_line_file_size = section->GetFileSize();
544 const char *symfile_dir_cstr =
545 m_objfile_sp->GetFileSpec().GetDirectory().GetCString();
546 if (symfile_dir_cstr) {
547 if (strcasestr(symfile_dir_cstr, ".dsym")) {
548 if (m_objfile_sp->GetType() == ObjectFile::eTypeDebugInfo) {
549 // We have a dSYM file that didn't have a any debug info. If the
550 // string table has a size of 1, then it was made from an
551 // executable with no debug info, or from an executable that was
554 section_list->FindSectionByType(eSectionTypeDWARFDebugStr, true)
556 if (section && section->GetFileSize() == 1) {
557 m_objfile_sp->GetModule()->ReportWarning(
558 "empty dSYM file detected, dSYM was created with an "
559 "executable with no debug info.");
566 if (debug_abbrev_file_size > 0 && debug_info_file_size > 0)
567 abilities |= CompileUnits | Functions | Blocks | GlobalVariables |
568 LocalVariables | VariableTypes;
570 if (debug_line_file_size > 0)
571 abilities |= LineTables;
576 const DWARFDataExtractor &
577 SymbolFileDWARF::GetCachedSectionData(lldb::SectionType sect_type,
578 DWARFDataSegment &data_segment) {
579 llvm::call_once(data_segment.m_flag, [this, sect_type, &data_segment] {
580 this->LoadSectionData(sect_type, std::ref(data_segment.m_data));
582 return data_segment.m_data;
585 void SymbolFileDWARF::LoadSectionData(lldb::SectionType sect_type,
586 DWARFDataExtractor &data) {
587 ModuleSP module_sp(m_objfile_sp->GetModule());
588 const SectionList *section_list = module_sp->GetSectionList();
592 SectionSP section_sp(section_list->FindSectionByType(sect_type, true));
597 m_objfile_sp->ReadSectionData(section_sp.get(), data);
600 DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() {
604 const DWARFDataExtractor &debug_abbrev_data = m_context.getOrLoadAbbrevData();
605 if (debug_abbrev_data.GetByteSize() == 0)
608 auto abbr = std::make_unique<DWARFDebugAbbrev>();
609 llvm::Error error = abbr->parse(debug_abbrev_data);
611 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
612 LLDB_LOG_ERROR(log, std::move(error),
613 "Unable to read .debug_abbrev section: {0}");
617 m_abbr = std::move(abbr);
621 const DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() const {
625 DWARFDebugInfo *SymbolFileDWARF::DebugInfo() {
626 if (m_info == nullptr) {
627 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
628 Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
629 static_cast<void *>(this));
630 if (m_context.getOrLoadDebugInfoData().GetByteSize() > 0)
631 m_info = std::make_unique<DWARFDebugInfo>(*this, m_context);
636 const DWARFDebugInfo *SymbolFileDWARF::DebugInfo() const {
641 SymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit) {
645 DWARFDebugInfo *info = DebugInfo();
647 // The compile unit ID is the index of the DWARF unit.
648 DWARFUnit *dwarf_cu = info->GetUnitAtIndex(comp_unit->GetID());
649 if (dwarf_cu && dwarf_cu->GetUserData() == nullptr)
650 dwarf_cu->SetUserData(comp_unit);
656 DWARFDebugRanges *SymbolFileDWARF::GetDebugRanges() {
658 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
659 Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
660 static_cast<void *>(this));
662 if (m_context.getOrLoadRangesData().GetByteSize() > 0)
663 m_ranges.reset(new DWARFDebugRanges());
666 m_ranges->Extract(m_context);
668 return m_ranges.get();
671 lldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFCompileUnit &dwarf_cu) {
673 CompileUnit *comp_unit = (CompileUnit *)dwarf_cu.GetUserData();
675 // We already parsed this compile unit, had out a shared pointer to it
676 cu_sp = comp_unit->shared_from_this();
678 if (&dwarf_cu.GetSymbolFileDWARF() != this) {
679 return dwarf_cu.GetSymbolFileDWARF().ParseCompileUnit(dwarf_cu);
680 } else if (dwarf_cu.GetOffset() == 0 && GetDebugMapSymfile()) {
681 // Let the debug map create the compile unit
682 cu_sp = m_debug_map_symfile->GetCompileUnit(this);
683 dwarf_cu.SetUserData(cu_sp.get());
685 ModuleSP module_sp(m_objfile_sp->GetModule());
687 const DWARFBaseDIE cu_die =
688 dwarf_cu.GetNonSkeletonUnit().GetUnitDIEOnly();
690 FileSpec cu_file_spec(cu_die.GetName(), dwarf_cu.GetPathStyle());
692 // If we have a full path to the compile unit, we don't need to
693 // resolve the file. This can be expensive e.g. when the source
694 // files are NFS mounted.
695 cu_file_spec.MakeAbsolute(dwarf_cu.GetCompilationDirectory());
697 std::string remapped_file;
698 if (module_sp->RemapSourceFile(cu_file_spec.GetPath(),
700 cu_file_spec.SetFile(remapped_file, FileSpec::Style::native);
703 LanguageType cu_language = DWARFUnit::LanguageTypeFromDWARF(
704 cu_die.GetAttributeValueAsUnsigned(DW_AT_language, 0));
706 bool is_optimized = dwarf_cu.GetNonSkeletonUnit().GetIsOptimized();
707 BuildCuTranslationTable();
708 cu_sp = std::make_shared<CompileUnit>(
709 module_sp, &dwarf_cu, cu_file_spec,
710 *GetDWARFUnitIndex(dwarf_cu.GetID()), cu_language,
711 is_optimized ? eLazyBoolYes : eLazyBoolNo);
713 dwarf_cu.SetUserData(cu_sp.get());
715 SetCompileUnitAtIndex(dwarf_cu.GetID(), cu_sp);
723 void SymbolFileDWARF::BuildCuTranslationTable() {
724 if (!m_lldb_cu_to_dwarf_unit.empty())
727 DWARFDebugInfo *info = DebugInfo();
731 if (!info->ContainsTypeUnits()) {
732 // We can use a 1-to-1 mapping. No need to build a translation table.
735 for (uint32_t i = 0, num = info->GetNumUnits(); i < num; ++i) {
736 if (auto *cu = llvm::dyn_cast<DWARFCompileUnit>(info->GetUnitAtIndex(i))) {
737 cu->SetID(m_lldb_cu_to_dwarf_unit.size());
738 m_lldb_cu_to_dwarf_unit.push_back(i);
743 llvm::Optional<uint32_t> SymbolFileDWARF::GetDWARFUnitIndex(uint32_t cu_idx) {
744 BuildCuTranslationTable();
745 if (m_lldb_cu_to_dwarf_unit.empty())
747 if (cu_idx >= m_lldb_cu_to_dwarf_unit.size())
749 return m_lldb_cu_to_dwarf_unit[cu_idx];
752 uint32_t SymbolFileDWARF::CalculateNumCompileUnits() {
753 DWARFDebugInfo *info = DebugInfo();
756 BuildCuTranslationTable();
757 return m_lldb_cu_to_dwarf_unit.empty() ? info->GetNumUnits()
758 : m_lldb_cu_to_dwarf_unit.size();
761 CompUnitSP SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx) {
762 ASSERT_MODULE_LOCK(this);
763 DWARFDebugInfo *info = DebugInfo();
767 if (llvm::Optional<uint32_t> dwarf_idx = GetDWARFUnitIndex(cu_idx)) {
768 if (auto *dwarf_cu = llvm::cast_or_null<DWARFCompileUnit>(
769 info->GetUnitAtIndex(*dwarf_idx)))
770 return ParseCompileUnit(*dwarf_cu);
775 Function *SymbolFileDWARF::ParseFunction(CompileUnit &comp_unit,
776 const DWARFDIE &die) {
777 ASSERT_MODULE_LOCK(this);
781 auto type_system_or_err =
782 GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
783 if (auto err = type_system_or_err.takeError()) {
784 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
785 std::move(err), "Unable to parse function");
788 DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser();
792 return dwarf_ast->ParseFunctionFromDWARF(comp_unit, die);
795 bool SymbolFileDWARF::FixupAddress(Address &addr) {
796 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
797 if (debug_map_symfile) {
798 return debug_map_symfile->LinkOSOAddress(addr);
800 // This is a normal DWARF file, no address fixups need to happen
803 lldb::LanguageType SymbolFileDWARF::ParseLanguage(CompileUnit &comp_unit) {
804 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
805 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
807 return dwarf_cu->GetLanguageType();
809 return eLanguageTypeUnknown;
812 size_t SymbolFileDWARF::ParseFunctions(CompileUnit &comp_unit) {
813 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
814 Timer scoped_timer(func_cat, "SymbolFileDWARF::ParseFunctions");
815 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
816 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
820 size_t functions_added = 0;
821 dwarf_cu = &dwarf_cu->GetNonSkeletonUnit();
822 for (DWARFDebugInfoEntry &entry : dwarf_cu->dies()) {
823 if (entry.Tag() != DW_TAG_subprogram)
826 DWARFDIE die(dwarf_cu, &entry);
827 if (comp_unit.FindFunctionByUID(die.GetID()))
829 if (ParseFunction(comp_unit, die))
833 return functions_added;
836 bool SymbolFileDWARF::ForEachExternalModule(
837 CompileUnit &comp_unit,
838 llvm::DenseSet<lldb_private::SymbolFile *> &visited_symbol_files,
839 llvm::function_ref<bool(Module &)> lambda) {
840 // Only visit each symbol file once.
841 if (!visited_symbol_files.insert(this).second)
844 UpdateExternalModuleListIfNeeded();
845 for (auto &p : m_external_type_modules) {
846 ModuleSP module = p.second;
850 // Invoke the action and potentially early-exit.
854 for (std::size_t i = 0; i < module->GetNumCompileUnits(); ++i) {
855 auto cu = module->GetCompileUnitAtIndex(i);
856 bool early_exit = cu->ForEachExternalModule(visited_symbol_files, lambda);
864 bool SymbolFileDWARF::ParseSupportFiles(CompileUnit &comp_unit,
865 FileSpecList &support_files) {
866 if (!comp_unit.GetLineTable())
867 ParseLineTable(comp_unit);
871 FileSpec SymbolFileDWARF::GetFile(DWARFUnit &unit, size_t file_idx) {
872 if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit)) {
873 if (CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(*dwarf_cu))
874 return lldb_cu->GetSupportFiles().GetFileSpecAtIndex(file_idx);
878 auto &tu = llvm::cast<DWARFTypeUnit>(unit);
879 return GetTypeUnitSupportFiles(tu).GetFileSpecAtIndex(file_idx);
883 SymbolFileDWARF::GetTypeUnitSupportFiles(DWARFTypeUnit &tu) {
884 static FileSpecList empty_list;
886 dw_offset_t offset = tu.GetLineTableOffset();
887 if (offset == DW_INVALID_OFFSET ||
888 offset == llvm::DenseMapInfo<dw_offset_t>::getEmptyKey() ||
889 offset == llvm::DenseMapInfo<dw_offset_t>::getTombstoneKey())
892 // Many type units can share a line table, so parse the support file list
893 // once, and cache it based on the offset field.
894 auto iter_bool = m_type_unit_support_files.try_emplace(offset);
895 FileSpecList &list = iter_bool.first->second;
896 if (iter_bool.second) {
897 uint64_t line_table_offset = offset;
898 llvm::DWARFDataExtractor data = m_context.getOrLoadLineData().GetAsLLVM();
899 llvm::DWARFContext &ctx = m_context.GetAsLLVM();
900 llvm::DWARFDebugLine::Prologue prologue;
901 llvm::Error error = prologue.parse(data, &line_table_offset, ctx);
903 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
904 LLDB_LOG_ERROR(log, std::move(error),
905 "SymbolFileDWARF::GetTypeUnitSupportFiles failed to parse "
906 "the line table prologue");
908 list = ParseSupportFilesFromPrologue(GetObjectFile()->GetModule(),
909 prologue, tu.GetPathStyle());
915 bool SymbolFileDWARF::ParseIsOptimized(CompileUnit &comp_unit) {
916 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
917 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
919 return dwarf_cu->GetIsOptimized();
923 bool SymbolFileDWARF::ParseImportedModules(
924 const lldb_private::SymbolContext &sc,
925 std::vector<SourceModule> &imported_modules) {
926 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
927 assert(sc.comp_unit);
928 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
931 if (!ClangModulesDeclVendor::LanguageSupportsClangModules(
932 sc.comp_unit->GetLanguage()))
934 UpdateExternalModuleListIfNeeded();
936 const DWARFDIE die = dwarf_cu->DIE();
940 for (DWARFDIE child_die = die.GetFirstChild(); child_die;
941 child_die = child_die.GetSibling()) {
942 if (child_die.Tag() != DW_TAG_imported_declaration)
945 DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import);
946 if (module_die.Tag() != DW_TAG_module)
949 if (const char *name =
950 module_die.GetAttributeValueAsString(DW_AT_name, nullptr)) {
952 module.path.push_back(ConstString(name));
954 DWARFDIE parent_die = module_die;
955 while ((parent_die = parent_die.GetParent())) {
956 if (parent_die.Tag() != DW_TAG_module)
958 if (const char *name =
959 parent_die.GetAttributeValueAsString(DW_AT_name, nullptr))
960 module.path.push_back(ConstString(name));
962 std::reverse(module.path.begin(), module.path.end());
963 if (const char *include_path = module_die.GetAttributeValueAsString(
964 DW_AT_LLVM_include_path, nullptr))
965 module.search_path = ConstString(include_path);
966 if (const char *sysroot = module_die.GetAttributeValueAsString(
967 DW_AT_LLVM_sysroot, nullptr))
968 module.sysroot = ConstString(sysroot);
969 imported_modules.push_back(module);
975 bool SymbolFileDWARF::ParseLineTable(CompileUnit &comp_unit) {
976 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
977 if (comp_unit.GetLineTable() != nullptr)
980 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
984 const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
988 const dw_offset_t cu_line_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(
989 DW_AT_stmt_list, DW_INVALID_OFFSET);
990 if (cu_line_offset == DW_INVALID_OFFSET)
993 llvm::DWARFDebugLine line;
994 const llvm::DWARFDebugLine::LineTable *line_table = ParseLLVMLineTable(
995 m_context, line, cu_line_offset, dwarf_cu->GetOffset());
1000 // FIXME: Rather than parsing the whole line table and then copying it over
1001 // into LLDB, we should explore using a callback to populate the line table
1002 // while we parse to reduce memory usage.
1003 std::unique_ptr<LineTable> line_table_up =
1004 std::make_unique<LineTable>(&comp_unit);
1005 LineSequence *sequence = line_table_up->CreateLineSequenceContainer();
1006 for (auto &row : line_table->Rows) {
1007 line_table_up->AppendLineEntryToSequence(
1008 sequence, row.Address.Address, row.Line, row.Column, row.File,
1009 row.IsStmt, row.BasicBlock, row.PrologueEnd, row.EpilogueBegin,
1011 if (row.EndSequence) {
1012 line_table_up->InsertSequence(sequence);
1013 sequence = line_table_up->CreateLineSequenceContainer();
1017 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) {
1018 // We have an object file that has a line table with addresses that are not
1019 // linked. We need to link the line table and convert the addresses that
1020 // are relative to the .o file into addresses for the main executable.
1021 comp_unit.SetLineTable(
1022 debug_map_symfile->LinkOSOLineTable(this, line_table_up.get()));
1024 comp_unit.SetLineTable(line_table_up.release());
1027 comp_unit.SetSupportFiles(ParseSupportFilesFromPrologue(
1028 comp_unit.GetModule(), line_table->Prologue, dwarf_cu->GetPathStyle(),
1029 dwarf_cu->GetCompilationDirectory().GetCString()));
1034 lldb_private::DebugMacrosSP
1035 SymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset) {
1036 auto iter = m_debug_macros_map.find(*offset);
1037 if (iter != m_debug_macros_map.end())
1038 return iter->second;
1040 const DWARFDataExtractor &debug_macro_data = m_context.getOrLoadMacroData();
1041 if (debug_macro_data.GetByteSize() == 0)
1042 return DebugMacrosSP();
1044 lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros());
1045 m_debug_macros_map[*offset] = debug_macros_sp;
1047 const DWARFDebugMacroHeader &header =
1048 DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset);
1049 DWARFDebugMacroEntry::ReadMacroEntries(
1050 debug_macro_data, m_context.getOrLoadStrData(), header.OffsetIs64Bit(),
1051 offset, this, debug_macros_sp);
1053 return debug_macros_sp;
1056 bool SymbolFileDWARF::ParseDebugMacros(CompileUnit &comp_unit) {
1057 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1059 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1060 if (dwarf_cu == nullptr)
1063 const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
1067 lldb::offset_t sect_offset =
1068 dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET);
1069 if (sect_offset == DW_INVALID_OFFSET)
1070 sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros,
1072 if (sect_offset == DW_INVALID_OFFSET)
1075 comp_unit.SetDebugMacros(ParseDebugMacros(§_offset));
1080 size_t SymbolFileDWARF::ParseBlocksRecursive(
1081 lldb_private::CompileUnit &comp_unit, Block *parent_block,
1082 const DWARFDIE &orig_die, addr_t subprogram_low_pc, uint32_t depth) {
1083 size_t blocks_added = 0;
1084 DWARFDIE die = orig_die;
1086 dw_tag_t tag = die.Tag();
1089 case DW_TAG_inlined_subroutine:
1090 case DW_TAG_subprogram:
1091 case DW_TAG_lexical_block: {
1092 Block *block = nullptr;
1093 if (tag == DW_TAG_subprogram) {
1094 // Skip any DW_TAG_subprogram DIEs that are inside of a normal or
1095 // inlined functions. These will be parsed on their own as separate
1101 block = parent_block;
1103 BlockSP block_sp(new Block(die.GetID()));
1104 parent_block->AddChild(block_sp);
1105 block = block_sp.get();
1107 DWARFRangeList ranges;
1108 const char *name = nullptr;
1109 const char *mangled_name = nullptr;
1113 int decl_column = 0;
1116 int call_column = 0;
1117 if (die.GetDIENamesAndRanges(name, mangled_name, ranges, decl_file,
1118 decl_line, decl_column, call_file, call_line,
1119 call_column, nullptr)) {
1120 if (tag == DW_TAG_subprogram) {
1121 assert(subprogram_low_pc == LLDB_INVALID_ADDRESS);
1122 subprogram_low_pc = ranges.GetMinRangeBase(0);
1123 } else if (tag == DW_TAG_inlined_subroutine) {
1124 // We get called here for inlined subroutines in two ways. The first
1125 // time is when we are making the Function object for this inlined
1126 // concrete instance. Since we're creating a top level block at
1127 // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS. So we
1128 // need to adjust the containing address. The second time is when we
1129 // are parsing the blocks inside the function that contains the
1130 // inlined concrete instance. Since these will be blocks inside the
1131 // containing "real" function the offset will be for that function.
1132 if (subprogram_low_pc == LLDB_INVALID_ADDRESS) {
1133 subprogram_low_pc = ranges.GetMinRangeBase(0);
1137 const size_t num_ranges = ranges.GetSize();
1138 for (size_t i = 0; i < num_ranges; ++i) {
1139 const DWARFRangeList::Entry &range = ranges.GetEntryRef(i);
1140 const addr_t range_base = range.GetRangeBase();
1141 if (range_base >= subprogram_low_pc)
1142 block->AddRange(Block::Range(range_base - subprogram_low_pc,
1143 range.GetByteSize()));
1145 GetObjectFile()->GetModule()->ReportError(
1146 "0x%8.8" PRIx64 ": adding range [0x%" PRIx64 "-0x%" PRIx64
1147 ") which has a base that is less than the function's low PC "
1148 "0x%" PRIx64 ". Please file a bug and attach the file at the "
1149 "start of this error message",
1150 block->GetID(), range_base, range.GetRangeEnd(),
1154 block->FinalizeRanges();
1156 if (tag != DW_TAG_subprogram &&
1157 (name != nullptr || mangled_name != nullptr)) {
1158 std::unique_ptr<Declaration> decl_up;
1159 if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1160 decl_up.reset(new Declaration(
1161 comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file),
1162 decl_line, decl_column));
1164 std::unique_ptr<Declaration> call_up;
1165 if (call_file != 0 || call_line != 0 || call_column != 0)
1166 call_up.reset(new Declaration(
1167 comp_unit.GetSupportFiles().GetFileSpecAtIndex(call_file),
1168 call_line, call_column));
1170 block->SetInlinedFunctionInfo(name, mangled_name, decl_up.get(),
1176 if (die.HasChildren()) {
1178 ParseBlocksRecursive(comp_unit, block, die.GetFirstChild(),
1179 subprogram_low_pc, depth + 1);
1187 // Only parse siblings of the block if we are not at depth zero. A depth of
1188 // zero indicates we are currently parsing the top level DW_TAG_subprogram
1194 die = die.GetSibling();
1196 return blocks_added;
1199 bool SymbolFileDWARF::ClassOrStructIsVirtual(const DWARFDIE &parent_die) {
1201 for (DWARFDIE die = parent_die.GetFirstChild(); die;
1202 die = die.GetSibling()) {
1203 dw_tag_t tag = die.Tag();
1204 bool check_virtuality = false;
1206 case DW_TAG_inheritance:
1207 case DW_TAG_subprogram:
1208 check_virtuality = true;
1213 if (check_virtuality) {
1214 if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0)
1222 void SymbolFileDWARF::ParseDeclsForContext(CompilerDeclContext decl_ctx) {
1223 auto *type_system = decl_ctx.GetTypeSystem();
1224 if (type_system != nullptr)
1225 type_system->GetDWARFParser()->EnsureAllDIEsInDeclContextHaveBeenParsed(
1229 user_id_t SymbolFileDWARF::GetUID(DIERef ref) {
1230 if (GetDebugMapSymfile())
1231 return GetID() | ref.die_offset();
1233 return user_id_t(GetDwoNum().getValueOr(0x7fffffff)) << 32 |
1235 (lldb::user_id_t(ref.section() == DIERef::Section::DebugTypes) << 63);
1238 llvm::Optional<SymbolFileDWARF::DecodedUID>
1239 SymbolFileDWARF::DecodeUID(lldb::user_id_t uid) {
1240 // This method can be called without going through the symbol vendor so we
1241 // need to lock the module.
1242 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1243 // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we
1244 // must make sure we use the correct DWARF file when resolving things. On
1245 // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1246 // SymbolFileDWARF classes, one for each .o file. We can often end up with
1247 // references to other DWARF objects and we must be ready to receive a
1248 // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1250 if (SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile()) {
1251 SymbolFileDWARF *dwarf = debug_map->GetSymbolFileByOSOIndex(
1252 debug_map->GetOSOIndexFromUserID(uid));
1254 *dwarf, {llvm::None, DIERef::Section::DebugInfo, dw_offset_t(uid)}};
1256 dw_offset_t die_offset = uid;
1257 if (die_offset == DW_INVALID_OFFSET)
1260 DIERef::Section section =
1261 uid >> 63 ? DIERef::Section::DebugTypes : DIERef::Section::DebugInfo;
1263 llvm::Optional<uint32_t> dwo_num = uid >> 32 & 0x7fffffff;
1264 if (*dwo_num == 0x7fffffff)
1265 dwo_num = llvm::None;
1267 return DecodedUID{*this, {dwo_num, section, die_offset}};
1271 SymbolFileDWARF::GetDIE(lldb::user_id_t uid) {
1272 // This method can be called without going through the symbol vendor so we
1273 // need to lock the module.
1274 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1276 llvm::Optional<DecodedUID> decoded = DecodeUID(uid);
1279 return decoded->dwarf.GetDIE(decoded->ref);
1284 CompilerDecl SymbolFileDWARF::GetDeclForUID(lldb::user_id_t type_uid) {
1285 // This method can be called without going through the symbol vendor so we
1286 // need to lock the module.
1287 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1288 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1289 // SymbolFileDWARF::GetDIE(). See comments inside the
1290 // SymbolFileDWARF::GetDIE() for details.
1291 if (DWARFDIE die = GetDIE(type_uid))
1292 return die.GetDecl();
1293 return CompilerDecl();
1297 SymbolFileDWARF::GetDeclContextForUID(lldb::user_id_t type_uid) {
1298 // This method can be called without going through the symbol vendor so we
1299 // need to lock the module.
1300 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1301 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1302 // SymbolFileDWARF::GetDIE(). See comments inside the
1303 // SymbolFileDWARF::GetDIE() for details.
1304 if (DWARFDIE die = GetDIE(type_uid))
1305 return die.GetDeclContext();
1306 return CompilerDeclContext();
1310 SymbolFileDWARF::GetDeclContextContainingUID(lldb::user_id_t type_uid) {
1311 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1312 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1313 // SymbolFileDWARF::GetDIE(). See comments inside the
1314 // SymbolFileDWARF::GetDIE() for details.
1315 if (DWARFDIE die = GetDIE(type_uid))
1316 return die.GetContainingDeclContext();
1317 return CompilerDeclContext();
1320 Type *SymbolFileDWARF::ResolveTypeUID(lldb::user_id_t type_uid) {
1321 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1322 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1323 // SymbolFileDWARF::GetDIE(). See comments inside the
1324 // SymbolFileDWARF::GetDIE() for details.
1325 if (DWARFDIE type_die = GetDIE(type_uid))
1326 return type_die.ResolveType();
1331 llvm::Optional<SymbolFile::ArrayInfo>
1332 SymbolFileDWARF::GetDynamicArrayInfoForUID(
1333 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1334 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1335 if (DWARFDIE type_die = GetDIE(type_uid))
1336 return DWARFASTParser::ParseChildArrayInfo(type_die, exe_ctx);
1341 Type *SymbolFileDWARF::ResolveTypeUID(const DIERef &die_ref) {
1342 return ResolveType(GetDIE(die_ref), true);
1345 Type *SymbolFileDWARF::ResolveTypeUID(const DWARFDIE &die,
1346 bool assert_not_being_parsed) {
1348 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
1350 GetObjectFile()->GetModule()->LogMessage(
1351 log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
1352 die.GetOffset(), die.GetTagAsCString(), die.GetName());
1354 // We might be coming in in the middle of a type tree (a class within a
1355 // class, an enum within a class), so parse any needed parent DIEs before
1356 // we get to this one...
1357 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die);
1360 switch (decl_ctx_die.Tag()) {
1361 case DW_TAG_structure_type:
1362 case DW_TAG_union_type:
1363 case DW_TAG_class_type: {
1364 // Get the type, which could be a forward declaration
1366 GetObjectFile()->GetModule()->LogMessage(
1368 "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' "
1369 "resolve parent forward type for 0x%8.8x",
1370 die.GetOffset(), die.GetTagAsCString(), die.GetName(),
1371 decl_ctx_die.GetOffset());
1379 return ResolveType(die);
1384 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
1385 // SymbolFileDWARF objects to detect if this DWARF file is the one that can
1386 // resolve a compiler_type.
1387 bool SymbolFileDWARF::HasForwardDeclForClangType(
1388 const CompilerType &compiler_type) {
1389 CompilerType compiler_type_no_qualifiers =
1390 ClangUtil::RemoveFastQualifiers(compiler_type);
1391 if (GetForwardDeclClangTypeToDie().count(
1392 compiler_type_no_qualifiers.GetOpaqueQualType())) {
1395 TypeSystem *type_system = compiler_type.GetTypeSystem();
1397 ClangASTContext *clang_type_system =
1398 llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1399 if (!clang_type_system)
1401 DWARFASTParserClang *ast_parser =
1402 static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1403 return ast_parser->GetClangASTImporter().CanImport(compiler_type);
1406 bool SymbolFileDWARF::CompleteType(CompilerType &compiler_type) {
1407 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1409 ClangASTContext *clang_type_system =
1410 llvm::dyn_cast_or_null<ClangASTContext>(compiler_type.GetTypeSystem());
1411 if (clang_type_system) {
1412 DWARFASTParserClang *ast_parser =
1413 static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1415 ast_parser->GetClangASTImporter().CanImport(compiler_type))
1416 return ast_parser->GetClangASTImporter().CompleteType(compiler_type);
1419 // We have a struct/union/class/enum that needs to be fully resolved.
1420 CompilerType compiler_type_no_qualifiers =
1421 ClangUtil::RemoveFastQualifiers(compiler_type);
1422 auto die_it = GetForwardDeclClangTypeToDie().find(
1423 compiler_type_no_qualifiers.GetOpaqueQualType());
1424 if (die_it == GetForwardDeclClangTypeToDie().end()) {
1425 // We have already resolved this type...
1429 DWARFDIE dwarf_die = GetDIE(die_it->getSecond());
1431 // Once we start resolving this type, remove it from the forward
1432 // declaration map in case anyone child members or other types require this
1433 // type to get resolved. The type will get resolved when all of the calls
1434 // to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition are done.
1435 GetForwardDeclClangTypeToDie().erase(die_it);
1437 Type *type = GetDIEToType().lookup(dwarf_die.GetDIE());
1439 Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO |
1440 DWARF_LOG_TYPE_COMPLETION));
1442 GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
1443 log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
1444 dwarf_die.GetID(), dwarf_die.GetTagAsCString(),
1445 type->GetName().AsCString());
1446 assert(compiler_type);
1447 DWARFASTParser *dwarf_ast = dwarf_die.GetDWARFParser();
1449 return dwarf_ast->CompleteTypeFromDWARF(dwarf_die, type, compiler_type);
1454 Type *SymbolFileDWARF::ResolveType(const DWARFDIE &die,
1455 bool assert_not_being_parsed,
1456 bool resolve_function_context) {
1458 Type *type = GetTypeForDIE(die, resolve_function_context).get();
1460 if (assert_not_being_parsed) {
1461 if (type != DIE_IS_BEING_PARSED)
1464 GetObjectFile()->GetModule()->ReportError(
1465 "Parsing a die that is being parsed die: 0x%8.8x: %s %s",
1466 die.GetOffset(), die.GetTagAsCString(), die.GetName());
1475 SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu) {
1476 // Check if the symbol vendor already knows about this compile unit?
1477 if (dwarf_cu.GetUserData() == nullptr) {
1478 // The symbol vendor doesn't know about this compile unit, we need to parse
1479 // and add it to the symbol vendor object.
1480 return ParseCompileUnit(dwarf_cu).get();
1482 return (CompileUnit *)dwarf_cu.GetUserData();
1485 size_t SymbolFileDWARF::GetObjCMethodDIEOffsets(ConstString class_name,
1486 DIEArray &method_die_offsets) {
1487 method_die_offsets.clear();
1488 m_index->GetObjCMethods(class_name, method_die_offsets);
1489 return method_die_offsets.size();
1492 bool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) {
1495 if (die && llvm::isa<DWARFCompileUnit>(die.GetCU())) {
1496 // Check if the symbol vendor already knows about this compile unit?
1498 GetCompUnitForDWARFCompUnit(llvm::cast<DWARFCompileUnit>(*die.GetCU()));
1500 sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
1501 if (sc.function == nullptr)
1502 sc.function = ParseFunction(*sc.comp_unit, die);
1505 sc.module_sp = sc.function->CalculateSymbolContextModule();
1513 lldb::ModuleSP SymbolFileDWARF::GetExternalModule(ConstString name) {
1514 UpdateExternalModuleListIfNeeded();
1515 const auto &pos = m_external_type_modules.find(name);
1516 if (pos != m_external_type_modules.end())
1519 return lldb::ModuleSP();
1523 SymbolFileDWARF::GetDIE(const DIERef &die_ref) {
1524 if (die_ref.dwo_num()) {
1526 ->GetUnitAtIndex(*die_ref.dwo_num())
1527 ->GetDwoSymbolFile()
1531 DWARFDebugInfo *debug_info = DebugInfo();
1533 return debug_info->GetDIE(die_ref);
1538 /// Return the DW_AT_(GNU_)dwo_name.
1539 static const char *GetDWOName(DWARFCompileUnit &dwarf_cu,
1540 const DWARFDebugInfoEntry &cu_die) {
1541 const char *dwo_name =
1542 cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_GNU_dwo_name, nullptr);
1545 cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_dwo_name, nullptr);
1549 /// Return the DW_AT_(GNU_)dwo_id.
1550 /// FIXME: Technically 0 is a valid hash.
1551 static uint64_t GetDWOId(DWARFCompileUnit &dwarf_cu,
1552 const DWARFDebugInfoEntry &cu_die) {
1554 cu_die.GetAttributeValueAsUnsigned(&dwarf_cu, DW_AT_GNU_dwo_id, 0);
1556 dwo_id = cu_die.GetAttributeValueAsUnsigned(&dwarf_cu, DW_AT_dwo_id, 0);
1560 llvm::Optional<uint64_t> SymbolFileDWARF::GetDWOId() {
1561 if (GetNumCompileUnits() == 1) {
1562 if (auto comp_unit = GetCompileUnitAtIndex(0))
1563 if (DWARFCompileUnit *cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(
1564 GetDWARFCompileUnit(comp_unit.get())))
1565 if (DWARFDebugInfoEntry *cu_die = cu->DIE().GetDIE())
1566 if (uint64_t dwo_id = ::GetDWOId(*cu, *cu_die))
1572 std::unique_ptr<SymbolFileDWARFDwo>
1573 SymbolFileDWARF::GetDwoSymbolFileForCompileUnit(
1574 DWARFUnit &unit, const DWARFDebugInfoEntry &cu_die) {
1575 // If this is a Darwin-style debug map (non-.dSYM) symbol file,
1576 // never attempt to load ELF-style DWO files since the -gmodules
1577 // support uses the same DWO machanism to specify full debug info
1578 // files for modules. This is handled in
1579 // UpdateExternalModuleListIfNeeded().
1580 if (GetDebugMapSymfile())
1583 DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit);
1584 // Only compile units can be split into two parts.
1588 const char *dwo_name = GetDWOName(*dwarf_cu, cu_die);
1592 SymbolFileDWARFDwp *dwp_symfile = GetDwpSymbolFile();
1594 uint64_t dwo_id = ::GetDWOId(*dwarf_cu, cu_die);
1595 std::unique_ptr<SymbolFileDWARFDwo> dwo_symfile =
1596 dwp_symfile->GetSymbolFileForDwoId(*dwarf_cu, dwo_id);
1601 FileSpec dwo_file(dwo_name);
1602 FileSystem::Instance().Resolve(dwo_file);
1603 if (dwo_file.IsRelative()) {
1604 const char *comp_dir =
1605 cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_comp_dir, nullptr);
1609 dwo_file.SetFile(comp_dir, FileSpec::Style::native);
1610 FileSystem::Instance().Resolve(dwo_file);
1611 dwo_file.AppendPathComponent(dwo_name);
1614 if (!FileSystem::Instance().Exists(dwo_file))
1617 const lldb::offset_t file_offset = 0;
1618 DataBufferSP dwo_file_data_sp;
1619 lldb::offset_t dwo_file_data_offset = 0;
1620 ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin(
1621 GetObjectFile()->GetModule(), &dwo_file, file_offset,
1622 FileSystem::Instance().GetByteSize(dwo_file), dwo_file_data_sp,
1623 dwo_file_data_offset);
1624 if (dwo_obj_file == nullptr)
1627 return std::make_unique<SymbolFileDWARFDwo>(dwo_obj_file, *dwarf_cu);
1630 void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() {
1631 if (m_fetched_external_modules)
1633 m_fetched_external_modules = true;
1634 DWARFDebugInfo *debug_info = DebugInfo();
1636 // Follow DWO skeleton unit breadcrumbs.
1637 const uint32_t num_compile_units = GetNumCompileUnits();
1638 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
1640 llvm::dyn_cast<DWARFCompileUnit>(debug_info->GetUnitAtIndex(cu_idx));
1644 const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
1645 if (!die || die.HasChildren() || !die.GetDIE())
1648 const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
1652 ConstString const_name(name);
1653 ModuleSP &module_sp = m_external_type_modules[const_name];
1657 const char *dwo_path = GetDWOName(*dwarf_cu, *die.GetDIE());
1661 ModuleSpec dwo_module_spec;
1662 dwo_module_spec.GetFileSpec().SetFile(dwo_path, FileSpec::Style::native);
1663 if (dwo_module_spec.GetFileSpec().IsRelative()) {
1664 const char *comp_dir =
1665 die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr);
1667 dwo_module_spec.GetFileSpec().SetFile(comp_dir,
1668 FileSpec::Style::native);
1669 FileSystem::Instance().Resolve(dwo_module_spec.GetFileSpec());
1670 dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path);
1673 dwo_module_spec.GetArchitecture() =
1674 m_objfile_sp->GetModule()->GetArchitecture();
1676 // When LLDB loads "external" modules it looks at the presence of
1677 // DW_AT_dwo_name. However, when the already created module
1678 // (corresponding to .dwo itself) is being processed, it will see
1679 // the presence of DW_AT_dwo_name (which contains the name of dwo
1680 // file) and will try to call ModuleList::GetSharedModule
1681 // again. In some cases (i.e., for empty files) Clang 4.0
1682 // generates a *.dwo file which has DW_AT_dwo_name, but no
1683 // DW_AT_comp_dir. In this case the method
1684 // ModuleList::GetSharedModule will fail and the warning will be
1685 // printed. However, as one can notice in this case we don't
1686 // actually need to try to load the already loaded module
1687 // (corresponding to .dwo) so we simply skip it.
1688 if (m_objfile_sp->GetFileSpec().GetFileNameExtension() == ".dwo" &&
1689 llvm::StringRef(m_objfile_sp->GetFileSpec().GetPath())
1690 .endswith(dwo_module_spec.GetFileSpec().GetPath())) {
1694 Status error = ModuleList::GetSharedModule(dwo_module_spec, module_sp,
1695 nullptr, nullptr, nullptr);
1697 GetObjectFile()->GetModule()->ReportWarning(
1698 "0x%8.8x: unable to locate module needed for external types: "
1699 "%s\nerror: %s\nDebugging will be degraded due to missing "
1700 "types. Rebuilding the project will regenerate the needed "
1702 die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str(),
1703 error.AsCString("unknown error"));
1707 // Verify the DWO hash.
1708 // FIXME: Technically "0" is a valid hash.
1709 uint64_t dwo_id = ::GetDWOId(*dwarf_cu, *die.GetDIE());
1714 llvm::dyn_cast_or_null<SymbolFileDWARF>(module_sp->GetSymbolFile());
1717 llvm::Optional<uint64_t> dwo_dwo_id = dwo_symfile->GetDWOId();
1721 if (dwo_id != dwo_dwo_id) {
1722 GetObjectFile()->GetModule()->ReportWarning(
1723 "0x%8.8x: Module %s is out-of-date (hash mismatch). Type information "
1724 "from this module may be incomplete or inconsistent with the rest of "
1725 "the program. Rebuilding the project will regenerate the needed "
1727 die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str());
1732 SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() {
1733 if (!m_global_aranges_up) {
1734 m_global_aranges_up.reset(new GlobalVariableMap());
1736 ModuleSP module_sp = GetObjectFile()->GetModule();
1738 const size_t num_cus = module_sp->GetNumCompileUnits();
1739 for (size_t i = 0; i < num_cus; ++i) {
1740 CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
1742 VariableListSP globals_sp = cu_sp->GetVariableList(true);
1744 const size_t num_globals = globals_sp->GetSize();
1745 for (size_t g = 0; g < num_globals; ++g) {
1746 VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
1747 if (var_sp && !var_sp->GetLocationIsConstantValueData()) {
1748 const DWARFExpression &location = var_sp->LocationExpression();
1749 Value location_result;
1751 if (location.Evaluate(nullptr, LLDB_INVALID_ADDRESS, nullptr,
1752 nullptr, location_result, &error)) {
1753 if (location_result.GetValueType() ==
1754 Value::eValueTypeFileAddress) {
1755 lldb::addr_t file_addr =
1756 location_result.GetScalar().ULongLong();
1757 lldb::addr_t byte_size = 1;
1758 if (var_sp->GetType())
1760 var_sp->GetType()->GetByteSize().getValueOr(0);
1761 m_global_aranges_up->Append(GlobalVariableMap::Entry(
1762 file_addr, byte_size, var_sp.get()));
1771 m_global_aranges_up->Sort();
1773 return *m_global_aranges_up;
1776 uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr,
1777 SymbolContextItem resolve_scope,
1778 SymbolContext &sc) {
1779 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1780 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1781 Timer scoped_timer(func_cat,
1783 "ResolveSymbolContext (so_addr = { "
1784 "section = %p, offset = 0x%" PRIx64
1785 " }, resolve_scope = 0x%8.8x)",
1786 static_cast<void *>(so_addr.GetSection().get()),
1787 so_addr.GetOffset(), resolve_scope);
1788 uint32_t resolved = 0;
1790 (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock |
1791 eSymbolContextLineEntry | eSymbolContextVariable)) {
1792 lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1794 DWARFDebugInfo *debug_info = DebugInfo();
1796 llvm::Expected<DWARFDebugAranges &> aranges =
1797 debug_info->GetCompileUnitAranges();
1799 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
1800 LLDB_LOG_ERROR(log, aranges.takeError(),
1801 "SymbolFileDWARF::ResolveSymbolContext failed to get cu "
1806 const dw_offset_t cu_offset = aranges->FindAddress(file_vm_addr);
1807 if (cu_offset == DW_INVALID_OFFSET) {
1808 // Global variables are not in the compile unit address ranges. The
1809 // only way to currently find global variables is to iterate over the
1810 // .debug_pubnames or the __apple_names table and find all items in
1811 // there that point to DW_TAG_variable DIEs and then find the address
1813 if (resolve_scope & eSymbolContextVariable) {
1814 GlobalVariableMap &map = GetGlobalAranges();
1815 const GlobalVariableMap::Entry *entry =
1816 map.FindEntryThatContains(file_vm_addr);
1817 if (entry && entry->data) {
1818 Variable *variable = entry->data;
1819 SymbolContextScope *scc = variable->GetSymbolContextScope();
1821 scc->CalculateSymbolContext(&sc);
1822 sc.variable = variable;
1824 return sc.GetResolvedMask();
1828 uint32_t cu_idx = DW_INVALID_INDEX;
1829 if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(
1830 debug_info->GetUnitAtOffset(DIERef::Section::DebugInfo,
1831 cu_offset, &cu_idx))) {
1832 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
1834 resolved |= eSymbolContextCompUnit;
1836 bool force_check_line_table = false;
1838 (eSymbolContextFunction | eSymbolContextBlock)) {
1839 DWARFDIE function_die = dwarf_cu->LookupAddress(file_vm_addr);
1843 sc.comp_unit->FindFunctionByUID(function_die.GetID()).get();
1844 if (sc.function == nullptr)
1845 sc.function = ParseFunction(*sc.comp_unit, function_die);
1847 if (sc.function && (resolve_scope & eSymbolContextBlock))
1848 block_die = function_die.LookupDeepestBlock(file_vm_addr);
1850 // We might have had a compile unit that had discontiguous
1851 // address ranges where the gaps are symbols that don't have
1852 // any debug info. Discontiguous compile unit address ranges
1853 // should only happen when there aren't other functions from
1854 // other compile units in these gaps. This helps keep the size
1855 // of the aranges down.
1856 force_check_line_table = true;
1859 if (sc.function != nullptr) {
1860 resolved |= eSymbolContextFunction;
1862 if (resolve_scope & eSymbolContextBlock) {
1863 Block &block = sc.function->GetBlock(true);
1866 sc.block = block.FindBlockByID(block_die.GetID());
1868 sc.block = block.FindBlockByID(function_die.GetID());
1870 resolved |= eSymbolContextBlock;
1875 if ((resolve_scope & eSymbolContextLineEntry) ||
1876 force_check_line_table) {
1877 LineTable *line_table = sc.comp_unit->GetLineTable();
1878 if (line_table != nullptr) {
1879 // And address that makes it into this function should be in
1880 // terms of this debug file if there is no debug map, or it
1881 // will be an address in the .o file which needs to be fixed up
1882 // to be in terms of the debug map executable. Either way,
1883 // calling FixupAddress() will work for us.
1884 Address exe_so_addr(so_addr);
1885 if (FixupAddress(exe_so_addr)) {
1886 if (line_table->FindLineEntryByAddress(exe_so_addr,
1888 resolved |= eSymbolContextLineEntry;
1894 if (force_check_line_table &&
1895 !(resolved & eSymbolContextLineEntry)) {
1896 // We might have had a compile unit that had discontiguous
1897 // address ranges where the gaps are symbols that don't have any
1898 // debug info. Discontiguous compile unit address ranges should
1899 // only happen when there aren't other functions from other
1900 // compile units in these gaps. This helps keep the size of the
1902 sc.comp_unit = nullptr;
1903 resolved &= ~eSymbolContextCompUnit;
1906 GetObjectFile()->GetModule()->ReportWarning(
1907 "0x%8.8x: compile unit %u failed to create a valid "
1908 "lldb_private::CompileUnit class.",
1918 uint32_t SymbolFileDWARF::ResolveSymbolContext(const FileSpec &file_spec,
1921 SymbolContextItem resolve_scope,
1922 SymbolContextList &sc_list) {
1923 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1924 const uint32_t prev_size = sc_list.GetSize();
1925 if (resolve_scope & eSymbolContextCompUnit) {
1926 for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
1928 CompileUnit *dc_cu = ParseCompileUnitAtIndex(cu_idx).get();
1932 bool file_spec_matches_cu_file_spec =
1933 FileSpec::Match(file_spec, dc_cu->GetPrimaryFile());
1934 if (check_inlines || file_spec_matches_cu_file_spec) {
1935 SymbolContext sc(m_objfile_sp->GetModule());
1936 sc.comp_unit = dc_cu;
1937 uint32_t file_idx = UINT32_MAX;
1939 // If we are looking for inline functions only and we don't find it
1940 // in the support files, we are done.
1941 if (check_inlines) {
1943 sc.comp_unit->GetSupportFiles().FindFileIndex(1, file_spec, true);
1944 if (file_idx == UINT32_MAX)
1949 LineTable *line_table = sc.comp_unit->GetLineTable();
1951 if (line_table != nullptr && line != 0) {
1952 // We will have already looked up the file index if we are
1953 // searching for inline entries.
1955 file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex(
1956 1, file_spec, true);
1958 if (file_idx != UINT32_MAX) {
1959 uint32_t found_line;
1960 uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex(
1961 0, file_idx, line, false, &sc.line_entry);
1962 found_line = sc.line_entry.line;
1964 while (line_idx != UINT32_MAX) {
1965 sc.function = nullptr;
1968 (eSymbolContextFunction | eSymbolContextBlock)) {
1969 const lldb::addr_t file_vm_addr =
1970 sc.line_entry.range.GetBaseAddress().GetFileAddress();
1971 if (file_vm_addr != LLDB_INVALID_ADDRESS) {
1972 DWARFDIE function_die =
1973 GetDWARFCompileUnit(dc_cu)->LookupAddress(file_vm_addr);
1977 sc.comp_unit->FindFunctionByUID(function_die.GetID())
1979 if (sc.function == nullptr)
1981 ParseFunction(*sc.comp_unit, function_die);
1983 if (sc.function && (resolve_scope & eSymbolContextBlock))
1985 function_die.LookupDeepestBlock(file_vm_addr);
1988 if (sc.function != nullptr) {
1989 Block &block = sc.function->GetBlock(true);
1992 sc.block = block.FindBlockByID(block_die.GetID());
1993 else if (function_die)
1994 sc.block = block.FindBlockByID(function_die.GetID());
2000 line_idx = line_table->FindLineEntryIndexByFileIndex(
2001 line_idx + 1, file_idx, found_line, true, &sc.line_entry);
2004 } else if (file_spec_matches_cu_file_spec && !check_inlines) {
2005 // only append the context if we aren't looking for inline call
2006 // sites by file and line and if the file spec matches that of
2010 } else if (file_spec_matches_cu_file_spec && !check_inlines) {
2011 // only append the context if we aren't looking for inline call
2012 // sites by file and line and if the file spec matches that of
2022 return sc_list.GetSize() - prev_size;
2025 void SymbolFileDWARF::PreloadSymbols() {
2026 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2030 std::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const {
2031 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
2033 return module_sp->GetMutex();
2034 return GetObjectFile()->GetModule()->GetMutex();
2037 bool SymbolFileDWARF::DeclContextMatchesThisSymbolFile(
2038 const lldb_private::CompilerDeclContext *decl_ctx) {
2039 if (decl_ctx == nullptr || !decl_ctx->IsValid()) {
2040 // Invalid namespace decl which means we aren't matching only things in
2041 // this symbol file, so return true to indicate it matches this symbol
2046 TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
2047 auto type_system_or_err = GetTypeSystemForLanguage(
2048 decl_ctx_type_system->GetMinimumLanguage(nullptr));
2049 if (auto err = type_system_or_err.takeError()) {
2050 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
2052 "Unable to match namespace decl using TypeSystem");
2056 if (decl_ctx_type_system == &type_system_or_err.get())
2057 return true; // The type systems match, return true
2059 // The namespace AST was valid, and it does not match...
2060 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2063 GetObjectFile()->GetModule()->LogMessage(
2064 log, "Valid namespace does not match symbol file");
2069 void SymbolFileDWARF::FindGlobalVariables(
2070 ConstString name, const CompilerDeclContext *parent_decl_ctx,
2071 uint32_t max_matches, VariableList &variables) {
2072 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2073 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2076 GetObjectFile()->GetModule()->LogMessage(
2078 "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2079 "parent_decl_ctx=%p, max_matches=%u, variables)",
2080 name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2083 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2086 DWARFDebugInfo *info = DebugInfo();
2090 // Remember how many variables are in the list before we search.
2091 const uint32_t original_size = variables.GetSize();
2093 llvm::StringRef basename;
2094 llvm::StringRef context;
2095 bool name_is_mangled = (bool)Mangled(name);
2097 if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(),
2099 basename = name.GetStringRef();
2101 DIEArray die_offsets;
2102 m_index->GetGlobalVariables(ConstString(basename), die_offsets);
2103 const size_t num_die_matches = die_offsets.size();
2104 if (num_die_matches) {
2106 sc.module_sp = m_objfile_sp->GetModule();
2107 assert(sc.module_sp);
2109 // Loop invariant: Variables up to this index have been checked for context
2111 uint32_t pruned_idx = original_size;
2114 for (size_t i = 0; i < num_die_matches && !done; ++i) {
2115 const DIERef &die_ref = die_offsets[i];
2116 DWARFDIE die = GetDIE(die_ref);
2119 switch (die.Tag()) {
2121 case DW_TAG_subprogram:
2122 case DW_TAG_inlined_subroutine:
2123 case DW_TAG_try_block:
2124 case DW_TAG_catch_block:
2127 case DW_TAG_variable: {
2128 auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2131 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2133 if (parent_decl_ctx) {
2134 DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2136 CompilerDeclContext actual_parent_decl_ctx =
2137 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2138 if (!actual_parent_decl_ctx ||
2139 actual_parent_decl_ctx != *parent_decl_ctx)
2144 ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false,
2146 while (pruned_idx < variables.GetSize()) {
2147 VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx);
2148 if (name_is_mangled ||
2149 var_sp->GetName().GetStringRef().contains(name.GetStringRef()))
2152 variables.RemoveVariableAtIndex(pruned_idx);
2155 if (variables.GetSize() - original_size >= max_matches)
2160 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2165 // Return the number of variable that were appended to the list
2166 const uint32_t num_matches = variables.GetSize() - original_size;
2167 if (log && num_matches > 0) {
2168 GetObjectFile()->GetModule()->LogMessage(
2170 "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2171 "parent_decl_ctx=%p, max_matches=%u, variables) => %u",
2172 name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2173 max_matches, num_matches);
2177 void SymbolFileDWARF::FindGlobalVariables(const RegularExpression ®ex,
2178 uint32_t max_matches,
2179 VariableList &variables) {
2180 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2181 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2184 GetObjectFile()->GetModule()->LogMessage(
2186 "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", "
2187 "max_matches=%u, variables)",
2188 regex.GetText().str().c_str(), max_matches);
2191 DWARFDebugInfo *info = DebugInfo();
2195 // Remember how many variables are in the list before we search.
2196 const uint32_t original_size = variables.GetSize();
2198 DIEArray die_offsets;
2199 m_index->GetGlobalVariables(regex, die_offsets);
2202 sc.module_sp = m_objfile_sp->GetModule();
2203 assert(sc.module_sp);
2205 const size_t num_matches = die_offsets.size();
2207 for (size_t i = 0; i < num_matches; ++i) {
2208 const DIERef &die_ref = die_offsets[i];
2209 DWARFDIE die = GetDIE(die_ref);
2212 DWARFCompileUnit *dwarf_cu =
2213 llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2216 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2218 ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2220 if (variables.GetSize() - original_size >= max_matches)
2223 m_index->ReportInvalidDIERef(die_ref, regex.GetText());
2228 bool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die,
2229 bool include_inlines,
2230 SymbolContextList &sc_list) {
2236 // If we were passed a die that is not a function, just return false...
2237 if (!(orig_die.Tag() == DW_TAG_subprogram ||
2238 (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2241 DWARFDIE die = orig_die;
2242 DWARFDIE inlined_die;
2243 if (die.Tag() == DW_TAG_inlined_subroutine) {
2247 die = die.GetParent();
2250 if (die.Tag() == DW_TAG_subprogram)
2256 assert(die && die.Tag() == DW_TAG_subprogram);
2257 if (GetFunction(die, sc)) {
2259 // Parse all blocks if needed
2261 Block &function_block = sc.function->GetBlock(true);
2262 sc.block = function_block.FindBlockByID(inlined_die.GetID());
2263 if (sc.block == nullptr)
2264 sc.block = function_block.FindBlockByID(inlined_die.GetOffset());
2265 if (sc.block == nullptr || !sc.block->GetStartAddress(addr))
2269 addr = sc.function->GetAddressRange().GetBaseAddress();
2273 if (auto section_sp = addr.GetSection()) {
2274 if (section_sp->GetPermissions() & ePermissionsExecutable) {
2284 bool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext *decl_ctx,
2285 const DWARFDIE &die) {
2286 // If we have no parent decl context to match this DIE matches, and if the
2287 // parent decl context isn't valid, we aren't trying to look for any
2288 // particular decl context so any die matches.
2289 if (decl_ctx == nullptr || !decl_ctx->IsValid())
2293 DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2295 CompilerDeclContext actual_decl_ctx =
2296 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2297 if (actual_decl_ctx)
2298 return decl_ctx->IsContainedInLookup(actual_decl_ctx);
2304 void SymbolFileDWARF::FindFunctions(ConstString name,
2305 const CompilerDeclContext *parent_decl_ctx,
2306 FunctionNameType name_type_mask,
2307 bool include_inlines,
2308 SymbolContextList &sc_list) {
2309 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2310 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2311 Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (name = '%s')",
2314 // eFunctionNameTypeAuto should be pre-resolved by a call to
2315 // Module::LookupInfo::LookupInfo()
2316 assert((name_type_mask & eFunctionNameTypeAuto) == 0);
2318 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2321 GetObjectFile()->GetModule()->LogMessage(
2323 "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, sc_list)",
2324 name.GetCString(), name_type_mask);
2327 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2330 // If name is empty then we won't find anything.
2334 // Remember how many sc_list are in the list before we search in case we are
2335 // appending the results to a variable list.
2337 const uint32_t original_size = sc_list.GetSize();
2339 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2341 CompilerDeclContext empty_decl_ctx;
2342 if (!parent_decl_ctx)
2343 parent_decl_ctx = &empty_decl_ctx;
2345 std::vector<DWARFDIE> dies;
2346 m_index->GetFunctions(name, *this, *parent_decl_ctx, name_type_mask, dies);
2347 for (const DWARFDIE &die : dies) {
2348 if (resolved_dies.insert(die.GetDIE()).second)
2349 ResolveFunction(die, include_inlines, sc_list);
2352 // Return the number of variable that were appended to the list
2353 const uint32_t num_matches = sc_list.GetSize() - original_size;
2355 if (log && num_matches > 0) {
2356 GetObjectFile()->GetModule()->LogMessage(
2358 "SymbolFileDWARF::FindFunctions (name=\"%s\", "
2359 "name_type_mask=0x%x, include_inlines=%d, sc_list) => %u",
2360 name.GetCString(), name_type_mask, include_inlines,
2365 void SymbolFileDWARF::FindFunctions(const RegularExpression ®ex,
2366 bool include_inlines,
2367 SymbolContextList &sc_list) {
2368 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2369 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2370 Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (regex = '%s')",
2371 regex.GetText().str().c_str());
2373 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2376 GetObjectFile()->GetModule()->LogMessage(
2377 log, "SymbolFileDWARF::FindFunctions (regex=\"%s\", sc_list)",
2378 regex.GetText().str().c_str());
2381 DWARFDebugInfo *info = DebugInfo();
2386 m_index->GetFunctions(regex, offsets);
2388 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2389 for (DIERef ref : offsets) {
2390 DWARFDIE die = info->GetDIE(ref);
2392 m_index->ReportInvalidDIERef(ref, regex.GetText());
2395 if (resolved_dies.insert(die.GetDIE()).second)
2396 ResolveFunction(die, include_inlines, sc_list);
2400 void SymbolFileDWARF::GetMangledNamesForFunction(
2401 const std::string &scope_qualified_name,
2402 std::vector<ConstString> &mangled_names) {
2403 DWARFDebugInfo *info = DebugInfo();
2404 uint32_t num_comp_units = 0;
2406 num_comp_units = info->GetNumUnits();
2408 for (uint32_t i = 0; i < num_comp_units; i++) {
2409 DWARFUnit *cu = info->GetUnitAtIndex(i);
2413 SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
2415 dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
2418 for (lldb::user_id_t uid :
2419 m_function_scope_qualified_name_map.lookup(scope_qualified_name)) {
2420 DWARFDIE die = GetDIE(uid);
2421 mangled_names.push_back(ConstString(die.GetMangledName()));
2425 void SymbolFileDWARF::FindTypes(
2426 ConstString name, const CompilerDeclContext *parent_decl_ctx,
2427 uint32_t max_matches,
2428 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
2430 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2431 // Make sure we haven't already searched this SymbolFile before.
2432 if (!searched_symbol_files.insert(this).second)
2435 DWARFDebugInfo *info = DebugInfo();
2439 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2442 if (parent_decl_ctx)
2443 GetObjectFile()->GetModule()->LogMessage(
2445 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2446 "%p (\"%s\"), max_matches=%u, type_list)",
2447 name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2448 parent_decl_ctx->GetName().AsCString("<NULL>"), max_matches);
2450 GetObjectFile()->GetModule()->LogMessage(
2452 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2453 "NULL, max_matches=%u, type_list)",
2454 name.GetCString(), max_matches);
2457 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2460 DIEArray die_offsets;
2461 m_index->GetTypes(name, die_offsets);
2462 const size_t num_die_matches = die_offsets.size();
2464 for (size_t i = 0; i < num_die_matches; ++i) {
2465 const DIERef &die_ref = die_offsets[i];
2466 DWARFDIE die = GetDIE(die_ref);
2468 if (!DIEInDeclContext(parent_decl_ctx, die))
2469 continue; // The containing decl contexts don't match
2471 Type *matching_type = ResolveType(die, true, true);
2472 if (matching_type) {
2473 // We found a type pointer, now find the shared pointer form our type
2475 types.InsertUnique(matching_type->shared_from_this());
2476 if (types.GetSize() >= max_matches)
2480 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2484 // Next search through the reachable Clang modules. This only applies for
2485 // DWARF objects compiled with -gmodules that haven't been processed by
2487 if (num_die_matches < max_matches) {
2488 UpdateExternalModuleListIfNeeded();
2490 for (const auto &pair : m_external_type_modules)
2491 if (ModuleSP external_module_sp = pair.second)
2492 if (SymbolFile *sym_file = external_module_sp->GetSymbolFile())
2493 sym_file->FindTypes(name, parent_decl_ctx, max_matches,
2494 searched_symbol_files, types);
2497 if (log && types.GetSize()) {
2498 if (parent_decl_ctx) {
2499 GetObjectFile()->GetModule()->LogMessage(
2501 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2502 "= %p (\"%s\"), max_matches=%u, type_list) => %u",
2503 name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2504 parent_decl_ctx->GetName().AsCString("<NULL>"), max_matches,
2507 GetObjectFile()->GetModule()->LogMessage(
2509 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2510 "= NULL, max_matches=%u, type_list) => %u",
2511 name.GetCString(), max_matches, types.GetSize());
2516 void SymbolFileDWARF::FindTypes(
2517 llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
2518 llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {
2519 // Make sure we haven't already searched this SymbolFile before.
2520 if (!searched_symbol_files.insert(this).second)
2523 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2524 if (pattern.empty())
2527 ConstString name = pattern.back().name;
2532 DIEArray die_offsets;
2533 m_index->GetTypes(name, die_offsets);
2534 const size_t num_die_matches = die_offsets.size();
2536 for (size_t i = 0; i < num_die_matches; ++i) {
2537 const DIERef &die_ref = die_offsets[i];
2538 DWARFDIE die = GetDIE(die_ref);
2541 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2544 if (!languages[die.GetCU()->GetLanguageType()])
2547 llvm::SmallVector<CompilerContext, 4> die_context;
2548 die.GetDeclContext(die_context);
2549 if (!contextMatches(die_context, pattern))
2552 if (Type *matching_type = ResolveType(die, true, true)) {
2553 // We found a type pointer, now find the shared pointer form our type
2555 types.InsertUnique(matching_type->shared_from_this());
2559 // Next search through the reachable Clang modules. This only applies for
2560 // DWARF objects compiled with -gmodules that haven't been processed by
2562 UpdateExternalModuleListIfNeeded();
2564 for (const auto &pair : m_external_type_modules)
2565 if (ModuleSP external_module_sp = pair.second)
2566 external_module_sp->FindTypes(pattern, languages, searched_symbol_files,
2571 SymbolFileDWARF::FindNamespace(ConstString name,
2572 const CompilerDeclContext *parent_decl_ctx) {
2573 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2574 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2577 GetObjectFile()->GetModule()->LogMessage(
2578 log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
2582 CompilerDeclContext namespace_decl_ctx;
2584 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2585 return namespace_decl_ctx;
2587 DWARFDebugInfo *info = DebugInfo();
2589 DIEArray die_offsets;
2590 m_index->GetNamespaces(name, die_offsets);
2591 const size_t num_matches = die_offsets.size();
2593 for (size_t i = 0; i < num_matches; ++i) {
2594 const DIERef &die_ref = die_offsets[i];
2595 DWARFDIE die = GetDIE(die_ref);
2598 if (!DIEInDeclContext(parent_decl_ctx, die))
2599 continue; // The containing decl contexts don't match
2601 DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2603 namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
2604 if (namespace_decl_ctx)
2608 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2613 if (log && namespace_decl_ctx) {
2614 GetObjectFile()->GetModule()->LogMessage(
2616 "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => "
2617 "CompilerDeclContext(%p/%p) \"%s\"",
2619 static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
2620 static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
2621 namespace_decl_ctx.GetName().AsCString("<NULL>"));
2624 return namespace_decl_ctx;
2627 TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
2628 bool resolve_function_context) {
2631 Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
2632 if (type_ptr == nullptr) {
2633 SymbolContextScope *scope;
2634 if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()))
2635 scope = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2637 scope = GetObjectFile()->GetModule().get();
2639 SymbolContext sc(scope);
2640 const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
2641 while (parent_die != nullptr) {
2642 if (parent_die->Tag() == DW_TAG_subprogram)
2644 parent_die = parent_die->GetParent();
2646 SymbolContext sc_backup = sc;
2647 if (resolve_function_context && parent_die != nullptr &&
2648 !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
2651 type_sp = ParseType(sc, die, nullptr);
2652 } else if (type_ptr != DIE_IS_BEING_PARSED) {
2653 // Grab the existing type from the master types lists
2654 type_sp = type_ptr->shared_from_this();
2661 SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
2663 DWARFDIE die = orig_die;
2666 // If this is the original DIE that we are searching for a declaration
2667 // for, then don't look in the cache as we don't want our own decl
2668 // context to be our decl context...
2669 if (orig_die != die) {
2670 switch (die.Tag()) {
2671 case DW_TAG_compile_unit:
2672 case DW_TAG_partial_unit:
2673 case DW_TAG_namespace:
2674 case DW_TAG_structure_type:
2675 case DW_TAG_union_type:
2676 case DW_TAG_class_type:
2677 case DW_TAG_lexical_block:
2678 case DW_TAG_subprogram:
2680 case DW_TAG_inlined_subroutine: {
2681 DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2692 DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
2694 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
2696 return decl_ctx_die;
2699 DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2701 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
2703 return decl_ctx_die;
2706 die = die.GetParent();
2712 Symbol *SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) {
2713 Symbol *objc_class_symbol = nullptr;
2715 Symtab *symtab = m_objfile_sp->GetSymtab();
2717 objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
2718 objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
2719 Symtab::eVisibilityAny);
2722 return objc_class_symbol;
2725 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If
2726 // they don't then we can end up looking through all class types for a complete
2727 // type and never find the full definition. We need to know if this attribute
2728 // is supported, so we determine this here and cache th result. We also need to
2729 // worry about the debug map
2731 // if we are doing darwin DWARF in .o file debugging.
2732 bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(DWARFUnit *cu) {
2733 if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) {
2734 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
2735 if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
2736 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2738 DWARFDebugInfo *debug_info = DebugInfo();
2739 const uint32_t num_compile_units = GetNumCompileUnits();
2740 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2741 DWARFUnit *dwarf_cu = debug_info->GetUnitAtIndex(cu_idx);
2742 if (dwarf_cu != cu &&
2743 dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) {
2744 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2749 if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo &&
2750 GetDebugMapSymfile())
2751 return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this);
2753 return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
2756 // This function can be used when a DIE is found that is a forward declaration
2757 // DIE and we want to try and find a type that has the complete definition.
2758 TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE(
2759 const DWARFDIE &die, ConstString type_name, bool must_be_implementation) {
2763 if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
2766 DIEArray die_offsets;
2767 m_index->GetCompleteObjCClass(type_name, must_be_implementation, die_offsets);
2769 const size_t num_matches = die_offsets.size();
2772 for (size_t i = 0; i < num_matches; ++i) {
2773 const DIERef &die_ref = die_offsets[i];
2774 DWARFDIE type_die = GetDIE(die_ref);
2777 bool try_resolving_type = false;
2779 // Don't try and resolve the DIE we are looking for with the DIE
2781 if (type_die != die) {
2782 switch (type_die.Tag()) {
2783 case DW_TAG_class_type:
2784 case DW_TAG_structure_type:
2785 try_resolving_type = true;
2792 if (try_resolving_type) {
2793 if (must_be_implementation &&
2794 type_die.Supports_DW_AT_APPLE_objc_complete_type())
2795 try_resolving_type = type_die.GetAttributeValueAsUnsigned(
2796 DW_AT_APPLE_objc_complete_type, 0);
2798 if (try_resolving_type) {
2799 Type *resolved_type = ResolveType(type_die, false, true);
2800 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2801 DEBUG_PRINTF("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
2802 " (cu 0x%8.8" PRIx64 ")\n",
2804 m_objfile_sp->GetFileSpec().GetFilename().AsCString(
2806 type_die.GetID(), type_cu->GetID());
2809 GetDIEToType()[die.GetDIE()] = resolved_type;
2810 type_sp = resolved_type->shared_from_this();
2816 m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
2823 // This function helps to ensure that the declaration contexts match for two
2824 // different DIEs. Often times debug information will refer to a forward
2825 // declaration of a type (the equivalent of "struct my_struct;". There will
2826 // often be a declaration of that type elsewhere that has the full definition.
2827 // When we go looking for the full type "my_struct", we will find one or more
2828 // matches in the accelerator tables and we will then need to make sure the
2829 // type was in the same declaration context as the original DIE. This function
2830 // can efficiently compare two DIEs and will return true when the declaration
2831 // context matches, and false when they don't.
2832 bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1,
2833 const DWARFDIE &die2) {
2837 std::vector<DWARFDIE> decl_ctx_1;
2838 std::vector<DWARFDIE> decl_ctx_2;
2839 // The declaration DIE stack is a stack of the declaration context DIEs all
2840 // the way back to the compile unit. If a type "T" is declared inside a class
2841 // "B", and class "B" is declared inside a class "A" and class "A" is in a
2842 // namespace "lldb", and the namespace is in a compile unit, there will be a
2845 // [0] DW_TAG_class_type for "B"
2846 // [1] DW_TAG_class_type for "A"
2847 // [2] DW_TAG_namespace for "lldb"
2848 // [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file.
2850 // We grab both contexts and make sure that everything matches all the way
2851 // back to the compiler unit.
2853 // First lets grab the decl contexts for both DIEs
2854 decl_ctx_1 = die1.GetDeclContextDIEs();
2855 decl_ctx_2 = die2.GetDeclContextDIEs();
2856 // Make sure the context arrays have the same size, otherwise we are done
2857 const size_t count1 = decl_ctx_1.size();
2858 const size_t count2 = decl_ctx_2.size();
2859 if (count1 != count2)
2862 // Make sure the DW_TAG values match all the way back up the compile unit. If
2863 // they don't, then we are done.
2864 DWARFDIE decl_ctx_die1;
2865 DWARFDIE decl_ctx_die2;
2867 for (i = 0; i < count1; i++) {
2868 decl_ctx_die1 = decl_ctx_1[i];
2869 decl_ctx_die2 = decl_ctx_2[i];
2870 if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
2875 // Make sure the top item in the decl context die array is always
2876 // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then
2877 // something went wrong in the DWARFDIE::GetDeclContextDIEs()
2879 dw_tag_t cu_tag = decl_ctx_1[count1 - 1].Tag();
2880 UNUSED_IF_ASSERT_DISABLED(cu_tag);
2881 assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit);
2884 // Always skip the compile unit when comparing by only iterating up to "count
2885 // - 1". Here we compare the names as we go.
2886 for (i = 0; i < count1 - 1; i++) {
2887 decl_ctx_die1 = decl_ctx_1[i];
2888 decl_ctx_die2 = decl_ctx_2[i];
2889 const char *name1 = decl_ctx_die1.GetName();
2890 const char *name2 = decl_ctx_die2.GetName();
2891 // If the string was from a DW_FORM_strp, then the pointer will often be
2896 // Name pointers are not equal, so only compare the strings if both are not
2898 if (name1 && name2) {
2899 // If the strings don't compare, we are done...
2900 if (strcmp(name1, name2) != 0)
2903 // One name was NULL while the other wasn't
2907 // We made it through all of the checks and the declaration contexts are
2912 TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(
2913 const DWARFDeclContext &dwarf_decl_ctx) {
2916 const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
2917 if (dwarf_decl_ctx_count > 0) {
2918 const ConstString type_name(dwarf_decl_ctx[0].name);
2919 const dw_tag_t tag = dwarf_decl_ctx[0].tag;
2922 Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION |
2923 DWARF_LOG_LOOKUPS));
2925 GetObjectFile()->GetModule()->LogMessage(
2927 "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%"
2928 "s, qualified-name='%s')",
2929 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2930 dwarf_decl_ctx.GetQualifiedName());
2933 DIEArray die_offsets;
2934 m_index->GetTypes(dwarf_decl_ctx, die_offsets);
2935 const size_t num_matches = die_offsets.size();
2937 // Get the type system that we are looking to find a type for. We will
2938 // use this to ensure any matches we find are in a language that this
2939 // type system supports
2940 const LanguageType language = dwarf_decl_ctx.GetLanguage();
2941 TypeSystem *type_system = nullptr;
2942 if (language != eLanguageTypeUnknown) {
2943 auto type_system_or_err = GetTypeSystemForLanguage(language);
2944 if (auto err = type_system_or_err.takeError()) {
2946 lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
2947 std::move(err), "Cannot get TypeSystem for language {}",
2948 Language::GetNameForLanguageType(language));
2950 type_system = &type_system_or_err.get();
2954 for (size_t i = 0; i < num_matches; ++i) {
2955 const DIERef &die_ref = die_offsets[i];
2956 DWARFDIE type_die = GetDIE(die_ref);
2959 // Make sure type_die's langauge matches the type system we are
2960 // looking for. We don't want to find a "Foo" type from Java if we
2961 // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
2963 !type_system->SupportsLanguage(type_die.GetLanguage()))
2965 bool try_resolving_type = false;
2967 // Don't try and resolve the DIE we are looking for with the DIE
2969 const dw_tag_t type_tag = type_die.Tag();
2970 // Make sure the tags match
2971 if (type_tag == tag) {
2972 // The tags match, lets try resolving this type
2973 try_resolving_type = true;
2975 // The tags don't match, but we need to watch our for a forward
2976 // declaration for a struct and ("struct foo") ends up being a
2977 // class ("class foo { ... };") or vice versa.
2979 case DW_TAG_class_type:
2980 // We had a "class foo", see if we ended up with a "struct foo
2982 try_resolving_type = (tag == DW_TAG_structure_type);
2984 case DW_TAG_structure_type:
2985 // We had a "struct foo", see if we ended up with a "class foo
2987 try_resolving_type = (tag == DW_TAG_class_type);
2990 // Tags don't match, don't event try to resolve using this type
2991 // whose name matches....
2996 if (try_resolving_type) {
2997 DWARFDeclContext type_dwarf_decl_ctx;
2998 type_die.GetDWARFDeclContext(type_dwarf_decl_ctx);
3001 GetObjectFile()->GetModule()->LogMessage(
3004 "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
3005 "qualified-name='%s') trying die=0x%8.8x (%s)",
3006 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3007 dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
3008 type_dwarf_decl_ctx.GetQualifiedName());
3011 // Make sure the decl contexts match all the way up
3012 if (dwarf_decl_ctx == type_dwarf_decl_ctx) {
3013 Type *resolved_type = ResolveType(type_die, false);
3014 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
3015 type_sp = resolved_type->shared_from_this();
3021 std::string qualified_name;
3022 type_die.GetQualifiedName(qualified_name);
3023 GetObjectFile()->GetModule()->LogMessage(
3026 "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
3027 "qualified-name='%s') ignoring die=0x%8.8x (%s)",
3028 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3029 dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
3030 qualified_name.c_str());
3034 m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
3043 TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die,
3044 bool *type_is_new_ptr) {
3048 auto type_system_or_err =
3049 GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
3050 if (auto err = type_system_or_err.takeError()) {
3051 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
3052 std::move(err), "Unable to parse type");
3056 DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser();
3060 TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, type_is_new_ptr);
3062 GetTypeList().Insert(type_sp);
3064 if (die.Tag() == DW_TAG_subprogram) {
3065 std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
3066 .GetScopeQualifiedName()
3068 if (scope_qualified_name.size()) {
3069 m_function_scope_qualified_name_map[scope_qualified_name].insert(
3078 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc,
3079 const DWARFDIE &orig_die,
3080 bool parse_siblings, bool parse_children) {
3081 size_t types_added = 0;
3082 DWARFDIE die = orig_die;
3085 const dw_tag_t tag = die.Tag();
3086 bool type_is_new = false;
3088 Tag dwarf_tag = static_cast<Tag>(tag);
3090 // TODO: Currently ParseTypeFromDWARF(...) which is called by ParseType(...)
3091 // does not handle DW_TAG_subrange_type. It is not clear if this is a bug or
3093 if (isType(dwarf_tag) && tag != DW_TAG_subrange_type)
3094 ParseType(sc, die, &type_is_new);
3099 if (parse_children && die.HasChildren()) {
3100 if (die.Tag() == DW_TAG_subprogram) {
3101 SymbolContext child_sc(sc);
3102 child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3103 types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3105 types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3109 die = die.GetSibling();
3116 size_t SymbolFileDWARF::ParseBlocksRecursive(Function &func) {
3117 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3118 CompileUnit *comp_unit = func.GetCompileUnit();
3119 lldbassert(comp_unit);
3121 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit);
3125 size_t functions_added = 0;
3126 const dw_offset_t function_die_offset = func.GetID();
3127 DWARFDIE function_die = dwarf_cu->GetDIE(function_die_offset);
3129 ParseBlocksRecursive(*comp_unit, &func.GetBlock(false), function_die,
3130 LLDB_INVALID_ADDRESS, 0);
3133 return functions_added;
3136 size_t SymbolFileDWARF::ParseTypes(CompileUnit &comp_unit) {
3137 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3138 size_t types_added = 0;
3139 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
3141 DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3142 if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3144 sc.comp_unit = &comp_unit;
3145 types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3152 size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) {
3153 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3154 if (sc.comp_unit != nullptr) {
3155 DWARFDebugInfo *info = DebugInfo();
3156 if (info == nullptr)
3160 DWARFDIE function_die = GetDIE(sc.function->GetID());
3162 const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress(
3163 DW_AT_low_pc, LLDB_INVALID_ADDRESS);
3164 if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3165 const size_t num_variables = ParseVariables(
3166 sc, function_die.GetFirstChild(), func_lo_pc, true, true);
3168 // Let all blocks know they have parse all their variables
3169 sc.function->GetBlock(false).SetDidParseVariables(true, true);
3170 return num_variables;
3172 } else if (sc.comp_unit) {
3173 DWARFUnit *dwarf_cu = info->GetUnitAtIndex(sc.comp_unit->GetID());
3175 if (dwarf_cu == nullptr)
3178 uint32_t vars_added = 0;
3179 VariableListSP variables(sc.comp_unit->GetVariableList(false));
3181 if (variables.get() == nullptr) {
3182 variables = std::make_shared<VariableList>();
3183 sc.comp_unit->SetVariableList(variables);
3185 DIEArray die_offsets;
3186 m_index->GetGlobalVariables(dwarf_cu->GetNonSkeletonUnit(),
3188 const size_t num_matches = die_offsets.size();
3190 for (size_t i = 0; i < num_matches; ++i) {
3191 const DIERef &die_ref = die_offsets[i];
3192 DWARFDIE die = GetDIE(die_ref);
3195 ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS));
3197 variables->AddVariableIfUnique(var_sp);
3201 m_index->ReportInvalidDIERef(die_ref, "");
3211 VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc,
3212 const DWARFDIE &die,
3213 const lldb::addr_t func_low_pc) {
3214 if (die.GetDWARF() != this)
3215 return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3221 var_sp = GetDIEToVariable()[die.GetDIE()];
3223 return var_sp; // Already been parsed!
3225 const dw_tag_t tag = die.Tag();
3226 ModuleSP module = GetObjectFile()->GetModule();
3228 if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3229 (tag == DW_TAG_formal_parameter && sc.function)) {
3230 DWARFAttributes attributes;
3231 const size_t num_attributes = die.GetAttributes(attributes);
3233 if (num_attributes > 0) {
3234 const char *name = nullptr;
3235 const char *mangled = nullptr;
3238 DWARFFormValue type_die_form;
3239 DWARFExpression location;
3240 bool is_external = false;
3241 bool is_artificial = false;
3242 bool location_is_const_value_data = false;
3243 bool has_explicit_location = false;
3244 DWARFFormValue const_value;
3245 Variable::RangeList scope_ranges;
3246 // AccessType accessibility = eAccessNone;
3248 for (i = 0; i < num_attributes; ++i) {
3249 dw_attr_t attr = attributes.AttributeAtIndex(i);
3250 DWARFFormValue form_value;
3252 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3254 case DW_AT_decl_file:
3255 decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3256 form_value.Unsigned()));
3258 case DW_AT_decl_line:
3259 decl.SetLine(form_value.Unsigned());
3261 case DW_AT_decl_column:
3262 decl.SetColumn(form_value.Unsigned());
3265 name = form_value.AsCString();
3267 case DW_AT_linkage_name:
3268 case DW_AT_MIPS_linkage_name:
3269 mangled = form_value.AsCString();
3272 type_die_form = form_value;
3274 case DW_AT_external:
3275 is_external = form_value.Boolean();
3277 case DW_AT_const_value:
3278 // If we have already found a DW_AT_location attribute, ignore this
3280 if (!has_explicit_location) {
3281 location_is_const_value_data = true;
3282 // The constant value will be either a block, a data value or a
3284 auto debug_info_data = die.GetData();
3285 if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3286 // Retrieve the value as a block expression.
3287 uint32_t block_offset =
3288 form_value.BlockData() - debug_info_data.GetDataStart();
3289 uint32_t block_length = form_value.Unsigned();
3290 location = DWARFExpression(
3292 DataExtractor(debug_info_data, block_offset, block_length),
3294 } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3295 // Retrieve the value as a data expression.
3296 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3297 if (auto data_length = form_value.GetFixedSize())
3298 location = DWARFExpression(
3300 DataExtractor(debug_info_data, data_offset, *data_length),
3303 const uint8_t *data_pointer = form_value.BlockData();
3305 form_value.Unsigned();
3306 } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3307 // we need to get the byte size of the type later after we
3308 // create the variable
3309 const_value = form_value;
3313 // Retrieve the value as a string expression.
3314 if (form_value.Form() == DW_FORM_strp) {
3315 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3316 if (auto data_length = form_value.GetFixedSize())
3317 location = DWARFExpression(module,
3318 DataExtractor(debug_info_data,
3323 const char *str = form_value.AsCString();
3324 uint32_t string_offset =
3325 str - (const char *)debug_info_data.GetDataStart();
3326 uint32_t string_length = strlen(str) + 1;
3327 location = DWARFExpression(module,
3328 DataExtractor(debug_info_data,
3336 case DW_AT_location: {
3337 location_is_const_value_data = false;
3338 has_explicit_location = true;
3339 if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3340 auto data = die.GetData();
3342 uint32_t block_offset =
3343 form_value.BlockData() - data.GetDataStart();
3344 uint32_t block_length = form_value.Unsigned();
3345 location = DWARFExpression(
3346 module, DataExtractor(data, block_offset, block_length),
3349 DataExtractor data = die.GetCU()->GetLocationData();
3350 dw_offset_t offset = form_value.Unsigned();
3351 if (form_value.Form() == DW_FORM_loclistx)
3352 offset = die.GetCU()->GetLoclistOffset(offset).getValueOr(-1);
3353 if (data.ValidOffset(offset)) {
3354 data = DataExtractor(data, offset, data.GetByteSize() - offset);
3355 location = DWARFExpression(module, data, die.GetCU());
3356 assert(func_low_pc != LLDB_INVALID_ADDRESS);
3357 location.SetLocationListAddresses(
3358 attributes.CompileUnitAtIndex(i)->GetBaseAddress(),
3363 case DW_AT_specification:
3364 spec_die = form_value.Reference();
3366 case DW_AT_start_scope:
3367 // TODO: Implement this.
3369 case DW_AT_artificial:
3370 is_artificial = form_value.Boolean();
3372 case DW_AT_accessibility:
3373 break; // accessibility =
3374 // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
3375 case DW_AT_declaration:
3376 case DW_AT_description:
3377 case DW_AT_endianity:
3379 case DW_AT_visibility:
3381 case DW_AT_abstract_origin:
3388 const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3389 const dw_tag_t parent_tag = die.GetParent().Tag();
3390 bool is_static_member =
3391 (parent_tag == DW_TAG_compile_unit ||
3392 parent_tag == DW_TAG_partial_unit) &&
3393 (parent_context_die.Tag() == DW_TAG_class_type ||
3394 parent_context_die.Tag() == DW_TAG_structure_type);
3396 ValueType scope = eValueTypeInvalid;
3398 const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3399 SymbolContextScope *symbol_context_scope = nullptr;
3401 bool has_explicit_mangled = mangled != nullptr;
3403 // LLDB relies on the mangled name (DW_TAG_linkage_name or
3404 // DW_AT_MIPS_linkage_name) to generate fully qualified names
3405 // of global variables with commands like "frame var j". For
3406 // example, if j were an int variable holding a value 4 and
3407 // declared in a namespace B which in turn is contained in a
3408 // namespace A, the command "frame var j" returns
3409 // "(int) A::B::j = 4".
3410 // If the compiler does not emit a linkage name, we should be
3411 // able to generate a fully qualified name from the
3412 // declaration context.
3413 if ((parent_tag == DW_TAG_compile_unit ||
3414 parent_tag == DW_TAG_partial_unit) &&
3415 Language::LanguageIsCPlusPlus(die.GetLanguage())) {
3416 DWARFDeclContext decl_ctx;
3418 die.GetDWARFDeclContext(decl_ctx);
3419 mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString();
3423 if (tag == DW_TAG_formal_parameter)
3424 scope = eValueTypeVariableArgument;
3426 // DWARF doesn't specify if a DW_TAG_variable is a local, global
3427 // or static variable, so we have to do a little digging:
3428 // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3429 // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3430 // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3431 // Clang likes to combine small global variables into the same symbol
3432 // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3433 // so we need to look through the whole expression.
3434 bool is_static_lifetime =
3435 has_explicit_mangled ||
3436 (has_explicit_location && !location.IsValid());
3437 // Check if the location has a DW_OP_addr with any address value...
3438 lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3439 if (!location_is_const_value_data) {
3440 bool op_error = false;
3441 location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error);
3444 location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0,
3446 GetObjectFile()->GetModule()->ReportError(
3447 "0x%8.8x: %s has an invalid location: %s", die.GetOffset(),
3448 die.GetTagAsCString(), strm.GetData());
3450 if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
3451 is_static_lifetime = true;
3453 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
3454 if (debug_map_symfile)
3455 // Set the module of the expression to the linked module
3456 // instead of the oject file so the relocated address can be
3458 location.SetModule(debug_map_symfile->GetObjectFile()->GetModule());
3460 if (is_static_lifetime) {
3462 scope = eValueTypeVariableGlobal;
3464 scope = eValueTypeVariableStatic;
3466 if (debug_map_symfile) {
3467 // When leaving the DWARF in the .o files on darwin, when we have a
3468 // global variable that wasn't initialized, the .o file might not
3469 // have allocated a virtual address for the global variable. In
3470 // this case it will have created a symbol for the global variable
3471 // that is undefined/data and external and the value will be the
3472 // byte size of the variable. When we do the address map in
3473 // SymbolFileDWARFDebugMap we rely on having an address, we need to
3474 // do some magic here so we can get the correct address for our
3475 // global variable. The address for all of these entries will be
3476 // zero, and there will be an undefined symbol in this object file,
3477 // and the executable will have a matching symbol with a good
3478 // address. So here we dig up the correct address and replace it in
3479 // the location for the variable, and set the variable's symbol
3480 // context scope to be that of the main executable so the file
3481 // address will resolve correctly.
3482 bool linked_oso_file_addr = false;
3483 if (is_external && location_DW_OP_addr == 0) {
3484 // we have a possible uninitialized extern global
3485 ConstString const_name(mangled ? mangled : name);
3486 ObjectFile *debug_map_objfile =
3487 debug_map_symfile->GetObjectFile();
3488 if (debug_map_objfile) {
3489 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3490 if (debug_map_symtab) {
3491 Symbol *exe_symbol =
3492 debug_map_symtab->FindFirstSymbolWithNameAndType(
3493 const_name, eSymbolTypeData, Symtab::eDebugYes,
3494 Symtab::eVisibilityExtern);
3496 if (exe_symbol->ValueIsAddress()) {
3497 const addr_t exe_file_addr =
3498 exe_symbol->GetAddressRef().GetFileAddress();
3499 if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3500 if (location.Update_DW_OP_addr(exe_file_addr)) {
3501 linked_oso_file_addr = true;
3502 symbol_context_scope = exe_symbol;
3511 if (!linked_oso_file_addr) {
3512 // The DW_OP_addr is not zero, but it contains a .o file address
3513 // which needs to be linked up correctly.
3514 const lldb::addr_t exe_file_addr =
3515 debug_map_symfile->LinkOSOFileAddress(this,
3516 location_DW_OP_addr);
3517 if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3518 // Update the file address for this variable
3519 location.Update_DW_OP_addr(exe_file_addr);
3521 // Variable didn't make it into the final executable
3527 if (location_is_const_value_data)
3528 scope = eValueTypeVariableStatic;
3530 scope = eValueTypeVariableLocal;
3531 if (debug_map_symfile) {
3532 // We need to check for TLS addresses that we need to fixup
3533 if (location.ContainsThreadLocalStorage()) {
3534 location.LinkThreadLocalStorage(
3535 debug_map_symfile->GetObjectFile()->GetModule(),
3536 [this, debug_map_symfile](
3537 lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
3538 return debug_map_symfile->LinkOSOFileAddress(
3539 this, unlinked_file_addr);
3541 scope = eValueTypeVariableThreadLocal;
3548 if (symbol_context_scope == nullptr) {
3549 switch (parent_tag) {
3550 case DW_TAG_subprogram:
3551 case DW_TAG_inlined_subroutine:
3552 case DW_TAG_lexical_block:
3554 symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(
3555 sc_parent_die.GetID());
3556 if (symbol_context_scope == nullptr)
3557 symbol_context_scope = sc.function;
3562 symbol_context_scope = sc.comp_unit;
3567 if (symbol_context_scope) {
3568 SymbolFileTypeSP type_sp(
3569 new SymbolFileType(*this, GetUID(type_die_form.Reference())));
3571 if (const_value.Form() && type_sp && type_sp->GetType())
3572 location.UpdateValue(const_value.Unsigned(),
3573 type_sp->GetType()->GetByteSize().getValueOr(0),
3574 die.GetCU()->GetAddressByteSize());
3576 var_sp = std::make_shared<Variable>(
3577 die.GetID(), name, mangled, type_sp, scope, symbol_context_scope,
3578 scope_ranges, &decl, location, is_external, is_artificial,
3581 var_sp->SetLocationIsConstantValueData(location_is_const_value_data);
3583 // Not ready to parse this variable yet. It might be a global or static
3584 // variable that is in a function scope and the function in the symbol
3585 // context wasn't filled in yet
3589 // Cache var_sp even if NULL (the variable was just a specification or was
3590 // missing vital information to be able to be displayed in the debugger
3591 // (missing location due to optimization, etc)) so we don't re-parse this
3592 // DIE over and over later...
3593 GetDIEToVariable()[die.GetDIE()] = var_sp;
3595 GetDIEToVariable()[spec_die.GetDIE()] = var_sp;
3601 SymbolFileDWARF::FindBlockContainingSpecification(
3602 const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
3603 // Give the concrete function die specified by "func_die_offset", find the
3604 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3605 // to "spec_block_die_offset"
3606 return FindBlockContainingSpecification(DebugInfo()->GetDIE(func_die_ref),
3607 spec_block_die_offset);
3611 SymbolFileDWARF::FindBlockContainingSpecification(
3612 const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
3614 switch (die.Tag()) {
3615 case DW_TAG_subprogram:
3616 case DW_TAG_inlined_subroutine:
3617 case DW_TAG_lexical_block: {
3618 if (die.GetReferencedDIE(DW_AT_specification).GetOffset() ==
3619 spec_block_die_offset)
3622 if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() ==
3623 spec_block_die_offset)
3630 // Give the concrete function die specified by "func_die_offset", find the
3631 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3632 // to "spec_block_die_offset"
3633 for (DWARFDIE child_die = die.GetFirstChild(); child_die;
3634 child_die = child_die.GetSibling()) {
3635 DWARFDIE result_die =
3636 FindBlockContainingSpecification(child_die, spec_block_die_offset);
3645 size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc,
3646 const DWARFDIE &orig_die,
3647 const lldb::addr_t func_low_pc,
3648 bool parse_siblings, bool parse_children,
3649 VariableList *cc_variable_list) {
3653 VariableListSP variable_list_sp;
3655 size_t vars_added = 0;
3656 DWARFDIE die = orig_die;
3658 dw_tag_t tag = die.Tag();
3660 // Check to see if we have already parsed this variable or constant?
3661 VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
3663 if (cc_variable_list)
3664 cc_variable_list->AddVariableIfUnique(var_sp);
3666 // We haven't already parsed it, lets do that now.
3667 if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3668 (tag == DW_TAG_formal_parameter && sc.function)) {
3669 if (variable_list_sp.get() == nullptr) {
3670 DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die);
3671 dw_tag_t parent_tag = sc_parent_die.Tag();
3672 switch (parent_tag) {
3673 case DW_TAG_compile_unit:
3674 case DW_TAG_partial_unit:
3675 if (sc.comp_unit != nullptr) {
3676 variable_list_sp = sc.comp_unit->GetVariableList(false);
3677 if (variable_list_sp.get() == nullptr) {
3678 variable_list_sp = std::make_shared<VariableList>();
3681 GetObjectFile()->GetModule()->ReportError(
3682 "parent 0x%8.8" PRIx64 " %s with no valid compile unit in "
3683 "symbol context for 0x%8.8" PRIx64 " %s.\n",
3684 sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(),
3685 orig_die.GetID(), orig_die.GetTagAsCString());
3689 case DW_TAG_subprogram:
3690 case DW_TAG_inlined_subroutine:
3691 case DW_TAG_lexical_block:
3692 if (sc.function != nullptr) {
3693 // Check to see if we already have parsed the variables for the
3696 Block *block = sc.function->GetBlock(true).FindBlockByID(
3697 sc_parent_die.GetID());
3698 if (block == nullptr) {
3699 // This must be a specification or abstract origin with a
3700 // concrete block counterpart in the current function. We need
3701 // to find the concrete block so we can correctly add the
3703 const DWARFDIE concrete_block_die =
3704 FindBlockContainingSpecification(
3705 GetDIE(sc.function->GetID()),
3706 sc_parent_die.GetOffset());
3707 if (concrete_block_die)
3708 block = sc.function->GetBlock(true).FindBlockByID(
3709 concrete_block_die.GetID());
3712 if (block != nullptr) {
3713 const bool can_create = false;
3714 variable_list_sp = block->GetBlockVariableList(can_create);
3715 if (variable_list_sp.get() == nullptr) {
3716 variable_list_sp = std::make_shared<VariableList>();
3717 block->SetVariableList(variable_list_sp);
3724 GetObjectFile()->GetModule()->ReportError(
3725 "didn't find appropriate parent DIE for variable list for "
3726 "0x%8.8" PRIx64 " %s.\n",
3727 orig_die.GetID(), orig_die.GetTagAsCString());
3732 if (variable_list_sp) {
3733 VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc));
3735 variable_list_sp->AddVariableIfUnique(var_sp);
3736 if (cc_variable_list)
3737 cc_variable_list->AddVariableIfUnique(var_sp);
3744 bool skip_children = (sc.function == nullptr && tag == DW_TAG_subprogram);
3746 if (!skip_children && parse_children && die.HasChildren()) {
3747 vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true,
3748 true, cc_variable_list);
3752 die = die.GetSibling();
3759 /// Collect call site parameters in a DW_TAG_call_site DIE.
3760 static CallSiteParameterArray
3761 CollectCallSiteParameters(ModuleSP module, DWARFDIE call_site_die) {
3762 CallSiteParameterArray parameters;
3763 for (DWARFDIE child = call_site_die.GetFirstChild(); child.IsValid();
3764 child = child.GetSibling()) {
3765 if (child.Tag() != DW_TAG_call_site_parameter)
3768 llvm::Optional<DWARFExpression> LocationInCallee;
3769 llvm::Optional<DWARFExpression> LocationInCaller;
3771 DWARFAttributes attributes;
3772 const size_t num_attributes = child.GetAttributes(attributes);
3774 // Parse the location at index \p attr_index within this call site parameter
3775 // DIE, or return None on failure.
3776 auto parse_simple_location =
3777 [&](int attr_index) -> llvm::Optional<DWARFExpression> {
3778 DWARFFormValue form_value;
3779 if (!attributes.ExtractFormValueAtIndex(attr_index, form_value))
3781 if (!DWARFFormValue::IsBlockForm(form_value.Form()))
3783 auto data = child.GetData();
3784 uint32_t block_offset = form_value.BlockData() - data.GetDataStart();
3785 uint32_t block_length = form_value.Unsigned();
3786 return DWARFExpression(module,
3787 DataExtractor(data, block_offset, block_length),
3791 for (size_t i = 0; i < num_attributes; ++i) {
3792 dw_attr_t attr = attributes.AttributeAtIndex(i);
3793 if (attr == DW_AT_location)
3794 LocationInCallee = parse_simple_location(i);
3795 if (attr == DW_AT_call_value)
3796 LocationInCaller = parse_simple_location(i);
3799 if (LocationInCallee && LocationInCaller) {
3800 CallSiteParameter param = {*LocationInCallee, *LocationInCaller};
3801 parameters.push_back(param);
3807 /// Collect call graph edges present in a function DIE.
3808 static std::vector<std::unique_ptr<lldb_private::CallEdge>>
3809 CollectCallEdges(ModuleSP module, DWARFDIE function_die) {
3810 // Check if the function has a supported call site-related attribute.
3811 // TODO: In the future it may be worthwhile to support call_all_source_calls.
3812 uint64_t has_call_edges =
3813 function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0);
3814 if (!has_call_edges)
3817 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3818 LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}",
3819 function_die.GetPubname());
3821 // Scan the DIE for TAG_call_site entries.
3822 // TODO: A recursive scan of all blocks in the subprogram is needed in order
3823 // to be DWARF5-compliant. This may need to be done lazily to be performant.
3824 // For now, assume that all entries are nested directly under the subprogram
3825 // (this is the kind of DWARF LLVM produces) and parse them eagerly.
3826 std::vector<std::unique_ptr<CallEdge>> call_edges;
3827 for (DWARFDIE child = function_die.GetFirstChild(); child.IsValid();
3828 child = child.GetSibling()) {
3829 if (child.Tag() != DW_TAG_call_site)
3832 llvm::Optional<DWARFDIE> call_origin;
3833 llvm::Optional<DWARFExpression> call_target;
3834 addr_t return_pc = LLDB_INVALID_ADDRESS;
3836 DWARFAttributes attributes;
3837 const size_t num_attributes = child.GetAttributes(attributes);
3838 for (size_t i = 0; i < num_attributes; ++i) {
3839 DWARFFormValue form_value;
3840 if (!attributes.ExtractFormValueAtIndex(i, form_value)) {
3841 LLDB_LOG(log, "CollectCallEdges: Could not extract TAG_call_site form");
3845 dw_attr_t attr = attributes.AttributeAtIndex(i);
3847 // Extract DW_AT_call_origin (the call target's DIE).
3848 if (attr == DW_AT_call_origin) {
3849 call_origin = form_value.Reference();
3850 if (!call_origin->IsValid()) {
3851 LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}",
3852 function_die.GetPubname());
3857 // Extract DW_AT_call_return_pc (the PC the call returns to) if it's
3858 // available. It should only ever be unavailable for tail call edges, in
3859 // which case use LLDB_INVALID_ADDRESS.
3860 if (attr == DW_AT_call_return_pc)
3861 return_pc = form_value.Address();
3863 // Extract DW_AT_call_target (the location of the address of the indirect
3865 if (attr == DW_AT_call_target) {
3866 if (!DWARFFormValue::IsBlockForm(form_value.Form())) {
3868 "CollectCallEdges: AT_call_target does not have block form");
3872 auto data = child.GetData();
3873 uint32_t block_offset = form_value.BlockData() - data.GetDataStart();
3874 uint32_t block_length = form_value.Unsigned();
3875 call_target = DWARFExpression(
3876 module, DataExtractor(data, block_offset, block_length),
3880 if (!call_origin && !call_target) {
3881 LLDB_LOG(log, "CollectCallEdges: call site without any call target");
3885 // Extract call site parameters.
3886 CallSiteParameterArray parameters =
3887 CollectCallSiteParameters(module, child);
3889 std::unique_ptr<CallEdge> edge;
3891 LLDB_LOG(log, "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x})",
3892 call_origin->GetPubname(), return_pc);
3893 edge = std::make_unique<DirectCallEdge>(call_origin->GetMangledName(),
3894 return_pc, std::move(parameters));
3897 StreamString call_target_desc;
3898 call_target->GetDescription(&call_target_desc, eDescriptionLevelBrief,
3899 LLDB_INVALID_ADDRESS, nullptr);
3900 LLDB_LOG(log, "CollectCallEdges: Found indirect call target: {0}",
3901 call_target_desc.GetString());
3903 edge = std::make_unique<IndirectCallEdge>(*call_target, return_pc,
3904 std::move(parameters));
3907 if (log && parameters.size()) {
3908 for (const CallSiteParameter ¶m : parameters) {
3909 StreamString callee_loc_desc, caller_loc_desc;
3910 param.LocationInCallee.GetDescription(&callee_loc_desc,
3911 eDescriptionLevelBrief,
3912 LLDB_INVALID_ADDRESS, nullptr);
3913 param.LocationInCaller.GetDescription(&caller_loc_desc,
3914 eDescriptionLevelBrief,
3915 LLDB_INVALID_ADDRESS, nullptr);
3916 LLDB_LOG(log, "CollectCallEdges: \tparam: {0} => {1}",
3917 callee_loc_desc.GetString(), caller_loc_desc.GetString());
3921 call_edges.push_back(std::move(edge));
3926 std::vector<std::unique_ptr<lldb_private::CallEdge>>
3927 SymbolFileDWARF::ParseCallEdgesInFunction(UserID func_id) {
3928 DWARFDIE func_die = GetDIE(func_id.GetID());
3929 if (func_die.IsValid())
3930 return CollectCallEdges(GetObjectFile()->GetModule(), func_die);
3934 // PluginInterface protocol
3935 ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); }
3937 uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; }
3939 void SymbolFileDWARF::Dump(lldb_private::Stream &s) {
3940 SymbolFile::Dump(s);
3944 void SymbolFileDWARF::DumpClangAST(Stream &s) {
3945 auto ts_or_err = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
3948 ClangASTContext *clang =
3949 llvm::dyn_cast_or_null<ClangASTContext>(&ts_or_err.get());
3955 SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() {
3956 if (m_debug_map_symfile == nullptr && !m_debug_map_module_wp.expired()) {
3957 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
3959 m_debug_map_symfile =
3960 (SymbolFileDWARFDebugMap *)module_sp->GetSymbolFile();
3963 return m_debug_map_symfile;
3966 SymbolFileDWARFDwp *SymbolFileDWARF::GetDwpSymbolFile() {
3967 llvm::call_once(m_dwp_symfile_once_flag, [this]() {
3968 ModuleSpec module_spec;
3969 module_spec.GetFileSpec() = m_objfile_sp->GetFileSpec();
3970 module_spec.GetSymbolFileSpec() =
3971 FileSpec(m_objfile_sp->GetFileSpec().GetPath() + ".dwp");
3973 FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths();
3974 FileSpec dwp_filespec =
3975 Symbols::LocateExecutableSymbolFile(module_spec, search_paths);
3976 if (FileSystem::Instance().Exists(dwp_filespec)) {
3977 m_dwp_symfile = SymbolFileDWARFDwp::Create(GetObjectFile()->GetModule(),
3981 return m_dwp_symfile.get();