1 //===-- SymbolFileDWARF.cpp -----------------------------------------------===//
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/DebugInfo/DWARF/DWARFDebugLoc.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/Progress.h"
20 #include "lldb/Core/Section.h"
21 #include "lldb/Core/StreamFile.h"
22 #include "lldb/Core/Value.h"
23 #include "lldb/Utility/ArchSpec.h"
24 #include "lldb/Utility/LLDBLog.h"
25 #include "lldb/Utility/RegularExpression.h"
26 #include "lldb/Utility/Scalar.h"
27 #include "lldb/Utility/StreamString.h"
28 #include "lldb/Utility/Timer.h"
30 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
31 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
33 #include "lldb/Host/FileSystem.h"
34 #include "lldb/Host/Host.h"
36 #include "lldb/Interpreter/OptionValueFileSpecList.h"
37 #include "lldb/Interpreter/OptionValueProperties.h"
39 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
40 #include "Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.h"
41 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
42 #include "lldb/Symbol/Block.h"
43 #include "lldb/Symbol/CompileUnit.h"
44 #include "lldb/Symbol/CompilerDecl.h"
45 #include "lldb/Symbol/CompilerDeclContext.h"
46 #include "lldb/Symbol/DebugMacros.h"
47 #include "lldb/Symbol/LineTable.h"
48 #include "lldb/Symbol/LocateSymbolFile.h"
49 #include "lldb/Symbol/ObjectFile.h"
50 #include "lldb/Symbol/SymbolFile.h"
51 #include "lldb/Symbol/TypeMap.h"
52 #include "lldb/Symbol/TypeSystem.h"
53 #include "lldb/Symbol/VariableList.h"
55 #include "lldb/Target/Language.h"
56 #include "lldb/Target/Target.h"
58 #include "AppleDWARFIndex.h"
59 #include "DWARFASTParser.h"
60 #include "DWARFASTParserClang.h"
61 #include "DWARFCompileUnit.h"
62 #include "DWARFDebugAbbrev.h"
63 #include "DWARFDebugAranges.h"
64 #include "DWARFDebugInfo.h"
65 #include "DWARFDebugMacro.h"
66 #include "DWARFDebugRanges.h"
67 #include "DWARFDeclContext.h"
68 #include "DWARFFormValue.h"
69 #include "DWARFTypeUnit.h"
70 #include "DWARFUnit.h"
71 #include "DebugNamesDWARFIndex.h"
72 #include "LogChannelDWARF.h"
73 #include "ManualDWARFIndex.h"
74 #include "SymbolFileDWARFDebugMap.h"
75 #include "SymbolFileDWARFDwo.h"
77 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
78 #include "llvm/Support/FileSystem.h"
79 #include "llvm/Support/FormatVariadic.h"
89 //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
91 #ifdef ENABLE_DEBUG_PRINTF
93 #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
95 #define DEBUG_PRINTF(fmt, ...)
99 using namespace lldb_private;
100 using namespace lldb_private::dwarf;
102 LLDB_PLUGIN_DEFINE(SymbolFileDWARF)
104 char SymbolFileDWARF::ID;
108 #define LLDB_PROPERTIES_symbolfiledwarf
109 #include "SymbolFileDWARFProperties.inc"
112 #define LLDB_PROPERTIES_symbolfiledwarf
113 #include "SymbolFileDWARFPropertiesEnum.inc"
116 class PluginProperties : public Properties {
118 static ConstString GetSettingName() {
119 return ConstString(SymbolFileDWARF::GetPluginNameStatic());
123 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
124 m_collection_sp->Initialize(g_symbolfiledwarf_properties);
127 bool IgnoreFileIndexes() const {
128 return GetPropertyAtIndexAs<bool>(ePropertyIgnoreIndexes, false);
134 static PluginProperties &GetGlobalPluginProperties() {
135 static PluginProperties g_settings;
139 static const llvm::DWARFDebugLine::LineTable *
140 ParseLLVMLineTable(lldb_private::DWARFContext &context,
141 llvm::DWARFDebugLine &line, dw_offset_t line_offset,
142 dw_offset_t unit_offset) {
143 Log *log = GetLog(DWARFLog::DebugInfo);
145 llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVMDWARF();
146 llvm::DWARFContext &ctx = context.GetAsLLVM();
147 llvm::Expected<const llvm::DWARFDebugLine::LineTable *> line_table =
148 line.getOrParseLineTable(
149 data, line_offset, ctx, nullptr, [&](llvm::Error e) {
152 "SymbolFileDWARF::ParseLineTable failed to parse: {0}");
156 LLDB_LOG_ERROR(log, line_table.takeError(),
157 "SymbolFileDWARF::ParseLineTable failed to parse: {0}");
163 static bool ParseLLVMLineTablePrologue(lldb_private::DWARFContext &context,
164 llvm::DWARFDebugLine::Prologue &prologue,
165 dw_offset_t line_offset,
166 dw_offset_t unit_offset) {
167 Log *log = GetLog(DWARFLog::DebugInfo);
169 llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVMDWARF();
170 llvm::DWARFContext &ctx = context.GetAsLLVM();
171 uint64_t offset = line_offset;
172 llvm::Error error = prologue.parse(
176 LLDB_LOG_ERROR(log, std::move(e),
177 "SymbolFileDWARF::ParseSupportFiles failed to parse "
178 "line table prologue: {0}");
182 LLDB_LOG_ERROR(log, std::move(error),
183 "SymbolFileDWARF::ParseSupportFiles failed to parse line "
184 "table prologue: {0}");
190 static std::optional<std::string>
191 GetFileByIndex(const llvm::DWARFDebugLine::Prologue &prologue, size_t idx,
192 llvm::StringRef compile_dir, FileSpec::Style style) {
193 // Try to get an absolute path first.
194 std::string abs_path;
195 auto absolute = llvm::DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath;
196 if (prologue.getFileNameByIndex(idx, compile_dir, absolute, abs_path, style))
197 return std::move(abs_path);
199 // Otherwise ask for a relative path.
200 std::string rel_path;
201 auto relative = llvm::DILineInfoSpecifier::FileLineInfoKind::RawValue;
202 if (!prologue.getFileNameByIndex(idx, compile_dir, relative, rel_path, style))
204 return std::move(rel_path);
208 ParseSupportFilesFromPrologue(const lldb::ModuleSP &module,
209 const llvm::DWARFDebugLine::Prologue &prologue,
210 FileSpec::Style style,
211 llvm::StringRef compile_dir = {}) {
212 FileSpecList support_files;
213 size_t first_file = 0;
214 if (prologue.getVersion() <= 4) {
215 // File index 0 is not valid before DWARF v5. Add a dummy entry to ensure
216 // support file list indices match those we get from the debug info and line
218 support_files.Append(FileSpec());
222 const size_t number_of_files = prologue.FileNames.size();
223 for (size_t idx = first_file; idx <= number_of_files; ++idx) {
224 std::string remapped_file;
225 if (auto file_path = GetFileByIndex(prologue, idx, compile_dir, style)) {
226 if (auto remapped = module->RemapSourceFile(llvm::StringRef(*file_path)))
227 remapped_file = *remapped;
229 remapped_file = std::move(*file_path);
232 // Unconditionally add an entry, so the indices match up.
233 support_files.EmplaceBack(remapped_file, style);
236 return support_files;
239 void SymbolFileDWARF::Initialize() {
240 LogChannelDWARF::Initialize();
241 PluginManager::RegisterPlugin(GetPluginNameStatic(),
242 GetPluginDescriptionStatic(), CreateInstance,
244 SymbolFileDWARFDebugMap::Initialize();
247 void SymbolFileDWARF::DebuggerInitialize(Debugger &debugger) {
248 if (!PluginManager::GetSettingForSymbolFilePlugin(
249 debugger, PluginProperties::GetSettingName())) {
250 const bool is_global_setting = true;
251 PluginManager::CreateSettingForSymbolFilePlugin(
252 debugger, GetGlobalPluginProperties().GetValueProperties(),
253 "Properties for the dwarf symbol-file plug-in.", is_global_setting);
257 void SymbolFileDWARF::Terminate() {
258 SymbolFileDWARFDebugMap::Terminate();
259 PluginManager::UnregisterPlugin(CreateInstance);
260 LogChannelDWARF::Terminate();
263 llvm::StringRef SymbolFileDWARF::GetPluginDescriptionStatic() {
264 return "DWARF and DWARF3 debug symbol file reader.";
267 SymbolFile *SymbolFileDWARF::CreateInstance(ObjectFileSP objfile_sp) {
268 return new SymbolFileDWARF(std::move(objfile_sp),
269 /*dwo_section_list*/ nullptr);
272 TypeList &SymbolFileDWARF::GetTypeList() {
273 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
274 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
275 return debug_map_symfile->GetTypeList();
276 return SymbolFileCommon::GetTypeList();
278 void SymbolFileDWARF::GetTypes(const DWARFDIE &die, dw_offset_t min_die_offset,
279 dw_offset_t max_die_offset, uint32_t type_mask,
282 const dw_offset_t die_offset = die.GetOffset();
284 if (die_offset >= max_die_offset)
287 if (die_offset >= min_die_offset) {
288 const dw_tag_t tag = die.Tag();
290 bool add_type = false;
293 case DW_TAG_array_type:
294 add_type = (type_mask & eTypeClassArray) != 0;
296 case DW_TAG_unspecified_type:
297 case DW_TAG_base_type:
298 add_type = (type_mask & eTypeClassBuiltin) != 0;
300 case DW_TAG_class_type:
301 add_type = (type_mask & eTypeClassClass) != 0;
303 case DW_TAG_structure_type:
304 add_type = (type_mask & eTypeClassStruct) != 0;
306 case DW_TAG_union_type:
307 add_type = (type_mask & eTypeClassUnion) != 0;
309 case DW_TAG_enumeration_type:
310 add_type = (type_mask & eTypeClassEnumeration) != 0;
312 case DW_TAG_subroutine_type:
313 case DW_TAG_subprogram:
314 case DW_TAG_inlined_subroutine:
315 add_type = (type_mask & eTypeClassFunction) != 0;
317 case DW_TAG_pointer_type:
318 add_type = (type_mask & eTypeClassPointer) != 0;
320 case DW_TAG_rvalue_reference_type:
321 case DW_TAG_reference_type:
322 add_type = (type_mask & eTypeClassReference) != 0;
325 add_type = (type_mask & eTypeClassTypedef) != 0;
327 case DW_TAG_ptr_to_member_type:
328 add_type = (type_mask & eTypeClassMemberPointer) != 0;
335 const bool assert_not_being_parsed = true;
336 Type *type = ResolveTypeUID(die, assert_not_being_parsed);
338 type_set.insert(type);
342 for (DWARFDIE child_die : die.children()) {
343 GetTypes(child_die, min_die_offset, max_die_offset, type_mask, type_set);
348 void SymbolFileDWARF::GetTypes(SymbolContextScope *sc_scope,
349 TypeClass type_mask, TypeList &type_list)
352 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
355 CompileUnit *comp_unit = nullptr;
357 comp_unit = sc_scope->CalculateSymbolContextCompileUnit();
359 const auto &get = [&](DWARFUnit *unit) {
362 unit = &unit->GetNonSkeletonUnit();
363 GetTypes(unit->DIE(), unit->GetOffset(), unit->GetNextUnitOffset(),
364 type_mask, type_set);
367 get(GetDWARFCompileUnit(comp_unit));
369 DWARFDebugInfo &info = DebugInfo();
370 const size_t num_cus = info.GetNumUnits();
371 for (size_t cu_idx = 0; cu_idx < num_cus; ++cu_idx)
372 get(info.GetUnitAtIndex(cu_idx));
375 std::set<CompilerType> compiler_type_set;
376 for (Type *type : type_set) {
377 CompilerType compiler_type = type->GetForwardCompilerType();
378 if (compiler_type_set.find(compiler_type) == compiler_type_set.end()) {
379 compiler_type_set.insert(compiler_type);
380 type_list.Insert(type->shared_from_this());
385 // Gets the first parent that is a lexical block, function or inlined
386 // subroutine, or compile unit.
388 SymbolFileDWARF::GetParentSymbolContextDIE(const DWARFDIE &child_die) {
390 for (die = child_die.GetParent(); die; die = die.GetParent()) {
391 dw_tag_t tag = die.Tag();
394 case DW_TAG_compile_unit:
395 case DW_TAG_partial_unit:
396 case DW_TAG_subprogram:
397 case DW_TAG_inlined_subroutine:
398 case DW_TAG_lexical_block:
407 SymbolFileDWARF::SymbolFileDWARF(ObjectFileSP objfile_sp,
408 SectionList *dwo_section_list)
409 : SymbolFileCommon(std::move(objfile_sp)), m_debug_map_module_wp(),
410 m_debug_map_symfile(nullptr),
411 m_context(m_objfile_sp->GetModule()->GetSectionList(), dwo_section_list),
412 m_fetched_external_modules(false),
413 m_supports_DW_AT_APPLE_objc_complete_type(eLazyBoolCalculate) {}
415 SymbolFileDWARF::~SymbolFileDWARF() = default;
417 static ConstString GetDWARFMachOSegmentName() {
418 static ConstString g_dwarf_section_name("__DWARF");
419 return g_dwarf_section_name;
422 UniqueDWARFASTTypeMap &SymbolFileDWARF::GetUniqueDWARFASTTypeMap() {
423 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
424 if (debug_map_symfile)
425 return debug_map_symfile->GetUniqueDWARFASTTypeMap();
427 return m_unique_ast_type_map;
430 llvm::Expected<lldb::TypeSystemSP>
431 SymbolFileDWARF::GetTypeSystemForLanguage(LanguageType language) {
432 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
433 return debug_map_symfile->GetTypeSystemForLanguage(language);
435 auto type_system_or_err =
436 m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
437 if (type_system_or_err)
438 if (auto ts = *type_system_or_err)
439 ts->SetSymbolFile(this);
440 return type_system_or_err;
443 void SymbolFileDWARF::InitializeObject() {
444 Log *log = GetLog(DWARFLog::DebugInfo);
446 InitializeFirstCodeAddress();
448 if (!GetGlobalPluginProperties().IgnoreFileIndexes()) {
449 StreamString module_desc;
450 GetObjectFile()->GetModule()->GetDescription(module_desc.AsRawOstream(),
451 lldb::eDescriptionLevelBrief);
452 DWARFDataExtractor apple_names, apple_namespaces, apple_types, apple_objc;
453 LoadSectionData(eSectionTypeDWARFAppleNames, apple_names);
454 LoadSectionData(eSectionTypeDWARFAppleNamespaces, apple_namespaces);
455 LoadSectionData(eSectionTypeDWARFAppleTypes, apple_types);
456 LoadSectionData(eSectionTypeDWARFAppleObjC, apple_objc);
458 if (apple_names.GetByteSize() > 0 || apple_namespaces.GetByteSize() > 0 ||
459 apple_types.GetByteSize() > 0 || apple_objc.GetByteSize() > 0) {
460 Progress progress(llvm::formatv("Loading Apple DWARF index for {0}",
461 module_desc.GetData()));
462 m_index = AppleDWARFIndex::Create(
463 *GetObjectFile()->GetModule(), apple_names, apple_namespaces,
464 apple_types, apple_objc, m_context.getOrLoadStrData());
470 DWARFDataExtractor debug_names;
471 LoadSectionData(eSectionTypeDWARFDebugNames, debug_names);
472 if (debug_names.GetByteSize() > 0) {
474 llvm::formatv("Loading DWARF5 index for {0}", module_desc.GetData()));
475 llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> index_or =
476 DebugNamesDWARFIndex::Create(*GetObjectFile()->GetModule(),
478 m_context.getOrLoadStrData(), *this);
480 m_index = std::move(*index_or);
483 LLDB_LOG_ERROR(log, index_or.takeError(),
484 "Unable to read .debug_names data: {0}");
489 std::make_unique<ManualDWARFIndex>(*GetObjectFile()->GetModule(), *this);
492 void SymbolFileDWARF::InitializeFirstCodeAddress() {
493 InitializeFirstCodeAddressRecursive(
494 *m_objfile_sp->GetModule()->GetSectionList());
495 if (m_first_code_address == LLDB_INVALID_ADDRESS)
496 m_first_code_address = 0;
499 void SymbolFileDWARF::InitializeFirstCodeAddressRecursive(
500 const lldb_private::SectionList §ion_list) {
501 for (SectionSP section_sp : section_list) {
502 if (section_sp->GetChildren().GetSize() > 0) {
503 InitializeFirstCodeAddressRecursive(section_sp->GetChildren());
504 } else if (section_sp->GetType() == eSectionTypeCode) {
505 m_first_code_address =
506 std::min(m_first_code_address, section_sp->GetFileAddress());
511 bool SymbolFileDWARF::SupportedVersion(uint16_t version) {
512 return version >= 2 && version <= 5;
515 uint32_t SymbolFileDWARF::CalculateAbilities() {
516 uint32_t abilities = 0;
517 if (m_objfile_sp != nullptr) {
518 const Section *section = nullptr;
519 const SectionList *section_list = m_objfile_sp->GetSectionList();
520 if (section_list == nullptr)
523 uint64_t debug_abbrev_file_size = 0;
524 uint64_t debug_info_file_size = 0;
525 uint64_t debug_line_file_size = 0;
527 section = section_list->FindSectionByName(GetDWARFMachOSegmentName()).get();
530 section_list = §ion->GetChildren();
533 section_list->FindSectionByType(eSectionTypeDWARFDebugInfo, true).get();
534 if (section != nullptr) {
535 debug_info_file_size = section->GetFileSize();
538 section_list->FindSectionByType(eSectionTypeDWARFDebugAbbrev, true)
541 debug_abbrev_file_size = section->GetFileSize();
543 DWARFDebugAbbrev *abbrev = DebugAbbrev();
545 std::set<dw_form_t> invalid_forms;
546 abbrev->GetUnsupportedForms(invalid_forms);
547 if (!invalid_forms.empty()) {
549 error.Printf("unsupported DW_FORM value%s:",
550 invalid_forms.size() > 1 ? "s" : "");
551 for (auto form : invalid_forms)
552 error.Printf(" %#x", form);
553 m_objfile_sp->GetModule()->ReportWarning(
554 "{0}", error.GetString().str().c_str());
560 section_list->FindSectionByType(eSectionTypeDWARFDebugLine, true)
563 debug_line_file_size = section->GetFileSize();
565 llvm::StringRef symfile_dir =
566 m_objfile_sp->GetFileSpec().GetDirectory().GetStringRef();
567 if (symfile_dir.contains_insensitive(".dsym")) {
568 if (m_objfile_sp->GetType() == ObjectFile::eTypeDebugInfo) {
569 // We have a dSYM file that didn't have a any debug info. If the
570 // string table has a size of 1, then it was made from an
571 // executable with no debug info, or from an executable that was
574 section_list->FindSectionByType(eSectionTypeDWARFDebugStr, true)
576 if (section && section->GetFileSize() == 1) {
577 m_objfile_sp->GetModule()->ReportWarning(
578 "empty dSYM file detected, dSYM was created with an "
579 "executable with no debug info.");
585 constexpr uint64_t MaxDebugInfoSize = (1ull) << DW_DIE_OFFSET_MAX_BITSIZE;
586 if (debug_info_file_size >= MaxDebugInfoSize) {
587 m_objfile_sp->GetModule()->ReportWarning(
588 "SymbolFileDWARF can't load this DWARF. It's larger then {0:x+16}",
593 if (debug_abbrev_file_size > 0 && debug_info_file_size > 0)
594 abilities |= CompileUnits | Functions | Blocks | GlobalVariables |
595 LocalVariables | VariableTypes;
597 if (debug_line_file_size > 0)
598 abilities |= LineTables;
603 void SymbolFileDWARF::LoadSectionData(lldb::SectionType sect_type,
604 DWARFDataExtractor &data) {
605 ModuleSP module_sp(m_objfile_sp->GetModule());
606 const SectionList *section_list = module_sp->GetSectionList();
610 SectionSP section_sp(section_list->FindSectionByType(sect_type, true));
615 m_objfile_sp->ReadSectionData(section_sp.get(), data);
618 DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() {
622 const DWARFDataExtractor &debug_abbrev_data = m_context.getOrLoadAbbrevData();
623 if (debug_abbrev_data.GetByteSize() == 0)
626 auto abbr = std::make_unique<DWARFDebugAbbrev>();
627 llvm::Error error = abbr->parse(debug_abbrev_data);
629 Log *log = GetLog(DWARFLog::DebugInfo);
630 LLDB_LOG_ERROR(log, std::move(error),
631 "Unable to read .debug_abbrev section: {0}");
635 m_abbr = std::move(abbr);
639 DWARFDebugInfo &SymbolFileDWARF::DebugInfo() {
640 llvm::call_once(m_info_once_flag, [&] {
641 LLDB_SCOPED_TIMERF("%s this = %p", LLVM_PRETTY_FUNCTION,
642 static_cast<void *>(this));
643 m_info = std::make_unique<DWARFDebugInfo>(*this, m_context);
648 DWARFCompileUnit *SymbolFileDWARF::GetDWARFCompileUnit(CompileUnit *comp_unit) {
652 // The compile unit ID is the index of the DWARF unit.
653 DWARFUnit *dwarf_cu = DebugInfo().GetUnitAtIndex(comp_unit->GetID());
654 if (dwarf_cu && dwarf_cu->GetUserData() == nullptr)
655 dwarf_cu->SetUserData(comp_unit);
657 // It must be DWARFCompileUnit when it created a CompileUnit.
658 return llvm::cast_or_null<DWARFCompileUnit>(dwarf_cu);
661 DWARFDebugRanges *SymbolFileDWARF::GetDebugRanges() {
663 LLDB_SCOPED_TIMERF("%s this = %p", LLVM_PRETTY_FUNCTION,
664 static_cast<void *>(this));
666 if (m_context.getOrLoadRangesData().GetByteSize() > 0)
667 m_ranges = std::make_unique<DWARFDebugRanges>();
670 m_ranges->Extract(m_context);
672 return m_ranges.get();
675 /// Make an absolute path out of \p file_spec and remap it using the
676 /// module's source remapping dictionary.
677 static void MakeAbsoluteAndRemap(FileSpec &file_spec, DWARFUnit &dwarf_cu,
678 const ModuleSP &module_sp) {
681 // If we have a full path to the compile unit, we don't need to
682 // resolve the file. This can be expensive e.g. when the source
683 // files are NFS mounted.
684 file_spec.MakeAbsolute(dwarf_cu.GetCompilationDirectory());
686 if (auto remapped_file = module_sp->RemapSourceFile(file_spec.GetPath()))
687 file_spec.SetFile(*remapped_file, FileSpec::Style::native);
690 /// Return the DW_AT_(GNU_)dwo_name.
691 static const char *GetDWOName(DWARFCompileUnit &dwarf_cu,
692 const DWARFDebugInfoEntry &cu_die) {
693 const char *dwo_name =
694 cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_GNU_dwo_name, nullptr);
697 cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_dwo_name, nullptr);
701 lldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFCompileUnit &dwarf_cu) {
703 CompileUnit *comp_unit = (CompileUnit *)dwarf_cu.GetUserData();
705 // We already parsed this compile unit, had out a shared pointer to it
706 cu_sp = comp_unit->shared_from_this();
708 if (GetDebugMapSymfile()) {
709 // Let the debug map create the compile unit
710 cu_sp = m_debug_map_symfile->GetCompileUnit(this, dwarf_cu);
711 dwarf_cu.SetUserData(cu_sp.get());
713 ModuleSP module_sp(m_objfile_sp->GetModule());
715 auto initialize_cu = [&](const FileSpec &file_spec,
716 LanguageType cu_language) {
717 BuildCuTranslationTable();
718 cu_sp = std::make_shared<CompileUnit>(
719 module_sp, &dwarf_cu, file_spec,
720 *GetDWARFUnitIndex(dwarf_cu.GetID()), cu_language,
723 dwarf_cu.SetUserData(cu_sp.get());
725 SetCompileUnitAtIndex(dwarf_cu.GetID(), cu_sp);
728 auto lazy_initialize_cu = [&]() {
729 // If the version is < 5, we can't do lazy initialization.
730 if (dwarf_cu.GetVersion() < 5)
733 // If there is no DWO, there is no reason to initialize
734 // lazily; we will do eager initialization in that case.
735 if (GetDebugMapSymfile())
737 const DWARFBaseDIE cu_die = dwarf_cu.GetUnitDIEOnly();
740 if (!GetDWOName(dwarf_cu, *cu_die.GetDIE()))
743 // With DWARFv5 we can assume that the first support
744 // file is also the name of the compile unit. This
745 // allows us to avoid loading the non-skeleton unit,
746 // which may be in a separate DWO file.
747 FileSpecList support_files;
748 if (!ParseSupportFiles(dwarf_cu, module_sp, support_files))
750 if (support_files.GetSize() == 0)
753 initialize_cu(support_files.GetFileSpecAtIndex(0),
754 eLanguageTypeUnknown);
755 cu_sp->SetSupportFiles(std::move(support_files));
759 if (!lazy_initialize_cu()) {
760 // Eagerly initialize compile unit
761 const DWARFBaseDIE cu_die =
762 dwarf_cu.GetNonSkeletonUnit().GetUnitDIEOnly();
764 LanguageType cu_language = SymbolFileDWARF::LanguageTypeFromDWARF(
765 dwarf_cu.GetDWARFLanguageType());
767 FileSpec cu_file_spec(cu_die.GetName(), dwarf_cu.GetPathStyle());
769 // Path needs to be remapped in this case. In the support files
770 // case ParseSupportFiles takes care of the remapping.
771 MakeAbsoluteAndRemap(cu_file_spec, dwarf_cu, module_sp);
773 initialize_cu(cu_file_spec, cu_language);
782 void SymbolFileDWARF::BuildCuTranslationTable() {
783 if (!m_lldb_cu_to_dwarf_unit.empty())
786 DWARFDebugInfo &info = DebugInfo();
787 if (!info.ContainsTypeUnits()) {
788 // We can use a 1-to-1 mapping. No need to build a translation table.
791 for (uint32_t i = 0, num = info.GetNumUnits(); i < num; ++i) {
792 if (auto *cu = llvm::dyn_cast<DWARFCompileUnit>(info.GetUnitAtIndex(i))) {
793 cu->SetID(m_lldb_cu_to_dwarf_unit.size());
794 m_lldb_cu_to_dwarf_unit.push_back(i);
799 std::optional<uint32_t> SymbolFileDWARF::GetDWARFUnitIndex(uint32_t cu_idx) {
800 BuildCuTranslationTable();
801 if (m_lldb_cu_to_dwarf_unit.empty())
803 if (cu_idx >= m_lldb_cu_to_dwarf_unit.size())
805 return m_lldb_cu_to_dwarf_unit[cu_idx];
808 uint32_t SymbolFileDWARF::CalculateNumCompileUnits() {
809 BuildCuTranslationTable();
810 return m_lldb_cu_to_dwarf_unit.empty() ? DebugInfo().GetNumUnits()
811 : m_lldb_cu_to_dwarf_unit.size();
814 CompUnitSP SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx) {
815 ASSERT_MODULE_LOCK(this);
816 if (std::optional<uint32_t> dwarf_idx = GetDWARFUnitIndex(cu_idx)) {
817 if (auto *dwarf_cu = llvm::cast_or_null<DWARFCompileUnit>(
818 DebugInfo().GetUnitAtIndex(*dwarf_idx)))
819 return ParseCompileUnit(*dwarf_cu);
824 Function *SymbolFileDWARF::ParseFunction(CompileUnit &comp_unit,
825 const DWARFDIE &die) {
826 ASSERT_MODULE_LOCK(this);
830 auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU()));
831 if (auto err = type_system_or_err.takeError()) {
832 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
833 "Unable to parse function: {0}");
836 auto ts = *type_system_or_err;
839 DWARFASTParser *dwarf_ast = ts->GetDWARFParser();
843 DWARFRangeList ranges = die.GetDIE()->GetAttributeAddressRanges(
844 die.GetCU(), /*check_hi_lo_pc=*/true);
845 if (ranges.IsEmpty())
848 // Union of all ranges in the function DIE (if the function is
850 lldb::addr_t lowest_func_addr = ranges.GetMinRangeBase(0);
851 lldb::addr_t highest_func_addr = ranges.GetMaxRangeEnd(0);
852 if (lowest_func_addr == LLDB_INVALID_ADDRESS ||
853 lowest_func_addr >= highest_func_addr ||
854 lowest_func_addr < m_first_code_address)
857 ModuleSP module_sp(die.GetModule());
858 AddressRange func_range;
859 func_range.GetBaseAddress().ResolveAddressUsingFileSections(
860 lowest_func_addr, module_sp->GetSectionList());
861 if (!func_range.GetBaseAddress().IsValid())
864 func_range.SetByteSize(highest_func_addr - lowest_func_addr);
865 if (!FixupAddress(func_range.GetBaseAddress()))
868 return dwarf_ast->ParseFunctionFromDWARF(comp_unit, die, func_range);
872 SymbolFileDWARF::ConstructFunctionDemangledName(const DWARFDIE &die) {
873 ASSERT_MODULE_LOCK(this);
874 if (!die.IsValid()) {
875 return ConstString();
878 auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU()));
879 if (auto err = type_system_or_err.takeError()) {
880 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
881 "Unable to construct demangled name for function: {0}");
882 return ConstString();
885 auto ts = *type_system_or_err;
887 LLDB_LOG(GetLog(LLDBLog::Symbols), "Type system no longer live");
888 return ConstString();
890 DWARFASTParser *dwarf_ast = ts->GetDWARFParser();
892 return ConstString();
894 return dwarf_ast->ConstructDemangledNameFromDWARF(die);
897 lldb::addr_t SymbolFileDWARF::FixupAddress(lldb::addr_t file_addr) {
898 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
899 if (debug_map_symfile)
900 return debug_map_symfile->LinkOSOFileAddress(this, file_addr);
904 bool SymbolFileDWARF::FixupAddress(Address &addr) {
905 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
906 if (debug_map_symfile) {
907 return debug_map_symfile->LinkOSOAddress(addr);
909 // This is a normal DWARF file, no address fixups need to happen
912 lldb::LanguageType SymbolFileDWARF::ParseLanguage(CompileUnit &comp_unit) {
913 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
914 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
916 return GetLanguage(dwarf_cu->GetNonSkeletonUnit());
918 return eLanguageTypeUnknown;
921 XcodeSDK SymbolFileDWARF::ParseXcodeSDK(CompileUnit &comp_unit) {
922 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
923 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
926 const DWARFBaseDIE cu_die = dwarf_cu->GetNonSkeletonUnit().GetUnitDIEOnly();
929 const char *sdk = cu_die.GetAttributeValueAsString(DW_AT_APPLE_sdk, nullptr);
932 const char *sysroot =
933 cu_die.GetAttributeValueAsString(DW_AT_LLVM_sysroot, "");
934 // Register the sysroot path remapping with the module belonging to
935 // the CU as well as the one belonging to the symbol file. The two
936 // would be different if this is an OSO object and module is the
937 // corresponding debug map, in which case both should be updated.
938 ModuleSP module_sp = comp_unit.GetModule();
940 module_sp->RegisterXcodeSDK(sdk, sysroot);
942 ModuleSP local_module_sp = m_objfile_sp->GetModule();
943 if (local_module_sp && local_module_sp != module_sp)
944 local_module_sp->RegisterXcodeSDK(sdk, sysroot);
949 size_t SymbolFileDWARF::ParseFunctions(CompileUnit &comp_unit) {
951 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
952 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
956 size_t functions_added = 0;
957 dwarf_cu = &dwarf_cu->GetNonSkeletonUnit();
958 for (DWARFDebugInfoEntry &entry : dwarf_cu->dies()) {
959 if (entry.Tag() != DW_TAG_subprogram)
962 DWARFDIE die(dwarf_cu, &entry);
963 if (comp_unit.FindFunctionByUID(die.GetID()))
965 if (ParseFunction(comp_unit, die))
969 return functions_added;
972 bool SymbolFileDWARF::ForEachExternalModule(
973 CompileUnit &comp_unit,
974 llvm::DenseSet<lldb_private::SymbolFile *> &visited_symbol_files,
975 llvm::function_ref<bool(Module &)> lambda) {
976 // Only visit each symbol file once.
977 if (!visited_symbol_files.insert(this).second)
980 UpdateExternalModuleListIfNeeded();
981 for (auto &p : m_external_type_modules) {
982 ModuleSP module = p.second;
986 // Invoke the action and potentially early-exit.
990 for (std::size_t i = 0; i < module->GetNumCompileUnits(); ++i) {
991 auto cu = module->GetCompileUnitAtIndex(i);
992 bool early_exit = cu->ForEachExternalModule(visited_symbol_files, lambda);
1000 bool SymbolFileDWARF::ParseSupportFiles(CompileUnit &comp_unit,
1001 FileSpecList &support_files) {
1002 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1003 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1007 if (!ParseSupportFiles(*dwarf_cu, comp_unit.GetModule(), support_files))
1010 comp_unit.SetSupportFiles(support_files);
1014 bool SymbolFileDWARF::ParseSupportFiles(DWARFUnit &dwarf_cu,
1015 const ModuleSP &module,
1016 FileSpecList &support_files) {
1018 dw_offset_t offset = dwarf_cu.GetLineTableOffset();
1019 if (offset == DW_INVALID_OFFSET)
1022 ElapsedTime elapsed(m_parse_time);
1023 llvm::DWARFDebugLine::Prologue prologue;
1024 if (!ParseLLVMLineTablePrologue(m_context, prologue, offset,
1025 dwarf_cu.GetOffset()))
1028 std::string comp_dir = dwarf_cu.GetCompilationDirectory().GetPath();
1029 support_files = ParseSupportFilesFromPrologue(
1030 module, prologue, dwarf_cu.GetPathStyle(), comp_dir);
1034 FileSpec SymbolFileDWARF::GetFile(DWARFUnit &unit, size_t file_idx) {
1035 if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit)) {
1036 if (CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(*dwarf_cu))
1037 return lldb_cu->GetSupportFiles().GetFileSpecAtIndex(file_idx);
1041 auto &tu = llvm::cast<DWARFTypeUnit>(unit);
1042 return GetTypeUnitSupportFiles(tu).GetFileSpecAtIndex(file_idx);
1045 const FileSpecList &
1046 SymbolFileDWARF::GetTypeUnitSupportFiles(DWARFTypeUnit &tu) {
1047 static FileSpecList empty_list;
1049 dw_offset_t offset = tu.GetLineTableOffset();
1050 if (offset == DW_INVALID_OFFSET ||
1051 offset == llvm::DenseMapInfo<dw_offset_t>::getEmptyKey() ||
1052 offset == llvm::DenseMapInfo<dw_offset_t>::getTombstoneKey())
1055 // Many type units can share a line table, so parse the support file list
1056 // once, and cache it based on the offset field.
1057 auto iter_bool = m_type_unit_support_files.try_emplace(offset);
1058 FileSpecList &list = iter_bool.first->second;
1059 if (iter_bool.second) {
1060 uint64_t line_table_offset = offset;
1061 llvm::DWARFDataExtractor data =
1062 m_context.getOrLoadLineData().GetAsLLVMDWARF();
1063 llvm::DWARFContext &ctx = m_context.GetAsLLVM();
1064 llvm::DWARFDebugLine::Prologue prologue;
1065 auto report = [](llvm::Error error) {
1066 Log *log = GetLog(DWARFLog::DebugInfo);
1067 LLDB_LOG_ERROR(log, std::move(error),
1068 "SymbolFileDWARF::GetTypeUnitSupportFiles failed to parse "
1069 "the line table prologue: {0}");
1071 ElapsedTime elapsed(m_parse_time);
1072 llvm::Error error = prologue.parse(data, &line_table_offset, report, ctx);
1074 report(std::move(error));
1076 list = ParseSupportFilesFromPrologue(GetObjectFile()->GetModule(),
1077 prologue, tu.GetPathStyle());
1083 bool SymbolFileDWARF::ParseIsOptimized(CompileUnit &comp_unit) {
1084 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1085 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1087 return dwarf_cu->GetNonSkeletonUnit().GetIsOptimized();
1091 bool SymbolFileDWARF::ParseImportedModules(
1092 const lldb_private::SymbolContext &sc,
1093 std::vector<SourceModule> &imported_modules) {
1094 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1095 assert(sc.comp_unit);
1096 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1099 if (!ClangModulesDeclVendor::LanguageSupportsClangModules(
1100 sc.comp_unit->GetLanguage()))
1102 UpdateExternalModuleListIfNeeded();
1104 const DWARFDIE die = dwarf_cu->DIE();
1108 for (DWARFDIE child_die : die.children()) {
1109 if (child_die.Tag() != DW_TAG_imported_declaration)
1112 DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import);
1113 if (module_die.Tag() != DW_TAG_module)
1116 if (const char *name =
1117 module_die.GetAttributeValueAsString(DW_AT_name, nullptr)) {
1118 SourceModule module;
1119 module.path.push_back(ConstString(name));
1121 DWARFDIE parent_die = module_die;
1122 while ((parent_die = parent_die.GetParent())) {
1123 if (parent_die.Tag() != DW_TAG_module)
1125 if (const char *name =
1126 parent_die.GetAttributeValueAsString(DW_AT_name, nullptr))
1127 module.path.push_back(ConstString(name));
1129 std::reverse(module.path.begin(), module.path.end());
1130 if (const char *include_path = module_die.GetAttributeValueAsString(
1131 DW_AT_LLVM_include_path, nullptr)) {
1132 FileSpec include_spec(include_path, dwarf_cu->GetPathStyle());
1133 MakeAbsoluteAndRemap(include_spec, *dwarf_cu,
1134 m_objfile_sp->GetModule());
1135 module.search_path = ConstString(include_spec.GetPath());
1137 if (const char *sysroot = dwarf_cu->DIE().GetAttributeValueAsString(
1138 DW_AT_LLVM_sysroot, nullptr))
1139 module.sysroot = ConstString(sysroot);
1140 imported_modules.push_back(module);
1146 bool SymbolFileDWARF::ParseLineTable(CompileUnit &comp_unit) {
1147 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1148 if (comp_unit.GetLineTable() != nullptr)
1151 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1155 dw_offset_t offset = dwarf_cu->GetLineTableOffset();
1156 if (offset == DW_INVALID_OFFSET)
1159 ElapsedTime elapsed(m_parse_time);
1160 llvm::DWARFDebugLine line;
1161 const llvm::DWARFDebugLine::LineTable *line_table =
1162 ParseLLVMLineTable(m_context, line, offset, dwarf_cu->GetOffset());
1167 // FIXME: Rather than parsing the whole line table and then copying it over
1168 // into LLDB, we should explore using a callback to populate the line table
1169 // while we parse to reduce memory usage.
1170 std::vector<std::unique_ptr<LineSequence>> sequences;
1171 // The Sequences view contains only valid line sequences. Don't iterate over
1172 // the Rows directly.
1173 for (const llvm::DWARFDebugLine::Sequence &seq : line_table->Sequences) {
1174 // Ignore line sequences that do not start after the first code address.
1175 // All addresses generated in a sequence are incremental so we only need
1176 // to check the first one of the sequence. Check the comment at the
1177 // m_first_code_address declaration for more details on this.
1178 if (seq.LowPC < m_first_code_address)
1180 std::unique_ptr<LineSequence> sequence =
1181 LineTable::CreateLineSequenceContainer();
1182 for (unsigned idx = seq.FirstRowIndex; idx < seq.LastRowIndex; ++idx) {
1183 const llvm::DWARFDebugLine::Row &row = line_table->Rows[idx];
1184 LineTable::AppendLineEntryToSequence(
1185 sequence.get(), row.Address.Address, row.Line, row.Column, row.File,
1186 row.IsStmt, row.BasicBlock, row.PrologueEnd, row.EpilogueBegin,
1189 sequences.push_back(std::move(sequence));
1192 std::unique_ptr<LineTable> line_table_up =
1193 std::make_unique<LineTable>(&comp_unit, std::move(sequences));
1195 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) {
1196 // We have an object file that has a line table with addresses that are not
1197 // linked. We need to link the line table and convert the addresses that
1198 // are relative to the .o file into addresses for the main executable.
1199 comp_unit.SetLineTable(
1200 debug_map_symfile->LinkOSOLineTable(this, line_table_up.get()));
1202 comp_unit.SetLineTable(line_table_up.release());
1208 lldb_private::DebugMacrosSP
1209 SymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset) {
1210 auto iter = m_debug_macros_map.find(*offset);
1211 if (iter != m_debug_macros_map.end())
1212 return iter->second;
1214 ElapsedTime elapsed(m_parse_time);
1215 const DWARFDataExtractor &debug_macro_data = m_context.getOrLoadMacroData();
1216 if (debug_macro_data.GetByteSize() == 0)
1217 return DebugMacrosSP();
1219 lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros());
1220 m_debug_macros_map[*offset] = debug_macros_sp;
1222 const DWARFDebugMacroHeader &header =
1223 DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset);
1224 DWARFDebugMacroEntry::ReadMacroEntries(
1225 debug_macro_data, m_context.getOrLoadStrData(), header.OffsetIs64Bit(),
1226 offset, this, debug_macros_sp);
1228 return debug_macros_sp;
1231 bool SymbolFileDWARF::ParseDebugMacros(CompileUnit &comp_unit) {
1232 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1234 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1235 if (dwarf_cu == nullptr)
1238 const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
1242 lldb::offset_t sect_offset =
1243 dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET);
1244 if (sect_offset == DW_INVALID_OFFSET)
1245 sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros,
1247 if (sect_offset == DW_INVALID_OFFSET)
1250 comp_unit.SetDebugMacros(ParseDebugMacros(§_offset));
1255 size_t SymbolFileDWARF::ParseBlocksRecursive(
1256 lldb_private::CompileUnit &comp_unit, Block *parent_block,
1257 const DWARFDIE &orig_die, addr_t subprogram_low_pc, uint32_t depth) {
1258 size_t blocks_added = 0;
1259 DWARFDIE die = orig_die;
1261 dw_tag_t tag = die.Tag();
1264 case DW_TAG_inlined_subroutine:
1265 case DW_TAG_subprogram:
1266 case DW_TAG_lexical_block: {
1267 Block *block = nullptr;
1268 if (tag == DW_TAG_subprogram) {
1269 // Skip any DW_TAG_subprogram DIEs that are inside of a normal or
1270 // inlined functions. These will be parsed on their own as separate
1276 block = parent_block;
1278 BlockSP block_sp(new Block(die.GetID()));
1279 parent_block->AddChild(block_sp);
1280 block = block_sp.get();
1282 DWARFRangeList ranges;
1283 const char *name = nullptr;
1284 const char *mangled_name = nullptr;
1286 std::optional<int> decl_file;
1287 std::optional<int> decl_line;
1288 std::optional<int> decl_column;
1289 std::optional<int> call_file;
1290 std::optional<int> call_line;
1291 std::optional<int> call_column;
1292 if (die.GetDIENamesAndRanges(name, mangled_name, ranges, decl_file,
1293 decl_line, decl_column, call_file, call_line,
1294 call_column, nullptr)) {
1295 if (tag == DW_TAG_subprogram) {
1296 assert(subprogram_low_pc == LLDB_INVALID_ADDRESS);
1297 subprogram_low_pc = ranges.GetMinRangeBase(0);
1298 } else if (tag == DW_TAG_inlined_subroutine) {
1299 // We get called here for inlined subroutines in two ways. The first
1300 // time is when we are making the Function object for this inlined
1301 // concrete instance. Since we're creating a top level block at
1302 // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS. So we
1303 // need to adjust the containing address. The second time is when we
1304 // are parsing the blocks inside the function that contains the
1305 // inlined concrete instance. Since these will be blocks inside the
1306 // containing "real" function the offset will be for that function.
1307 if (subprogram_low_pc == LLDB_INVALID_ADDRESS) {
1308 subprogram_low_pc = ranges.GetMinRangeBase(0);
1312 const size_t num_ranges = ranges.GetSize();
1313 for (size_t i = 0; i < num_ranges; ++i) {
1314 const DWARFRangeList::Entry &range = ranges.GetEntryRef(i);
1315 const addr_t range_base = range.GetRangeBase();
1316 if (range_base >= subprogram_low_pc)
1317 block->AddRange(Block::Range(range_base - subprogram_low_pc,
1318 range.GetByteSize()));
1320 GetObjectFile()->GetModule()->ReportError(
1321 "{0:x8}: adding range [{1:x16}-{2:x16}) which has a base "
1322 "that is less than the function's low PC {3:x16}. Please file "
1323 "a bug and attach the file at the "
1324 "start of this error message",
1325 block->GetID(), range_base, range.GetRangeEnd(),
1329 block->FinalizeRanges();
1331 if (tag != DW_TAG_subprogram &&
1332 (name != nullptr || mangled_name != nullptr)) {
1333 std::unique_ptr<Declaration> decl_up;
1334 if (decl_file || decl_line || decl_column)
1335 decl_up = std::make_unique<Declaration>(
1336 comp_unit.GetSupportFiles().GetFileSpecAtIndex(
1337 decl_file ? *decl_file : 0),
1338 decl_line ? *decl_line : 0, decl_column ? *decl_column : 0);
1340 std::unique_ptr<Declaration> call_up;
1341 if (call_file || call_line || call_column)
1342 call_up = std::make_unique<Declaration>(
1343 comp_unit.GetSupportFiles().GetFileSpecAtIndex(
1344 call_file ? *call_file : 0),
1345 call_line ? *call_line : 0, call_column ? *call_column : 0);
1347 block->SetInlinedFunctionInfo(name, mangled_name, decl_up.get(),
1353 if (die.HasChildren()) {
1355 ParseBlocksRecursive(comp_unit, block, die.GetFirstChild(),
1356 subprogram_low_pc, depth + 1);
1364 // Only parse siblings of the block if we are not at depth zero. A depth of
1365 // zero indicates we are currently parsing the top level DW_TAG_subprogram
1371 die = die.GetSibling();
1373 return blocks_added;
1376 bool SymbolFileDWARF::ClassOrStructIsVirtual(const DWARFDIE &parent_die) {
1378 for (DWARFDIE die : parent_die.children()) {
1379 dw_tag_t tag = die.Tag();
1380 bool check_virtuality = false;
1382 case DW_TAG_inheritance:
1383 case DW_TAG_subprogram:
1384 check_virtuality = true;
1389 if (check_virtuality) {
1390 if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0)
1398 void SymbolFileDWARF::ParseDeclsForContext(CompilerDeclContext decl_ctx) {
1399 auto *type_system = decl_ctx.GetTypeSystem();
1400 if (type_system != nullptr)
1401 type_system->GetDWARFParser()->EnsureAllDIEsInDeclContextHaveBeenParsed(
1406 SymbolFileDWARF::GetDIE(lldb::user_id_t uid) { return GetDIE(DIERef(uid)); }
1408 CompilerDecl SymbolFileDWARF::GetDeclForUID(lldb::user_id_t type_uid) {
1409 // This method can be called without going through the symbol vendor so we
1410 // need to lock the module.
1411 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1412 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1413 // SymbolFileDWARF::GetDIE(). See comments inside the
1414 // SymbolFileDWARF::GetDIE() for details.
1415 if (DWARFDIE die = GetDIE(type_uid))
1416 return GetDecl(die);
1417 return CompilerDecl();
1421 SymbolFileDWARF::GetDeclContextForUID(lldb::user_id_t type_uid) {
1422 // This method can be called without going through the symbol vendor so we
1423 // need to lock the module.
1424 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1425 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1426 // SymbolFileDWARF::GetDIE(). See comments inside the
1427 // SymbolFileDWARF::GetDIE() for details.
1428 if (DWARFDIE die = GetDIE(type_uid))
1429 return GetDeclContext(die);
1430 return CompilerDeclContext();
1434 SymbolFileDWARF::GetDeclContextContainingUID(lldb::user_id_t type_uid) {
1435 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1436 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1437 // SymbolFileDWARF::GetDIE(). See comments inside the
1438 // SymbolFileDWARF::GetDIE() for details.
1439 if (DWARFDIE die = GetDIE(type_uid))
1440 return GetContainingDeclContext(die);
1441 return CompilerDeclContext();
1444 Type *SymbolFileDWARF::ResolveTypeUID(lldb::user_id_t type_uid) {
1445 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1446 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1447 // SymbolFileDWARF::GetDIE(). See comments inside the
1448 // SymbolFileDWARF::GetDIE() for details.
1449 if (DWARFDIE type_die = GetDIE(type_uid))
1450 return type_die.ResolveType();
1455 std::optional<SymbolFile::ArrayInfo> SymbolFileDWARF::GetDynamicArrayInfoForUID(
1456 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1457 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1458 if (DWARFDIE type_die = GetDIE(type_uid))
1459 return DWARFASTParser::ParseChildArrayInfo(type_die, exe_ctx);
1461 return std::nullopt;
1464 Type *SymbolFileDWARF::ResolveTypeUID(const DIERef &die_ref) {
1465 return ResolveType(GetDIE(die_ref), true);
1468 Type *SymbolFileDWARF::ResolveTypeUID(const DWARFDIE &die,
1469 bool assert_not_being_parsed) {
1471 Log *log = GetLog(DWARFLog::DebugInfo);
1473 GetObjectFile()->GetModule()->LogMessage(
1474 log, "SymbolFileDWARF::ResolveTypeUID (die = {0:x16}) {1} '{2}'",
1475 die.GetOffset(), die.GetTagAsCString(), die.GetName());
1477 // We might be coming in in the middle of a type tree (a class within a
1478 // class, an enum within a class), so parse any needed parent DIEs before
1479 // we get to this one...
1480 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die);
1483 switch (decl_ctx_die.Tag()) {
1484 case DW_TAG_structure_type:
1485 case DW_TAG_union_type:
1486 case DW_TAG_class_type: {
1487 // Get the type, which could be a forward declaration
1489 GetObjectFile()->GetModule()->LogMessage(
1491 "SymbolFileDWARF::ResolveTypeUID (die = {0:x16}) "
1493 "resolve parent forward type for {3:x16})",
1494 die.GetOffset(), die.GetTagAsCString(), die.GetName(),
1495 decl_ctx_die.GetOffset());
1503 return ResolveType(die);
1508 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
1509 // SymbolFileDWARF objects to detect if this DWARF file is the one that can
1510 // resolve a compiler_type.
1511 bool SymbolFileDWARF::HasForwardDeclForClangType(
1512 const CompilerType &compiler_type) {
1513 CompilerType compiler_type_no_qualifiers =
1514 ClangUtil::RemoveFastQualifiers(compiler_type);
1515 if (GetForwardDeclClangTypeToDie().count(
1516 compiler_type_no_qualifiers.GetOpaqueQualType())) {
1519 auto type_system = compiler_type.GetTypeSystem();
1520 auto clang_type_system = type_system.dyn_cast_or_null<TypeSystemClang>();
1521 if (!clang_type_system)
1523 DWARFASTParserClang *ast_parser =
1524 static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1525 return ast_parser->GetClangASTImporter().CanImport(compiler_type);
1528 bool SymbolFileDWARF::CompleteType(CompilerType &compiler_type) {
1529 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1530 auto clang_type_system =
1531 compiler_type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
1532 if (clang_type_system) {
1533 DWARFASTParserClang *ast_parser =
1534 static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1536 ast_parser->GetClangASTImporter().CanImport(compiler_type))
1537 return ast_parser->GetClangASTImporter().CompleteType(compiler_type);
1540 // We have a struct/union/class/enum that needs to be fully resolved.
1541 CompilerType compiler_type_no_qualifiers =
1542 ClangUtil::RemoveFastQualifiers(compiler_type);
1543 auto die_it = GetForwardDeclClangTypeToDie().find(
1544 compiler_type_no_qualifiers.GetOpaqueQualType());
1545 if (die_it == GetForwardDeclClangTypeToDie().end()) {
1546 // We have already resolved this type...
1550 DWARFDIE dwarf_die = GetDIE(die_it->getSecond());
1552 // Once we start resolving this type, remove it from the forward
1553 // declaration map in case anyone child members or other types require this
1554 // type to get resolved. The type will get resolved when all of the calls
1555 // to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition are done.
1556 GetForwardDeclClangTypeToDie().erase(die_it);
1558 Type *type = GetDIEToType().lookup(dwarf_die.GetDIE());
1560 Log *log = GetLog(DWARFLog::DebugInfo | DWARFLog::TypeCompletion);
1562 GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
1563 log, "{0:x8}: {1} '{2}' resolving forward declaration...",
1564 dwarf_die.GetID(), dwarf_die.GetTagAsCString(),
1565 type->GetName().AsCString());
1566 assert(compiler_type);
1567 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*dwarf_die.GetCU()))
1568 return dwarf_ast->CompleteTypeFromDWARF(dwarf_die, type, compiler_type);
1573 Type *SymbolFileDWARF::ResolveType(const DWARFDIE &die,
1574 bool assert_not_being_parsed,
1575 bool resolve_function_context) {
1577 Type *type = GetTypeForDIE(die, resolve_function_context).get();
1579 if (assert_not_being_parsed) {
1580 if (type != DIE_IS_BEING_PARSED)
1583 GetObjectFile()->GetModule()->ReportError(
1584 "Parsing a die that is being parsed die: {0:x16}: {1} {2}",
1585 die.GetOffset(), die.GetTagAsCString(), die.GetName());
1594 SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu) {
1595 if (dwarf_cu.IsDWOUnit()) {
1596 DWARFCompileUnit *non_dwo_cu =
1597 static_cast<DWARFCompileUnit *>(dwarf_cu.GetUserData());
1599 return non_dwo_cu->GetSymbolFileDWARF().GetCompUnitForDWARFCompUnit(
1602 // Check if the symbol vendor already knows about this compile unit?
1603 if (dwarf_cu.GetUserData() == nullptr) {
1604 // The symbol vendor doesn't know about this compile unit, we need to parse
1605 // and add it to the symbol vendor object.
1606 return ParseCompileUnit(dwarf_cu).get();
1608 return static_cast<CompileUnit *>(dwarf_cu.GetUserData());
1611 void SymbolFileDWARF::GetObjCMethods(
1612 ConstString class_name, llvm::function_ref<bool(DWARFDIE die)> callback) {
1613 m_index->GetObjCMethods(class_name, callback);
1616 bool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) {
1619 if (die && llvm::isa<DWARFCompileUnit>(die.GetCU())) {
1620 // Check if the symbol vendor already knows about this compile unit?
1622 GetCompUnitForDWARFCompUnit(llvm::cast<DWARFCompileUnit>(*die.GetCU()));
1624 sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
1625 if (sc.function == nullptr)
1626 sc.function = ParseFunction(*sc.comp_unit, die);
1629 sc.module_sp = sc.function->CalculateSymbolContextModule();
1637 lldb::ModuleSP SymbolFileDWARF::GetExternalModule(ConstString name) {
1638 UpdateExternalModuleListIfNeeded();
1639 const auto &pos = m_external_type_modules.find(name);
1640 if (pos == m_external_type_modules.end())
1641 return lldb::ModuleSP();
1646 SymbolFileDWARF::GetDIE(const DIERef &die_ref) {
1647 // This method can be called without going through the symbol vendor so we
1648 // need to lock the module.
1649 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1651 SymbolFileDWARF *symbol_file = nullptr;
1653 // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we
1654 // must make sure we use the correct DWARF file when resolving things. On
1655 // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1656 // SymbolFileDWARF classes, one for each .o file. We can often end up with
1657 // references to other DWARF objects and we must be ready to receive a
1658 // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1660 std::optional<uint32_t> file_index = die_ref.file_index();
1662 if (SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile()) {
1663 symbol_file = debug_map->GetSymbolFileByOSOIndex(*file_index); // OSO case
1665 return symbol_file->DebugInfo().GetDIE(die_ref);
1669 if (*file_index == DIERef::k_file_index_mask)
1670 symbol_file = m_dwp_symfile.get(); // DWP case
1672 symbol_file = this->DebugInfo()
1673 .GetUnitAtIndex(*die_ref.file_index())
1674 ->GetDwoSymbolFile(); // DWO case
1675 } else if (die_ref.die_offset() == DW_INVALID_OFFSET) {
1680 return symbol_file->GetDIE(die_ref);
1682 return DebugInfo().GetDIE(die_ref);
1685 /// Return the DW_AT_(GNU_)dwo_id.
1686 static std::optional<uint64_t> GetDWOId(DWARFCompileUnit &dwarf_cu,
1687 const DWARFDebugInfoEntry &cu_die) {
1688 std::optional<uint64_t> dwo_id =
1689 cu_die.GetAttributeValueAsOptionalUnsigned(&dwarf_cu, DW_AT_GNU_dwo_id);
1692 return cu_die.GetAttributeValueAsOptionalUnsigned(&dwarf_cu, DW_AT_dwo_id);
1695 std::optional<uint64_t> SymbolFileDWARF::GetDWOId() {
1696 if (GetNumCompileUnits() == 1) {
1697 if (auto comp_unit = GetCompileUnitAtIndex(0))
1698 if (DWARFCompileUnit *cu = GetDWARFCompileUnit(comp_unit.get()))
1699 if (DWARFDebugInfoEntry *cu_die = cu->DIE().GetDIE())
1700 return ::GetDWOId(*cu, *cu_die);
1705 std::shared_ptr<SymbolFileDWARFDwo>
1706 SymbolFileDWARF::GetDwoSymbolFileForCompileUnit(
1707 DWARFUnit &unit, const DWARFDebugInfoEntry &cu_die) {
1708 // If this is a Darwin-style debug map (non-.dSYM) symbol file,
1709 // never attempt to load ELF-style DWO files since the -gmodules
1710 // support uses the same DWO mechanism to specify full debug info
1711 // files for modules. This is handled in
1712 // UpdateExternalModuleListIfNeeded().
1713 if (GetDebugMapSymfile())
1716 DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit);
1717 // Only compile units can be split into two parts and we should only
1718 // look for a DWO file if there is a valid DWO ID.
1719 if (!dwarf_cu || !dwarf_cu->GetDWOId().has_value())
1722 const char *dwo_name = GetDWOName(*dwarf_cu, cu_die);
1724 unit.SetDwoError(Status::createWithFormat(
1725 "missing DWO name in skeleton DIE {0:x16}", cu_die.GetOffset()));
1729 if (std::shared_ptr<SymbolFileDWARFDwo> dwp_sp = GetDwpSymbolFile())
1732 const char *comp_dir = nullptr;
1733 FileSpec dwo_file(dwo_name);
1734 FileSystem::Instance().Resolve(dwo_file);
1735 if (dwo_file.IsRelative()) {
1736 comp_dir = cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_comp_dir,
1739 unit.SetDwoError(Status::createWithFormat(
1740 "unable to locate relative .dwo debug file \"{0}\" for "
1741 "skeleton DIE {1:x16} without valid DW_AT_comp_dir "
1743 dwo_name, cu_die.GetOffset()));
1747 dwo_file.SetFile(comp_dir, FileSpec::Style::native);
1748 if (dwo_file.IsRelative()) {
1749 // if DW_AT_comp_dir is relative, it should be relative to the location
1750 // of the executable, not to the location from which the debugger was
1752 dwo_file.PrependPathComponent(
1753 m_objfile_sp->GetFileSpec().GetDirectory().GetStringRef());
1755 FileSystem::Instance().Resolve(dwo_file);
1756 dwo_file.AppendPathComponent(dwo_name);
1759 if (!FileSystem::Instance().Exists(dwo_file)) {
1760 unit.SetDwoError(Status::createWithFormat(
1761 "unable to locate .dwo debug file \"{0}\" for skeleton DIE "
1763 dwo_file.GetPath().c_str(), cu_die.GetOffset()));
1765 if (m_dwo_warning_issued.test_and_set(std::memory_order_relaxed) == false) {
1766 GetObjectFile()->GetModule()->ReportWarning(
1767 "unable to locate separate debug file (dwo, dwp). Debugging will be "
1773 const lldb::offset_t file_offset = 0;
1774 DataBufferSP dwo_file_data_sp;
1775 lldb::offset_t dwo_file_data_offset = 0;
1776 ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin(
1777 GetObjectFile()->GetModule(), &dwo_file, file_offset,
1778 FileSystem::Instance().GetByteSize(dwo_file), dwo_file_data_sp,
1779 dwo_file_data_offset);
1780 if (dwo_obj_file == nullptr) {
1781 unit.SetDwoError(Status::createWithFormat(
1782 "unable to load object file for .dwo debug file \"{0}\" for "
1784 dwo_name, cu_die.GetOffset()));
1788 return std::make_shared<SymbolFileDWARFDwo>(*this, dwo_obj_file,
1792 void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() {
1793 if (m_fetched_external_modules)
1795 m_fetched_external_modules = true;
1796 DWARFDebugInfo &debug_info = DebugInfo();
1798 // Follow DWO skeleton unit breadcrumbs.
1799 const uint32_t num_compile_units = GetNumCompileUnits();
1800 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
1802 llvm::dyn_cast<DWARFCompileUnit>(debug_info.GetUnitAtIndex(cu_idx));
1806 const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
1807 if (!die || die.HasChildren() || !die.GetDIE())
1810 const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
1814 ConstString const_name(name);
1815 ModuleSP &module_sp = m_external_type_modules[const_name];
1819 const char *dwo_path = GetDWOName(*dwarf_cu, *die.GetDIE());
1823 ModuleSpec dwo_module_spec;
1824 dwo_module_spec.GetFileSpec().SetFile(dwo_path, FileSpec::Style::native);
1825 if (dwo_module_spec.GetFileSpec().IsRelative()) {
1826 const char *comp_dir =
1827 die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr);
1829 dwo_module_spec.GetFileSpec().SetFile(comp_dir,
1830 FileSpec::Style::native);
1831 FileSystem::Instance().Resolve(dwo_module_spec.GetFileSpec());
1832 dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path);
1835 dwo_module_spec.GetArchitecture() =
1836 m_objfile_sp->GetModule()->GetArchitecture();
1838 // When LLDB loads "external" modules it looks at the presence of
1839 // DW_AT_dwo_name. However, when the already created module
1840 // (corresponding to .dwo itself) is being processed, it will see
1841 // the presence of DW_AT_dwo_name (which contains the name of dwo
1842 // file) and will try to call ModuleList::GetSharedModule
1843 // again. In some cases (i.e., for empty files) Clang 4.0
1844 // generates a *.dwo file which has DW_AT_dwo_name, but no
1845 // DW_AT_comp_dir. In this case the method
1846 // ModuleList::GetSharedModule will fail and the warning will be
1847 // printed. However, as one can notice in this case we don't
1848 // actually need to try to load the already loaded module
1849 // (corresponding to .dwo) so we simply skip it.
1850 if (m_objfile_sp->GetFileSpec().GetFileNameExtension() == ".dwo" &&
1851 llvm::StringRef(m_objfile_sp->GetFileSpec().GetPath())
1852 .endswith(dwo_module_spec.GetFileSpec().GetPath())) {
1856 Status error = ModuleList::GetSharedModule(dwo_module_spec, module_sp,
1857 nullptr, nullptr, nullptr);
1859 GetObjectFile()->GetModule()->ReportWarning(
1860 "{0:x16}: unable to locate module needed for external types: "
1861 "{1}\nerror: {2}\nDebugging will be degraded due to missing "
1862 "types. Rebuilding the project will regenerate the needed "
1864 die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str(),
1865 error.AsCString("unknown error"));
1869 // Verify the DWO hash.
1870 // FIXME: Technically "0" is a valid hash.
1871 std::optional<uint64_t> dwo_id = ::GetDWOId(*dwarf_cu, *die.GetDIE());
1876 llvm::dyn_cast_or_null<SymbolFileDWARF>(module_sp->GetSymbolFile());
1879 std::optional<uint64_t> dwo_dwo_id = dwo_symfile->GetDWOId();
1883 if (dwo_id != dwo_dwo_id) {
1884 GetObjectFile()->GetModule()->ReportWarning(
1885 "{0:x16}: Module {1} is out-of-date (hash mismatch). Type "
1887 "from this module may be incomplete or inconsistent with the rest of "
1888 "the program. Rebuilding the project will regenerate the needed "
1890 die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str());
1895 SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() {
1896 if (!m_global_aranges_up) {
1897 m_global_aranges_up = std::make_unique<GlobalVariableMap>();
1899 ModuleSP module_sp = GetObjectFile()->GetModule();
1901 const size_t num_cus = module_sp->GetNumCompileUnits();
1902 for (size_t i = 0; i < num_cus; ++i) {
1903 CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
1905 VariableListSP globals_sp = cu_sp->GetVariableList(true);
1907 const size_t num_globals = globals_sp->GetSize();
1908 for (size_t g = 0; g < num_globals; ++g) {
1909 VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
1910 if (var_sp && !var_sp->GetLocationIsConstantValueData()) {
1911 const DWARFExpressionList &location =
1912 var_sp->LocationExpressionList();
1913 Value location_result;
1915 ExecutionContext exe_ctx;
1916 if (location.Evaluate(&exe_ctx, nullptr, LLDB_INVALID_ADDRESS,
1917 nullptr, nullptr, location_result,
1919 if (location_result.GetValueType() ==
1920 Value::ValueType::FileAddress) {
1921 lldb::addr_t file_addr =
1922 location_result.GetScalar().ULongLong();
1923 lldb::addr_t byte_size = 1;
1924 if (var_sp->GetType())
1926 var_sp->GetType()->GetByteSize(nullptr).value_or(0);
1927 m_global_aranges_up->Append(GlobalVariableMap::Entry(
1928 file_addr, byte_size, var_sp.get()));
1937 m_global_aranges_up->Sort();
1939 return *m_global_aranges_up;
1942 void SymbolFileDWARF::ResolveFunctionAndBlock(lldb::addr_t file_vm_addr,
1944 SymbolContext &sc) {
1945 assert(sc.comp_unit);
1946 DWARFCompileUnit &cu =
1947 GetDWARFCompileUnit(sc.comp_unit)->GetNonSkeletonUnit();
1948 DWARFDIE function_die = cu.LookupAddress(file_vm_addr);
1951 sc.function = sc.comp_unit->FindFunctionByUID(function_die.GetID()).get();
1952 if (sc.function == nullptr)
1953 sc.function = ParseFunction(*sc.comp_unit, function_die);
1955 if (sc.function && lookup_block)
1956 block_die = function_die.LookupDeepestBlock(file_vm_addr);
1959 if (!sc.function || !lookup_block)
1962 Block &block = sc.function->GetBlock(true);
1964 sc.block = block.FindBlockByID(block_die.GetID());
1966 sc.block = block.FindBlockByID(function_die.GetID());
1969 uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr,
1970 SymbolContextItem resolve_scope,
1971 SymbolContext &sc) {
1972 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1973 LLDB_SCOPED_TIMERF("SymbolFileDWARF::"
1974 "ResolveSymbolContext (so_addr = { "
1975 "section = %p, offset = 0x%" PRIx64
1976 " }, resolve_scope = 0x%8.8x)",
1977 static_cast<void *>(so_addr.GetSection().get()),
1978 so_addr.GetOffset(), resolve_scope);
1979 uint32_t resolved = 0;
1981 (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock |
1982 eSymbolContextLineEntry | eSymbolContextVariable)) {
1983 lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1985 DWARFDebugInfo &debug_info = DebugInfo();
1986 const DWARFDebugAranges &aranges = debug_info.GetCompileUnitAranges();
1987 const dw_offset_t cu_offset = aranges.FindAddress(file_vm_addr);
1988 if (cu_offset == DW_INVALID_OFFSET) {
1989 // Global variables are not in the compile unit address ranges. The only
1990 // way to currently find global variables is to iterate over the
1991 // .debug_pubnames or the __apple_names table and find all items in there
1992 // that point to DW_TAG_variable DIEs and then find the address that
1994 if (resolve_scope & eSymbolContextVariable) {
1995 GlobalVariableMap &map = GetGlobalAranges();
1996 const GlobalVariableMap::Entry *entry =
1997 map.FindEntryThatContains(file_vm_addr);
1998 if (entry && entry->data) {
1999 Variable *variable = entry->data;
2000 SymbolContextScope *scc = variable->GetSymbolContextScope();
2002 scc->CalculateSymbolContext(&sc);
2003 sc.variable = variable;
2005 return sc.GetResolvedMask();
2009 uint32_t cu_idx = DW_INVALID_INDEX;
2010 if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(
2011 debug_info.GetUnitAtOffset(DIERef::Section::DebugInfo, cu_offset,
2013 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2015 resolved |= eSymbolContextCompUnit;
2017 bool force_check_line_table = false;
2018 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {
2019 ResolveFunctionAndBlock(file_vm_addr,
2020 resolve_scope & eSymbolContextBlock, sc);
2022 resolved |= eSymbolContextFunction;
2024 // We might have had a compile unit that had discontiguous address
2025 // ranges where the gaps are symbols that don't have any debug
2026 // info. Discontiguous compile unit address ranges should only
2027 // happen when there aren't other functions from other compile
2028 // units in these gaps. This helps keep the size of the aranges
2030 force_check_line_table = true;
2033 resolved |= eSymbolContextBlock;
2036 if ((resolve_scope & eSymbolContextLineEntry) ||
2037 force_check_line_table) {
2038 LineTable *line_table = sc.comp_unit->GetLineTable();
2039 if (line_table != nullptr) {
2040 // And address that makes it into this function should be in terms
2041 // of this debug file if there is no debug map, or it will be an
2042 // address in the .o file which needs to be fixed up to be in
2043 // terms of the debug map executable. Either way, calling
2044 // FixupAddress() will work for us.
2045 Address exe_so_addr(so_addr);
2046 if (FixupAddress(exe_so_addr)) {
2047 if (line_table->FindLineEntryByAddress(exe_so_addr,
2049 resolved |= eSymbolContextLineEntry;
2055 if (force_check_line_table && !(resolved & eSymbolContextLineEntry)) {
2056 // We might have had a compile unit that had discontiguous address
2057 // ranges where the gaps are symbols that don't have any debug info.
2058 // Discontiguous compile unit address ranges should only happen when
2059 // there aren't other functions from other compile units in these
2060 // gaps. This helps keep the size of the aranges down.
2061 sc.comp_unit = nullptr;
2062 resolved &= ~eSymbolContextCompUnit;
2065 GetObjectFile()->GetModule()->ReportWarning(
2066 "{0:x16}: compile unit {1} failed to create a valid "
2067 "lldb_private::CompileUnit class.",
2076 uint32_t SymbolFileDWARF::ResolveSymbolContext(
2077 const SourceLocationSpec &src_location_spec,
2078 SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
2079 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2080 const bool check_inlines = src_location_spec.GetCheckInlines();
2081 const uint32_t prev_size = sc_list.GetSize();
2082 if (resolve_scope & eSymbolContextCompUnit) {
2083 for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
2085 CompileUnit *dc_cu = ParseCompileUnitAtIndex(cu_idx).get();
2089 bool file_spec_matches_cu_file_spec = FileSpec::Match(
2090 src_location_spec.GetFileSpec(), dc_cu->GetPrimaryFile());
2091 if (check_inlines || file_spec_matches_cu_file_spec) {
2092 dc_cu->ResolveSymbolContext(src_location_spec, resolve_scope, sc_list);
2098 return sc_list.GetSize() - prev_size;
2101 void SymbolFileDWARF::PreloadSymbols() {
2102 // Get the symbol table for the symbol file prior to taking the module lock
2103 // so that it is available without needing to take the module lock. The DWARF
2104 // indexing might end up needing to relocate items when DWARF sections are
2105 // loaded as they might end up getting the section contents which can call
2106 // ObjectFileELF::RelocateSection() which in turn will ask for the symbol
2107 // table and can cause deadlocks.
2109 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2113 std::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const {
2114 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
2116 return module_sp->GetMutex();
2117 return GetObjectFile()->GetModule()->GetMutex();
2120 bool SymbolFileDWARF::DeclContextMatchesThisSymbolFile(
2121 const lldb_private::CompilerDeclContext &decl_ctx) {
2122 if (!decl_ctx.IsValid()) {
2123 // Invalid namespace decl which means we aren't matching only things in
2124 // this symbol file, so return true to indicate it matches this symbol
2129 TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem();
2130 auto type_system_or_err = GetTypeSystemForLanguage(
2131 decl_ctx_type_system->GetMinimumLanguage(nullptr));
2132 if (auto err = type_system_or_err.takeError()) {
2133 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2134 "Unable to match namespace decl using TypeSystem: {0}");
2138 if (decl_ctx_type_system == type_system_or_err->get())
2139 return true; // The type systems match, return true
2141 // The namespace AST was valid, and it does not match...
2142 Log *log = GetLog(DWARFLog::Lookups);
2145 GetObjectFile()->GetModule()->LogMessage(
2146 log, "Valid namespace does not match symbol file");
2151 void SymbolFileDWARF::FindGlobalVariables(
2152 ConstString name, const CompilerDeclContext &parent_decl_ctx,
2153 uint32_t max_matches, VariableList &variables) {
2154 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2155 Log *log = GetLog(DWARFLog::Lookups);
2158 GetObjectFile()->GetModule()->LogMessage(
2160 "SymbolFileDWARF::FindGlobalVariables (name=\"{0}\", "
2161 "parent_decl_ctx={1:p}, max_matches={2}, variables)",
2162 name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2165 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2168 // Remember how many variables are in the list before we search.
2169 const uint32_t original_size = variables.GetSize();
2171 llvm::StringRef basename;
2172 llvm::StringRef context;
2173 bool name_is_mangled = Mangled::GetManglingScheme(name.GetStringRef()) !=
2174 Mangled::eManglingSchemeNone;
2176 if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(),
2178 basename = name.GetStringRef();
2180 // Loop invariant: Variables up to this index have been checked for context
2182 uint32_t pruned_idx = original_size;
2185 m_index->GetGlobalVariables(ConstString(basename), [&](DWARFDIE die) {
2187 sc.module_sp = m_objfile_sp->GetModule();
2188 assert(sc.module_sp);
2190 if (die.Tag() != DW_TAG_variable)
2193 auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2196 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2198 if (parent_decl_ctx) {
2199 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) {
2200 CompilerDeclContext actual_parent_decl_ctx =
2201 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2203 /// If the actual namespace is inline (i.e., had a DW_AT_export_symbols)
2204 /// and a child (possibly through other layers of inline namespaces)
2205 /// of the namespace referred to by 'basename', allow the lookup to
2207 if (!actual_parent_decl_ctx ||
2208 (actual_parent_decl_ctx != parent_decl_ctx &&
2209 !parent_decl_ctx.IsContainedInLookup(actual_parent_decl_ctx)))
2214 ParseAndAppendGlobalVariable(sc, die, variables);
2215 while (pruned_idx < variables.GetSize()) {
2216 VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx);
2217 if (name_is_mangled ||
2218 var_sp->GetName().GetStringRef().contains(name.GetStringRef()))
2221 variables.RemoveVariableAtIndex(pruned_idx);
2224 return variables.GetSize() - original_size < max_matches;
2227 // Return the number of variable that were appended to the list
2228 const uint32_t num_matches = variables.GetSize() - original_size;
2229 if (log && num_matches > 0) {
2230 GetObjectFile()->GetModule()->LogMessage(
2232 "SymbolFileDWARF::FindGlobalVariables (name=\"{0}\", "
2233 "parent_decl_ctx={1:p}, max_matches={2}, variables) => {3}",
2234 name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2235 max_matches, num_matches);
2239 void SymbolFileDWARF::FindGlobalVariables(const RegularExpression ®ex,
2240 uint32_t max_matches,
2241 VariableList &variables) {
2242 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2243 Log *log = GetLog(DWARFLog::Lookups);
2246 GetObjectFile()->GetModule()->LogMessage(
2248 "SymbolFileDWARF::FindGlobalVariables (regex=\"{0}\", "
2249 "max_matches={1}, variables)",
2250 regex.GetText().str().c_str(), max_matches);
2253 // Remember how many variables are in the list before we search.
2254 const uint32_t original_size = variables.GetSize();
2257 m_index->GetGlobalVariables(regex, [&](DWARFDIE die) {
2259 sc.module_sp = m_objfile_sp->GetModule();
2260 assert(sc.module_sp);
2262 DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2265 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2267 ParseAndAppendGlobalVariable(sc, die, variables);
2269 return variables.GetSize() - original_size < max_matches;
2273 bool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die,
2274 bool include_inlines,
2275 SymbolContextList &sc_list) {
2281 // If we were passed a die that is not a function, just return false...
2282 if (!(orig_die.Tag() == DW_TAG_subprogram ||
2283 (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2286 DWARFDIE die = orig_die;
2287 DWARFDIE inlined_die;
2288 if (die.Tag() == DW_TAG_inlined_subroutine) {
2292 die = die.GetParent();
2295 if (die.Tag() == DW_TAG_subprogram)
2301 assert(die && die.Tag() == DW_TAG_subprogram);
2302 if (GetFunction(die, sc)) {
2304 // Parse all blocks if needed
2306 Block &function_block = sc.function->GetBlock(true);
2307 sc.block = function_block.FindBlockByID(inlined_die.GetID());
2308 if (sc.block == nullptr)
2309 sc.block = function_block.FindBlockByID(inlined_die.GetOffset());
2310 if (sc.block == nullptr || !sc.block->GetStartAddress(addr))
2314 addr = sc.function->GetAddressRange().GetBaseAddress();
2324 bool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext &decl_ctx,
2325 const DWARFDIE &die,
2326 bool only_root_namespaces) {
2327 // If we have no parent decl context to match this DIE matches, and if the
2328 // parent decl context isn't valid, we aren't trying to look for any
2329 // particular decl context so any die matches.
2330 if (!decl_ctx.IsValid()) {
2331 // ...But if we are only checking root decl contexts, confirm that the
2332 // 'die' is a top-level context.
2333 if (only_root_namespaces)
2334 return die.GetParent().Tag() == dwarf::DW_TAG_compile_unit;
2340 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) {
2341 if (CompilerDeclContext actual_decl_ctx =
2342 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die))
2343 return decl_ctx.IsContainedInLookup(actual_decl_ctx);
2349 void SymbolFileDWARF::FindFunctions(const Module::LookupInfo &lookup_info,
2350 const CompilerDeclContext &parent_decl_ctx,
2351 bool include_inlines,
2352 SymbolContextList &sc_list) {
2353 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2354 ConstString name = lookup_info.GetLookupName();
2355 FunctionNameType name_type_mask = lookup_info.GetNameTypeMask();
2357 // eFunctionNameTypeAuto should be pre-resolved by a call to
2358 // Module::LookupInfo::LookupInfo()
2359 assert((name_type_mask & eFunctionNameTypeAuto) == 0);
2361 Log *log = GetLog(DWARFLog::Lookups);
2364 GetObjectFile()->GetModule()->LogMessage(
2366 "SymbolFileDWARF::FindFunctions (name=\"{0}\", name_type_mask={1:x}, "
2368 name.GetCString(), name_type_mask);
2371 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2374 // If name is empty then we won't find anything.
2378 // Remember how many sc_list are in the list before we search in case we are
2379 // appending the results to a variable list.
2381 const uint32_t original_size = sc_list.GetSize();
2383 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2385 m_index->GetFunctions(lookup_info, *this, parent_decl_ctx, [&](DWARFDIE die) {
2386 if (resolved_dies.insert(die.GetDIE()).second)
2387 ResolveFunction(die, include_inlines, sc_list);
2390 // With -gsimple-template-names, a templated type's DW_AT_name will not
2391 // contain the template parameters. Try again stripping '<' and anything
2392 // after, filtering out entries with template parameters that don't match.
2394 const llvm::StringRef name_ref = name.GetStringRef();
2395 auto it = name_ref.find('<');
2396 if (it != llvm::StringRef::npos) {
2397 const llvm::StringRef name_no_template_params = name_ref.slice(0, it);
2399 Module::LookupInfo no_tp_lookup_info(lookup_info);
2400 no_tp_lookup_info.SetLookupName(ConstString(name_no_template_params));
2401 m_index->GetFunctions(no_tp_lookup_info, *this, parent_decl_ctx, [&](DWARFDIE die) {
2402 if (resolved_dies.insert(die.GetDIE()).second)
2403 ResolveFunction(die, include_inlines, sc_list);
2409 // Return the number of variable that were appended to the list
2410 const uint32_t num_matches = sc_list.GetSize() - original_size;
2412 if (log && num_matches > 0) {
2413 GetObjectFile()->GetModule()->LogMessage(
2415 "SymbolFileDWARF::FindFunctions (name=\"{0}\", "
2416 "name_type_mask={1:x}, include_inlines={2:d}, sc_list) => {3}",
2417 name.GetCString(), name_type_mask, include_inlines, num_matches);
2421 void SymbolFileDWARF::FindFunctions(const RegularExpression ®ex,
2422 bool include_inlines,
2423 SymbolContextList &sc_list) {
2424 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2425 LLDB_SCOPED_TIMERF("SymbolFileDWARF::FindFunctions (regex = '%s')",
2426 regex.GetText().str().c_str());
2428 Log *log = GetLog(DWARFLog::Lookups);
2431 GetObjectFile()->GetModule()->LogMessage(
2432 log, "SymbolFileDWARF::FindFunctions (regex=\"{0}\", sc_list)",
2433 regex.GetText().str().c_str());
2436 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2437 m_index->GetFunctions(regex, [&](DWARFDIE die) {
2438 if (resolved_dies.insert(die.GetDIE()).second)
2439 ResolveFunction(die, include_inlines, sc_list);
2444 void SymbolFileDWARF::GetMangledNamesForFunction(
2445 const std::string &scope_qualified_name,
2446 std::vector<ConstString> &mangled_names) {
2447 DWARFDebugInfo &info = DebugInfo();
2448 uint32_t num_comp_units = info.GetNumUnits();
2449 for (uint32_t i = 0; i < num_comp_units; i++) {
2450 DWARFUnit *cu = info.GetUnitAtIndex(i);
2454 SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
2456 dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
2459 for (DIERef die_ref :
2460 m_function_scope_qualified_name_map.lookup(scope_qualified_name)) {
2461 DWARFDIE die = GetDIE(die_ref);
2462 mangled_names.push_back(ConstString(die.GetMangledName()));
2466 void SymbolFileDWARF::FindTypes(
2467 ConstString name, const CompilerDeclContext &parent_decl_ctx,
2468 uint32_t max_matches,
2469 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
2471 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2472 // Make sure we haven't already searched this SymbolFile before.
2473 if (!searched_symbol_files.insert(this).second)
2476 Log *log = GetLog(DWARFLog::Lookups);
2479 if (parent_decl_ctx)
2480 GetObjectFile()->GetModule()->LogMessage(
2482 "SymbolFileDWARF::FindTypes (sc, name=\"{0}\", parent_decl_ctx = "
2483 "{1:p} (\"{2}\"), max_matches={3}, type_list)",
2484 name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2485 parent_decl_ctx.GetName().AsCString("<NULL>"), max_matches);
2487 GetObjectFile()->GetModule()->LogMessage(
2489 "SymbolFileDWARF::FindTypes (sc, name=\"{0}\", parent_decl_ctx = "
2490 "NULL, max_matches={1}, type_list)",
2491 name.GetCString(), max_matches);
2494 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2497 // Unlike FindFunctions(), FindTypes() following cannot produce false
2500 const llvm::StringRef name_ref = name.GetStringRef();
2501 auto name_bracket_index = name_ref.find('<');
2502 m_index->GetTypes(name, [&](DWARFDIE die) {
2503 if (!DIEInDeclContext(parent_decl_ctx, die))
2504 return true; // The containing decl contexts don't match
2506 Type *matching_type = ResolveType(die, true, true);
2510 // With -gsimple-template-names, a templated type's DW_AT_name will not
2511 // contain the template parameters. Make sure that if the original query
2512 // didn't contain a '<', we filter out entries with template parameters.
2513 if (name_bracket_index == llvm::StringRef::npos &&
2514 matching_type->IsTemplateType())
2517 // We found a type pointer, now find the shared pointer form our type
2519 types.InsertUnique(matching_type->shared_from_this());
2520 return types.GetSize() < max_matches;
2523 // With -gsimple-template-names, a templated type's DW_AT_name will not
2524 // contain the template parameters. Try again stripping '<' and anything
2525 // after, filtering out entries with template parameters that don't match.
2526 if (types.GetSize() < max_matches) {
2527 if (name_bracket_index != llvm::StringRef::npos) {
2528 const llvm::StringRef name_no_template_params =
2529 name_ref.slice(0, name_bracket_index);
2530 const llvm::StringRef template_params =
2531 name_ref.slice(name_bracket_index, name_ref.size());
2532 m_index->GetTypes(ConstString(name_no_template_params), [&](DWARFDIE die) {
2533 if (!DIEInDeclContext(parent_decl_ctx, die))
2534 return true; // The containing decl contexts don't match
2536 const llvm::StringRef base_name = GetTypeForDIE(die)->GetBaseName().AsCString();
2537 auto it = base_name.find('<');
2538 // If the candidate qualified name doesn't have '<', it doesn't have
2539 // template params to compare.
2540 if (it == llvm::StringRef::npos)
2543 // Filter out non-matching instantiations by comparing template params.
2544 const llvm::StringRef base_name_template_params =
2545 base_name.slice(it, base_name.size());
2547 if (template_params != base_name_template_params)
2550 Type *matching_type = ResolveType(die, true, true);
2554 // We found a type pointer, now find the shared pointer form our type
2556 types.InsertUnique(matching_type->shared_from_this());
2557 return types.GetSize() < max_matches;
2562 // Next search through the reachable Clang modules. This only applies for
2563 // DWARF objects compiled with -gmodules that haven't been processed by
2565 if (types.GetSize() < max_matches) {
2566 UpdateExternalModuleListIfNeeded();
2568 for (const auto &pair : m_external_type_modules)
2569 if (ModuleSP external_module_sp = pair.second)
2570 if (SymbolFile *sym_file = external_module_sp->GetSymbolFile())
2571 sym_file->FindTypes(name, parent_decl_ctx, max_matches,
2572 searched_symbol_files, types);
2575 if (log && types.GetSize()) {
2576 if (parent_decl_ctx) {
2577 GetObjectFile()->GetModule()->LogMessage(
2579 "SymbolFileDWARF::FindTypes (sc, name=\"{0}\", parent_decl_ctx "
2580 "= {1:p} (\"{2}\"), max_matches={3}, type_list) => {4}",
2581 name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2582 parent_decl_ctx.GetName().AsCString("<NULL>"), max_matches,
2585 GetObjectFile()->GetModule()->LogMessage(
2587 "SymbolFileDWARF::FindTypes (sc, name=\"{0}\", parent_decl_ctx "
2588 "= NULL, max_matches={1}, type_list) => {2}",
2589 name.GetCString(), max_matches, types.GetSize());
2594 void SymbolFileDWARF::FindTypes(
2595 llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
2596 llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {
2597 // Make sure we haven't already searched this SymbolFile before.
2598 if (!searched_symbol_files.insert(this).second)
2601 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2602 if (pattern.empty())
2605 ConstString name = pattern.back().name;
2610 m_index->GetTypes(name, [&](DWARFDIE die) {
2611 if (!languages[GetLanguageFamily(*die.GetCU())])
2614 llvm::SmallVector<CompilerContext, 4> die_context;
2615 die.GetDeclContext(die_context);
2616 if (!contextMatches(die_context, pattern))
2619 if (Type *matching_type = ResolveType(die, true, true)) {
2620 // We found a type pointer, now find the shared pointer form our type
2622 types.InsertUnique(matching_type->shared_from_this());
2627 // Next search through the reachable Clang modules. This only applies for
2628 // DWARF objects compiled with -gmodules that haven't been processed by
2630 UpdateExternalModuleListIfNeeded();
2632 for (const auto &pair : m_external_type_modules)
2633 if (ModuleSP external_module_sp = pair.second)
2634 external_module_sp->FindTypes(pattern, languages, searched_symbol_files,
2639 SymbolFileDWARF::FindNamespace(ConstString name,
2640 const CompilerDeclContext &parent_decl_ctx,
2641 bool only_root_namespaces) {
2642 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2643 Log *log = GetLog(DWARFLog::Lookups);
2646 GetObjectFile()->GetModule()->LogMessage(
2647 log, "SymbolFileDWARF::FindNamespace (sc, name=\"{0}\")",
2651 CompilerDeclContext namespace_decl_ctx;
2653 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2654 return namespace_decl_ctx;
2656 m_index->GetNamespaces(name, [&](DWARFDIE die) {
2657 if (!DIEInDeclContext(parent_decl_ctx, die, only_root_namespaces))
2658 return true; // The containing decl contexts don't match
2660 DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU());
2664 namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
2665 return !namespace_decl_ctx.IsValid();
2668 if (log && namespace_decl_ctx) {
2669 GetObjectFile()->GetModule()->LogMessage(
2671 "SymbolFileDWARF::FindNamespace (sc, name=\"{0}\") => "
2672 "CompilerDeclContext({1:p}/{2:p}) \"{3}\"",
2674 static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
2675 static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
2676 namespace_decl_ctx.GetName().AsCString("<NULL>"));
2679 return namespace_decl_ctx;
2682 TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
2683 bool resolve_function_context) {
2686 Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
2687 if (type_ptr == nullptr) {
2688 SymbolContextScope *scope;
2689 if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()))
2690 scope = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2692 scope = GetObjectFile()->GetModule().get();
2694 SymbolContext sc(scope);
2695 const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
2696 while (parent_die != nullptr) {
2697 if (parent_die->Tag() == DW_TAG_subprogram)
2699 parent_die = parent_die->GetParent();
2701 SymbolContext sc_backup = sc;
2702 if (resolve_function_context && parent_die != nullptr &&
2703 !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
2706 type_sp = ParseType(sc, die, nullptr);
2707 } else if (type_ptr != DIE_IS_BEING_PARSED) {
2708 // Get the original shared pointer for this type
2709 type_sp = type_ptr->shared_from_this();
2716 SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
2718 DWARFDIE die = orig_die;
2721 // If this is the original DIE that we are searching for a declaration
2722 // for, then don't look in the cache as we don't want our own decl
2723 // context to be our decl context...
2724 if (orig_die != die) {
2725 switch (die.Tag()) {
2726 case DW_TAG_compile_unit:
2727 case DW_TAG_partial_unit:
2728 case DW_TAG_namespace:
2729 case DW_TAG_structure_type:
2730 case DW_TAG_union_type:
2731 case DW_TAG_class_type:
2732 case DW_TAG_lexical_block:
2733 case DW_TAG_subprogram:
2735 case DW_TAG_inlined_subroutine: {
2736 DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2747 DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
2749 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
2751 return decl_ctx_die;
2754 DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2756 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
2758 return decl_ctx_die;
2761 die = die.GetParent();
2767 Symbol *SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) {
2768 Symbol *objc_class_symbol = nullptr;
2770 Symtab *symtab = m_objfile_sp->GetSymtab();
2772 objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
2773 objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
2774 Symtab::eVisibilityAny);
2777 return objc_class_symbol;
2780 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If
2781 // they don't then we can end up looking through all class types for a complete
2782 // type and never find the full definition. We need to know if this attribute
2783 // is supported, so we determine this here and cache th result. We also need to
2784 // worry about the debug map
2786 // if we are doing darwin DWARF in .o file debugging.
2787 bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(DWARFUnit *cu) {
2788 if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) {
2789 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
2790 if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
2791 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2793 DWARFDebugInfo &debug_info = DebugInfo();
2794 const uint32_t num_compile_units = GetNumCompileUnits();
2795 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2796 DWARFUnit *dwarf_cu = debug_info.GetUnitAtIndex(cu_idx);
2797 if (dwarf_cu != cu &&
2798 dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) {
2799 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2804 if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo &&
2805 GetDebugMapSymfile())
2806 return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this);
2808 return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
2811 // This function can be used when a DIE is found that is a forward declaration
2812 // DIE and we want to try and find a type that has the complete definition.
2813 TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE(
2814 const DWARFDIE &die, ConstString type_name, bool must_be_implementation) {
2818 if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
2821 m_index->GetCompleteObjCClass(
2822 type_name, must_be_implementation, [&](DWARFDIE type_die) {
2823 bool try_resolving_type = false;
2825 // Don't try and resolve the DIE we are looking for with the DIE
2827 if (type_die != die) {
2828 switch (type_die.Tag()) {
2829 case DW_TAG_class_type:
2830 case DW_TAG_structure_type:
2831 try_resolving_type = true;
2837 if (!try_resolving_type)
2840 if (must_be_implementation &&
2841 type_die.Supports_DW_AT_APPLE_objc_complete_type())
2842 try_resolving_type = type_die.GetAttributeValueAsUnsigned(
2843 DW_AT_APPLE_objc_complete_type, 0);
2844 if (!try_resolving_type)
2847 Type *resolved_type = ResolveType(type_die, false, true);
2848 if (!resolved_type || resolved_type == DIE_IS_BEING_PARSED)
2852 "resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
2853 " (cu 0x%8.8" PRIx64 ")\n",
2855 m_objfile_sp->GetFileSpec().GetFilename().AsCString("<Unknown>"),
2856 type_die.GetID(), type_cu->GetID());
2859 GetDIEToType()[die.GetDIE()] = resolved_type;
2860 type_sp = resolved_type->shared_from_this();
2866 // This function helps to ensure that the declaration contexts match for two
2867 // different DIEs. Often times debug information will refer to a forward
2868 // declaration of a type (the equivalent of "struct my_struct;". There will
2869 // often be a declaration of that type elsewhere that has the full definition.
2870 // When we go looking for the full type "my_struct", we will find one or more
2871 // matches in the accelerator tables and we will then need to make sure the
2872 // type was in the same declaration context as the original DIE. This function
2873 // can efficiently compare two DIEs and will return true when the declaration
2874 // context matches, and false when they don't.
2875 bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1,
2876 const DWARFDIE &die2) {
2880 std::vector<DWARFDIE> decl_ctx_1;
2881 std::vector<DWARFDIE> decl_ctx_2;
2882 // The declaration DIE stack is a stack of the declaration context DIEs all
2883 // the way back to the compile unit. If a type "T" is declared inside a class
2884 // "B", and class "B" is declared inside a class "A" and class "A" is in a
2885 // namespace "lldb", and the namespace is in a compile unit, there will be a
2888 // [0] DW_TAG_class_type for "B"
2889 // [1] DW_TAG_class_type for "A"
2890 // [2] DW_TAG_namespace for "lldb"
2891 // [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file.
2893 // We grab both contexts and make sure that everything matches all the way
2894 // back to the compiler unit.
2896 // First lets grab the decl contexts for both DIEs
2897 decl_ctx_1 = die1.GetDeclContextDIEs();
2898 decl_ctx_2 = die2.GetDeclContextDIEs();
2899 // Make sure the context arrays have the same size, otherwise we are done
2900 const size_t count1 = decl_ctx_1.size();
2901 const size_t count2 = decl_ctx_2.size();
2902 if (count1 != count2)
2905 // Make sure the DW_TAG values match all the way back up the compile unit. If
2906 // they don't, then we are done.
2907 DWARFDIE decl_ctx_die1;
2908 DWARFDIE decl_ctx_die2;
2910 for (i = 0; i < count1; i++) {
2911 decl_ctx_die1 = decl_ctx_1[i];
2912 decl_ctx_die2 = decl_ctx_2[i];
2913 if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
2918 // Make sure the top item in the decl context die array is always
2919 // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then
2920 // something went wrong in the DWARFDIE::GetDeclContextDIEs()
2922 dw_tag_t cu_tag = decl_ctx_1[count1 - 1].Tag();
2923 UNUSED_IF_ASSERT_DISABLED(cu_tag);
2924 assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit);
2927 // Always skip the compile unit when comparing by only iterating up to "count
2928 // - 1". Here we compare the names as we go.
2929 for (i = 0; i < count1 - 1; i++) {
2930 decl_ctx_die1 = decl_ctx_1[i];
2931 decl_ctx_die2 = decl_ctx_2[i];
2932 const char *name1 = decl_ctx_die1.GetName();
2933 const char *name2 = decl_ctx_die2.GetName();
2934 // If the string was from a DW_FORM_strp, then the pointer will often be
2939 // Name pointers are not equal, so only compare the strings if both are not
2941 if (name1 && name2) {
2942 // If the strings don't compare, we are done...
2943 if (strcmp(name1, name2) != 0)
2946 // One name was NULL while the other wasn't
2950 // We made it through all of the checks and the declaration contexts are
2956 SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(const DWARFDIE &die) {
2959 if (die.GetName()) {
2960 const dw_tag_t tag = die.Tag();
2962 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups);
2964 GetObjectFile()->GetModule()->LogMessage(
2966 "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag={0}, "
2968 DW_TAG_value_to_name(tag), die.GetName());
2971 // Get the type system that we are looking to find a type for. We will
2972 // use this to ensure any matches we find are in a language that this
2973 // type system supports
2974 const LanguageType language = GetLanguage(*die.GetCU());
2975 TypeSystemSP type_system = nullptr;
2976 if (language != eLanguageTypeUnknown) {
2977 auto type_system_or_err = GetTypeSystemForLanguage(language);
2978 if (auto err = type_system_or_err.takeError()) {
2979 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2980 "Cannot get TypeSystem for language {1}: {0}",
2981 Language::GetNameForLanguageType(language));
2983 type_system = *type_system_or_err;
2987 // See comments below about -gsimple-template-names for why we attempt to
2988 // compute missing template parameter names.
2989 ConstString template_params;
2991 DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
2993 template_params = dwarf_ast->GetDIEClassTemplateParams(die);
2996 m_index->GetTypes(GetDWARFDeclContext(die), [&](DWARFDIE type_die) {
2997 // Make sure type_die's language matches the type system we are
2998 // looking for. We don't want to find a "Foo" type from Java if we
2999 // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
3001 !type_system->SupportsLanguage(GetLanguage(*type_die.GetCU())))
3003 bool try_resolving_type = false;
3005 // Don't try and resolve the DIE we are looking for with the DIE
3007 const dw_tag_t type_tag = type_die.Tag();
3008 // Make sure the tags match
3009 if (type_tag == tag) {
3010 // The tags match, lets try resolving this type
3011 try_resolving_type = true;
3013 // The tags don't match, but we need to watch our for a forward
3014 // declaration for a struct and ("struct foo") ends up being a
3015 // class ("class foo { ... };") or vice versa.
3017 case DW_TAG_class_type:
3018 // We had a "class foo", see if we ended up with a "struct foo
3020 try_resolving_type = (tag == DW_TAG_structure_type);
3022 case DW_TAG_structure_type:
3023 // We had a "struct foo", see if we ended up with a "class foo
3025 try_resolving_type = (tag == DW_TAG_class_type);
3028 // Tags don't match, don't event try to resolve using this type
3029 // whose name matches....
3034 if (!try_resolving_type) {
3036 GetObjectFile()->GetModule()->LogMessage(
3039 "FindDefinitionTypeForDWARFDeclContext(tag={0}, "
3040 "name='{1}') ignoring die={2:x16} ({3})",
3041 DW_TAG_value_to_name(tag), die.GetName(), type_die.GetOffset(),
3042 type_die.GetName());
3047 DWARFDeclContext type_dwarf_decl_ctx = GetDWARFDeclContext(type_die);
3050 GetObjectFile()->GetModule()->LogMessage(
3053 "FindDefinitionTypeForDWARFDeclContext(tag={0}, "
3054 "name='{1}') trying die={2:x16} ({3})",
3055 DW_TAG_value_to_name(tag), die.GetName(), type_die.GetOffset(),
3056 type_dwarf_decl_ctx.GetQualifiedName());
3059 // Make sure the decl contexts match all the way up
3060 if (GetDWARFDeclContext(die) != type_dwarf_decl_ctx)
3063 Type *resolved_type = ResolveType(type_die, false);
3064 if (!resolved_type || resolved_type == DIE_IS_BEING_PARSED)
3067 // With -gsimple-template-names, the DIE name may not contain the template
3068 // parameters. If the declaration has template parameters but doesn't
3069 // contain '<', check that the child template parameters match.
3070 if (template_params) {
3071 llvm::StringRef test_base_name =
3072 GetTypeForDIE(type_die)->GetBaseName().GetStringRef();
3073 auto i = test_base_name.find('<');
3075 // Full name from clang AST doesn't contain '<' so this type_die isn't
3076 // a template parameter, but we're expecting template parameters, so
3078 if (i == llvm::StringRef::npos)
3081 llvm::StringRef test_template_params =
3082 test_base_name.slice(i, test_base_name.size());
3083 // Bail if template parameters don't match.
3084 if (test_template_params != template_params.GetStringRef())
3088 type_sp = resolved_type->shared_from_this();
3095 TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die,
3096 bool *type_is_new_ptr) {
3100 auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU()));
3101 if (auto err = type_system_or_err.takeError()) {
3102 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
3103 "Unable to parse type: {0}");
3106 auto ts = *type_system_or_err;
3110 DWARFASTParser *dwarf_ast = ts->GetDWARFParser();
3114 TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, type_is_new_ptr);
3116 if (die.Tag() == DW_TAG_subprogram) {
3117 std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
3118 .GetScopeQualifiedName()
3120 if (scope_qualified_name.size()) {
3121 m_function_scope_qualified_name_map[scope_qualified_name].insert(
3130 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc,
3131 const DWARFDIE &orig_die,
3132 bool parse_siblings, bool parse_children) {
3133 size_t types_added = 0;
3134 DWARFDIE die = orig_die;
3137 const dw_tag_t tag = die.Tag();
3138 bool type_is_new = false;
3140 Tag dwarf_tag = static_cast<Tag>(tag);
3142 // TODO: Currently ParseTypeFromDWARF(...) which is called by ParseType(...)
3143 // does not handle DW_TAG_subrange_type. It is not clear if this is a bug or
3145 if (isType(dwarf_tag) && tag != DW_TAG_subrange_type)
3146 ParseType(sc, die, &type_is_new);
3151 if (parse_children && die.HasChildren()) {
3152 if (die.Tag() == DW_TAG_subprogram) {
3153 SymbolContext child_sc(sc);
3154 child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3155 types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3157 types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3161 die = die.GetSibling();
3168 size_t SymbolFileDWARF::ParseBlocksRecursive(Function &func) {
3169 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3170 CompileUnit *comp_unit = func.GetCompileUnit();
3171 lldbassert(comp_unit);
3173 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit);
3177 size_t functions_added = 0;
3178 const dw_offset_t function_die_offset = DIERef(func.GetID()).die_offset();
3179 DWARFDIE function_die =
3180 dwarf_cu->GetNonSkeletonUnit().GetDIE(function_die_offset);
3182 ParseBlocksRecursive(*comp_unit, &func.GetBlock(false), function_die,
3183 LLDB_INVALID_ADDRESS, 0);
3186 return functions_added;
3189 size_t SymbolFileDWARF::ParseTypes(CompileUnit &comp_unit) {
3190 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3191 size_t types_added = 0;
3192 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
3194 DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3195 if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3197 sc.comp_unit = &comp_unit;
3198 types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3205 size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) {
3206 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3207 if (sc.comp_unit != nullptr) {
3209 DWARFDIE function_die = GetDIE(sc.function->GetID());
3211 dw_addr_t func_lo_pc = LLDB_INVALID_ADDRESS;
3212 DWARFRangeList ranges = function_die.GetDIE()->GetAttributeAddressRanges(
3213 function_die.GetCU(), /*check_hi_lo_pc=*/true);
3214 if (!ranges.IsEmpty())
3215 func_lo_pc = ranges.GetMinRangeBase(0);
3216 if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3217 const size_t num_variables =
3218 ParseVariablesInFunctionContext(sc, function_die, func_lo_pc);
3220 // Let all blocks know they have parse all their variables
3221 sc.function->GetBlock(false).SetDidParseVariables(true, true);
3222 return num_variables;
3224 } else if (sc.comp_unit) {
3225 DWARFUnit *dwarf_cu = DebugInfo().GetUnitAtIndex(sc.comp_unit->GetID());
3227 if (dwarf_cu == nullptr)
3230 uint32_t vars_added = 0;
3231 VariableListSP variables(sc.comp_unit->GetVariableList(false));
3233 if (variables.get() == nullptr) {
3234 variables = std::make_shared<VariableList>();
3235 sc.comp_unit->SetVariableList(variables);
3237 m_index->GetGlobalVariables(*dwarf_cu, [&](DWARFDIE die) {
3238 VariableSP var_sp(ParseVariableDIECached(sc, die));
3240 variables->AddVariableIfUnique(var_sp);
3252 VariableSP SymbolFileDWARF::ParseVariableDIECached(const SymbolContext &sc,
3253 const DWARFDIE &die) {
3257 DIEToVariableSP &die_to_variable = die.GetDWARF()->GetDIEToVariable();
3259 VariableSP var_sp = die_to_variable[die.GetDIE()];
3263 var_sp = ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS);
3265 die_to_variable[die.GetDIE()] = var_sp;
3266 if (DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification))
3267 die_to_variable[spec_die.GetDIE()] = var_sp;
3272 /// Creates a DWARFExpressionList from an DW_AT_location form_value.
3273 static DWARFExpressionList GetExprListFromAtLocation(DWARFFormValue form_value,
3275 const DWARFDIE &die,
3276 const addr_t func_low_pc) {
3277 if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3278 const DWARFDataExtractor &data = die.GetData();
3280 uint32_t block_offset = form_value.BlockData() - data.GetDataStart();
3281 uint32_t block_length = form_value.Unsigned();
3282 return DWARFExpressionList(
3283 module, DataExtractor(data, block_offset, block_length), die.GetCU());
3286 DWARFExpressionList location_list(module, DWARFExpression(), die.GetCU());
3287 DataExtractor data = die.GetCU()->GetLocationData();
3288 dw_offset_t offset = form_value.Unsigned();
3289 if (form_value.Form() == DW_FORM_loclistx)
3290 offset = die.GetCU()->GetLoclistOffset(offset).value_or(-1);
3291 if (data.ValidOffset(offset)) {
3292 data = DataExtractor(data, offset, data.GetByteSize() - offset);
3293 const DWARFUnit *dwarf_cu = form_value.GetUnit();
3294 if (DWARFExpression::ParseDWARFLocationList(dwarf_cu, data, &location_list))
3295 location_list.SetFuncFileAddress(func_low_pc);
3298 return location_list;
3301 /// Creates a DWARFExpressionList from an DW_AT_const_value. This is either a
3302 /// block form, or a string, or a data form. For data forms, this returns an
3303 /// empty list, as we cannot initialize it properly without a SymbolFileType.
3304 static DWARFExpressionList
3305 GetExprListFromAtConstValue(DWARFFormValue form_value, ModuleSP module,
3306 const DWARFDIE &die) {
3307 const DWARFDataExtractor &debug_info_data = die.GetData();
3308 if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3309 // Retrieve the value as a block expression.
3310 uint32_t block_offset =
3311 form_value.BlockData() - debug_info_data.GetDataStart();
3312 uint32_t block_length = form_value.Unsigned();
3313 return DWARFExpressionList(
3314 module, DataExtractor(debug_info_data, block_offset, block_length),
3317 if (const char *str = form_value.AsCString())
3318 return DWARFExpressionList(module,
3319 DataExtractor(str, strlen(str) + 1,
3320 die.GetCU()->GetByteOrder(),
3321 die.GetCU()->GetAddressByteSize()),
3323 return DWARFExpressionList(module, DWARFExpression(), die.GetCU());
3326 /// Global variables that are not initialized may have their address set to
3327 /// zero. Since multiple variables may have this address, we cannot apply the
3328 /// OSO relink address approach we normally use.
3329 /// However, the executable will have a matching symbol with a good address;
3330 /// this function attempts to find the correct address by looking into the
3331 /// executable's symbol table. If it succeeds, the expr_list is updated with
3332 /// the new address and the executable's symbol is returned.
3333 static Symbol *fixupExternalAddrZeroVariable(
3334 SymbolFileDWARFDebugMap &debug_map_symfile, llvm::StringRef name,
3335 DWARFExpressionList &expr_list, const DWARFDIE &die) {
3336 ObjectFile *debug_map_objfile = debug_map_symfile.GetObjectFile();
3337 if (!debug_map_objfile)
3340 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3341 if (!debug_map_symtab)
3343 Symbol *exe_symbol = debug_map_symtab->FindFirstSymbolWithNameAndType(
3344 ConstString(name), eSymbolTypeData, Symtab::eDebugYes,
3345 Symtab::eVisibilityExtern);
3346 if (!exe_symbol || !exe_symbol->ValueIsAddress())
3348 const addr_t exe_file_addr = exe_symbol->GetAddressRef().GetFileAddress();
3349 if (exe_file_addr == LLDB_INVALID_ADDRESS)
3352 DWARFExpression *location = expr_list.GetMutableExpressionAtAddress();
3353 if (location->Update_DW_OP_addr(die.GetCU(), exe_file_addr))
3358 VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc,
3359 const DWARFDIE &die,
3360 const lldb::addr_t func_low_pc) {
3361 if (die.GetDWARF() != this)
3362 return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3367 const dw_tag_t tag = die.Tag();
3368 ModuleSP module = GetObjectFile()->GetModule();
3370 if (tag != DW_TAG_variable && tag != DW_TAG_constant &&
3371 (tag != DW_TAG_formal_parameter || !sc.function))
3374 DWARFAttributes attributes = die.GetAttributes();
3375 const char *name = nullptr;
3376 const char *mangled = nullptr;
3378 DWARFFormValue type_die_form;
3379 bool is_external = false;
3380 bool is_artificial = false;
3381 DWARFFormValue const_value_form, location_form;
3382 Variable::RangeList scope_ranges;
3384 for (size_t i = 0; i < attributes.Size(); ++i) {
3385 dw_attr_t attr = attributes.AttributeAtIndex(i);
3386 DWARFFormValue form_value;
3388 if (!attributes.ExtractFormValueAtIndex(i, form_value))
3391 case DW_AT_decl_file:
3393 attributes.CompileUnitAtIndex(i)->GetFile(form_value.Unsigned()));
3395 case DW_AT_decl_line:
3396 decl.SetLine(form_value.Unsigned());
3398 case DW_AT_decl_column:
3399 decl.SetColumn(form_value.Unsigned());
3402 name = form_value.AsCString();
3404 case DW_AT_linkage_name:
3405 case DW_AT_MIPS_linkage_name:
3406 mangled = form_value.AsCString();
3409 type_die_form = form_value;
3411 case DW_AT_external:
3412 is_external = form_value.Boolean();
3414 case DW_AT_const_value:
3415 const_value_form = form_value;
3417 case DW_AT_location:
3418 location_form = form_value;
3420 case DW_AT_start_scope:
3421 // TODO: Implement this.
3423 case DW_AT_artificial:
3424 is_artificial = form_value.Boolean();
3426 case DW_AT_declaration:
3427 case DW_AT_description:
3428 case DW_AT_endianity:
3430 case DW_AT_specification:
3431 case DW_AT_visibility:
3433 case DW_AT_abstract_origin:
3439 // Prefer DW_AT_location over DW_AT_const_value. Both can be emitted e.g.
3440 // for static constexpr member variables -- DW_AT_const_value will be
3441 // present in the class declaration and DW_AT_location in the DIE defining
3443 bool location_is_const_value_data =
3444 const_value_form.IsValid() && !location_form.IsValid();
3446 DWARFExpressionList location_list = [&] {
3447 if (location_form.IsValid())
3448 return GetExprListFromAtLocation(location_form, module, die, func_low_pc);
3449 if (const_value_form.IsValid())
3450 return GetExprListFromAtConstValue(const_value_form, module, die);
3451 return DWARFExpressionList(module, DWARFExpression(), die.GetCU());
3454 const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3455 const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3456 const dw_tag_t parent_tag = sc_parent_die.Tag();
3457 bool is_static_member = (parent_tag == DW_TAG_compile_unit ||
3458 parent_tag == DW_TAG_partial_unit) &&
3459 (parent_context_die.Tag() == DW_TAG_class_type ||
3460 parent_context_die.Tag() == DW_TAG_structure_type);
3462 ValueType scope = eValueTypeInvalid;
3463 SymbolContextScope *symbol_context_scope = nullptr;
3465 bool has_explicit_mangled = mangled != nullptr;
3467 // LLDB relies on the mangled name (DW_TAG_linkage_name or
3468 // DW_AT_MIPS_linkage_name) to generate fully qualified names
3469 // of global variables with commands like "frame var j". For
3470 // example, if j were an int variable holding a value 4 and
3471 // declared in a namespace B which in turn is contained in a
3472 // namespace A, the command "frame var j" returns
3473 // "(int) A::B::j = 4".
3474 // If the compiler does not emit a linkage name, we should be
3475 // able to generate a fully qualified name from the
3476 // declaration context.
3477 if ((parent_tag == DW_TAG_compile_unit ||
3478 parent_tag == DW_TAG_partial_unit) &&
3479 Language::LanguageIsCPlusPlus(GetLanguage(*die.GetCU())))
3481 GetDWARFDeclContext(die).GetQualifiedNameAsConstString().GetCString();
3484 if (tag == DW_TAG_formal_parameter)
3485 scope = eValueTypeVariableArgument;
3487 // DWARF doesn't specify if a DW_TAG_variable is a local, global
3488 // or static variable, so we have to do a little digging:
3489 // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3490 // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3491 // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3492 // Clang likes to combine small global variables into the same symbol
3493 // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3494 // so we need to look through the whole expression.
3495 bool has_explicit_location = location_form.IsValid();
3496 bool is_static_lifetime =
3497 has_explicit_mangled ||
3498 (has_explicit_location && !location_list.IsValid());
3499 // Check if the location has a DW_OP_addr with any address value...
3500 lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3501 if (!location_is_const_value_data) {
3502 bool op_error = false;
3503 const DWARFExpression* location = location_list.GetAlwaysValidExpr();
3505 location_DW_OP_addr =
3506 location->GetLocation_DW_OP_addr(location_form.GetUnit(), op_error);
3509 location->DumpLocation(&strm, eDescriptionLevelFull, nullptr);
3510 GetObjectFile()->GetModule()->ReportError(
3511 "{0:x16}: {1} has an invalid location: {2}", die.GetOffset(),
3512 die.GetTagAsCString(), strm.GetData());
3514 if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
3515 is_static_lifetime = true;
3517 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
3518 if (debug_map_symfile)
3519 // Set the module of the expression to the linked module
3520 // instead of the object file so the relocated address can be
3522 location_list.SetModule(debug_map_symfile->GetObjectFile()->GetModule());
3524 if (is_static_lifetime) {
3526 scope = eValueTypeVariableGlobal;
3528 scope = eValueTypeVariableStatic;
3530 if (debug_map_symfile) {
3531 bool linked_oso_file_addr = false;
3533 if (is_external && location_DW_OP_addr == 0) {
3534 if (Symbol *exe_symbol = fixupExternalAddrZeroVariable(
3535 *debug_map_symfile, mangled ? mangled : name, location_list,
3537 linked_oso_file_addr = true;
3538 symbol_context_scope = exe_symbol;
3542 if (!linked_oso_file_addr) {
3543 // The DW_OP_addr is not zero, but it contains a .o file address
3544 // which needs to be linked up correctly.
3545 const lldb::addr_t exe_file_addr =
3546 debug_map_symfile->LinkOSOFileAddress(this, location_DW_OP_addr);
3547 if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3548 // Update the file address for this variable
3549 DWARFExpression *location =
3550 location_list.GetMutableExpressionAtAddress();
3551 location->Update_DW_OP_addr(die.GetCU(), exe_file_addr);
3553 // Variable didn't make it into the final executable
3559 if (location_is_const_value_data &&
3560 die.GetDIE()->IsGlobalOrStaticScopeVariable())
3561 scope = eValueTypeVariableStatic;
3563 scope = eValueTypeVariableLocal;
3564 if (debug_map_symfile) {
3565 // We need to check for TLS addresses that we need to fixup
3566 if (location_list.ContainsThreadLocalStorage()) {
3567 location_list.LinkThreadLocalStorage(
3568 debug_map_symfile->GetObjectFile()->GetModule(),
3569 [this, debug_map_symfile](
3570 lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
3571 return debug_map_symfile->LinkOSOFileAddress(
3572 this, unlinked_file_addr);
3574 scope = eValueTypeVariableThreadLocal;
3581 if (symbol_context_scope == nullptr) {
3582 switch (parent_tag) {
3583 case DW_TAG_subprogram:
3584 case DW_TAG_inlined_subroutine:
3585 case DW_TAG_lexical_block:
3587 symbol_context_scope =
3588 sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID());
3589 if (symbol_context_scope == nullptr)
3590 symbol_context_scope = sc.function;
3595 symbol_context_scope = sc.comp_unit;
3600 if (!symbol_context_scope) {
3601 // Not ready to parse this variable yet. It might be a global or static
3602 // variable that is in a function scope and the function in the symbol
3603 // context wasn't filled in yet
3607 auto type_sp = std::make_shared<SymbolFileType>(
3608 *this, type_die_form.Reference().GetID());
3610 bool use_type_size_for_value =
3611 location_is_const_value_data &&
3612 DWARFFormValue::IsDataForm(const_value_form.Form());
3613 if (use_type_size_for_value && type_sp->GetType()) {
3614 DWARFExpression *location = location_list.GetMutableExpressionAtAddress();
3615 location->UpdateValue(const_value_form.Unsigned(),
3616 type_sp->GetType()->GetByteSize(nullptr).value_or(0),
3617 die.GetCU()->GetAddressByteSize());
3620 return std::make_shared<Variable>(
3621 die.GetID(), name, mangled, type_sp, scope, symbol_context_scope,
3622 scope_ranges, &decl, location_list, is_external, is_artificial,
3623 location_is_const_value_data, is_static_member);
3627 SymbolFileDWARF::FindBlockContainingSpecification(
3628 const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
3629 // Give the concrete function die specified by "func_die_offset", find the
3630 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3631 // to "spec_block_die_offset"
3632 return FindBlockContainingSpecification(DebugInfo().GetDIE(func_die_ref),
3633 spec_block_die_offset);
3637 SymbolFileDWARF::FindBlockContainingSpecification(
3638 const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
3640 switch (die.Tag()) {
3641 case DW_TAG_subprogram:
3642 case DW_TAG_inlined_subroutine:
3643 case DW_TAG_lexical_block: {
3644 if (die.GetReferencedDIE(DW_AT_specification).GetOffset() ==
3645 spec_block_die_offset)
3648 if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() ==
3649 spec_block_die_offset)
3656 // Give the concrete function die specified by "func_die_offset", find the
3657 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3658 // to "spec_block_die_offset"
3659 for (DWARFDIE child_die : die.children()) {
3660 DWARFDIE result_die =
3661 FindBlockContainingSpecification(child_die, spec_block_die_offset);
3670 void SymbolFileDWARF::ParseAndAppendGlobalVariable(
3671 const SymbolContext &sc, const DWARFDIE &die,
3672 VariableList &cc_variable_list) {
3676 dw_tag_t tag = die.Tag();
3677 if (tag != DW_TAG_variable && tag != DW_TAG_constant)
3680 // Check to see if we have already parsed this variable or constant?
3681 VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
3683 cc_variable_list.AddVariableIfUnique(var_sp);
3687 // We haven't parsed the variable yet, lets do that now. Also, let us include
3688 // the variable in the relevant compilation unit's variable list, if it
3690 VariableListSP variable_list_sp;
3691 DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3692 dw_tag_t parent_tag = sc_parent_die.Tag();
3693 switch (parent_tag) {
3694 case DW_TAG_compile_unit:
3695 case DW_TAG_partial_unit:
3696 if (sc.comp_unit != nullptr) {
3697 variable_list_sp = sc.comp_unit->GetVariableList(false);
3699 GetObjectFile()->GetModule()->ReportError(
3700 "parent {0:x8} {1} with no valid compile unit in "
3701 "symbol context for {2:x8} {3}.\n",
3702 sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(), die.GetID(),
3703 die.GetTagAsCString());
3709 GetObjectFile()->GetModule()->ReportError(
3710 "didn't find appropriate parent DIE for variable list for {0:x8} "
3712 die.GetID(), die.GetTagAsCString());
3716 var_sp = ParseVariableDIECached(sc, die);
3720 cc_variable_list.AddVariableIfUnique(var_sp);
3721 if (variable_list_sp)
3722 variable_list_sp->AddVariableIfUnique(var_sp);
3726 SymbolFileDWARF::MergeBlockAbstractParameters(const DWARFDIE &block_die,
3727 DIEArray &&variable_dies) {
3728 // DW_TAG_inline_subroutine objects may omit DW_TAG_formal_parameter in
3729 // instances of the function when they are unused (i.e., the parameter's
3730 // location list would be empty). The current DW_TAG_inline_subroutine may
3731 // refer to another DW_TAG_subprogram that might actually have the definitions
3732 // of the parameters and we need to include these so they show up in the
3733 // variables for this function (for example, in a stack trace). Let us try to
3734 // find the abstract subprogram that might contain the parameter definitions
3735 // and merge with the concrete parameters.
3737 // Nothing to merge if the block is not an inlined function.
3738 if (block_die.Tag() != DW_TAG_inlined_subroutine) {
3739 return std::move(variable_dies);
3742 // Nothing to merge if the block does not have abstract parameters.
3743 DWARFDIE abs_die = block_die.GetReferencedDIE(DW_AT_abstract_origin);
3744 if (!abs_die || abs_die.Tag() != DW_TAG_subprogram ||
3745 !abs_die.HasChildren()) {
3746 return std::move(variable_dies);
3749 // For each abstract parameter, if we have its concrete counterpart, insert
3750 // it. Otherwise, insert the abstract parameter.
3751 DIEArray::iterator concrete_it = variable_dies.begin();
3752 DWARFDIE abstract_child = abs_die.GetFirstChild();
3754 bool did_merge_abstract = false;
3755 for (; abstract_child; abstract_child = abstract_child.GetSibling()) {
3756 if (abstract_child.Tag() == DW_TAG_formal_parameter) {
3757 if (concrete_it == variable_dies.end() ||
3758 GetDIE(*concrete_it).Tag() != DW_TAG_formal_parameter) {
3759 // We arrived at the end of the concrete parameter list, so all
3760 // the remaining abstract parameters must have been omitted.
3761 // Let us insert them to the merged list here.
3762 merged.push_back(*abstract_child.GetDIERef());
3763 did_merge_abstract = true;
3767 DWARFDIE origin_of_concrete =
3768 GetDIE(*concrete_it).GetReferencedDIE(DW_AT_abstract_origin);
3769 if (origin_of_concrete == abstract_child) {
3770 // The current abstract parameter is the origin of the current
3771 // concrete parameter, just push the concrete parameter.
3772 merged.push_back(*concrete_it);
3775 // Otherwise, the parameter must have been omitted from the concrete
3776 // function, so insert the abstract one.
3777 merged.push_back(*abstract_child.GetDIERef());
3778 did_merge_abstract = true;
3783 // Shortcut if no merging happened.
3784 if (!did_merge_abstract)
3785 return std::move(variable_dies);
3787 // We inserted all the abstract parameters (or their concrete counterparts).
3788 // Let us insert all the remaining concrete variables to the merged list.
3789 // During the insertion, let us check there are no remaining concrete
3790 // formal parameters. If that's the case, then just bailout from the merge -
3791 // the variable list is malformed.
3792 for (; concrete_it != variable_dies.end(); ++concrete_it) {
3793 if (GetDIE(*concrete_it).Tag() == DW_TAG_formal_parameter) {
3794 return std::move(variable_dies);
3796 merged.push_back(*concrete_it);
3801 size_t SymbolFileDWARF::ParseVariablesInFunctionContext(
3802 const SymbolContext &sc, const DWARFDIE &die,
3803 const lldb::addr_t func_low_pc) {
3804 if (!die || !sc.function)
3807 DIEArray dummy_block_variables; // The recursive call should not add anything
3808 // to this vector because |die| should be a
3809 // subprogram, so all variables will be added
3810 // to the subprogram's list.
3811 return ParseVariablesInFunctionContextRecursive(sc, die, func_low_pc,
3812 dummy_block_variables);
3815 // This method parses all the variables in the blocks in the subtree of |die|,
3816 // and inserts them to the variable list for all the nested blocks.
3817 // The uninserted variables for the current block are accumulated in
3819 size_t SymbolFileDWARF::ParseVariablesInFunctionContextRecursive(
3820 const lldb_private::SymbolContext &sc, const DWARFDIE &die,
3821 lldb::addr_t func_low_pc, DIEArray &accumulator) {
3822 size_t vars_added = 0;
3823 dw_tag_t tag = die.Tag();
3825 if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3826 (tag == DW_TAG_formal_parameter)) {
3827 accumulator.push_back(*die.GetDIERef());
3831 case DW_TAG_subprogram:
3832 case DW_TAG_inlined_subroutine:
3833 case DW_TAG_lexical_block: {
3834 // If we start a new block, compute a new block variable list and recurse.
3836 sc.function->GetBlock(/*can_create=*/true).FindBlockByID(die.GetID());
3837 if (block == nullptr) {
3838 // This must be a specification or abstract origin with a
3839 // concrete block counterpart in the current function. We need
3840 // to find the concrete block so we can correctly add the
3842 const DWARFDIE concrete_block_die = FindBlockContainingSpecification(
3843 GetDIE(sc.function->GetID()), die.GetOffset());
3844 if (concrete_block_die)
3845 block = sc.function->GetBlock(/*can_create=*/true)
3846 .FindBlockByID(concrete_block_die.GetID());
3849 if (block == nullptr)
3852 const bool can_create = false;
3853 VariableListSP block_variable_list_sp =
3854 block->GetBlockVariableList(can_create);
3855 if (block_variable_list_sp.get() == nullptr) {
3856 block_variable_list_sp = std::make_shared<VariableList>();
3857 block->SetVariableList(block_variable_list_sp);
3860 DIEArray block_variables;
3861 for (DWARFDIE child = die.GetFirstChild(); child;
3862 child = child.GetSibling()) {
3863 vars_added += ParseVariablesInFunctionContextRecursive(
3864 sc, child, func_low_pc, block_variables);
3867 MergeBlockAbstractParameters(die, std::move(block_variables));
3868 vars_added += PopulateBlockVariableList(*block_variable_list_sp, sc,
3869 block_variables, func_low_pc);
3874 // Recurse to children with the same variable accumulator.
3875 for (DWARFDIE child = die.GetFirstChild(); child;
3876 child = child.GetSibling()) {
3877 vars_added += ParseVariablesInFunctionContextRecursive(
3878 sc, child, func_low_pc, accumulator);
3886 size_t SymbolFileDWARF::PopulateBlockVariableList(
3887 VariableList &variable_list, const lldb_private::SymbolContext &sc,
3888 llvm::ArrayRef<DIERef> variable_dies, lldb::addr_t func_low_pc) {
3889 // Parse the variable DIEs and insert them to the list.
3890 for (auto &die : variable_dies) {
3891 if (VariableSP var_sp = ParseVariableDIE(sc, GetDIE(die), func_low_pc)) {
3892 variable_list.AddVariableIfUnique(var_sp);
3895 return variable_dies.size();
3898 /// Collect call site parameters in a DW_TAG_call_site DIE.
3899 static CallSiteParameterArray
3900 CollectCallSiteParameters(ModuleSP module, DWARFDIE call_site_die) {
3901 CallSiteParameterArray parameters;
3902 for (DWARFDIE child : call_site_die.children()) {
3903 if (child.Tag() != DW_TAG_call_site_parameter &&
3904 child.Tag() != DW_TAG_GNU_call_site_parameter)
3907 std::optional<DWARFExpressionList> LocationInCallee;
3908 std::optional<DWARFExpressionList> LocationInCaller;
3910 DWARFAttributes attributes = child.GetAttributes();
3912 // Parse the location at index \p attr_index within this call site parameter
3913 // DIE, or return std::nullopt on failure.
3914 auto parse_simple_location =
3915 [&](int attr_index) -> std::optional<DWARFExpressionList> {
3916 DWARFFormValue form_value;
3917 if (!attributes.ExtractFormValueAtIndex(attr_index, form_value))
3919 if (!DWARFFormValue::IsBlockForm(form_value.Form()))
3921 auto data = child.GetData();
3922 uint32_t block_offset = form_value.BlockData() - data.GetDataStart();
3923 uint32_t block_length = form_value.Unsigned();
3924 return DWARFExpressionList(
3925 module, DataExtractor(data, block_offset, block_length),
3929 for (size_t i = 0; i < attributes.Size(); ++i) {
3930 dw_attr_t attr = attributes.AttributeAtIndex(i);
3931 if (attr == DW_AT_location)
3932 LocationInCallee = parse_simple_location(i);
3933 if (attr == DW_AT_call_value || attr == DW_AT_GNU_call_site_value)
3934 LocationInCaller = parse_simple_location(i);
3937 if (LocationInCallee && LocationInCaller) {
3938 CallSiteParameter param = {*LocationInCallee, *LocationInCaller};
3939 parameters.push_back(param);
3945 /// Collect call graph edges present in a function DIE.
3946 std::vector<std::unique_ptr<lldb_private::CallEdge>>
3947 SymbolFileDWARF::CollectCallEdges(ModuleSP module, DWARFDIE function_die) {
3948 // Check if the function has a supported call site-related attribute.
3949 // TODO: In the future it may be worthwhile to support call_all_source_calls.
3950 bool has_call_edges =
3951 function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0) ||
3952 function_die.GetAttributeValueAsUnsigned(DW_AT_GNU_all_call_sites, 0);
3953 if (!has_call_edges)
3956 Log *log = GetLog(LLDBLog::Step);
3957 LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}",
3958 function_die.GetPubname());
3960 // Scan the DIE for TAG_call_site entries.
3961 // TODO: A recursive scan of all blocks in the subprogram is needed in order
3962 // to be DWARF5-compliant. This may need to be done lazily to be performant.
3963 // For now, assume that all entries are nested directly under the subprogram
3964 // (this is the kind of DWARF LLVM produces) and parse them eagerly.
3965 std::vector<std::unique_ptr<CallEdge>> call_edges;
3966 for (DWARFDIE child : function_die.children()) {
3967 if (child.Tag() != DW_TAG_call_site && child.Tag() != DW_TAG_GNU_call_site)
3970 std::optional<DWARFDIE> call_origin;
3971 std::optional<DWARFExpressionList> call_target;
3972 addr_t return_pc = LLDB_INVALID_ADDRESS;
3973 addr_t call_inst_pc = LLDB_INVALID_ADDRESS;
3974 addr_t low_pc = LLDB_INVALID_ADDRESS;
3975 bool tail_call = false;
3977 // Second DW_AT_low_pc may come from DW_TAG_subprogram referenced by
3978 // DW_TAG_GNU_call_site's DW_AT_abstract_origin overwriting our 'low_pc'.
3979 // So do not inherit attributes from DW_AT_abstract_origin.
3980 DWARFAttributes attributes = child.GetAttributes(DWARFDIE::Recurse::no);
3981 for (size_t i = 0; i < attributes.Size(); ++i) {
3982 DWARFFormValue form_value;
3983 if (!attributes.ExtractFormValueAtIndex(i, form_value)) {
3984 LLDB_LOG(log, "CollectCallEdges: Could not extract TAG_call_site form");
3988 dw_attr_t attr = attributes.AttributeAtIndex(i);
3990 if (attr == DW_AT_call_tail_call || attr == DW_AT_GNU_tail_call)
3991 tail_call = form_value.Boolean();
3993 // Extract DW_AT_call_origin (the call target's DIE).
3994 if (attr == DW_AT_call_origin || attr == DW_AT_abstract_origin) {
3995 call_origin = form_value.Reference();
3996 if (!call_origin->IsValid()) {
3997 LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}",
3998 function_die.GetPubname());
4003 if (attr == DW_AT_low_pc)
4004 low_pc = form_value.Address();
4006 // Extract DW_AT_call_return_pc (the PC the call returns to) if it's
4007 // available. It should only ever be unavailable for tail call edges, in
4008 // which case use LLDB_INVALID_ADDRESS.
4009 if (attr == DW_AT_call_return_pc)
4010 return_pc = form_value.Address();
4012 // Extract DW_AT_call_pc (the PC at the call/branch instruction). It
4013 // should only ever be unavailable for non-tail calls, in which case use
4014 // LLDB_INVALID_ADDRESS.
4015 if (attr == DW_AT_call_pc)
4016 call_inst_pc = form_value.Address();
4018 // Extract DW_AT_call_target (the location of the address of the indirect
4020 if (attr == DW_AT_call_target || attr == DW_AT_GNU_call_site_target) {
4021 if (!DWARFFormValue::IsBlockForm(form_value.Form())) {
4023 "CollectCallEdges: AT_call_target does not have block form");
4027 auto data = child.GetData();
4028 uint32_t block_offset = form_value.BlockData() - data.GetDataStart();
4029 uint32_t block_length = form_value.Unsigned();
4030 call_target = DWARFExpressionList(
4031 module, DataExtractor(data, block_offset, block_length),
4035 if (!call_origin && !call_target) {
4036 LLDB_LOG(log, "CollectCallEdges: call site without any call target");
4040 addr_t caller_address;
4041 CallEdge::AddrType caller_address_type;
4042 if (return_pc != LLDB_INVALID_ADDRESS) {
4043 caller_address = return_pc;
4044 caller_address_type = CallEdge::AddrType::AfterCall;
4045 } else if (low_pc != LLDB_INVALID_ADDRESS) {
4046 caller_address = low_pc;
4047 caller_address_type = CallEdge::AddrType::AfterCall;
4048 } else if (call_inst_pc != LLDB_INVALID_ADDRESS) {
4049 caller_address = call_inst_pc;
4050 caller_address_type = CallEdge::AddrType::Call;
4052 LLDB_LOG(log, "CollectCallEdges: No caller address");
4055 // Adjust any PC forms. It needs to be fixed up if the main executable
4056 // contains a debug map (i.e. pointers to object files), because we need a
4057 // file address relative to the executable's text section.
4058 caller_address = FixupAddress(caller_address);
4060 // Extract call site parameters.
4061 CallSiteParameterArray parameters =
4062 CollectCallSiteParameters(module, child);
4064 std::unique_ptr<CallEdge> edge;
4067 "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x}) "
4069 call_origin->GetPubname(), return_pc, call_inst_pc);
4070 edge = std::make_unique<DirectCallEdge>(
4071 call_origin->GetMangledName(), caller_address_type, caller_address,
4072 tail_call, std::move(parameters));
4075 StreamString call_target_desc;
4076 call_target->GetDescription(&call_target_desc, eDescriptionLevelBrief,
4078 LLDB_LOG(log, "CollectCallEdges: Found indirect call target: {0}",
4079 call_target_desc.GetString());
4081 edge = std::make_unique<IndirectCallEdge>(
4082 *call_target, caller_address_type, caller_address, tail_call,
4083 std::move(parameters));
4086 if (log && parameters.size()) {
4087 for (const CallSiteParameter ¶m : parameters) {
4088 StreamString callee_loc_desc, caller_loc_desc;
4089 param.LocationInCallee.GetDescription(&callee_loc_desc,
4090 eDescriptionLevelBrief, nullptr);
4091 param.LocationInCaller.GetDescription(&caller_loc_desc,
4092 eDescriptionLevelBrief, nullptr);
4093 LLDB_LOG(log, "CollectCallEdges: \tparam: {0} => {1}",
4094 callee_loc_desc.GetString(), caller_loc_desc.GetString());
4098 call_edges.push_back(std::move(edge));
4103 std::vector<std::unique_ptr<lldb_private::CallEdge>>
4104 SymbolFileDWARF::ParseCallEdgesInFunction(lldb_private::UserID func_id) {
4105 // ParseCallEdgesInFunction must be called at the behest of an exclusively
4106 // locked lldb::Function instance. Storage for parsed call edges is owned by
4107 // the lldb::Function instance: locking at the SymbolFile level would be too
4108 // late, because the act of storing results from ParseCallEdgesInFunction
4110 DWARFDIE func_die = GetDIE(func_id.GetID());
4111 if (func_die.IsValid())
4112 return CollectCallEdges(GetObjectFile()->GetModule(), func_die);
4116 void SymbolFileDWARF::Dump(lldb_private::Stream &s) {
4117 SymbolFileCommon::Dump(s);
4121 void SymbolFileDWARF::DumpClangAST(Stream &s) {
4122 auto ts_or_err = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
4125 auto ts = *ts_or_err;
4126 TypeSystemClang *clang = llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
4129 clang->Dump(s.AsRawOstream());
4132 SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() {
4133 if (m_debug_map_symfile == nullptr) {
4134 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
4136 m_debug_map_symfile = llvm::cast<SymbolFileDWARFDebugMap>(
4137 module_sp->GetSymbolFile()->GetBackingSymbolFile());
4140 return m_debug_map_symfile;
4143 const std::shared_ptr<SymbolFileDWARFDwo> &SymbolFileDWARF::GetDwpSymbolFile() {
4144 llvm::call_once(m_dwp_symfile_once_flag, [this]() {
4145 ModuleSpec module_spec;
4146 module_spec.GetFileSpec() = m_objfile_sp->GetFileSpec();
4147 module_spec.GetSymbolFileSpec() =
4148 FileSpec(m_objfile_sp->GetModule()->GetFileSpec().GetPath() + ".dwp");
4150 FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths();
4151 FileSpec dwp_filespec =
4152 Symbols::LocateExecutableSymbolFile(module_spec, search_paths);
4153 if (FileSystem::Instance().Exists(dwp_filespec)) {
4154 DataBufferSP dwp_file_data_sp;
4155 lldb::offset_t dwp_file_data_offset = 0;
4156 ObjectFileSP dwp_obj_file = ObjectFile::FindPlugin(
4157 GetObjectFile()->GetModule(), &dwp_filespec, 0,
4158 FileSystem::Instance().GetByteSize(dwp_filespec), dwp_file_data_sp,
4159 dwp_file_data_offset);
4162 m_dwp_symfile = std::make_shared<SymbolFileDWARFDwo>(
4163 *this, dwp_obj_file, DIERef::k_file_index_mask);
4166 return m_dwp_symfile;
4169 llvm::Expected<lldb::TypeSystemSP>
4170 SymbolFileDWARF::GetTypeSystem(DWARFUnit &unit) {
4171 return unit.GetSymbolFileDWARF().GetTypeSystemForLanguage(GetLanguage(unit));
4174 DWARFASTParser *SymbolFileDWARF::GetDWARFParser(DWARFUnit &unit) {
4175 auto type_system_or_err = GetTypeSystem(unit);
4176 if (auto err = type_system_or_err.takeError()) {
4177 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
4178 "Unable to get DWARFASTParser: {0}");
4181 if (auto ts = *type_system_or_err)
4182 return ts->GetDWARFParser();
4186 CompilerDecl SymbolFileDWARF::GetDecl(const DWARFDIE &die) {
4187 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
4188 return dwarf_ast->GetDeclForUIDFromDWARF(die);
4189 return CompilerDecl();
4192 CompilerDeclContext SymbolFileDWARF::GetDeclContext(const DWARFDIE &die) {
4193 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
4194 return dwarf_ast->GetDeclContextForUIDFromDWARF(die);
4195 return CompilerDeclContext();
4199 SymbolFileDWARF::GetContainingDeclContext(const DWARFDIE &die) {
4200 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
4201 return dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
4202 return CompilerDeclContext();
4205 DWARFDeclContext SymbolFileDWARF::GetDWARFDeclContext(const DWARFDIE &die) {
4208 DWARFDeclContext dwarf_decl_ctx =
4209 die.GetDIE()->GetDWARFDeclContext(die.GetCU());
4210 return dwarf_decl_ctx;
4213 LanguageType SymbolFileDWARF::LanguageTypeFromDWARF(uint64_t val) {
4214 // Note: user languages between lo_user and hi_user must be handled
4217 case DW_LANG_Mips_Assembler:
4218 return eLanguageTypeMipsAssembler;
4220 return static_cast<LanguageType>(val);
4224 LanguageType SymbolFileDWARF::GetLanguage(DWARFUnit &unit) {
4225 return LanguageTypeFromDWARF(unit.GetDWARFLanguageType());
4228 LanguageType SymbolFileDWARF::GetLanguageFamily(DWARFUnit &unit) {
4229 auto lang = (llvm::dwarf::SourceLanguage)unit.GetDWARFLanguageType();
4230 if (llvm::dwarf::isCPlusPlus(lang))
4231 lang = DW_LANG_C_plus_plus;
4232 return LanguageTypeFromDWARF(lang);
4235 StatsDuration::Duration SymbolFileDWARF::GetDebugInfoIndexTime() {
4237 return m_index->GetIndexTime();
4241 Status SymbolFileDWARF::CalculateFrameVariableError(StackFrame &frame) {
4242 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
4243 CompileUnit *cu = frame.GetSymbolContext(eSymbolContextCompUnit).comp_unit;
4247 DWARFCompileUnit *dwarf_cu = GetDWARFCompileUnit(cu);
4251 // Check if we have a skeleton compile unit that had issues trying to load
4252 // its .dwo/.dwp file. First pares the Unit DIE to make sure we see any .dwo
4254 dwarf_cu->ExtractUnitDIEIfNeeded();
4255 const Status &dwo_error = dwarf_cu->GetDwoError();
4256 if (dwo_error.Fail())
4259 // Don't return an error for assembly files as they typically don't have
4260 // varaible information.
4261 if (dwarf_cu->GetDWARFLanguageType() == DW_LANG_Mips_Assembler)
4264 // Check if this compile unit has any variable DIEs. If it doesn't then there
4265 // is not variable information for the entire compile unit.
4266 if (dwarf_cu->HasAny({DW_TAG_variable, DW_TAG_formal_parameter}))
4269 return Status("no variable information is available in debug info for this "
4273 void SymbolFileDWARF::GetCompileOptions(
4274 std::unordered_map<lldb::CompUnitSP, lldb_private::Args> &args) {
4276 const uint32_t num_compile_units = GetNumCompileUnits();
4278 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
4279 lldb::CompUnitSP comp_unit = GetCompileUnitAtIndex(cu_idx);
4283 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit.get());
4287 const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
4291 const char *flags = die.GetAttributeValueAsString(DW_AT_APPLE_flags, NULL);
4295 args.insert({comp_unit, Args(flags)});