1 //===-- SymbolFileDWARF.cpp ------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "SymbolFileDWARF.h"
11 #include "llvm/ADT/Optional.h"
12 #include "llvm/Support/Casting.h"
13 #include "llvm/Support/Threading.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleList.h"
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Core/Section.h"
20 #include "lldb/Core/StreamFile.h"
21 #include "lldb/Core/Value.h"
22 #include "lldb/Utility/ArchSpec.h"
23 #include "lldb/Utility/RegularExpression.h"
24 #include "lldb/Utility/Scalar.h"
25 #include "lldb/Utility/StreamString.h"
26 #include "lldb/Utility/Timer.h"
28 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
29 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
31 #include "lldb/Host/FileSystem.h"
32 #include "lldb/Host/Host.h"
34 #include "lldb/Interpreter/OptionValueFileSpecList.h"
35 #include "lldb/Interpreter/OptionValueProperties.h"
37 #include "lldb/Symbol/Block.h"
38 #include "lldb/Symbol/ClangASTContext.h"
39 #include "lldb/Symbol/ClangUtil.h"
40 #include "lldb/Symbol/CompileUnit.h"
41 #include "lldb/Symbol/CompilerDecl.h"
42 #include "lldb/Symbol/CompilerDeclContext.h"
43 #include "lldb/Symbol/DebugMacros.h"
44 #include "lldb/Symbol/LineTable.h"
45 #include "lldb/Symbol/LocateSymbolFile.h"
46 #include "lldb/Symbol/ObjectFile.h"
47 #include "lldb/Symbol/SymbolFile.h"
48 #include "lldb/Symbol/TypeMap.h"
49 #include "lldb/Symbol/TypeSystem.h"
50 #include "lldb/Symbol/VariableList.h"
52 #include "lldb/Target/Language.h"
53 #include "lldb/Target/Target.h"
55 #include "AppleDWARFIndex.h"
56 #include "DWARFASTParser.h"
57 #include "DWARFASTParserClang.h"
58 #include "DWARFCompileUnit.h"
59 #include "DWARFDebugAbbrev.h"
60 #include "DWARFDebugAranges.h"
61 #include "DWARFDebugInfo.h"
62 #include "DWARFDebugMacro.h"
63 #include "DWARFDebugRanges.h"
64 #include "DWARFDeclContext.h"
65 #include "DWARFFormValue.h"
66 #include "DWARFTypeUnit.h"
67 #include "DWARFUnit.h"
68 #include "DebugNamesDWARFIndex.h"
69 #include "LogChannelDWARF.h"
70 #include "ManualDWARFIndex.h"
71 #include "SymbolFileDWARFDebugMap.h"
72 #include "SymbolFileDWARFDwo.h"
73 #include "SymbolFileDWARFDwp.h"
75 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
76 #include "llvm/Support/FileSystem.h"
85 //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
87 #ifdef ENABLE_DEBUG_PRINTF
89 #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
91 #define DEBUG_PRINTF(fmt, ...)
95 using namespace lldb_private;
98 // child_requires_parent_class_union_or_struct_to_be_completed (dw_tag_t tag)
104 // case DW_TAG_subprogram:
105 // case DW_TAG_inlined_subroutine:
106 // case DW_TAG_class_type:
107 // case DW_TAG_structure_type:
108 // case DW_TAG_union_type:
117 #define LLDB_PROPERTIES_symbolfiledwarf
118 #include "SymbolFileDWARFProperties.inc"
121 #define LLDB_PROPERTIES_symbolfiledwarf
122 #include "SymbolFileDWARFPropertiesEnum.inc"
125 class PluginProperties : public Properties {
127 static ConstString GetSettingName() {
128 return SymbolFileDWARF::GetPluginNameStatic();
132 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
133 m_collection_sp->Initialize(g_symbolfiledwarf_properties);
136 FileSpecList GetSymLinkPaths() {
137 const OptionValueFileSpecList *option_value =
138 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(
139 nullptr, true, ePropertySymLinkPaths);
140 assert(option_value);
141 return option_value->GetCurrentValue();
144 bool IgnoreFileIndexes() const {
145 return m_collection_sp->GetPropertyAtIndexAsBoolean(
146 nullptr, ePropertyIgnoreIndexes, false);
150 typedef std::shared_ptr<PluginProperties> SymbolFileDWARFPropertiesSP;
152 static const SymbolFileDWARFPropertiesSP &GetGlobalPluginProperties() {
153 static const auto g_settings_sp(std::make_shared<PluginProperties>());
154 return g_settings_sp;
159 static const llvm::DWARFDebugLine::LineTable *
160 ParseLLVMLineTable(lldb_private::DWARFContext &context,
161 llvm::DWARFDebugLine &line, dw_offset_t line_offset,
162 dw_offset_t unit_offset) {
163 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
165 llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVM();
166 llvm::DWARFContext &ctx = context.GetAsLLVM();
167 llvm::Expected<const llvm::DWARFDebugLine::LineTable *> line_table =
168 line.getOrParseLineTable(
169 data, line_offset, ctx, nullptr, [&](llvm::Error e) {
170 LLDB_LOG_ERROR(log, std::move(e),
171 "SymbolFileDWARF::ParseLineTable failed to parse");
175 LLDB_LOG_ERROR(log, line_table.takeError(),
176 "SymbolFileDWARF::ParseLineTable failed to parse");
182 static FileSpecList ParseSupportFilesFromPrologue(
183 const lldb::ModuleSP &module,
184 const llvm::DWARFDebugLine::Prologue &prologue, FileSpec::Style style,
185 llvm::StringRef compile_dir = {}, FileSpec first_file = {}) {
186 FileSpecList support_files;
187 support_files.Append(first_file);
189 const size_t number_of_files = prologue.FileNames.size();
190 for (size_t idx = 1; idx <= number_of_files; ++idx) {
191 std::string original_file;
192 if (!prologue.getFileNameByIndex(
194 llvm::DILineInfoSpecifier::FileLineInfoKind::Default, original_file,
196 // Always add an entry so the indexes remain correct.
197 support_files.EmplaceBack();
201 std::string remapped_file;
202 if (!prologue.getFileNameByIndex(
204 llvm::DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
205 remapped_file, style)) {
206 // Always add an entry so the indexes remain correct.
207 support_files.EmplaceBack(original_file, style);
211 module->RemapSourceFile(llvm::StringRef(original_file), remapped_file);
212 support_files.EmplaceBack(remapped_file, style);
215 return support_files;
218 FileSpecList SymbolFileDWARF::GetSymlinkPaths() {
219 return GetGlobalPluginProperties()->GetSymLinkPaths();
222 void SymbolFileDWARF::Initialize() {
223 LogChannelDWARF::Initialize();
224 PluginManager::RegisterPlugin(GetPluginNameStatic(),
225 GetPluginDescriptionStatic(), CreateInstance,
229 void SymbolFileDWARF::DebuggerInitialize(Debugger &debugger) {
230 if (!PluginManager::GetSettingForSymbolFilePlugin(
231 debugger, PluginProperties::GetSettingName())) {
232 const bool is_global_setting = true;
233 PluginManager::CreateSettingForSymbolFilePlugin(
234 debugger, GetGlobalPluginProperties()->GetValueProperties(),
235 ConstString("Properties for the dwarf symbol-file plug-in."),
240 void SymbolFileDWARF::Terminate() {
241 PluginManager::UnregisterPlugin(CreateInstance);
242 LogChannelDWARF::Terminate();
245 lldb_private::ConstString SymbolFileDWARF::GetPluginNameStatic() {
246 static ConstString g_name("dwarf");
250 const char *SymbolFileDWARF::GetPluginDescriptionStatic() {
251 return "DWARF and DWARF3 debug symbol file reader.";
254 SymbolFile *SymbolFileDWARF::CreateInstance(ObjectFileSP objfile_sp) {
255 return new SymbolFileDWARF(std::move(objfile_sp),
256 /*dwo_section_list*/ nullptr);
259 TypeList &SymbolFileDWARF::GetTypeList() {
260 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
261 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
262 return debug_map_symfile->GetTypeList();
263 return SymbolFile::GetTypeList();
265 void SymbolFileDWARF::GetTypes(const DWARFDIE &die, dw_offset_t min_die_offset,
266 dw_offset_t max_die_offset, uint32_t type_mask,
269 const dw_offset_t die_offset = die.GetOffset();
271 if (die_offset >= max_die_offset)
274 if (die_offset >= min_die_offset) {
275 const dw_tag_t tag = die.Tag();
277 bool add_type = false;
280 case DW_TAG_array_type:
281 add_type = (type_mask & eTypeClassArray) != 0;
283 case DW_TAG_unspecified_type:
284 case DW_TAG_base_type:
285 add_type = (type_mask & eTypeClassBuiltin) != 0;
287 case DW_TAG_class_type:
288 add_type = (type_mask & eTypeClassClass) != 0;
290 case DW_TAG_structure_type:
291 add_type = (type_mask & eTypeClassStruct) != 0;
293 case DW_TAG_union_type:
294 add_type = (type_mask & eTypeClassUnion) != 0;
296 case DW_TAG_enumeration_type:
297 add_type = (type_mask & eTypeClassEnumeration) != 0;
299 case DW_TAG_subroutine_type:
300 case DW_TAG_subprogram:
301 case DW_TAG_inlined_subroutine:
302 add_type = (type_mask & eTypeClassFunction) != 0;
304 case DW_TAG_pointer_type:
305 add_type = (type_mask & eTypeClassPointer) != 0;
307 case DW_TAG_rvalue_reference_type:
308 case DW_TAG_reference_type:
309 add_type = (type_mask & eTypeClassReference) != 0;
312 add_type = (type_mask & eTypeClassTypedef) != 0;
314 case DW_TAG_ptr_to_member_type:
315 add_type = (type_mask & eTypeClassMemberPointer) != 0;
322 const bool assert_not_being_parsed = true;
323 Type *type = ResolveTypeUID(die, assert_not_being_parsed);
325 if (type_set.find(type) == type_set.end())
326 type_set.insert(type);
331 for (DWARFDIE child_die = die.GetFirstChild(); child_die.IsValid();
332 child_die = child_die.GetSibling()) {
333 GetTypes(child_die, min_die_offset, max_die_offset, type_mask, type_set);
338 void SymbolFileDWARF::GetTypes(SymbolContextScope *sc_scope,
339 TypeClass type_mask, TypeList &type_list)
342 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
345 CompileUnit *comp_unit = nullptr;
346 DWARFUnit *dwarf_cu = nullptr;
348 comp_unit = sc_scope->CalculateSymbolContextCompileUnit();
351 dwarf_cu = GetDWARFCompileUnit(comp_unit);
354 GetTypes(dwarf_cu->DIE(), dwarf_cu->GetOffset(),
355 dwarf_cu->GetNextUnitOffset(), type_mask, type_set);
357 DWARFDebugInfo *info = DebugInfo();
359 const size_t num_cus = info->GetNumUnits();
360 for (size_t cu_idx = 0; cu_idx < num_cus; ++cu_idx) {
361 dwarf_cu = info->GetUnitAtIndex(cu_idx);
363 GetTypes(dwarf_cu->DIE(), 0, UINT32_MAX, type_mask, type_set);
369 std::set<CompilerType> compiler_type_set;
370 for (Type *type : type_set) {
371 CompilerType compiler_type = type->GetForwardCompilerType();
372 if (compiler_type_set.find(compiler_type) == compiler_type_set.end()) {
373 compiler_type_set.insert(compiler_type);
374 type_list.Insert(type->shared_from_this());
379 // Gets the first parent that is a lexical block, function or inlined
380 // subroutine, or compile unit.
382 SymbolFileDWARF::GetParentSymbolContextDIE(const DWARFDIE &child_die) {
384 for (die = child_die.GetParent(); die; die = die.GetParent()) {
385 dw_tag_t tag = die.Tag();
388 case DW_TAG_compile_unit:
389 case DW_TAG_partial_unit:
390 case DW_TAG_subprogram:
391 case DW_TAG_inlined_subroutine:
392 case DW_TAG_lexical_block:
401 SymbolFileDWARF::SymbolFileDWARF(ObjectFileSP objfile_sp,
402 SectionList *dwo_section_list)
403 : SymbolFile(std::move(objfile_sp)),
404 UserID(0x7fffffff00000000), // Used by SymbolFileDWARFDebugMap to
405 // when this class parses .o files to
406 // contain the .o file index/ID
407 m_debug_map_module_wp(), m_debug_map_symfile(nullptr),
408 m_context(m_objfile_sp->GetModule()->GetSectionList(), dwo_section_list),
409 m_data_debug_loc(), m_abbr(), m_info(), m_fetched_external_modules(false),
410 m_supports_DW_AT_APPLE_objc_complete_type(eLazyBoolCalculate),
411 m_unique_ast_type_map() {}
413 SymbolFileDWARF::~SymbolFileDWARF() {}
415 static ConstString GetDWARFMachOSegmentName() {
416 static ConstString g_dwarf_section_name("__DWARF");
417 return g_dwarf_section_name;
420 UniqueDWARFASTTypeMap &SymbolFileDWARF::GetUniqueDWARFASTTypeMap() {
421 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
422 if (debug_map_symfile)
423 return debug_map_symfile->GetUniqueDWARFASTTypeMap();
425 return m_unique_ast_type_map;
428 llvm::Expected<TypeSystem &>
429 SymbolFileDWARF::GetTypeSystemForLanguage(LanguageType language) {
430 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
431 return debug_map_symfile->GetTypeSystemForLanguage(language);
433 auto type_system_or_err =
434 m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
435 if (type_system_or_err) {
436 type_system_or_err->SetSymbolFile(this);
438 return type_system_or_err;
441 void SymbolFileDWARF::InitializeObject() {
442 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
444 if (!GetGlobalPluginProperties()->IgnoreFileIndexes()) {
445 DWARFDataExtractor apple_names, apple_namespaces, apple_types, apple_objc;
446 LoadSectionData(eSectionTypeDWARFAppleNames, apple_names);
447 LoadSectionData(eSectionTypeDWARFAppleNamespaces, apple_namespaces);
448 LoadSectionData(eSectionTypeDWARFAppleTypes, apple_types);
449 LoadSectionData(eSectionTypeDWARFAppleObjC, apple_objc);
451 m_index = AppleDWARFIndex::Create(
452 *GetObjectFile()->GetModule(), apple_names, apple_namespaces,
453 apple_types, apple_objc, m_context.getOrLoadStrData());
458 DWARFDataExtractor debug_names;
459 LoadSectionData(eSectionTypeDWARFDebugNames, debug_names);
460 if (debug_names.GetByteSize() > 0) {
461 llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> index_or =
462 DebugNamesDWARFIndex::Create(
463 *GetObjectFile()->GetModule(), debug_names,
464 m_context.getOrLoadStrData(), DebugInfo());
466 m_index = std::move(*index_or);
469 LLDB_LOG_ERROR(log, index_or.takeError(),
470 "Unable to read .debug_names data: {0}");
474 m_index = std::make_unique<ManualDWARFIndex>(*GetObjectFile()->GetModule(),
478 bool SymbolFileDWARF::SupportedVersion(uint16_t version) {
479 return version >= 2 && version <= 5;
482 uint32_t SymbolFileDWARF::CalculateAbilities() {
483 uint32_t abilities = 0;
484 if (m_objfile_sp != nullptr) {
485 const Section *section = nullptr;
486 const SectionList *section_list = m_objfile_sp->GetSectionList();
487 if (section_list == nullptr)
490 uint64_t debug_abbrev_file_size = 0;
491 uint64_t debug_info_file_size = 0;
492 uint64_t debug_line_file_size = 0;
494 section = section_list->FindSectionByName(GetDWARFMachOSegmentName()).get();
497 section_list = §ion->GetChildren();
500 section_list->FindSectionByType(eSectionTypeDWARFDebugInfo, true).get();
501 if (section != nullptr) {
502 debug_info_file_size = section->GetFileSize();
505 section_list->FindSectionByType(eSectionTypeDWARFDebugAbbrev, true)
508 debug_abbrev_file_size = section->GetFileSize();
510 DWARFDebugAbbrev *abbrev = DebugAbbrev();
512 std::set<dw_form_t> invalid_forms;
513 abbrev->GetUnsupportedForms(invalid_forms);
514 if (!invalid_forms.empty()) {
516 error.Printf("unsupported DW_FORM value%s:",
517 invalid_forms.size() > 1 ? "s" : "");
518 for (auto form : invalid_forms)
519 error.Printf(" %#x", form);
520 m_objfile_sp->GetModule()->ReportWarning(
521 "%s", error.GetString().str().c_str());
527 section_list->FindSectionByType(eSectionTypeDWARFDebugLine, true)
530 debug_line_file_size = section->GetFileSize();
532 const char *symfile_dir_cstr =
533 m_objfile_sp->GetFileSpec().GetDirectory().GetCString();
534 if (symfile_dir_cstr) {
535 if (strcasestr(symfile_dir_cstr, ".dsym")) {
536 if (m_objfile_sp->GetType() == ObjectFile::eTypeDebugInfo) {
537 // We have a dSYM file that didn't have a any debug info. If the
538 // string table has a size of 1, then it was made from an
539 // executable with no debug info, or from an executable that was
542 section_list->FindSectionByType(eSectionTypeDWARFDebugStr, true)
544 if (section && section->GetFileSize() == 1) {
545 m_objfile_sp->GetModule()->ReportWarning(
546 "empty dSYM file detected, dSYM was created with an "
547 "executable with no debug info.");
554 if (debug_abbrev_file_size > 0 && debug_info_file_size > 0)
555 abilities |= CompileUnits | Functions | Blocks | GlobalVariables |
556 LocalVariables | VariableTypes;
558 if (debug_line_file_size > 0)
559 abilities |= LineTables;
564 const DWARFDataExtractor &
565 SymbolFileDWARF::GetCachedSectionData(lldb::SectionType sect_type,
566 DWARFDataSegment &data_segment) {
567 llvm::call_once(data_segment.m_flag, [this, sect_type, &data_segment] {
568 this->LoadSectionData(sect_type, std::ref(data_segment.m_data));
570 return data_segment.m_data;
573 void SymbolFileDWARF::LoadSectionData(lldb::SectionType sect_type,
574 DWARFDataExtractor &data) {
575 ModuleSP module_sp(m_objfile_sp->GetModule());
576 const SectionList *section_list = module_sp->GetSectionList();
580 SectionSP section_sp(section_list->FindSectionByType(sect_type, true));
585 m_objfile_sp->ReadSectionData(section_sp.get(), data);
588 const DWARFDataExtractor &SymbolFileDWARF::DebugLocData() {
589 const DWARFDataExtractor &debugLocData = get_debug_loc_data();
590 if (debugLocData.GetByteSize() > 0)
592 return get_debug_loclists_data();
595 const DWARFDataExtractor &SymbolFileDWARF::get_debug_loc_data() {
596 return GetCachedSectionData(eSectionTypeDWARFDebugLoc, m_data_debug_loc);
599 const DWARFDataExtractor &SymbolFileDWARF::get_debug_loclists_data() {
600 return GetCachedSectionData(eSectionTypeDWARFDebugLocLists,
601 m_data_debug_loclists);
604 DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() {
608 const DWARFDataExtractor &debug_abbrev_data = m_context.getOrLoadAbbrevData();
609 if (debug_abbrev_data.GetByteSize() == 0)
612 auto abbr = std::make_unique<DWARFDebugAbbrev>();
613 llvm::Error error = abbr->parse(debug_abbrev_data);
615 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
616 LLDB_LOG_ERROR(log, std::move(error),
617 "Unable to read .debug_abbrev section: {0}");
621 m_abbr = std::move(abbr);
625 const DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() const {
629 DWARFDebugInfo *SymbolFileDWARF::DebugInfo() {
630 if (m_info == nullptr) {
631 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
632 Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
633 static_cast<void *>(this));
634 if (m_context.getOrLoadDebugInfoData().GetByteSize() > 0)
635 m_info = std::make_unique<DWARFDebugInfo>(*this, m_context);
640 const DWARFDebugInfo *SymbolFileDWARF::DebugInfo() const {
645 SymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit) {
649 DWARFDebugInfo *info = DebugInfo();
651 // The compile unit ID is the index of the DWARF unit.
652 DWARFUnit *dwarf_cu = info->GetUnitAtIndex(comp_unit->GetID());
653 if (dwarf_cu && dwarf_cu->GetUserData() == nullptr)
654 dwarf_cu->SetUserData(comp_unit);
660 DWARFDebugRanges *SymbolFileDWARF::GetDebugRanges() {
662 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
663 Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
664 static_cast<void *>(this));
666 if (m_context.getOrLoadRangesData().GetByteSize() > 0)
667 m_ranges.reset(new DWARFDebugRanges());
670 m_ranges->Extract(m_context);
672 return m_ranges.get();
675 DWARFDebugRngLists *SymbolFileDWARF::GetDebugRngLists() {
677 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
678 Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
679 static_cast<void *>(this));
681 if (m_context.getOrLoadRngListsData().GetByteSize() > 0)
682 m_rnglists.reset(new DWARFDebugRngLists());
685 m_rnglists->Extract(m_context);
687 return m_rnglists.get();
690 lldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFCompileUnit &dwarf_cu) {
692 CompileUnit *comp_unit = (CompileUnit *)dwarf_cu.GetUserData();
694 // We already parsed this compile unit, had out a shared pointer to it
695 cu_sp = comp_unit->shared_from_this();
697 if (&dwarf_cu.GetSymbolFileDWARF() != this) {
698 return dwarf_cu.GetSymbolFileDWARF().ParseCompileUnit(dwarf_cu);
699 } else if (dwarf_cu.GetOffset() == 0 && GetDebugMapSymfile()) {
700 // Let the debug map create the compile unit
701 cu_sp = m_debug_map_symfile->GetCompileUnit(this);
702 dwarf_cu.SetUserData(cu_sp.get());
704 ModuleSP module_sp(m_objfile_sp->GetModule());
706 const DWARFDIE cu_die = dwarf_cu.DIE();
708 FileSpec cu_file_spec(cu_die.GetName(), dwarf_cu.GetPathStyle());
710 // If we have a full path to the compile unit, we don't need to
711 // resolve the file. This can be expensive e.g. when the source
712 // files are NFS mounted.
713 cu_file_spec.MakeAbsolute(dwarf_cu.GetCompilationDirectory());
715 std::string remapped_file;
716 if (module_sp->RemapSourceFile(cu_file_spec.GetPath(),
718 cu_file_spec.SetFile(remapped_file, FileSpec::Style::native);
721 LanguageType cu_language = DWARFUnit::LanguageTypeFromDWARF(
722 cu_die.GetAttributeValueAsUnsigned(DW_AT_language, 0));
724 bool is_optimized = dwarf_cu.GetIsOptimized();
725 BuildCuTranslationTable();
726 cu_sp = std::make_shared<CompileUnit>(
727 module_sp, &dwarf_cu, cu_file_spec,
728 *GetDWARFUnitIndex(dwarf_cu.GetID()), cu_language,
729 is_optimized ? eLazyBoolYes : eLazyBoolNo);
731 dwarf_cu.SetUserData(cu_sp.get());
733 SetCompileUnitAtIndex(dwarf_cu.GetID(), cu_sp);
741 void SymbolFileDWARF::BuildCuTranslationTable() {
742 if (!m_lldb_cu_to_dwarf_unit.empty())
745 DWARFDebugInfo *info = DebugInfo();
749 if (!info->ContainsTypeUnits()) {
750 // We can use a 1-to-1 mapping. No need to build a translation table.
753 for (uint32_t i = 0, num = info->GetNumUnits(); i < num; ++i) {
754 if (auto *cu = llvm::dyn_cast<DWARFCompileUnit>(info->GetUnitAtIndex(i))) {
755 cu->SetID(m_lldb_cu_to_dwarf_unit.size());
756 m_lldb_cu_to_dwarf_unit.push_back(i);
761 llvm::Optional<uint32_t> SymbolFileDWARF::GetDWARFUnitIndex(uint32_t cu_idx) {
762 BuildCuTranslationTable();
763 if (m_lldb_cu_to_dwarf_unit.empty())
765 if (cu_idx >= m_lldb_cu_to_dwarf_unit.size())
767 return m_lldb_cu_to_dwarf_unit[cu_idx];
770 uint32_t SymbolFileDWARF::CalculateNumCompileUnits() {
771 DWARFDebugInfo *info = DebugInfo();
774 BuildCuTranslationTable();
775 return m_lldb_cu_to_dwarf_unit.empty() ? info->GetNumUnits()
776 : m_lldb_cu_to_dwarf_unit.size();
779 CompUnitSP SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx) {
780 ASSERT_MODULE_LOCK(this);
781 DWARFDebugInfo *info = DebugInfo();
785 if (llvm::Optional<uint32_t> dwarf_idx = GetDWARFUnitIndex(cu_idx)) {
786 if (auto *dwarf_cu = llvm::cast_or_null<DWARFCompileUnit>(
787 info->GetUnitAtIndex(*dwarf_idx)))
788 return ParseCompileUnit(*dwarf_cu);
793 Function *SymbolFileDWARF::ParseFunction(CompileUnit &comp_unit,
794 const DWARFDIE &die) {
795 ASSERT_MODULE_LOCK(this);
799 auto type_system_or_err =
800 GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
801 if (auto err = type_system_or_err.takeError()) {
802 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
803 std::move(err), "Unable to parse function");
806 DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser();
810 return dwarf_ast->ParseFunctionFromDWARF(comp_unit, die);
813 bool SymbolFileDWARF::FixupAddress(Address &addr) {
814 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
815 if (debug_map_symfile) {
816 return debug_map_symfile->LinkOSOAddress(addr);
818 // This is a normal DWARF file, no address fixups need to happen
821 lldb::LanguageType SymbolFileDWARF::ParseLanguage(CompileUnit &comp_unit) {
822 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
823 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
825 return dwarf_cu->GetLanguageType();
827 return eLanguageTypeUnknown;
830 size_t SymbolFileDWARF::ParseFunctions(CompileUnit &comp_unit) {
831 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
832 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
836 size_t functions_added = 0;
837 std::vector<DWARFDIE> function_dies;
838 dwarf_cu->AppendDIEsWithTag(DW_TAG_subprogram, function_dies);
839 for (const DWARFDIE &die : function_dies) {
840 if (comp_unit.FindFunctionByUID(die.GetID()))
842 if (ParseFunction(comp_unit, die))
846 return functions_added;
849 void SymbolFileDWARF::ForEachExternalModule(
850 CompileUnit &comp_unit, llvm::function_ref<void(ModuleSP)> f) {
851 UpdateExternalModuleListIfNeeded();
853 for (auto &p : m_external_type_modules) {
854 ModuleSP module = p.second;
856 for (std::size_t i = 0; i < module->GetNumCompileUnits(); ++i)
857 module->GetCompileUnitAtIndex(i)->ForEachExternalModule(f);
861 bool SymbolFileDWARF::ParseSupportFiles(CompileUnit &comp_unit,
862 FileSpecList &support_files) {
863 if (!comp_unit.GetLineTable())
864 ParseLineTable(comp_unit);
868 FileSpec SymbolFileDWARF::GetFile(DWARFUnit &unit, size_t file_idx) {
869 if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit)) {
870 if (CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(*dwarf_cu))
871 return lldb_cu->GetSupportFiles().GetFileSpecAtIndex(file_idx);
875 auto &tu = llvm::cast<DWARFTypeUnit>(unit);
876 return GetTypeUnitSupportFiles(tu).GetFileSpecAtIndex(file_idx);
880 SymbolFileDWARF::GetTypeUnitSupportFiles(DWARFTypeUnit &tu) {
881 static FileSpecList empty_list;
883 dw_offset_t offset = tu.GetLineTableOffset();
884 if (offset == DW_INVALID_OFFSET ||
885 offset == llvm::DenseMapInfo<dw_offset_t>::getEmptyKey() ||
886 offset == llvm::DenseMapInfo<dw_offset_t>::getTombstoneKey())
889 // Many type units can share a line table, so parse the support file list
890 // once, and cache it based on the offset field.
891 auto iter_bool = m_type_unit_support_files.try_emplace(offset);
892 FileSpecList &list = iter_bool.first->second;
893 if (iter_bool.second) {
894 uint64_t line_table_offset = offset;
895 llvm::DWARFDataExtractor data = m_context.getOrLoadLineData().GetAsLLVM();
896 llvm::DWARFContext &ctx = m_context.GetAsLLVM();
897 llvm::DWARFDebugLine::Prologue prologue;
898 llvm::Error error = prologue.parse(data, &line_table_offset, ctx);
900 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
901 LLDB_LOG_ERROR(log, std::move(error),
902 "SymbolFileDWARF::GetTypeUnitSupportFiles failed to parse "
903 "the line table prologue");
905 list = ParseSupportFilesFromPrologue(GetObjectFile()->GetModule(),
906 prologue, tu.GetPathStyle());
912 bool SymbolFileDWARF::ParseIsOptimized(CompileUnit &comp_unit) {
913 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
914 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
916 return dwarf_cu->GetIsOptimized();
920 bool SymbolFileDWARF::ParseImportedModules(
921 const lldb_private::SymbolContext &sc,
922 std::vector<SourceModule> &imported_modules) {
923 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
924 assert(sc.comp_unit);
925 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
928 if (!ClangModulesDeclVendor::LanguageSupportsClangModules(
929 sc.comp_unit->GetLanguage()))
931 UpdateExternalModuleListIfNeeded();
933 const DWARFDIE die = dwarf_cu->DIE();
937 for (DWARFDIE child_die = die.GetFirstChild(); child_die;
938 child_die = child_die.GetSibling()) {
939 if (child_die.Tag() != DW_TAG_imported_declaration)
942 DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import);
943 if (module_die.Tag() != DW_TAG_module)
946 if (const char *name =
947 module_die.GetAttributeValueAsString(DW_AT_name, nullptr)) {
949 module.path.push_back(ConstString(name));
951 DWARFDIE parent_die = module_die;
952 while ((parent_die = parent_die.GetParent())) {
953 if (parent_die.Tag() != DW_TAG_module)
955 if (const char *name =
956 parent_die.GetAttributeValueAsString(DW_AT_name, nullptr))
957 module.path.push_back(ConstString(name));
959 std::reverse(module.path.begin(), module.path.end());
960 if (const char *include_path = module_die.GetAttributeValueAsString(
961 DW_AT_LLVM_include_path, nullptr))
962 module.search_path = ConstString(include_path);
963 if (const char *sysroot = module_die.GetAttributeValueAsString(
964 DW_AT_LLVM_isysroot, nullptr))
965 module.sysroot = ConstString(sysroot);
966 imported_modules.push_back(module);
972 bool SymbolFileDWARF::ParseLineTable(CompileUnit &comp_unit) {
973 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
974 if (comp_unit.GetLineTable() != nullptr)
977 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
981 const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
985 const dw_offset_t cu_line_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(
986 DW_AT_stmt_list, DW_INVALID_OFFSET);
987 if (cu_line_offset == DW_INVALID_OFFSET)
990 llvm::DWARFDebugLine line;
991 const llvm::DWARFDebugLine::LineTable *line_table = ParseLLVMLineTable(
992 m_context, line, cu_line_offset, dwarf_cu->GetOffset());
997 // FIXME: Rather than parsing the whole line table and then copying it over
998 // into LLDB, we should explore using a callback to populate the line table
999 // while we parse to reduce memory usage.
1000 std::unique_ptr<LineTable> line_table_up =
1001 std::make_unique<LineTable>(&comp_unit);
1002 LineSequence *sequence = line_table_up->CreateLineSequenceContainer();
1003 for (auto &row : line_table->Rows) {
1004 line_table_up->AppendLineEntryToSequence(
1005 sequence, row.Address.Address, row.Line, row.Column, row.File,
1006 row.IsStmt, row.BasicBlock, row.PrologueEnd, row.EpilogueBegin,
1008 if (row.EndSequence) {
1009 line_table_up->InsertSequence(sequence);
1010 sequence = line_table_up->CreateLineSequenceContainer();
1014 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) {
1015 // We have an object file that has a line table with addresses that are not
1016 // linked. We need to link the line table and convert the addresses that
1017 // are relative to the .o file into addresses for the main executable.
1018 comp_unit.SetLineTable(
1019 debug_map_symfile->LinkOSOLineTable(this, line_table_up.get()));
1021 comp_unit.SetLineTable(line_table_up.release());
1024 comp_unit.SetSupportFiles(ParseSupportFilesFromPrologue(
1025 comp_unit.GetModule(), line_table->Prologue, dwarf_cu->GetPathStyle(),
1026 dwarf_cu->GetCompilationDirectory().GetCString(), FileSpec(comp_unit)));
1031 lldb_private::DebugMacrosSP
1032 SymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset) {
1033 auto iter = m_debug_macros_map.find(*offset);
1034 if (iter != m_debug_macros_map.end())
1035 return iter->second;
1037 const DWARFDataExtractor &debug_macro_data = m_context.getOrLoadMacroData();
1038 if (debug_macro_data.GetByteSize() == 0)
1039 return DebugMacrosSP();
1041 lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros());
1042 m_debug_macros_map[*offset] = debug_macros_sp;
1044 const DWARFDebugMacroHeader &header =
1045 DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset);
1046 DWARFDebugMacroEntry::ReadMacroEntries(
1047 debug_macro_data, m_context.getOrLoadStrData(), header.OffsetIs64Bit(),
1048 offset, this, debug_macros_sp);
1050 return debug_macros_sp;
1053 bool SymbolFileDWARF::ParseDebugMacros(CompileUnit &comp_unit) {
1054 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1056 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1057 if (dwarf_cu == nullptr)
1060 const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
1064 lldb::offset_t sect_offset =
1065 dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET);
1066 if (sect_offset == DW_INVALID_OFFSET)
1067 sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros,
1069 if (sect_offset == DW_INVALID_OFFSET)
1072 comp_unit.SetDebugMacros(ParseDebugMacros(§_offset));
1077 size_t SymbolFileDWARF::ParseBlocksRecursive(
1078 lldb_private::CompileUnit &comp_unit, Block *parent_block,
1079 const DWARFDIE &orig_die, addr_t subprogram_low_pc, uint32_t depth) {
1080 size_t blocks_added = 0;
1081 DWARFDIE die = orig_die;
1083 dw_tag_t tag = die.Tag();
1086 case DW_TAG_inlined_subroutine:
1087 case DW_TAG_subprogram:
1088 case DW_TAG_lexical_block: {
1089 Block *block = nullptr;
1090 if (tag == DW_TAG_subprogram) {
1091 // Skip any DW_TAG_subprogram DIEs that are inside of a normal or
1092 // inlined functions. These will be parsed on their own as separate
1098 block = parent_block;
1100 BlockSP block_sp(new Block(die.GetID()));
1101 parent_block->AddChild(block_sp);
1102 block = block_sp.get();
1104 DWARFRangeList ranges;
1105 const char *name = nullptr;
1106 const char *mangled_name = nullptr;
1110 int decl_column = 0;
1113 int call_column = 0;
1114 if (die.GetDIENamesAndRanges(name, mangled_name, ranges, decl_file,
1115 decl_line, decl_column, call_file, call_line,
1116 call_column, nullptr)) {
1117 if (tag == DW_TAG_subprogram) {
1118 assert(subprogram_low_pc == LLDB_INVALID_ADDRESS);
1119 subprogram_low_pc = ranges.GetMinRangeBase(0);
1120 } else if (tag == DW_TAG_inlined_subroutine) {
1121 // We get called here for inlined subroutines in two ways. The first
1122 // time is when we are making the Function object for this inlined
1123 // concrete instance. Since we're creating a top level block at
1124 // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS. So we
1125 // need to adjust the containing address. The second time is when we
1126 // are parsing the blocks inside the function that contains the
1127 // inlined concrete instance. Since these will be blocks inside the
1128 // containing "real" function the offset will be for that function.
1129 if (subprogram_low_pc == LLDB_INVALID_ADDRESS) {
1130 subprogram_low_pc = ranges.GetMinRangeBase(0);
1134 const size_t num_ranges = ranges.GetSize();
1135 for (size_t i = 0; i < num_ranges; ++i) {
1136 const DWARFRangeList::Entry &range = ranges.GetEntryRef(i);
1137 const addr_t range_base = range.GetRangeBase();
1138 if (range_base >= subprogram_low_pc)
1139 block->AddRange(Block::Range(range_base - subprogram_low_pc,
1140 range.GetByteSize()));
1142 GetObjectFile()->GetModule()->ReportError(
1143 "0x%8.8" PRIx64 ": adding range [0x%" PRIx64 "-0x%" PRIx64
1144 ") which has a base that is less than the function's low PC "
1145 "0x%" PRIx64 ". Please file a bug and attach the file at the "
1146 "start of this error message",
1147 block->GetID(), range_base, range.GetRangeEnd(),
1151 block->FinalizeRanges();
1153 if (tag != DW_TAG_subprogram &&
1154 (name != nullptr || mangled_name != nullptr)) {
1155 std::unique_ptr<Declaration> decl_up;
1156 if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1157 decl_up.reset(new Declaration(
1158 comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file),
1159 decl_line, decl_column));
1161 std::unique_ptr<Declaration> call_up;
1162 if (call_file != 0 || call_line != 0 || call_column != 0)
1163 call_up.reset(new Declaration(
1164 comp_unit.GetSupportFiles().GetFileSpecAtIndex(call_file),
1165 call_line, call_column));
1167 block->SetInlinedFunctionInfo(name, mangled_name, decl_up.get(),
1173 if (die.HasChildren()) {
1175 ParseBlocksRecursive(comp_unit, block, die.GetFirstChild(),
1176 subprogram_low_pc, depth + 1);
1184 // Only parse siblings of the block if we are not at depth zero. A depth of
1185 // zero indicates we are currently parsing the top level DW_TAG_subprogram
1191 die = die.GetSibling();
1193 return blocks_added;
1196 bool SymbolFileDWARF::ClassOrStructIsVirtual(const DWARFDIE &parent_die) {
1198 for (DWARFDIE die = parent_die.GetFirstChild(); die;
1199 die = die.GetSibling()) {
1200 dw_tag_t tag = die.Tag();
1201 bool check_virtuality = false;
1203 case DW_TAG_inheritance:
1204 case DW_TAG_subprogram:
1205 check_virtuality = true;
1210 if (check_virtuality) {
1211 if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0)
1219 void SymbolFileDWARF::ParseDeclsForContext(CompilerDeclContext decl_ctx) {
1220 auto *type_system = decl_ctx.GetTypeSystem();
1221 if (type_system != nullptr)
1222 type_system->GetDWARFParser()->EnsureAllDIEsInDeclContextHaveBeenParsed(
1226 user_id_t SymbolFileDWARF::GetUID(DIERef ref) {
1227 if (GetDebugMapSymfile())
1228 return GetID() | ref.die_offset();
1230 return user_id_t(GetDwoNum().getValueOr(0x7fffffff)) << 32 |
1232 (lldb::user_id_t(ref.section() == DIERef::Section::DebugTypes) << 63);
1235 llvm::Optional<SymbolFileDWARF::DecodedUID>
1236 SymbolFileDWARF::DecodeUID(lldb::user_id_t uid) {
1237 // This method can be called without going through the symbol vendor so we
1238 // need to lock the module.
1239 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1240 // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we
1241 // must make sure we use the correct DWARF file when resolving things. On
1242 // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1243 // SymbolFileDWARF classes, one for each .o file. We can often end up with
1244 // references to other DWARF objects and we must be ready to receive a
1245 // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1247 if (SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile()) {
1248 SymbolFileDWARF *dwarf = debug_map->GetSymbolFileByOSOIndex(
1249 debug_map->GetOSOIndexFromUserID(uid));
1251 *dwarf, {llvm::None, DIERef::Section::DebugInfo, dw_offset_t(uid)}};
1253 dw_offset_t die_offset = uid;
1254 if (die_offset == DW_INVALID_OFFSET)
1257 DIERef::Section section =
1258 uid >> 63 ? DIERef::Section::DebugTypes : DIERef::Section::DebugInfo;
1260 llvm::Optional<uint32_t> dwo_num = uid >> 32 & 0x7fffffff;
1261 if (*dwo_num == 0x7fffffff)
1262 dwo_num = llvm::None;
1264 return DecodedUID{*this, {dwo_num, section, die_offset}};
1268 SymbolFileDWARF::GetDIE(lldb::user_id_t uid) {
1269 // This method can be called without going through the symbol vendor so we
1270 // need to lock the module.
1271 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1273 llvm::Optional<DecodedUID> decoded = DecodeUID(uid);
1276 return decoded->dwarf.GetDIE(decoded->ref);
1281 CompilerDecl SymbolFileDWARF::GetDeclForUID(lldb::user_id_t type_uid) {
1282 // This method can be called without going through the symbol vendor so we
1283 // need to lock the module.
1284 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1285 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1286 // SymbolFileDWARF::GetDIE(). See comments inside the
1287 // SymbolFileDWARF::GetDIE() for details.
1288 if (DWARFDIE die = GetDIE(type_uid))
1289 return die.GetDecl();
1290 return CompilerDecl();
1294 SymbolFileDWARF::GetDeclContextForUID(lldb::user_id_t type_uid) {
1295 // This method can be called without going through the symbol vendor so we
1296 // need to lock the module.
1297 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1298 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1299 // SymbolFileDWARF::GetDIE(). See comments inside the
1300 // SymbolFileDWARF::GetDIE() for details.
1301 if (DWARFDIE die = GetDIE(type_uid))
1302 return die.GetDeclContext();
1303 return CompilerDeclContext();
1307 SymbolFileDWARF::GetDeclContextContainingUID(lldb::user_id_t type_uid) {
1308 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1309 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1310 // SymbolFileDWARF::GetDIE(). See comments inside the
1311 // SymbolFileDWARF::GetDIE() for details.
1312 if (DWARFDIE die = GetDIE(type_uid))
1313 return die.GetContainingDeclContext();
1314 return CompilerDeclContext();
1317 Type *SymbolFileDWARF::ResolveTypeUID(lldb::user_id_t type_uid) {
1318 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1319 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1320 // SymbolFileDWARF::GetDIE(). See comments inside the
1321 // SymbolFileDWARF::GetDIE() for details.
1322 if (DWARFDIE type_die = GetDIE(type_uid))
1323 return type_die.ResolveType();
1328 llvm::Optional<SymbolFile::ArrayInfo>
1329 SymbolFileDWARF::GetDynamicArrayInfoForUID(
1330 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1331 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1332 if (DWARFDIE type_die = GetDIE(type_uid))
1333 return DWARFASTParser::ParseChildArrayInfo(type_die, exe_ctx);
1338 Type *SymbolFileDWARF::ResolveTypeUID(const DIERef &die_ref) {
1339 return ResolveType(GetDIE(die_ref), true);
1342 Type *SymbolFileDWARF::ResolveTypeUID(const DWARFDIE &die,
1343 bool assert_not_being_parsed) {
1345 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
1347 GetObjectFile()->GetModule()->LogMessage(
1348 log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
1349 die.GetOffset(), die.GetTagAsCString(), die.GetName());
1351 // We might be coming in in the middle of a type tree (a class within a
1352 // class, an enum within a class), so parse any needed parent DIEs before
1353 // we get to this one...
1354 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die);
1357 switch (decl_ctx_die.Tag()) {
1358 case DW_TAG_structure_type:
1359 case DW_TAG_union_type:
1360 case DW_TAG_class_type: {
1361 // Get the type, which could be a forward declaration
1363 GetObjectFile()->GetModule()->LogMessage(
1365 "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' "
1366 "resolve parent forward type for 0x%8.8x",
1367 die.GetOffset(), die.GetTagAsCString(), die.GetName(),
1368 decl_ctx_die.GetOffset());
1376 return ResolveType(die);
1381 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
1382 // SymbolFileDWARF objects to detect if this DWARF file is the one that can
1383 // resolve a compiler_type.
1384 bool SymbolFileDWARF::HasForwardDeclForClangType(
1385 const CompilerType &compiler_type) {
1386 CompilerType compiler_type_no_qualifiers =
1387 ClangUtil::RemoveFastQualifiers(compiler_type);
1388 if (GetForwardDeclClangTypeToDie().count(
1389 compiler_type_no_qualifiers.GetOpaqueQualType())) {
1392 TypeSystem *type_system = compiler_type.GetTypeSystem();
1394 ClangASTContext *clang_type_system =
1395 llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1396 if (!clang_type_system)
1398 DWARFASTParserClang *ast_parser =
1399 static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1400 return ast_parser->GetClangASTImporter().CanImport(compiler_type);
1403 bool SymbolFileDWARF::CompleteType(CompilerType &compiler_type) {
1404 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1406 ClangASTContext *clang_type_system =
1407 llvm::dyn_cast_or_null<ClangASTContext>(compiler_type.GetTypeSystem());
1408 if (clang_type_system) {
1409 DWARFASTParserClang *ast_parser =
1410 static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1412 ast_parser->GetClangASTImporter().CanImport(compiler_type))
1413 return ast_parser->GetClangASTImporter().CompleteType(compiler_type);
1416 // We have a struct/union/class/enum that needs to be fully resolved.
1417 CompilerType compiler_type_no_qualifiers =
1418 ClangUtil::RemoveFastQualifiers(compiler_type);
1419 auto die_it = GetForwardDeclClangTypeToDie().find(
1420 compiler_type_no_qualifiers.GetOpaqueQualType());
1421 if (die_it == GetForwardDeclClangTypeToDie().end()) {
1422 // We have already resolved this type...
1426 DWARFDIE dwarf_die = GetDIE(die_it->getSecond());
1428 // Once we start resolving this type, remove it from the forward
1429 // declaration map in case anyone child members or other types require this
1430 // type to get resolved. The type will get resolved when all of the calls
1431 // to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition are done.
1432 GetForwardDeclClangTypeToDie().erase(die_it);
1434 Type *type = GetDIEToType().lookup(dwarf_die.GetDIE());
1436 Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO |
1437 DWARF_LOG_TYPE_COMPLETION));
1439 GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
1440 log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
1441 dwarf_die.GetID(), dwarf_die.GetTagAsCString(),
1442 type->GetName().AsCString());
1443 assert(compiler_type);
1444 DWARFASTParser *dwarf_ast = dwarf_die.GetDWARFParser();
1446 return dwarf_ast->CompleteTypeFromDWARF(dwarf_die, type, compiler_type);
1451 Type *SymbolFileDWARF::ResolveType(const DWARFDIE &die,
1452 bool assert_not_being_parsed,
1453 bool resolve_function_context) {
1455 Type *type = GetTypeForDIE(die, resolve_function_context).get();
1457 if (assert_not_being_parsed) {
1458 if (type != DIE_IS_BEING_PARSED)
1461 GetObjectFile()->GetModule()->ReportError(
1462 "Parsing a die that is being parsed die: 0x%8.8x: %s %s",
1463 die.GetOffset(), die.GetTagAsCString(), die.GetName());
1472 SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu) {
1473 // Check if the symbol vendor already knows about this compile unit?
1474 if (dwarf_cu.GetUserData() == nullptr) {
1475 // The symbol vendor doesn't know about this compile unit, we need to parse
1476 // and add it to the symbol vendor object.
1477 return ParseCompileUnit(dwarf_cu).get();
1479 return (CompileUnit *)dwarf_cu.GetUserData();
1482 size_t SymbolFileDWARF::GetObjCMethodDIEOffsets(ConstString class_name,
1483 DIEArray &method_die_offsets) {
1484 method_die_offsets.clear();
1485 m_index->GetObjCMethods(class_name, method_die_offsets);
1486 return method_die_offsets.size();
1489 bool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) {
1492 if (die && llvm::isa<DWARFCompileUnit>(die.GetCU())) {
1493 // Check if the symbol vendor already knows about this compile unit?
1495 GetCompUnitForDWARFCompUnit(llvm::cast<DWARFCompileUnit>(*die.GetCU()));
1497 sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
1498 if (sc.function == nullptr)
1499 sc.function = ParseFunction(*sc.comp_unit, die);
1502 sc.module_sp = sc.function->CalculateSymbolContextModule();
1510 lldb::ModuleSP SymbolFileDWARF::GetDWOModule(ConstString name) {
1511 UpdateExternalModuleListIfNeeded();
1512 const auto &pos = m_external_type_modules.find(name);
1513 if (pos != m_external_type_modules.end())
1516 return lldb::ModuleSP();
1520 SymbolFileDWARF::GetDIE(const DIERef &die_ref) {
1521 if (die_ref.dwo_num()) {
1523 ->GetUnitAtIndex(*die_ref.dwo_num())
1524 ->GetDwoSymbolFile()
1528 DWARFDebugInfo *debug_info = DebugInfo();
1530 return debug_info->GetDIE(die_ref);
1535 std::unique_ptr<SymbolFileDWARFDwo>
1536 SymbolFileDWARF::GetDwoSymbolFileForCompileUnit(
1537 DWARFUnit &unit, const DWARFDebugInfoEntry &cu_die) {
1538 // If we are using a dSYM file, we never want the standard DWO files since
1539 // the -gmodules support uses the same DWO machanism to specify full debug
1540 // info files for modules.
1541 if (GetDebugMapSymfile())
1544 DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit);
1545 // Only compile units can be split into two parts.
1549 const char *dwo_name =
1550 cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_GNU_dwo_name, nullptr);
1554 SymbolFileDWARFDwp *dwp_symfile = GetDwpSymbolFile();
1557 cu_die.GetAttributeValueAsUnsigned(dwarf_cu, DW_AT_GNU_dwo_id, 0);
1558 std::unique_ptr<SymbolFileDWARFDwo> dwo_symfile =
1559 dwp_symfile->GetSymbolFileForDwoId(*dwarf_cu, dwo_id);
1564 FileSpec dwo_file(dwo_name);
1565 FileSystem::Instance().Resolve(dwo_file);
1566 if (dwo_file.IsRelative()) {
1567 const char *comp_dir =
1568 cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_comp_dir, nullptr);
1572 dwo_file.SetFile(comp_dir, FileSpec::Style::native);
1573 FileSystem::Instance().Resolve(dwo_file);
1574 dwo_file.AppendPathComponent(dwo_name);
1577 if (!FileSystem::Instance().Exists(dwo_file))
1580 const lldb::offset_t file_offset = 0;
1581 DataBufferSP dwo_file_data_sp;
1582 lldb::offset_t dwo_file_data_offset = 0;
1583 ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin(
1584 GetObjectFile()->GetModule(), &dwo_file, file_offset,
1585 FileSystem::Instance().GetByteSize(dwo_file), dwo_file_data_sp,
1586 dwo_file_data_offset);
1587 if (dwo_obj_file == nullptr)
1590 return std::make_unique<SymbolFileDWARFDwo>(dwo_obj_file, *dwarf_cu);
1593 void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() {
1594 if (m_fetched_external_modules)
1596 m_fetched_external_modules = true;
1598 DWARFDebugInfo *debug_info = DebugInfo();
1600 const uint32_t num_compile_units = GetNumCompileUnits();
1601 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
1602 DWARFUnit *dwarf_cu = debug_info->GetUnitAtIndex(cu_idx);
1604 const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
1605 if (die && !die.HasChildren()) {
1606 const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
1609 ConstString const_name(name);
1610 if (m_external_type_modules.find(const_name) ==
1611 m_external_type_modules.end()) {
1613 const char *dwo_path =
1614 die.GetAttributeValueAsString(DW_AT_GNU_dwo_name, nullptr);
1616 ModuleSpec dwo_module_spec;
1617 dwo_module_spec.GetFileSpec().SetFile(dwo_path,
1618 FileSpec::Style::native);
1619 if (dwo_module_spec.GetFileSpec().IsRelative()) {
1620 const char *comp_dir =
1621 die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr);
1623 dwo_module_spec.GetFileSpec().SetFile(comp_dir,
1624 FileSpec::Style::native);
1625 FileSystem::Instance().Resolve(dwo_module_spec.GetFileSpec());
1626 dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path);
1629 dwo_module_spec.GetArchitecture() =
1630 m_objfile_sp->GetModule()->GetArchitecture();
1632 // When LLDB loads "external" modules it looks at the presence of
1633 // DW_AT_GNU_dwo_name. However, when the already created module
1634 // (corresponding to .dwo itself) is being processed, it will see
1635 // the presence of DW_AT_GNU_dwo_name (which contains the name of
1636 // dwo file) and will try to call ModuleList::GetSharedModule
1637 // again. In some cases (i.e. for empty files) Clang 4.0 generates
1638 // a *.dwo file which has DW_AT_GNU_dwo_name, but no
1639 // DW_AT_comp_dir. In this case the method
1640 // ModuleList::GetSharedModule will fail and the warning will be
1641 // printed. However, as one can notice in this case we don't
1642 // actually need to try to load the already loaded module
1643 // (corresponding to .dwo) so we simply skip it.
1644 if (m_objfile_sp->GetFileSpec().GetFileNameExtension() == ".dwo" &&
1645 llvm::StringRef(m_objfile_sp->GetFileSpec().GetPath())
1646 .endswith(dwo_module_spec.GetFileSpec().GetPath())) {
1650 Status error = ModuleList::GetSharedModule(
1651 dwo_module_spec, module_sp, nullptr, nullptr, nullptr);
1653 GetObjectFile()->GetModule()->ReportWarning(
1654 "0x%8.8x: unable to locate module needed for external types: "
1655 "%s\nerror: %s\nDebugging will be degraded due to missing "
1656 "types. Rebuilding your project will regenerate the needed "
1659 dwo_module_spec.GetFileSpec().GetPath().c_str(),
1660 error.AsCString("unknown error"));
1663 m_external_type_modules[const_name] = module_sp;
1670 SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() {
1671 if (!m_global_aranges_up) {
1672 m_global_aranges_up.reset(new GlobalVariableMap());
1674 ModuleSP module_sp = GetObjectFile()->GetModule();
1676 const size_t num_cus = module_sp->GetNumCompileUnits();
1677 for (size_t i = 0; i < num_cus; ++i) {
1678 CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
1680 VariableListSP globals_sp = cu_sp->GetVariableList(true);
1682 const size_t num_globals = globals_sp->GetSize();
1683 for (size_t g = 0; g < num_globals; ++g) {
1684 VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
1685 if (var_sp && !var_sp->GetLocationIsConstantValueData()) {
1686 const DWARFExpression &location = var_sp->LocationExpression();
1687 Value location_result;
1689 if (location.Evaluate(nullptr, LLDB_INVALID_ADDRESS, nullptr,
1690 nullptr, location_result, &error)) {
1691 if (location_result.GetValueType() ==
1692 Value::eValueTypeFileAddress) {
1693 lldb::addr_t file_addr =
1694 location_result.GetScalar().ULongLong();
1695 lldb::addr_t byte_size = 1;
1696 if (var_sp->GetType())
1698 var_sp->GetType()->GetByteSize().getValueOr(0);
1699 m_global_aranges_up->Append(GlobalVariableMap::Entry(
1700 file_addr, byte_size, var_sp.get()));
1709 m_global_aranges_up->Sort();
1711 return *m_global_aranges_up;
1714 uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr,
1715 SymbolContextItem resolve_scope,
1716 SymbolContext &sc) {
1717 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1718 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1719 Timer scoped_timer(func_cat,
1721 "ResolveSymbolContext (so_addr = { "
1722 "section = %p, offset = 0x%" PRIx64
1723 " }, resolve_scope = 0x%8.8x)",
1724 static_cast<void *>(so_addr.GetSection().get()),
1725 so_addr.GetOffset(), resolve_scope);
1726 uint32_t resolved = 0;
1728 (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock |
1729 eSymbolContextLineEntry | eSymbolContextVariable)) {
1730 lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1732 DWARFDebugInfo *debug_info = DebugInfo();
1734 llvm::Expected<DWARFDebugAranges &> aranges =
1735 debug_info->GetCompileUnitAranges();
1737 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
1738 LLDB_LOG_ERROR(log, aranges.takeError(),
1739 "SymbolFileDWARF::ResolveSymbolContext failed to get cu "
1744 const dw_offset_t cu_offset = aranges->FindAddress(file_vm_addr);
1745 if (cu_offset == DW_INVALID_OFFSET) {
1746 // Global variables are not in the compile unit address ranges. The
1747 // only way to currently find global variables is to iterate over the
1748 // .debug_pubnames or the __apple_names table and find all items in
1749 // there that point to DW_TAG_variable DIEs and then find the address
1751 if (resolve_scope & eSymbolContextVariable) {
1752 GlobalVariableMap &map = GetGlobalAranges();
1753 const GlobalVariableMap::Entry *entry =
1754 map.FindEntryThatContains(file_vm_addr);
1755 if (entry && entry->data) {
1756 Variable *variable = entry->data;
1757 SymbolContextScope *scc = variable->GetSymbolContextScope();
1759 scc->CalculateSymbolContext(&sc);
1760 sc.variable = variable;
1762 return sc.GetResolvedMask();
1766 uint32_t cu_idx = DW_INVALID_INDEX;
1767 if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(
1768 debug_info->GetUnitAtOffset(DIERef::Section::DebugInfo,
1769 cu_offset, &cu_idx))) {
1770 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
1772 resolved |= eSymbolContextCompUnit;
1774 bool force_check_line_table = false;
1776 (eSymbolContextFunction | eSymbolContextBlock)) {
1777 DWARFDIE function_die = dwarf_cu->LookupAddress(file_vm_addr);
1781 sc.comp_unit->FindFunctionByUID(function_die.GetID()).get();
1782 if (sc.function == nullptr)
1783 sc.function = ParseFunction(*sc.comp_unit, function_die);
1785 if (sc.function && (resolve_scope & eSymbolContextBlock))
1786 block_die = function_die.LookupDeepestBlock(file_vm_addr);
1788 // We might have had a compile unit that had discontiguous
1789 // address ranges where the gaps are symbols that don't have
1790 // any debug info. Discontiguous compile unit address ranges
1791 // should only happen when there aren't other functions from
1792 // other compile units in these gaps. This helps keep the size
1793 // of the aranges down.
1794 force_check_line_table = true;
1797 if (sc.function != nullptr) {
1798 resolved |= eSymbolContextFunction;
1800 if (resolve_scope & eSymbolContextBlock) {
1801 Block &block = sc.function->GetBlock(true);
1804 sc.block = block.FindBlockByID(block_die.GetID());
1806 sc.block = block.FindBlockByID(function_die.GetID());
1808 resolved |= eSymbolContextBlock;
1813 if ((resolve_scope & eSymbolContextLineEntry) ||
1814 force_check_line_table) {
1815 LineTable *line_table = sc.comp_unit->GetLineTable();
1816 if (line_table != nullptr) {
1817 // And address that makes it into this function should be in
1818 // terms of this debug file if there is no debug map, or it
1819 // will be an address in the .o file which needs to be fixed up
1820 // to be in terms of the debug map executable. Either way,
1821 // calling FixupAddress() will work for us.
1822 Address exe_so_addr(so_addr);
1823 if (FixupAddress(exe_so_addr)) {
1824 if (line_table->FindLineEntryByAddress(exe_so_addr,
1826 resolved |= eSymbolContextLineEntry;
1832 if (force_check_line_table &&
1833 !(resolved & eSymbolContextLineEntry)) {
1834 // We might have had a compile unit that had discontiguous
1835 // address ranges where the gaps are symbols that don't have any
1836 // debug info. Discontiguous compile unit address ranges should
1837 // only happen when there aren't other functions from other
1838 // compile units in these gaps. This helps keep the size of the
1840 sc.comp_unit = nullptr;
1841 resolved &= ~eSymbolContextCompUnit;
1844 GetObjectFile()->GetModule()->ReportWarning(
1845 "0x%8.8x: compile unit %u failed to create a valid "
1846 "lldb_private::CompileUnit class.",
1856 uint32_t SymbolFileDWARF::ResolveSymbolContext(const FileSpec &file_spec,
1859 SymbolContextItem resolve_scope,
1860 SymbolContextList &sc_list) {
1861 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1862 const uint32_t prev_size = sc_list.GetSize();
1863 if (resolve_scope & eSymbolContextCompUnit) {
1864 for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
1866 CompileUnit *dc_cu = ParseCompileUnitAtIndex(cu_idx).get();
1870 const bool full_match = (bool)file_spec.GetDirectory();
1871 bool file_spec_matches_cu_file_spec =
1872 FileSpec::Equal(file_spec, *dc_cu, full_match);
1873 if (check_inlines || file_spec_matches_cu_file_spec) {
1874 SymbolContext sc(m_objfile_sp->GetModule());
1875 sc.comp_unit = dc_cu;
1876 uint32_t file_idx = UINT32_MAX;
1878 // If we are looking for inline functions only and we don't find it
1879 // in the support files, we are done.
1880 if (check_inlines) {
1882 sc.comp_unit->GetSupportFiles().FindFileIndex(1, file_spec, true);
1883 if (file_idx == UINT32_MAX)
1888 LineTable *line_table = sc.comp_unit->GetLineTable();
1890 if (line_table != nullptr && line != 0) {
1891 // We will have already looked up the file index if we are
1892 // searching for inline entries.
1894 file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex(
1895 1, file_spec, true);
1897 if (file_idx != UINT32_MAX) {
1898 uint32_t found_line;
1899 uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex(
1900 0, file_idx, line, false, &sc.line_entry);
1901 found_line = sc.line_entry.line;
1903 while (line_idx != UINT32_MAX) {
1904 sc.function = nullptr;
1907 (eSymbolContextFunction | eSymbolContextBlock)) {
1908 const lldb::addr_t file_vm_addr =
1909 sc.line_entry.range.GetBaseAddress().GetFileAddress();
1910 if (file_vm_addr != LLDB_INVALID_ADDRESS) {
1911 DWARFDIE function_die =
1912 GetDWARFCompileUnit(dc_cu)->LookupAddress(file_vm_addr);
1916 sc.comp_unit->FindFunctionByUID(function_die.GetID())
1918 if (sc.function == nullptr)
1920 ParseFunction(*sc.comp_unit, function_die);
1922 if (sc.function && (resolve_scope & eSymbolContextBlock))
1924 function_die.LookupDeepestBlock(file_vm_addr);
1927 if (sc.function != nullptr) {
1928 Block &block = sc.function->GetBlock(true);
1931 sc.block = block.FindBlockByID(block_die.GetID());
1932 else if (function_die)
1933 sc.block = block.FindBlockByID(function_die.GetID());
1939 line_idx = line_table->FindLineEntryIndexByFileIndex(
1940 line_idx + 1, file_idx, found_line, true, &sc.line_entry);
1943 } else if (file_spec_matches_cu_file_spec && !check_inlines) {
1944 // only append the context if we aren't looking for inline call
1945 // sites by file and line and if the file spec matches that of
1949 } else if (file_spec_matches_cu_file_spec && !check_inlines) {
1950 // only append the context if we aren't looking for inline call
1951 // sites by file and line and if the file spec matches that of
1961 return sc_list.GetSize() - prev_size;
1964 void SymbolFileDWARF::PreloadSymbols() {
1965 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1969 std::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const {
1970 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
1972 return module_sp->GetMutex();
1973 return GetObjectFile()->GetModule()->GetMutex();
1976 bool SymbolFileDWARF::DeclContextMatchesThisSymbolFile(
1977 const lldb_private::CompilerDeclContext *decl_ctx) {
1978 if (decl_ctx == nullptr || !decl_ctx->IsValid()) {
1979 // Invalid namespace decl which means we aren't matching only things in
1980 // this symbol file, so return true to indicate it matches this symbol
1985 TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
1986 auto type_system_or_err = GetTypeSystemForLanguage(
1987 decl_ctx_type_system->GetMinimumLanguage(nullptr));
1988 if (auto err = type_system_or_err.takeError()) {
1989 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
1991 "Unable to match namespace decl using TypeSystem");
1995 if (decl_ctx_type_system == &type_system_or_err.get())
1996 return true; // The type systems match, return true
1998 // The namespace AST was valid, and it does not match...
1999 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2002 GetObjectFile()->GetModule()->LogMessage(
2003 log, "Valid namespace does not match symbol file");
2008 void SymbolFileDWARF::FindGlobalVariables(
2009 ConstString name, const CompilerDeclContext *parent_decl_ctx,
2010 uint32_t max_matches, VariableList &variables) {
2011 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2012 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2015 GetObjectFile()->GetModule()->LogMessage(
2017 "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2018 "parent_decl_ctx=%p, max_matches=%u, variables)",
2019 name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2022 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2025 DWARFDebugInfo *info = DebugInfo();
2029 // Remember how many variables are in the list before we search.
2030 const uint32_t original_size = variables.GetSize();
2032 llvm::StringRef basename;
2033 llvm::StringRef context;
2034 bool name_is_mangled = (bool)Mangled(name);
2036 if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(),
2038 basename = name.GetStringRef();
2040 DIEArray die_offsets;
2041 m_index->GetGlobalVariables(ConstString(basename), die_offsets);
2042 const size_t num_die_matches = die_offsets.size();
2043 if (num_die_matches) {
2045 sc.module_sp = m_objfile_sp->GetModule();
2046 assert(sc.module_sp);
2048 // Loop invariant: Variables up to this index have been checked for context
2050 uint32_t pruned_idx = original_size;
2053 for (size_t i = 0; i < num_die_matches && !done; ++i) {
2054 const DIERef &die_ref = die_offsets[i];
2055 DWARFDIE die = GetDIE(die_ref);
2058 switch (die.Tag()) {
2060 case DW_TAG_subprogram:
2061 case DW_TAG_inlined_subroutine:
2062 case DW_TAG_try_block:
2063 case DW_TAG_catch_block:
2066 case DW_TAG_variable: {
2067 auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2070 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2072 if (parent_decl_ctx) {
2073 DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2075 CompilerDeclContext actual_parent_decl_ctx =
2076 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2077 if (!actual_parent_decl_ctx ||
2078 actual_parent_decl_ctx != *parent_decl_ctx)
2083 ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false,
2085 while (pruned_idx < variables.GetSize()) {
2086 VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx);
2087 if (name_is_mangled ||
2088 var_sp->GetName().GetStringRef().contains(name.GetStringRef()))
2091 variables.RemoveVariableAtIndex(pruned_idx);
2094 if (variables.GetSize() - original_size >= max_matches)
2099 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2104 // Return the number of variable that were appended to the list
2105 const uint32_t num_matches = variables.GetSize() - original_size;
2106 if (log && num_matches > 0) {
2107 GetObjectFile()->GetModule()->LogMessage(
2109 "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2110 "parent_decl_ctx=%p, max_matches=%u, variables) => %u",
2111 name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2112 max_matches, num_matches);
2116 void SymbolFileDWARF::FindGlobalVariables(const RegularExpression ®ex,
2117 uint32_t max_matches,
2118 VariableList &variables) {
2119 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2120 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2123 GetObjectFile()->GetModule()->LogMessage(
2125 "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", "
2126 "max_matches=%u, variables)",
2127 regex.GetText().str().c_str(), max_matches);
2130 DWARFDebugInfo *info = DebugInfo();
2134 // Remember how many variables are in the list before we search.
2135 const uint32_t original_size = variables.GetSize();
2137 DIEArray die_offsets;
2138 m_index->GetGlobalVariables(regex, die_offsets);
2141 sc.module_sp = m_objfile_sp->GetModule();
2142 assert(sc.module_sp);
2144 const size_t num_matches = die_offsets.size();
2146 for (size_t i = 0; i < num_matches; ++i) {
2147 const DIERef &die_ref = die_offsets[i];
2148 DWARFDIE die = GetDIE(die_ref);
2151 DWARFCompileUnit *dwarf_cu =
2152 llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2155 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2157 ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2159 if (variables.GetSize() - original_size >= max_matches)
2162 m_index->ReportInvalidDIERef(die_ref, regex.GetText());
2167 bool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die,
2168 bool include_inlines,
2169 SymbolContextList &sc_list) {
2175 // If we were passed a die that is not a function, just return false...
2176 if (!(orig_die.Tag() == DW_TAG_subprogram ||
2177 (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2180 DWARFDIE die = orig_die;
2181 DWARFDIE inlined_die;
2182 if (die.Tag() == DW_TAG_inlined_subroutine) {
2186 die = die.GetParent();
2189 if (die.Tag() == DW_TAG_subprogram)
2195 assert(die && die.Tag() == DW_TAG_subprogram);
2196 if (GetFunction(die, sc)) {
2198 // Parse all blocks if needed
2200 Block &function_block = sc.function->GetBlock(true);
2201 sc.block = function_block.FindBlockByID(inlined_die.GetID());
2202 if (sc.block == nullptr)
2203 sc.block = function_block.FindBlockByID(inlined_die.GetOffset());
2204 if (sc.block == nullptr || !sc.block->GetStartAddress(addr))
2208 addr = sc.function->GetAddressRange().GetBaseAddress();
2211 if (addr.IsValid()) {
2220 bool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext *decl_ctx,
2221 const DWARFDIE &die) {
2222 // If we have no parent decl context to match this DIE matches, and if the
2223 // parent decl context isn't valid, we aren't trying to look for any
2224 // particular decl context so any die matches.
2225 if (decl_ctx == nullptr || !decl_ctx->IsValid())
2229 DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2231 CompilerDeclContext actual_decl_ctx =
2232 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2233 if (actual_decl_ctx)
2234 return decl_ctx->IsContainedInLookup(actual_decl_ctx);
2240 void SymbolFileDWARF::FindFunctions(ConstString name,
2241 const CompilerDeclContext *parent_decl_ctx,
2242 FunctionNameType name_type_mask,
2243 bool include_inlines,
2244 SymbolContextList &sc_list) {
2245 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2246 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2247 Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (name = '%s')",
2250 // eFunctionNameTypeAuto should be pre-resolved by a call to
2251 // Module::LookupInfo::LookupInfo()
2252 assert((name_type_mask & eFunctionNameTypeAuto) == 0);
2254 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2257 GetObjectFile()->GetModule()->LogMessage(
2259 "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, sc_list)",
2260 name.GetCString(), name_type_mask);
2263 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2266 // If name is empty then we won't find anything.
2270 // Remember how many sc_list are in the list before we search in case we are
2271 // appending the results to a variable list.
2273 const uint32_t original_size = sc_list.GetSize();
2275 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2277 CompilerDeclContext empty_decl_ctx;
2278 if (!parent_decl_ctx)
2279 parent_decl_ctx = &empty_decl_ctx;
2281 std::vector<DWARFDIE> dies;
2282 m_index->GetFunctions(name, *this, *parent_decl_ctx, name_type_mask, dies);
2283 for (const DWARFDIE &die : dies) {
2284 if (resolved_dies.insert(die.GetDIE()).second)
2285 ResolveFunction(die, include_inlines, sc_list);
2288 // Return the number of variable that were appended to the list
2289 const uint32_t num_matches = sc_list.GetSize() - original_size;
2291 if (log && num_matches > 0) {
2292 GetObjectFile()->GetModule()->LogMessage(
2294 "SymbolFileDWARF::FindFunctions (name=\"%s\", "
2295 "name_type_mask=0x%x, include_inlines=%d, sc_list) => %u",
2296 name.GetCString(), name_type_mask, include_inlines,
2301 void SymbolFileDWARF::FindFunctions(const RegularExpression ®ex,
2302 bool include_inlines,
2303 SymbolContextList &sc_list) {
2304 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2305 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2306 Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (regex = '%s')",
2307 regex.GetText().str().c_str());
2309 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2312 GetObjectFile()->GetModule()->LogMessage(
2313 log, "SymbolFileDWARF::FindFunctions (regex=\"%s\", sc_list)",
2314 regex.GetText().str().c_str());
2317 DWARFDebugInfo *info = DebugInfo();
2322 m_index->GetFunctions(regex, offsets);
2324 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2325 for (DIERef ref : offsets) {
2326 DWARFDIE die = info->GetDIE(ref);
2328 m_index->ReportInvalidDIERef(ref, regex.GetText());
2331 if (resolved_dies.insert(die.GetDIE()).second)
2332 ResolveFunction(die, include_inlines, sc_list);
2336 void SymbolFileDWARF::GetMangledNamesForFunction(
2337 const std::string &scope_qualified_name,
2338 std::vector<ConstString> &mangled_names) {
2339 DWARFDebugInfo *info = DebugInfo();
2340 uint32_t num_comp_units = 0;
2342 num_comp_units = info->GetNumUnits();
2344 for (uint32_t i = 0; i < num_comp_units; i++) {
2345 DWARFUnit *cu = info->GetUnitAtIndex(i);
2349 SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
2351 dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
2354 for (lldb::user_id_t uid :
2355 m_function_scope_qualified_name_map.lookup(scope_qualified_name)) {
2356 DWARFDIE die = GetDIE(uid);
2357 mangled_names.push_back(ConstString(die.GetMangledName()));
2361 void SymbolFileDWARF::FindTypes(
2362 ConstString name, const CompilerDeclContext *parent_decl_ctx,
2363 uint32_t max_matches,
2364 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
2366 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2367 // Make sure we haven't already searched this SymbolFile before...
2368 if (searched_symbol_files.count(this))
2371 searched_symbol_files.insert(this);
2373 DWARFDebugInfo *info = DebugInfo();
2377 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2380 if (parent_decl_ctx)
2381 GetObjectFile()->GetModule()->LogMessage(
2383 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2384 "%p (\"%s\"), max_matches=%u, type_list)",
2385 name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2386 parent_decl_ctx->GetName().AsCString("<NULL>"), max_matches);
2388 GetObjectFile()->GetModule()->LogMessage(
2390 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2391 "NULL, max_matches=%u, type_list)",
2392 name.GetCString(), max_matches);
2395 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2398 DIEArray die_offsets;
2399 m_index->GetTypes(name, die_offsets);
2400 const size_t num_die_matches = die_offsets.size();
2402 for (size_t i = 0; i < num_die_matches; ++i) {
2403 const DIERef &die_ref = die_offsets[i];
2404 DWARFDIE die = GetDIE(die_ref);
2406 if (!DIEInDeclContext(parent_decl_ctx, die))
2407 continue; // The containing decl contexts don't match
2409 Type *matching_type = ResolveType(die, true, true);
2410 if (matching_type) {
2411 // We found a type pointer, now find the shared pointer form our type
2413 types.InsertUnique(matching_type->shared_from_this());
2414 if (types.GetSize() >= max_matches)
2418 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2422 // Next search through the reachable Clang modules. This only applies for
2423 // DWARF objects compiled with -gmodules that haven't been processed by
2425 if (num_die_matches < max_matches) {
2426 UpdateExternalModuleListIfNeeded();
2428 for (const auto &pair : m_external_type_modules)
2429 if (ModuleSP external_module_sp = pair.second)
2430 if (SymbolFile *sym_file = external_module_sp->GetSymbolFile())
2431 sym_file->FindTypes(name, parent_decl_ctx, max_matches,
2432 searched_symbol_files, types);
2435 if (log && types.GetSize()) {
2436 if (parent_decl_ctx) {
2437 GetObjectFile()->GetModule()->LogMessage(
2439 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2440 "= %p (\"%s\"), max_matches=%u, type_list) => %u",
2441 name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2442 parent_decl_ctx->GetName().AsCString("<NULL>"), max_matches,
2445 GetObjectFile()->GetModule()->LogMessage(
2447 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2448 "= NULL, max_matches=%u, type_list) => %u",
2449 name.GetCString(), max_matches, types.GetSize());
2454 void SymbolFileDWARF::FindTypes(llvm::ArrayRef<CompilerContext> pattern,
2455 LanguageSet languages, TypeMap &types) {
2456 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2457 if (pattern.empty())
2460 ConstString name = pattern.back().name;
2465 DIEArray die_offsets;
2466 m_index->GetTypes(name, die_offsets);
2467 const size_t num_die_matches = die_offsets.size();
2469 for (size_t i = 0; i < num_die_matches; ++i) {
2470 const DIERef &die_ref = die_offsets[i];
2471 DWARFDIE die = GetDIE(die_ref);
2474 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2477 if (!languages[die.GetCU()->GetLanguageType()])
2480 llvm::SmallVector<CompilerContext, 4> die_context;
2481 die.GetDeclContext(die_context);
2482 if (!contextMatches(die_context, pattern))
2485 if (Type *matching_type = ResolveType(die, true, true))
2486 // We found a type pointer, now find the shared pointer form our type
2488 types.InsertUnique(matching_type->shared_from_this());
2493 SymbolFileDWARF::FindNamespace(ConstString name,
2494 const CompilerDeclContext *parent_decl_ctx) {
2495 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2496 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2499 GetObjectFile()->GetModule()->LogMessage(
2500 log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
2504 CompilerDeclContext namespace_decl_ctx;
2506 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2507 return namespace_decl_ctx;
2509 DWARFDebugInfo *info = DebugInfo();
2511 DIEArray die_offsets;
2512 m_index->GetNamespaces(name, die_offsets);
2513 const size_t num_matches = die_offsets.size();
2515 for (size_t i = 0; i < num_matches; ++i) {
2516 const DIERef &die_ref = die_offsets[i];
2517 DWARFDIE die = GetDIE(die_ref);
2520 if (!DIEInDeclContext(parent_decl_ctx, die))
2521 continue; // The containing decl contexts don't match
2523 DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2525 namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
2526 if (namespace_decl_ctx)
2530 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2535 if (log && namespace_decl_ctx) {
2536 GetObjectFile()->GetModule()->LogMessage(
2538 "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => "
2539 "CompilerDeclContext(%p/%p) \"%s\"",
2541 static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
2542 static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
2543 namespace_decl_ctx.GetName().AsCString("<NULL>"));
2546 return namespace_decl_ctx;
2549 TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
2550 bool resolve_function_context) {
2553 Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
2554 if (type_ptr == nullptr) {
2555 SymbolContextScope *scope;
2556 if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()))
2557 scope = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2559 scope = GetObjectFile()->GetModule().get();
2561 SymbolContext sc(scope);
2562 const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
2563 while (parent_die != nullptr) {
2564 if (parent_die->Tag() == DW_TAG_subprogram)
2566 parent_die = parent_die->GetParent();
2568 SymbolContext sc_backup = sc;
2569 if (resolve_function_context && parent_die != nullptr &&
2570 !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
2573 type_sp = ParseType(sc, die, nullptr);
2574 } else if (type_ptr != DIE_IS_BEING_PARSED) {
2575 // Grab the existing type from the master types lists
2576 type_sp = type_ptr->shared_from_this();
2583 SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
2585 DWARFDIE die = orig_die;
2588 // If this is the original DIE that we are searching for a declaration
2589 // for, then don't look in the cache as we don't want our own decl
2590 // context to be our decl context...
2591 if (orig_die != die) {
2592 switch (die.Tag()) {
2593 case DW_TAG_compile_unit:
2594 case DW_TAG_partial_unit:
2595 case DW_TAG_namespace:
2596 case DW_TAG_structure_type:
2597 case DW_TAG_union_type:
2598 case DW_TAG_class_type:
2599 case DW_TAG_lexical_block:
2600 case DW_TAG_subprogram:
2602 case DW_TAG_inlined_subroutine: {
2603 DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2614 DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
2616 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
2618 return decl_ctx_die;
2621 DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2623 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
2625 return decl_ctx_die;
2628 die = die.GetParent();
2634 Symbol *SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) {
2635 Symbol *objc_class_symbol = nullptr;
2637 Symtab *symtab = m_objfile_sp->GetSymtab();
2639 objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
2640 objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
2641 Symtab::eVisibilityAny);
2644 return objc_class_symbol;
2647 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If
2648 // they don't then we can end up looking through all class types for a complete
2649 // type and never find the full definition. We need to know if this attribute
2650 // is supported, so we determine this here and cache th result. We also need to
2651 // worry about the debug map
2653 // if we are doing darwin DWARF in .o file debugging.
2654 bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(DWARFUnit *cu) {
2655 if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) {
2656 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
2657 if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
2658 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2660 DWARFDebugInfo *debug_info = DebugInfo();
2661 const uint32_t num_compile_units = GetNumCompileUnits();
2662 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2663 DWARFUnit *dwarf_cu = debug_info->GetUnitAtIndex(cu_idx);
2664 if (dwarf_cu != cu &&
2665 dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) {
2666 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2671 if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo &&
2672 GetDebugMapSymfile())
2673 return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this);
2675 return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
2678 // This function can be used when a DIE is found that is a forward declaration
2679 // DIE and we want to try and find a type that has the complete definition.
2680 TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE(
2681 const DWARFDIE &die, ConstString type_name, bool must_be_implementation) {
2685 if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
2688 DIEArray die_offsets;
2689 m_index->GetCompleteObjCClass(type_name, must_be_implementation, die_offsets);
2691 const size_t num_matches = die_offsets.size();
2694 for (size_t i = 0; i < num_matches; ++i) {
2695 const DIERef &die_ref = die_offsets[i];
2696 DWARFDIE type_die = GetDIE(die_ref);
2699 bool try_resolving_type = false;
2701 // Don't try and resolve the DIE we are looking for with the DIE
2703 if (type_die != die) {
2704 switch (type_die.Tag()) {
2705 case DW_TAG_class_type:
2706 case DW_TAG_structure_type:
2707 try_resolving_type = true;
2714 if (try_resolving_type) {
2715 if (must_be_implementation &&
2716 type_die.Supports_DW_AT_APPLE_objc_complete_type())
2717 try_resolving_type = type_die.GetAttributeValueAsUnsigned(
2718 DW_AT_APPLE_objc_complete_type, 0);
2720 if (try_resolving_type) {
2721 Type *resolved_type = ResolveType(type_die, false, true);
2722 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2723 DEBUG_PRINTF("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
2724 " (cu 0x%8.8" PRIx64 ")\n",
2726 m_objfile_sp->GetFileSpec().GetFilename().AsCString(
2728 type_die.GetID(), type_cu->GetID());
2731 GetDIEToType()[die.GetDIE()] = resolved_type;
2732 type_sp = resolved_type->shared_from_this();
2738 m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
2745 // This function helps to ensure that the declaration contexts match for two
2746 // different DIEs. Often times debug information will refer to a forward
2747 // declaration of a type (the equivalent of "struct my_struct;". There will
2748 // often be a declaration of that type elsewhere that has the full definition.
2749 // When we go looking for the full type "my_struct", we will find one or more
2750 // matches in the accelerator tables and we will then need to make sure the
2751 // type was in the same declaration context as the original DIE. This function
2752 // can efficiently compare two DIEs and will return true when the declaration
2753 // context matches, and false when they don't.
2754 bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1,
2755 const DWARFDIE &die2) {
2759 std::vector<DWARFDIE> decl_ctx_1;
2760 std::vector<DWARFDIE> decl_ctx_2;
2761 // The declaration DIE stack is a stack of the declaration context DIEs all
2762 // the way back to the compile unit. If a type "T" is declared inside a class
2763 // "B", and class "B" is declared inside a class "A" and class "A" is in a
2764 // namespace "lldb", and the namespace is in a compile unit, there will be a
2767 // [0] DW_TAG_class_type for "B"
2768 // [1] DW_TAG_class_type for "A"
2769 // [2] DW_TAG_namespace for "lldb"
2770 // [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file.
2772 // We grab both contexts and make sure that everything matches all the way
2773 // back to the compiler unit.
2775 // First lets grab the decl contexts for both DIEs
2776 decl_ctx_1 = die1.GetDeclContextDIEs();
2777 decl_ctx_2 = die2.GetDeclContextDIEs();
2778 // Make sure the context arrays have the same size, otherwise we are done
2779 const size_t count1 = decl_ctx_1.size();
2780 const size_t count2 = decl_ctx_2.size();
2781 if (count1 != count2)
2784 // Make sure the DW_TAG values match all the way back up the compile unit. If
2785 // they don't, then we are done.
2786 DWARFDIE decl_ctx_die1;
2787 DWARFDIE decl_ctx_die2;
2789 for (i = 0; i < count1; i++) {
2790 decl_ctx_die1 = decl_ctx_1[i];
2791 decl_ctx_die2 = decl_ctx_2[i];
2792 if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
2797 // Make sure the top item in the decl context die array is always
2798 // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then
2799 // something went wrong in the DWARFDIE::GetDeclContextDIEs()
2801 dw_tag_t cu_tag = decl_ctx_1[count1 - 1].Tag();
2802 UNUSED_IF_ASSERT_DISABLED(cu_tag);
2803 assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit);
2806 // Always skip the compile unit when comparing by only iterating up to "count
2807 // - 1". Here we compare the names as we go.
2808 for (i = 0; i < count1 - 1; i++) {
2809 decl_ctx_die1 = decl_ctx_1[i];
2810 decl_ctx_die2 = decl_ctx_2[i];
2811 const char *name1 = decl_ctx_die1.GetName();
2812 const char *name2 = decl_ctx_die2.GetName();
2813 // If the string was from a DW_FORM_strp, then the pointer will often be
2818 // Name pointers are not equal, so only compare the strings if both are not
2820 if (name1 && name2) {
2821 // If the strings don't compare, we are done...
2822 if (strcmp(name1, name2) != 0)
2825 // One name was NULL while the other wasn't
2829 // We made it through all of the checks and the declaration contexts are
2834 TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(
2835 const DWARFDeclContext &dwarf_decl_ctx) {
2838 const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
2839 if (dwarf_decl_ctx_count > 0) {
2840 const ConstString type_name(dwarf_decl_ctx[0].name);
2841 const dw_tag_t tag = dwarf_decl_ctx[0].tag;
2844 Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION |
2845 DWARF_LOG_LOOKUPS));
2847 GetObjectFile()->GetModule()->LogMessage(
2849 "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%"
2850 "s, qualified-name='%s')",
2851 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2852 dwarf_decl_ctx.GetQualifiedName());
2855 DIEArray die_offsets;
2856 m_index->GetTypes(dwarf_decl_ctx, die_offsets);
2857 const size_t num_matches = die_offsets.size();
2859 // Get the type system that we are looking to find a type for. We will
2860 // use this to ensure any matches we find are in a language that this
2861 // type system supports
2862 const LanguageType language = dwarf_decl_ctx.GetLanguage();
2863 TypeSystem *type_system = nullptr;
2864 if (language != eLanguageTypeUnknown) {
2865 auto type_system_or_err = GetTypeSystemForLanguage(language);
2866 if (auto err = type_system_or_err.takeError()) {
2868 lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
2869 std::move(err), "Cannot get TypeSystem for language {}",
2870 Language::GetNameForLanguageType(language));
2872 type_system = &type_system_or_err.get();
2876 for (size_t i = 0; i < num_matches; ++i) {
2877 const DIERef &die_ref = die_offsets[i];
2878 DWARFDIE type_die = GetDIE(die_ref);
2881 // Make sure type_die's langauge matches the type system we are
2882 // looking for. We don't want to find a "Foo" type from Java if we
2883 // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
2885 !type_system->SupportsLanguage(type_die.GetLanguage()))
2887 bool try_resolving_type = false;
2889 // Don't try and resolve the DIE we are looking for with the DIE
2891 const dw_tag_t type_tag = type_die.Tag();
2892 // Make sure the tags match
2893 if (type_tag == tag) {
2894 // The tags match, lets try resolving this type
2895 try_resolving_type = true;
2897 // The tags don't match, but we need to watch our for a forward
2898 // declaration for a struct and ("struct foo") ends up being a
2899 // class ("class foo { ... };") or vice versa.
2901 case DW_TAG_class_type:
2902 // We had a "class foo", see if we ended up with a "struct foo
2904 try_resolving_type = (tag == DW_TAG_structure_type);
2906 case DW_TAG_structure_type:
2907 // We had a "struct foo", see if we ended up with a "class foo
2909 try_resolving_type = (tag == DW_TAG_class_type);
2912 // Tags don't match, don't event try to resolve using this type
2913 // whose name matches....
2918 if (try_resolving_type) {
2919 DWARFDeclContext type_dwarf_decl_ctx;
2920 type_die.GetDWARFDeclContext(type_dwarf_decl_ctx);
2923 GetObjectFile()->GetModule()->LogMessage(
2926 "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2927 "qualified-name='%s') trying die=0x%8.8x (%s)",
2928 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2929 dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2930 type_dwarf_decl_ctx.GetQualifiedName());
2933 // Make sure the decl contexts match all the way up
2934 if (dwarf_decl_ctx == type_dwarf_decl_ctx) {
2935 Type *resolved_type = ResolveType(type_die, false);
2936 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2937 type_sp = resolved_type->shared_from_this();
2943 std::string qualified_name;
2944 type_die.GetQualifiedName(qualified_name);
2945 GetObjectFile()->GetModule()->LogMessage(
2948 "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2949 "qualified-name='%s') ignoring die=0x%8.8x (%s)",
2950 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2951 dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2952 qualified_name.c_str());
2956 m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
2965 TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die,
2966 bool *type_is_new_ptr) {
2970 auto type_system_or_err =
2971 GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
2972 if (auto err = type_system_or_err.takeError()) {
2973 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
2974 std::move(err), "Unable to parse type");
2978 DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser();
2982 TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, type_is_new_ptr);
2984 GetTypeList().Insert(type_sp);
2986 if (die.Tag() == DW_TAG_subprogram) {
2987 std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
2988 .GetScopeQualifiedName()
2990 if (scope_qualified_name.size()) {
2991 m_function_scope_qualified_name_map[scope_qualified_name].insert(
3000 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc,
3001 const DWARFDIE &orig_die,
3002 bool parse_siblings, bool parse_children) {
3003 size_t types_added = 0;
3004 DWARFDIE die = orig_die;
3007 const dw_tag_t tag = die.Tag();
3008 bool type_is_new = false;
3010 Tag dwarf_tag = static_cast<Tag>(tag);
3012 // TODO: Currently ParseTypeFromDWARF(...) which is called by ParseType(...)
3013 // does not handle DW_TAG_subrange_type. It is not clear if this is a bug or
3015 if (isType(dwarf_tag) && tag != DW_TAG_subrange_type)
3016 ParseType(sc, die, &type_is_new);
3021 if (parse_children && die.HasChildren()) {
3022 if (die.Tag() == DW_TAG_subprogram) {
3023 SymbolContext child_sc(sc);
3024 child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3025 types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3027 types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3031 die = die.GetSibling();
3038 size_t SymbolFileDWARF::ParseBlocksRecursive(Function &func) {
3039 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3040 CompileUnit *comp_unit = func.GetCompileUnit();
3041 lldbassert(comp_unit);
3043 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit);
3047 size_t functions_added = 0;
3048 const dw_offset_t function_die_offset = func.GetID();
3049 DWARFDIE function_die = dwarf_cu->GetDIE(function_die_offset);
3051 ParseBlocksRecursive(*comp_unit, &func.GetBlock(false), function_die,
3052 LLDB_INVALID_ADDRESS, 0);
3055 return functions_added;
3058 size_t SymbolFileDWARF::ParseTypes(CompileUnit &comp_unit) {
3059 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3060 size_t types_added = 0;
3061 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
3063 DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3064 if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3066 sc.comp_unit = &comp_unit;
3067 types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3074 size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) {
3075 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3076 if (sc.comp_unit != nullptr) {
3077 DWARFDebugInfo *info = DebugInfo();
3078 if (info == nullptr)
3082 DWARFDIE function_die = GetDIE(sc.function->GetID());
3084 const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress(
3085 DW_AT_low_pc, LLDB_INVALID_ADDRESS);
3086 if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3087 const size_t num_variables = ParseVariables(
3088 sc, function_die.GetFirstChild(), func_lo_pc, true, true);
3090 // Let all blocks know they have parse all their variables
3091 sc.function->GetBlock(false).SetDidParseVariables(true, true);
3092 return num_variables;
3094 } else if (sc.comp_unit) {
3095 DWARFUnit *dwarf_cu = info->GetUnitAtIndex(sc.comp_unit->GetID());
3097 if (dwarf_cu == nullptr)
3100 uint32_t vars_added = 0;
3101 VariableListSP variables(sc.comp_unit->GetVariableList(false));
3103 if (variables.get() == nullptr) {
3104 variables = std::make_shared<VariableList>();
3105 sc.comp_unit->SetVariableList(variables);
3107 DIEArray die_offsets;
3108 m_index->GetGlobalVariables(dwarf_cu->GetNonSkeletonUnit(),
3110 const size_t num_matches = die_offsets.size();
3112 for (size_t i = 0; i < num_matches; ++i) {
3113 const DIERef &die_ref = die_offsets[i];
3114 DWARFDIE die = GetDIE(die_ref);
3117 ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS));
3119 variables->AddVariableIfUnique(var_sp);
3123 m_index->ReportInvalidDIERef(die_ref, "");
3133 VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc,
3134 const DWARFDIE &die,
3135 const lldb::addr_t func_low_pc) {
3136 if (die.GetDWARF() != this)
3137 return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3143 var_sp = GetDIEToVariable()[die.GetDIE()];
3145 return var_sp; // Already been parsed!
3147 const dw_tag_t tag = die.Tag();
3148 ModuleSP module = GetObjectFile()->GetModule();
3150 if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3151 (tag == DW_TAG_formal_parameter && sc.function)) {
3152 DWARFAttributes attributes;
3153 const size_t num_attributes = die.GetAttributes(attributes);
3155 if (num_attributes > 0) {
3156 const char *name = nullptr;
3157 const char *mangled = nullptr;
3160 DWARFFormValue type_die_form;
3161 DWARFExpression location;
3162 bool is_external = false;
3163 bool is_artificial = false;
3164 bool location_is_const_value_data = false;
3165 bool has_explicit_location = false;
3166 DWARFFormValue const_value;
3167 Variable::RangeList scope_ranges;
3168 // AccessType accessibility = eAccessNone;
3170 for (i = 0; i < num_attributes; ++i) {
3171 dw_attr_t attr = attributes.AttributeAtIndex(i);
3172 DWARFFormValue form_value;
3174 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3176 case DW_AT_decl_file:
3177 decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3178 form_value.Unsigned()));
3180 case DW_AT_decl_line:
3181 decl.SetLine(form_value.Unsigned());
3183 case DW_AT_decl_column:
3184 decl.SetColumn(form_value.Unsigned());
3187 name = form_value.AsCString();
3189 case DW_AT_linkage_name:
3190 case DW_AT_MIPS_linkage_name:
3191 mangled = form_value.AsCString();
3194 type_die_form = form_value;
3196 case DW_AT_external:
3197 is_external = form_value.Boolean();
3199 case DW_AT_const_value:
3200 // If we have already found a DW_AT_location attribute, ignore this
3202 if (!has_explicit_location) {
3203 location_is_const_value_data = true;
3204 // The constant value will be either a block, a data value or a
3206 auto debug_info_data = die.GetData();
3207 if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3208 // Retrieve the value as a block expression.
3209 uint32_t block_offset =
3210 form_value.BlockData() - debug_info_data.GetDataStart();
3211 uint32_t block_length = form_value.Unsigned();
3212 location = DWARFExpression(
3214 DataExtractor(debug_info_data, block_offset, block_length),
3216 } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3217 // Retrieve the value as a data expression.
3218 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3219 if (auto data_length = form_value.GetFixedSize())
3220 location = DWARFExpression(
3222 DataExtractor(debug_info_data, data_offset, *data_length),
3225 const uint8_t *data_pointer = form_value.BlockData();
3227 form_value.Unsigned();
3228 } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3229 // we need to get the byte size of the type later after we
3230 // create the variable
3231 const_value = form_value;
3235 // Retrieve the value as a string expression.
3236 if (form_value.Form() == DW_FORM_strp) {
3237 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3238 if (auto data_length = form_value.GetFixedSize())
3239 location = DWARFExpression(module,
3240 DataExtractor(debug_info_data,
3245 const char *str = form_value.AsCString();
3246 uint32_t string_offset =
3247 str - (const char *)debug_info_data.GetDataStart();
3248 uint32_t string_length = strlen(str) + 1;
3249 location = DWARFExpression(module,
3250 DataExtractor(debug_info_data,
3258 case DW_AT_location: {
3259 location_is_const_value_data = false;
3260 has_explicit_location = true;
3261 if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3262 auto data = die.GetData();
3264 uint32_t block_offset =
3265 form_value.BlockData() - data.GetDataStart();
3266 uint32_t block_length = form_value.Unsigned();
3267 location = DWARFExpression(
3268 module, DataExtractor(data, block_offset, block_length),
3271 DataExtractor data = DebugLocData();
3272 const dw_offset_t offset = form_value.Unsigned();
3273 if (data.ValidOffset(offset)) {
3274 data = DataExtractor(data, offset, data.GetByteSize() - offset);
3275 location = DWARFExpression(module, data, die.GetCU());
3276 assert(func_low_pc != LLDB_INVALID_ADDRESS);
3277 location.SetLocationListSlide(
3279 attributes.CompileUnitAtIndex(i)->GetBaseAddress());
3283 case DW_AT_specification:
3284 spec_die = form_value.Reference();
3286 case DW_AT_start_scope:
3287 // TODO: Implement this.
3289 case DW_AT_artificial:
3290 is_artificial = form_value.Boolean();
3292 case DW_AT_accessibility:
3293 break; // accessibility =
3294 // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
3295 case DW_AT_declaration:
3296 case DW_AT_description:
3297 case DW_AT_endianity:
3299 case DW_AT_visibility:
3301 case DW_AT_abstract_origin:
3308 const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3309 const dw_tag_t parent_tag = die.GetParent().Tag();
3310 bool is_static_member =
3311 (parent_tag == DW_TAG_compile_unit ||
3312 parent_tag == DW_TAG_partial_unit) &&
3313 (parent_context_die.Tag() == DW_TAG_class_type ||
3314 parent_context_die.Tag() == DW_TAG_structure_type);
3316 ValueType scope = eValueTypeInvalid;
3318 const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3319 SymbolContextScope *symbol_context_scope = nullptr;
3321 bool has_explicit_mangled = mangled != nullptr;
3323 // LLDB relies on the mangled name (DW_TAG_linkage_name or
3324 // DW_AT_MIPS_linkage_name) to generate fully qualified names
3325 // of global variables with commands like "frame var j". For
3326 // example, if j were an int variable holding a value 4 and
3327 // declared in a namespace B which in turn is contained in a
3328 // namespace A, the command "frame var j" returns
3329 // "(int) A::B::j = 4".
3330 // If the compiler does not emit a linkage name, we should be
3331 // able to generate a fully qualified name from the
3332 // declaration context.
3333 if ((parent_tag == DW_TAG_compile_unit ||
3334 parent_tag == DW_TAG_partial_unit) &&
3335 Language::LanguageIsCPlusPlus(die.GetLanguage())) {
3336 DWARFDeclContext decl_ctx;
3338 die.GetDWARFDeclContext(decl_ctx);
3339 mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString();
3343 if (tag == DW_TAG_formal_parameter)
3344 scope = eValueTypeVariableArgument;
3346 // DWARF doesn't specify if a DW_TAG_variable is a local, global
3347 // or static variable, so we have to do a little digging:
3348 // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3349 // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3350 // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3351 // Clang likes to combine small global variables into the same symbol
3352 // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3353 // so we need to look through the whole expression.
3354 bool is_static_lifetime =
3355 has_explicit_mangled ||
3356 (has_explicit_location && !location.IsValid());
3357 // Check if the location has a DW_OP_addr with any address value...
3358 lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3359 if (!location_is_const_value_data) {
3360 bool op_error = false;
3361 location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error);
3364 location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0,
3366 GetObjectFile()->GetModule()->ReportError(
3367 "0x%8.8x: %s has an invalid location: %s", die.GetOffset(),
3368 die.GetTagAsCString(), strm.GetData());
3370 if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
3371 is_static_lifetime = true;
3373 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
3374 if (debug_map_symfile)
3375 // Set the module of the expression to the linked module
3376 // instead of the oject file so the relocated address can be
3378 location.SetModule(debug_map_symfile->GetObjectFile()->GetModule());
3380 if (is_static_lifetime) {
3382 scope = eValueTypeVariableGlobal;
3384 scope = eValueTypeVariableStatic;
3386 if (debug_map_symfile) {
3387 // When leaving the DWARF in the .o files on darwin, when we have a
3388 // global variable that wasn't initialized, the .o file might not
3389 // have allocated a virtual address for the global variable. In
3390 // this case it will have created a symbol for the global variable
3391 // that is undefined/data and external and the value will be the
3392 // byte size of the variable. When we do the address map in
3393 // SymbolFileDWARFDebugMap we rely on having an address, we need to
3394 // do some magic here so we can get the correct address for our
3395 // global variable. The address for all of these entries will be
3396 // zero, and there will be an undefined symbol in this object file,
3397 // and the executable will have a matching symbol with a good
3398 // address. So here we dig up the correct address and replace it in
3399 // the location for the variable, and set the variable's symbol
3400 // context scope to be that of the main executable so the file
3401 // address will resolve correctly.
3402 bool linked_oso_file_addr = false;
3403 if (is_external && location_DW_OP_addr == 0) {
3404 // we have a possible uninitialized extern global
3405 ConstString const_name(mangled ? mangled : name);
3406 ObjectFile *debug_map_objfile =
3407 debug_map_symfile->GetObjectFile();
3408 if (debug_map_objfile) {
3409 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3410 if (debug_map_symtab) {
3411 Symbol *exe_symbol =
3412 debug_map_symtab->FindFirstSymbolWithNameAndType(
3413 const_name, eSymbolTypeData, Symtab::eDebugYes,
3414 Symtab::eVisibilityExtern);
3416 if (exe_symbol->ValueIsAddress()) {
3417 const addr_t exe_file_addr =
3418 exe_symbol->GetAddressRef().GetFileAddress();
3419 if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3420 if (location.Update_DW_OP_addr(exe_file_addr)) {
3421 linked_oso_file_addr = true;
3422 symbol_context_scope = exe_symbol;
3431 if (!linked_oso_file_addr) {
3432 // The DW_OP_addr is not zero, but it contains a .o file address
3433 // which needs to be linked up correctly.
3434 const lldb::addr_t exe_file_addr =
3435 debug_map_symfile->LinkOSOFileAddress(this,
3436 location_DW_OP_addr);
3437 if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3438 // Update the file address for this variable
3439 location.Update_DW_OP_addr(exe_file_addr);
3441 // Variable didn't make it into the final executable
3447 if (location_is_const_value_data)
3448 scope = eValueTypeVariableStatic;
3450 scope = eValueTypeVariableLocal;
3451 if (debug_map_symfile) {
3452 // We need to check for TLS addresses that we need to fixup
3453 if (location.ContainsThreadLocalStorage()) {
3454 location.LinkThreadLocalStorage(
3455 debug_map_symfile->GetObjectFile()->GetModule(),
3456 [this, debug_map_symfile](
3457 lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
3458 return debug_map_symfile->LinkOSOFileAddress(
3459 this, unlinked_file_addr);
3461 scope = eValueTypeVariableThreadLocal;
3468 if (symbol_context_scope == nullptr) {
3469 switch (parent_tag) {
3470 case DW_TAG_subprogram:
3471 case DW_TAG_inlined_subroutine:
3472 case DW_TAG_lexical_block:
3474 symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(
3475 sc_parent_die.GetID());
3476 if (symbol_context_scope == nullptr)
3477 symbol_context_scope = sc.function;
3482 symbol_context_scope = sc.comp_unit;
3487 if (symbol_context_scope) {
3488 SymbolFileTypeSP type_sp(
3489 new SymbolFileType(*this, GetUID(type_die_form.Reference())));
3491 if (const_value.Form() && type_sp && type_sp->GetType())
3492 location.UpdateValue(const_value.Unsigned(),
3493 type_sp->GetType()->GetByteSize().getValueOr(0),
3494 die.GetCU()->GetAddressByteSize());
3496 var_sp = std::make_shared<Variable>(
3497 die.GetID(), name, mangled, type_sp, scope, symbol_context_scope,
3498 scope_ranges, &decl, location, is_external, is_artificial,
3501 var_sp->SetLocationIsConstantValueData(location_is_const_value_data);
3503 // Not ready to parse this variable yet. It might be a global or static
3504 // variable that is in a function scope and the function in the symbol
3505 // context wasn't filled in yet
3509 // Cache var_sp even if NULL (the variable was just a specification or was
3510 // missing vital information to be able to be displayed in the debugger
3511 // (missing location due to optimization, etc)) so we don't re-parse this
3512 // DIE over and over later...
3513 GetDIEToVariable()[die.GetDIE()] = var_sp;
3515 GetDIEToVariable()[spec_die.GetDIE()] = var_sp;
3521 SymbolFileDWARF::FindBlockContainingSpecification(
3522 const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
3523 // Give the concrete function die specified by "func_die_offset", find the
3524 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3525 // to "spec_block_die_offset"
3526 return FindBlockContainingSpecification(DebugInfo()->GetDIE(func_die_ref),
3527 spec_block_die_offset);
3531 SymbolFileDWARF::FindBlockContainingSpecification(
3532 const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
3534 switch (die.Tag()) {
3535 case DW_TAG_subprogram:
3536 case DW_TAG_inlined_subroutine:
3537 case DW_TAG_lexical_block: {
3538 if (die.GetReferencedDIE(DW_AT_specification).GetOffset() ==
3539 spec_block_die_offset)
3542 if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() ==
3543 spec_block_die_offset)
3550 // Give the concrete function die specified by "func_die_offset", find the
3551 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3552 // to "spec_block_die_offset"
3553 for (DWARFDIE child_die = die.GetFirstChild(); child_die;
3554 child_die = child_die.GetSibling()) {
3555 DWARFDIE result_die =
3556 FindBlockContainingSpecification(child_die, spec_block_die_offset);
3565 size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc,
3566 const DWARFDIE &orig_die,
3567 const lldb::addr_t func_low_pc,
3568 bool parse_siblings, bool parse_children,
3569 VariableList *cc_variable_list) {
3573 VariableListSP variable_list_sp;
3575 size_t vars_added = 0;
3576 DWARFDIE die = orig_die;
3578 dw_tag_t tag = die.Tag();
3580 // Check to see if we have already parsed this variable or constant?
3581 VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
3583 if (cc_variable_list)
3584 cc_variable_list->AddVariableIfUnique(var_sp);
3586 // We haven't already parsed it, lets do that now.
3587 if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3588 (tag == DW_TAG_formal_parameter && sc.function)) {
3589 if (variable_list_sp.get() == nullptr) {
3590 DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die);
3591 dw_tag_t parent_tag = sc_parent_die.Tag();
3592 switch (parent_tag) {
3593 case DW_TAG_compile_unit:
3594 case DW_TAG_partial_unit:
3595 if (sc.comp_unit != nullptr) {
3596 variable_list_sp = sc.comp_unit->GetVariableList(false);
3597 if (variable_list_sp.get() == nullptr) {
3598 variable_list_sp = std::make_shared<VariableList>();
3601 GetObjectFile()->GetModule()->ReportError(
3602 "parent 0x%8.8" PRIx64 " %s with no valid compile unit in "
3603 "symbol context for 0x%8.8" PRIx64 " %s.\n",
3604 sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(),
3605 orig_die.GetID(), orig_die.GetTagAsCString());
3609 case DW_TAG_subprogram:
3610 case DW_TAG_inlined_subroutine:
3611 case DW_TAG_lexical_block:
3612 if (sc.function != nullptr) {
3613 // Check to see if we already have parsed the variables for the
3616 Block *block = sc.function->GetBlock(true).FindBlockByID(
3617 sc_parent_die.GetID());
3618 if (block == nullptr) {
3619 // This must be a specification or abstract origin with a
3620 // concrete block counterpart in the current function. We need
3621 // to find the concrete block so we can correctly add the
3623 const DWARFDIE concrete_block_die =
3624 FindBlockContainingSpecification(
3625 GetDIE(sc.function->GetID()),
3626 sc_parent_die.GetOffset());
3627 if (concrete_block_die)
3628 block = sc.function->GetBlock(true).FindBlockByID(
3629 concrete_block_die.GetID());
3632 if (block != nullptr) {
3633 const bool can_create = false;
3634 variable_list_sp = block->GetBlockVariableList(can_create);
3635 if (variable_list_sp.get() == nullptr) {
3636 variable_list_sp = std::make_shared<VariableList>();
3637 block->SetVariableList(variable_list_sp);
3644 GetObjectFile()->GetModule()->ReportError(
3645 "didn't find appropriate parent DIE for variable list for "
3646 "0x%8.8" PRIx64 " %s.\n",
3647 orig_die.GetID(), orig_die.GetTagAsCString());
3652 if (variable_list_sp) {
3653 VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc));
3655 variable_list_sp->AddVariableIfUnique(var_sp);
3656 if (cc_variable_list)
3657 cc_variable_list->AddVariableIfUnique(var_sp);
3664 bool skip_children = (sc.function == nullptr && tag == DW_TAG_subprogram);
3666 if (!skip_children && parse_children && die.HasChildren()) {
3667 vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true,
3668 true, cc_variable_list);
3672 die = die.GetSibling();
3679 /// Collect call site parameters in a DW_TAG_call_site DIE.
3680 static CallSiteParameterArray
3681 CollectCallSiteParameters(ModuleSP module, DWARFDIE call_site_die) {
3682 CallSiteParameterArray parameters;
3683 for (DWARFDIE child = call_site_die.GetFirstChild(); child.IsValid();
3684 child = child.GetSibling()) {
3685 if (child.Tag() != DW_TAG_call_site_parameter)
3688 llvm::Optional<DWARFExpression> LocationInCallee = {};
3689 llvm::Optional<DWARFExpression> LocationInCaller = {};
3691 DWARFAttributes attributes;
3692 const size_t num_attributes = child.GetAttributes(attributes);
3694 // Parse the location at index \p attr_index within this call site parameter
3695 // DIE, or return None on failure.
3696 auto parse_simple_location =
3697 [&](int attr_index) -> llvm::Optional<DWARFExpression> {
3698 DWARFFormValue form_value;
3699 if (!attributes.ExtractFormValueAtIndex(attr_index, form_value))
3701 if (!DWARFFormValue::IsBlockForm(form_value.Form()))
3703 auto data = child.GetData();
3704 uint32_t block_offset = form_value.BlockData() - data.GetDataStart();
3705 uint32_t block_length = form_value.Unsigned();
3706 return DWARFExpression(module,
3707 DataExtractor(data, block_offset, block_length),
3711 for (size_t i = 0; i < num_attributes; ++i) {
3712 dw_attr_t attr = attributes.AttributeAtIndex(i);
3713 if (attr == DW_AT_location)
3714 LocationInCallee = parse_simple_location(i);
3715 if (attr == DW_AT_call_value)
3716 LocationInCaller = parse_simple_location(i);
3719 if (LocationInCallee && LocationInCaller) {
3720 CallSiteParameter param = {*LocationInCallee, *LocationInCaller};
3721 parameters.push_back(param);
3727 /// Collect call graph edges present in a function DIE.
3728 static std::vector<lldb_private::CallEdge>
3729 CollectCallEdges(ModuleSP module, DWARFDIE function_die) {
3730 // Check if the function has a supported call site-related attribute.
3731 // TODO: In the future it may be worthwhile to support call_all_source_calls.
3732 uint64_t has_call_edges =
3733 function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0);
3734 if (!has_call_edges)
3737 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3738 LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}",
3739 function_die.GetPubname());
3741 // Scan the DIE for TAG_call_site entries.
3742 // TODO: A recursive scan of all blocks in the subprogram is needed in order
3743 // to be DWARF5-compliant. This may need to be done lazily to be performant.
3744 // For now, assume that all entries are nested directly under the subprogram
3745 // (this is the kind of DWARF LLVM produces) and parse them eagerly.
3746 std::vector<CallEdge> call_edges;
3747 for (DWARFDIE child = function_die.GetFirstChild(); child.IsValid();
3748 child = child.GetSibling()) {
3749 if (child.Tag() != DW_TAG_call_site)
3752 // Extract DW_AT_call_origin (the call target's DIE).
3753 DWARFDIE call_origin = child.GetReferencedDIE(DW_AT_call_origin);
3754 if (!call_origin.IsValid()) {
3755 LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}",
3756 function_die.GetPubname());
3760 // Extract DW_AT_call_return_pc (the PC the call returns to) if it's
3761 // available. It should only ever be unavailable for tail call edges, in
3762 // which case use LLDB_INVALID_ADDRESS.
3763 addr_t return_pc = child.GetAttributeValueAsAddress(DW_AT_call_return_pc,
3764 LLDB_INVALID_ADDRESS);
3766 // Extract call site parameters.
3767 CallSiteParameterArray parameters =
3768 CollectCallSiteParameters(module, child);
3770 LLDB_LOG(log, "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x})",
3771 call_origin.GetPubname(), return_pc);
3772 if (log && parameters.size()) {
3773 for (const CallSiteParameter ¶m : parameters) {
3774 StreamString callee_loc_desc, caller_loc_desc;
3775 param.LocationInCallee.GetDescription(&callee_loc_desc,
3776 eDescriptionLevelBrief,
3777 LLDB_INVALID_ADDRESS, nullptr);
3778 param.LocationInCaller.GetDescription(&caller_loc_desc,
3779 eDescriptionLevelBrief,
3780 LLDB_INVALID_ADDRESS, nullptr);
3781 LLDB_LOG(log, "CollectCallEdges: \tparam: {0} => {1}",
3782 callee_loc_desc.GetString(), caller_loc_desc.GetString());
3786 call_edges.emplace_back(call_origin.GetMangledName(), return_pc,
3787 std::move(parameters));
3792 std::vector<lldb_private::CallEdge>
3793 SymbolFileDWARF::ParseCallEdgesInFunction(UserID func_id) {
3794 DWARFDIE func_die = GetDIE(func_id.GetID());
3795 if (func_die.IsValid())
3796 return CollectCallEdges(GetObjectFile()->GetModule(), func_die);
3800 // PluginInterface protocol
3801 ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); }
3803 uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; }
3805 void SymbolFileDWARF::Dump(lldb_private::Stream &s) {
3806 SymbolFile::Dump(s);
3810 void SymbolFileDWARF::DumpClangAST(Stream &s) {
3811 auto ts_or_err = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
3814 ClangASTContext *clang =
3815 llvm::dyn_cast_or_null<ClangASTContext>(&ts_or_err.get());
3821 SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() {
3822 if (m_debug_map_symfile == nullptr && !m_debug_map_module_wp.expired()) {
3823 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
3825 m_debug_map_symfile =
3826 (SymbolFileDWARFDebugMap *)module_sp->GetSymbolFile();
3829 return m_debug_map_symfile;
3832 DWARFExpression::LocationListFormat
3833 SymbolFileDWARF::GetLocationListFormat() const {
3834 if (m_data_debug_loclists.m_data.GetByteSize() > 0)
3835 return DWARFExpression::LocLists;
3836 return DWARFExpression::RegularLocationList;
3839 SymbolFileDWARFDwp *SymbolFileDWARF::GetDwpSymbolFile() {
3840 llvm::call_once(m_dwp_symfile_once_flag, [this]() {
3841 ModuleSpec module_spec;
3842 module_spec.GetFileSpec() = m_objfile_sp->GetFileSpec();
3843 module_spec.GetSymbolFileSpec() =
3844 FileSpec(m_objfile_sp->GetFileSpec().GetPath() + ".dwp");
3846 FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths();
3847 FileSpec dwp_filespec =
3848 Symbols::LocateExecutableSymbolFile(module_spec, search_paths);
3849 if (FileSystem::Instance().Exists(dwp_filespec)) {
3850 m_dwp_symfile = SymbolFileDWARFDwp::Create(GetObjectFile()->GetModule(),
3854 return m_dwp_symfile.get();