1 //===- DWARFVerifier.cpp --------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
8 #include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
9 #include "llvm/ADT/SmallSet.h"
10 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
11 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
12 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
13 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
14 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
15 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
16 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
17 #include "llvm/Support/DJB.h"
18 #include "llvm/Support/FormatVariadic.h"
19 #include "llvm/Support/WithColor.h"
20 #include "llvm/Support/raw_ostream.h"
26 using namespace dwarf;
27 using namespace object;
29 DWARFVerifier::DieRangeInfo::address_range_iterator
30 DWARFVerifier::DieRangeInfo::insert(const DWARFAddressRange &R) {
31 auto Begin = Ranges.begin();
32 auto End = Ranges.end();
33 auto Pos = std::lower_bound(Begin, End, R);
36 if (Pos->intersects(R))
40 if (Iter->intersects(R))
45 Ranges.insert(Pos, R);
49 DWARFVerifier::DieRangeInfo::die_range_info_iterator
50 DWARFVerifier::DieRangeInfo::insert(const DieRangeInfo &RI) {
51 auto End = Children.end();
52 auto Iter = Children.begin();
54 if (Iter->intersects(RI))
59 return Children.end();
62 bool DWARFVerifier::DieRangeInfo::contains(const DieRangeInfo &RHS) const {
63 auto I1 = Ranges.begin(), E1 = Ranges.end();
64 auto I2 = RHS.Ranges.begin(), E2 = RHS.Ranges.end();
68 DWARFAddressRange R = *I2;
70 bool Covered = I1->LowPC <= R.LowPC;
71 if (R.LowPC == R.HighPC || (Covered && R.HighPC <= I1->HighPC)) {
79 if (R.LowPC < I1->HighPC)
86 bool DWARFVerifier::DieRangeInfo::intersects(const DieRangeInfo &RHS) const {
87 auto I1 = Ranges.begin(), E1 = Ranges.end();
88 auto I2 = RHS.Ranges.begin(), E2 = RHS.Ranges.end();
89 while (I1 != E1 && I2 != E2) {
90 if (I1->intersects(*I2))
92 if (I1->LowPC < I2->LowPC)
100 bool DWARFVerifier::verifyUnitHeader(const DWARFDataExtractor DebugInfoData,
101 uint32_t *Offset, unsigned UnitIndex,
102 uint8_t &UnitType, bool &isUnitDWARF64) {
103 uint64_t AbbrOffset, Length;
104 uint8_t AddrSize = 0;
108 bool ValidLength = false;
109 bool ValidVersion = false;
110 bool ValidAddrSize = false;
111 bool ValidType = true;
112 bool ValidAbbrevOffset = true;
114 uint32_t OffsetStart = *Offset;
115 Length = DebugInfoData.getU32(Offset);
116 if (Length == UINT32_MAX) {
117 Length = DebugInfoData.getU64(Offset);
118 isUnitDWARF64 = true;
120 Version = DebugInfoData.getU16(Offset);
123 UnitType = DebugInfoData.getU8(Offset);
124 AddrSize = DebugInfoData.getU8(Offset);
125 AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
126 ValidType = dwarf::isUnitType(UnitType);
129 AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
130 AddrSize = DebugInfoData.getU8(Offset);
133 if (!DCtx.getDebugAbbrev()->getAbbreviationDeclarationSet(AbbrOffset))
134 ValidAbbrevOffset = false;
136 ValidLength = DebugInfoData.isValidOffset(OffsetStart + Length + 3);
137 ValidVersion = DWARFContext::isSupportedVersion(Version);
138 ValidAddrSize = AddrSize == 4 || AddrSize == 8;
139 if (!ValidLength || !ValidVersion || !ValidAddrSize || !ValidAbbrevOffset ||
142 error() << format("Units[%d] - start offset: 0x%08x \n", UnitIndex,
145 note() << "The length for this unit is too "
146 "large for the .debug_info provided.\n";
148 note() << "The 16 bit unit header version is not valid.\n";
150 note() << "The unit type encoding is not valid.\n";
151 if (!ValidAbbrevOffset)
152 note() << "The offset into the .debug_abbrev section is "
155 note() << "The address size is unsupported.\n";
157 *Offset = OffsetStart + Length + (isUnitDWARF64 ? 12 : 4);
161 unsigned DWARFVerifier::verifyUnitContents(DWARFUnit &Unit) {
162 unsigned NumUnitErrors = 0;
163 unsigned NumDies = Unit.getNumDIEs();
164 for (unsigned I = 0; I < NumDies; ++I) {
165 auto Die = Unit.getDIEAtIndex(I);
167 if (Die.getTag() == DW_TAG_null)
170 for (auto AttrValue : Die.attributes()) {
171 NumUnitErrors += verifyDebugInfoAttribute(Die, AttrValue);
172 NumUnitErrors += verifyDebugInfoForm(Die, AttrValue);
175 NumUnitErrors += verifyDebugInfoCallSite(Die);
178 DWARFDie Die = Unit.getUnitDIE(/* ExtractUnitDIEOnly = */ false);
180 error() << "Compilation unit without DIE.\n";
182 return NumUnitErrors;
185 if (!dwarf::isUnitType(Die.getTag())) {
186 error() << "Compilation unit root DIE is not a unit DIE: "
187 << dwarf::TagString(Die.getTag()) << ".\n";
191 uint8_t UnitType = Unit.getUnitType();
192 if (!DWARFUnit::isMatchingUnitTypeAndTag(UnitType, Die.getTag())) {
193 error() << "Compilation unit type (" << dwarf::UnitTypeString(UnitType)
194 << ") and root DIE (" << dwarf::TagString(Die.getTag())
195 << ") do not match.\n";
200 NumUnitErrors += verifyDieRanges(Die, RI);
202 return NumUnitErrors;
205 unsigned DWARFVerifier::verifyDebugInfoCallSite(const DWARFDie &Die) {
206 if (Die.getTag() != DW_TAG_call_site)
209 DWARFDie Curr = Die.getParent();
210 for (; Curr.isValid() && !Curr.isSubprogramDIE(); Curr = Die.getParent()) {
211 if (Curr.getTag() == DW_TAG_inlined_subroutine) {
212 error() << "Call site entry nested within inlined subroutine:";
218 if (!Curr.isValid()) {
219 error() << "Call site entry not nested within a valid subprogram:";
224 Optional<DWARFFormValue> CallAttr =
225 Curr.find({DW_AT_call_all_calls, DW_AT_call_all_source_calls,
226 DW_AT_call_all_tail_calls});
228 error() << "Subprogram with call site entry has no DW_AT_call attribute:";
230 Die.dump(OS, /*indent*/ 1);
237 unsigned DWARFVerifier::verifyAbbrevSection(const DWARFDebugAbbrev *Abbrev) {
238 unsigned NumErrors = 0;
240 const DWARFAbbreviationDeclarationSet *AbbrDecls =
241 Abbrev->getAbbreviationDeclarationSet(0);
242 for (auto AbbrDecl : *AbbrDecls) {
243 SmallDenseSet<uint16_t> AttributeSet;
244 for (auto Attribute : AbbrDecl.attributes()) {
245 auto Result = AttributeSet.insert(Attribute.Attr);
246 if (!Result.second) {
247 error() << "Abbreviation declaration contains multiple "
248 << AttributeString(Attribute.Attr) << " attributes.\n";
258 bool DWARFVerifier::handleDebugAbbrev() {
259 OS << "Verifying .debug_abbrev...\n";
261 const DWARFObject &DObj = DCtx.getDWARFObj();
262 unsigned NumErrors = 0;
263 if (!DObj.getAbbrevSection().empty())
264 NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrev());
265 if (!DObj.getAbbrevDWOSection().empty())
266 NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrevDWO());
268 return NumErrors == 0;
271 unsigned DWARFVerifier::verifyUnitSection(const DWARFSection &S,
272 DWARFSectionKind SectionKind) {
273 const DWARFObject &DObj = DCtx.getDWARFObj();
274 DWARFDataExtractor DebugInfoData(DObj, S, DCtx.isLittleEndian(), 0);
275 unsigned NumDebugInfoErrors = 0;
276 uint32_t OffsetStart = 0, Offset = 0, UnitIdx = 0;
277 uint8_t UnitType = 0;
278 bool isUnitDWARF64 = false;
279 bool isHeaderChainValid = true;
280 bool hasDIE = DebugInfoData.isValidOffset(Offset);
281 DWARFUnitVector TypeUnitVector;
282 DWARFUnitVector CompileUnitVector;
284 OffsetStart = Offset;
285 if (!verifyUnitHeader(DebugInfoData, &Offset, UnitIdx, UnitType,
287 isHeaderChainValid = false;
291 DWARFUnitHeader Header;
292 Header.extract(DCtx, DebugInfoData, &OffsetStart, SectionKind);
295 case dwarf::DW_UT_type:
296 case dwarf::DW_UT_split_type: {
297 Unit = TypeUnitVector.addUnit(llvm::make_unique<DWARFTypeUnit>(
298 DCtx, S, Header, DCtx.getDebugAbbrev(), &DObj.getRangeSection(),
299 &DObj.getLocSection(), DObj.getStringSection(),
300 DObj.getStringOffsetSection(), &DObj.getAppleObjCSection(),
301 DObj.getLineSection(), DCtx.isLittleEndian(), false,
305 case dwarf::DW_UT_skeleton:
306 case dwarf::DW_UT_split_compile:
307 case dwarf::DW_UT_compile:
308 case dwarf::DW_UT_partial:
309 // UnitType = 0 means that we are verifying a compile unit in DWARF v4.
311 Unit = CompileUnitVector.addUnit(llvm::make_unique<DWARFCompileUnit>(
312 DCtx, S, Header, DCtx.getDebugAbbrev(), &DObj.getRangeSection(),
313 &DObj.getLocSection(), DObj.getStringSection(),
314 DObj.getStringOffsetSection(), &DObj.getAppleObjCSection(),
315 DObj.getLineSection(), DCtx.isLittleEndian(), false,
319 default: { llvm_unreachable("Invalid UnitType."); }
321 NumDebugInfoErrors += verifyUnitContents(*Unit);
323 hasDIE = DebugInfoData.isValidOffset(Offset);
326 if (UnitIdx == 0 && !hasDIE) {
327 warn() << "Section is empty.\n";
328 isHeaderChainValid = true;
330 if (!isHeaderChainValid)
331 ++NumDebugInfoErrors;
332 NumDebugInfoErrors += verifyDebugInfoReferences();
333 return NumDebugInfoErrors;
336 bool DWARFVerifier::handleDebugInfo() {
337 const DWARFObject &DObj = DCtx.getDWARFObj();
338 unsigned NumErrors = 0;
340 OS << "Verifying .debug_info Unit Header Chain...\n";
341 DObj.forEachInfoSections([&](const DWARFSection &S) {
342 NumErrors += verifyUnitSection(S, DW_SECT_INFO);
345 OS << "Verifying .debug_types Unit Header Chain...\n";
346 DObj.forEachTypesSections([&](const DWARFSection &S) {
347 NumErrors += verifyUnitSection(S, DW_SECT_TYPES);
349 return NumErrors == 0;
352 unsigned DWARFVerifier::verifyDieRanges(const DWARFDie &Die,
353 DieRangeInfo &ParentRI) {
354 unsigned NumErrors = 0;
359 auto RangesOrError = Die.getAddressRanges();
360 if (!RangesOrError) {
361 // FIXME: Report the error.
363 llvm::consumeError(RangesOrError.takeError());
367 DWARFAddressRangesVector Ranges = RangesOrError.get();
368 // Build RI for this DIE and check that ranges within this DIE do not
370 DieRangeInfo RI(Die);
372 // TODO support object files better
374 // Some object file formats (i.e. non-MachO) support COMDAT. ELF in
375 // particular does so by placing each function into a section. The DWARF data
376 // for the function at that point uses a section relative DW_FORM_addrp for
377 // the DW_AT_low_pc and a DW_FORM_data4 for the offset as the DW_AT_high_pc.
378 // In such a case, when the Die is the CU, the ranges will overlap, and we
379 // will flag valid conflicting ranges as invalid.
381 // For such targets, we should read the ranges from the CU and partition them
382 // by the section id. The ranges within a particular section should be
383 // disjoint, although the ranges across sections may overlap. We would map
384 // the child die to the entity that it references and the section with which
385 // it is associated. The child would then be checked against the range
386 // information for the associated section.
388 // For now, simply elide the range verification for the CU DIEs if we are
389 // processing an object file.
391 if (!IsObjectFile || IsMachOObject || Die.getTag() != DW_TAG_compile_unit) {
392 for (auto Range : Ranges) {
393 if (!Range.valid()) {
395 error() << "Invalid address range " << Range << "\n";
399 // Verify that ranges don't intersect.
400 const auto IntersectingRange = RI.insert(Range);
401 if (IntersectingRange != RI.Ranges.end()) {
403 error() << "DIE has overlapping address ranges: " << Range << " and "
404 << *IntersectingRange << "\n";
410 // Verify that children don't intersect.
411 const auto IntersectingChild = ParentRI.insert(RI);
412 if (IntersectingChild != ParentRI.Children.end()) {
414 error() << "DIEs have overlapping address ranges:";
416 dump(IntersectingChild->Die) << '\n';
419 // Verify that ranges are contained within their parent.
420 bool ShouldBeContained = !Ranges.empty() && !ParentRI.Ranges.empty() &&
421 !(Die.getTag() == DW_TAG_subprogram &&
422 ParentRI.Die.getTag() == DW_TAG_subprogram);
423 if (ShouldBeContained && !ParentRI.contains(RI)) {
425 error() << "DIE address ranges are not contained in its parent's ranges:";
427 dump(Die, 2) << '\n';
430 // Recursively check children.
431 for (DWARFDie Child : Die)
432 NumErrors += verifyDieRanges(Child, RI);
437 unsigned DWARFVerifier::verifyDebugInfoAttribute(const DWARFDie &Die,
438 DWARFAttribute &AttrValue) {
439 unsigned NumErrors = 0;
440 auto ReportError = [&](const Twine &TitleMsg) {
442 error() << TitleMsg << '\n';
446 const DWARFObject &DObj = DCtx.getDWARFObj();
447 const auto Attr = AttrValue.Attr;
450 // Make sure the offset in the DW_AT_ranges attribute is valid.
451 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
452 if (*SectionOffset >= DObj.getRangeSection().Data.size())
453 ReportError("DW_AT_ranges offset is beyond .debug_ranges bounds:");
456 ReportError("DIE has invalid DW_AT_ranges encoding:");
458 case DW_AT_stmt_list:
459 // Make sure the offset in the DW_AT_stmt_list attribute is valid.
460 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
461 if (*SectionOffset >= DObj.getLineSection().Data.size())
462 ReportError("DW_AT_stmt_list offset is beyond .debug_line bounds: " +
463 llvm::formatv("{0:x8}", *SectionOffset));
466 ReportError("DIE has invalid DW_AT_stmt_list encoding:");
468 case DW_AT_location: {
469 auto VerifyLocationExpr = [&](StringRef D) {
470 DWARFUnit *U = Die.getDwarfUnit();
471 DataExtractor Data(D, DCtx.isLittleEndian(), 0);
472 DWARFExpression Expression(Data, U->getVersion(),
473 U->getAddressByteSize());
474 bool Error = llvm::any_of(Expression, [](DWARFExpression::Operation &Op) {
477 if (Error || !Expression.verify(U))
478 ReportError("DIE contains invalid DWARF expression:");
480 if (Optional<ArrayRef<uint8_t>> Expr = AttrValue.Value.getAsBlock()) {
481 // Verify inlined location.
482 VerifyLocationExpr(llvm::toStringRef(*Expr));
483 } else if (auto LocOffset = AttrValue.Value.getAsSectionOffset()) {
484 // Verify location list.
485 if (auto DebugLoc = DCtx.getDebugLoc())
486 if (auto LocList = DebugLoc->getLocationListAtOffset(*LocOffset))
487 for (const auto &Entry : LocList->Entries)
488 VerifyLocationExpr({Entry.Loc.data(), Entry.Loc.size()});
492 case DW_AT_specification:
493 case DW_AT_abstract_origin: {
494 if (auto ReferencedDie = Die.getAttributeValueAsReferencedDie(Attr)) {
495 auto DieTag = Die.getTag();
496 auto RefTag = ReferencedDie.getTag();
497 if (DieTag == RefTag)
499 if (DieTag == DW_TAG_inlined_subroutine && RefTag == DW_TAG_subprogram)
501 if (DieTag == DW_TAG_variable && RefTag == DW_TAG_member)
503 ReportError("DIE with tag " + TagString(DieTag) + " has " +
504 AttributeString(Attr) +
505 " that points to DIE with "
506 "incompatible tag " +
512 DWARFDie TypeDie = Die.getAttributeValueAsReferencedDie(DW_AT_type);
513 if (TypeDie && !isType(TypeDie.getTag())) {
514 ReportError("DIE has " + AttributeString(Attr) +
515 " with incompatible tag " + TagString(TypeDie.getTag()));
525 unsigned DWARFVerifier::verifyDebugInfoForm(const DWARFDie &Die,
526 DWARFAttribute &AttrValue) {
527 const DWARFObject &DObj = DCtx.getDWARFObj();
528 auto DieCU = Die.getDwarfUnit();
529 unsigned NumErrors = 0;
530 const auto Form = AttrValue.Value.getForm();
536 case DW_FORM_ref_udata: {
537 // Verify all CU relative references are valid CU offsets.
538 Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
541 auto CUSize = DieCU->getNextUnitOffset() - DieCU->getOffset();
542 auto CUOffset = AttrValue.Value.getRawUValue();
543 if (CUOffset >= CUSize) {
545 error() << FormEncodingString(Form) << " CU offset "
546 << format("0x%08" PRIx64, CUOffset)
547 << " is invalid (must be less than CU size of "
548 << format("0x%08" PRIx32, CUSize) << "):\n";
549 Die.dump(OS, 0, DumpOpts);
552 // Valid reference, but we will verify it points to an actual
554 ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
559 case DW_FORM_ref_addr: {
560 // Verify all absolute DIE references have valid offsets in the
561 // .debug_info section.
562 Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
565 if (*RefVal >= DieCU->getInfoSection().Data.size()) {
567 error() << "DW_FORM_ref_addr offset beyond .debug_info "
571 // Valid reference, but we will verify it points to an actual
573 ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
579 auto SecOffset = AttrValue.Value.getAsSectionOffset();
580 assert(SecOffset); // DW_FORM_strp is a section offset.
581 if (SecOffset && *SecOffset >= DObj.getStringSection().size()) {
583 error() << "DW_FORM_strp offset beyond .debug_str bounds:\n";
592 case DW_FORM_strx4: {
593 auto Index = AttrValue.Value.getRawUValue();
594 auto DieCU = Die.getDwarfUnit();
595 // Check that we have a valid DWARF v5 string offsets table.
596 if (!DieCU->getStringOffsetsTableContribution()) {
598 error() << FormEncodingString(Form)
599 << " used without a valid string offsets table:\n";
603 // Check that the index is within the bounds of the section.
604 unsigned ItemSize = DieCU->getDwarfStringOffsetsByteSize();
605 // Use a 64-bit type to calculate the offset to guard against overflow.
607 (uint64_t)DieCU->getStringOffsetsBase() + Index * ItemSize;
608 if (DObj.getStringOffsetSection().Data.size() < Offset + ItemSize) {
610 error() << FormEncodingString(Form) << " uses index "
611 << format("%" PRIu64, Index) << ", which is too large:\n";
615 // Check that the string offset is valid.
616 uint64_t StringOffset = *DieCU->getStringOffsetSectionItem(Index);
617 if (StringOffset >= DObj.getStringSection().size()) {
619 error() << FormEncodingString(Form) << " uses index "
620 << format("%" PRIu64, Index)
621 << ", but the referenced string"
622 " offset is beyond .debug_str bounds:\n";
633 unsigned DWARFVerifier::verifyDebugInfoReferences() {
634 // Take all references and make sure they point to an actual DIE by
635 // getting the DIE by offset and emitting an error
636 OS << "Verifying .debug_info references...\n";
637 unsigned NumErrors = 0;
638 for (const std::pair<uint64_t, std::set<uint32_t>> &Pair :
639 ReferenceToDIEOffsets) {
640 if (DCtx.getDIEForOffset(Pair.first))
643 error() << "invalid DIE reference " << format("0x%08" PRIx64, Pair.first)
644 << ". Offset is in between DIEs:\n";
645 for (auto Offset : Pair.second)
646 dump(DCtx.getDIEForOffset(Offset)) << '\n';
652 void DWARFVerifier::verifyDebugLineStmtOffsets() {
653 std::map<uint64_t, DWARFDie> StmtListToDie;
654 for (const auto &CU : DCtx.compile_units()) {
655 auto Die = CU->getUnitDIE();
656 // Get the attribute value as a section offset. No need to produce an
657 // error here if the encoding isn't correct because we validate this in
658 // the .debug_info verifier.
659 auto StmtSectionOffset = toSectionOffset(Die.find(DW_AT_stmt_list));
660 if (!StmtSectionOffset)
662 const uint32_t LineTableOffset = *StmtSectionOffset;
663 auto LineTable = DCtx.getLineTableForUnit(CU.get());
664 if (LineTableOffset < DCtx.getDWARFObj().getLineSection().Data.size()) {
666 ++NumDebugLineErrors;
667 error() << ".debug_line[" << format("0x%08" PRIx32, LineTableOffset)
668 << "] was not able to be parsed for CU:\n";
673 // Make sure we don't get a valid line table back if the offset is wrong.
674 assert(LineTable == nullptr);
675 // Skip this line table as it isn't valid. No need to create an error
676 // here because we validate this in the .debug_info verifier.
679 auto Iter = StmtListToDie.find(LineTableOffset);
680 if (Iter != StmtListToDie.end()) {
681 ++NumDebugLineErrors;
682 error() << "two compile unit DIEs, "
683 << format("0x%08" PRIx32, Iter->second.getOffset()) << " and "
684 << format("0x%08" PRIx32, Die.getOffset())
685 << ", have the same DW_AT_stmt_list section offset:\n";
688 // Already verified this line table before, no need to do it again.
691 StmtListToDie[LineTableOffset] = Die;
695 void DWARFVerifier::verifyDebugLineRows() {
696 for (const auto &CU : DCtx.compile_units()) {
697 auto Die = CU->getUnitDIE();
698 auto LineTable = DCtx.getLineTableForUnit(CU.get());
699 // If there is no line table we will have created an error in the
700 // .debug_info verifier or in verifyDebugLineStmtOffsets().
705 uint32_t MaxDirIndex = LineTable->Prologue.IncludeDirectories.size();
706 uint32_t FileIndex = 1;
707 StringMap<uint16_t> FullPathMap;
708 for (const auto &FileName : LineTable->Prologue.FileNames) {
709 // Verify directory index.
710 if (FileName.DirIdx > MaxDirIndex) {
711 ++NumDebugLineErrors;
712 error() << ".debug_line["
713 << format("0x%08" PRIx64,
714 *toSectionOffset(Die.find(DW_AT_stmt_list)))
715 << "].prologue.file_names[" << FileIndex
716 << "].dir_idx contains an invalid index: " << FileName.DirIdx
720 // Check file paths for duplicates.
721 std::string FullPath;
722 const bool HasFullPath = LineTable->getFileNameByIndex(
723 FileIndex, CU->getCompilationDir(),
724 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FullPath);
725 assert(HasFullPath && "Invalid index?");
727 auto It = FullPathMap.find(FullPath);
728 if (It == FullPathMap.end())
729 FullPathMap[FullPath] = FileIndex;
730 else if (It->second != FileIndex) {
731 warn() << ".debug_line["
732 << format("0x%08" PRIx64,
733 *toSectionOffset(Die.find(DW_AT_stmt_list)))
734 << "].prologue.file_names[" << FileIndex
735 << "] is a duplicate of file_names[" << It->second << "]\n";
742 uint64_t PrevAddress = 0;
743 uint32_t RowIndex = 0;
744 for (const auto &Row : LineTable->Rows) {
745 // Verify row address.
746 if (Row.Address.Address < PrevAddress) {
747 ++NumDebugLineErrors;
748 error() << ".debug_line["
749 << format("0x%08" PRIx64,
750 *toSectionOffset(Die.find(DW_AT_stmt_list)))
751 << "] row[" << RowIndex
752 << "] decreases in address from previous row:\n";
754 DWARFDebugLine::Row::dumpTableHeader(OS);
756 LineTable->Rows[RowIndex - 1].dump(OS);
761 // Verify file index.
762 if (!LineTable->hasFileAtIndex(Row.File)) {
763 ++NumDebugLineErrors;
764 bool isDWARF5 = LineTable->Prologue.getVersion() >= 5;
765 error() << ".debug_line["
766 << format("0x%08" PRIx64,
767 *toSectionOffset(Die.find(DW_AT_stmt_list)))
768 << "][" << RowIndex << "] has invalid file index " << Row.File
769 << " (valid values are [" << (isDWARF5 ? "0," : "1,")
770 << LineTable->Prologue.FileNames.size()
771 << (isDWARF5 ? ")" : "]") << "):\n";
772 DWARFDebugLine::Row::dumpTableHeader(OS);
779 PrevAddress = Row.Address.Address;
785 DWARFVerifier::DWARFVerifier(raw_ostream &S, DWARFContext &D,
786 DIDumpOptions DumpOpts)
787 : OS(S), DCtx(D), DumpOpts(std::move(DumpOpts)), IsObjectFile(false),
788 IsMachOObject(false) {
789 if (const auto *F = DCtx.getDWARFObj().getFile()) {
790 IsObjectFile = F->isRelocatableObject();
791 IsMachOObject = F->isMachO();
795 bool DWARFVerifier::handleDebugLine() {
796 NumDebugLineErrors = 0;
797 OS << "Verifying .debug_line...\n";
798 verifyDebugLineStmtOffsets();
799 verifyDebugLineRows();
800 return NumDebugLineErrors == 0;
803 unsigned DWARFVerifier::verifyAppleAccelTable(const DWARFSection *AccelSection,
804 DataExtractor *StrData,
805 const char *SectionName) {
806 unsigned NumErrors = 0;
807 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), *AccelSection,
808 DCtx.isLittleEndian(), 0);
809 AppleAcceleratorTable AccelTable(AccelSectionData, *StrData);
811 OS << "Verifying " << SectionName << "...\n";
813 // Verify that the fixed part of the header is not too short.
814 if (!AccelSectionData.isValidOffset(AccelTable.getSizeHdr())) {
815 error() << "Section is too small to fit a section header.\n";
819 // Verify that the section is not too short.
820 if (Error E = AccelTable.extract()) {
821 error() << toString(std::move(E)) << '\n';
825 // Verify that all buckets have a valid hash index or are empty.
826 uint32_t NumBuckets = AccelTable.getNumBuckets();
827 uint32_t NumHashes = AccelTable.getNumHashes();
829 uint32_t BucketsOffset =
830 AccelTable.getSizeHdr() + AccelTable.getHeaderDataLength();
831 uint32_t HashesBase = BucketsOffset + NumBuckets * 4;
832 uint32_t OffsetsBase = HashesBase + NumHashes * 4;
833 for (uint32_t BucketIdx = 0; BucketIdx < NumBuckets; ++BucketIdx) {
834 uint32_t HashIdx = AccelSectionData.getU32(&BucketsOffset);
835 if (HashIdx >= NumHashes && HashIdx != UINT32_MAX) {
836 error() << format("Bucket[%d] has invalid hash index: %u.\n", BucketIdx,
841 uint32_t NumAtoms = AccelTable.getAtomsDesc().size();
843 error() << "No atoms: failed to read HashData.\n";
846 if (!AccelTable.validateForms()) {
847 error() << "Unsupported form: failed to read HashData.\n";
851 for (uint32_t HashIdx = 0; HashIdx < NumHashes; ++HashIdx) {
852 uint32_t HashOffset = HashesBase + 4 * HashIdx;
853 uint32_t DataOffset = OffsetsBase + 4 * HashIdx;
854 uint32_t Hash = AccelSectionData.getU32(&HashOffset);
855 uint32_t HashDataOffset = AccelSectionData.getU32(&DataOffset);
856 if (!AccelSectionData.isValidOffsetForDataOfSize(HashDataOffset,
858 error() << format("Hash[%d] has invalid HashData offset: 0x%08x.\n",
859 HashIdx, HashDataOffset);
864 uint32_t StringOffset;
865 uint32_t StringCount = 0;
868 while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) {
869 const uint32_t NumHashDataObjects =
870 AccelSectionData.getU32(&HashDataOffset);
871 for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects;
873 std::tie(Offset, Tag) = AccelTable.readAtoms(HashDataOffset);
874 auto Die = DCtx.getDIEForOffset(Offset);
876 const uint32_t BucketIdx =
877 NumBuckets ? (Hash % NumBuckets) : UINT32_MAX;
878 StringOffset = StrpOffset;
879 const char *Name = StrData->getCStr(&StringOffset);
884 "%s Bucket[%d] Hash[%d] = 0x%08x "
886 "DIE[%d] = 0x%08x is not a valid DIE offset for \"%s\".\n",
887 SectionName, BucketIdx, HashIdx, Hash, StringCount, StrpOffset,
888 HashDataIdx, Offset, Name);
893 if ((Tag != dwarf::DW_TAG_null) && (Die.getTag() != Tag)) {
894 error() << "Tag " << dwarf::TagString(Tag)
895 << " in accelerator table does not match Tag "
896 << dwarf::TagString(Die.getTag()) << " of DIE[" << HashDataIdx
908 DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) {
909 // A map from CU offset to the (first) Name Index offset which claims to index
911 DenseMap<uint32_t, uint32_t> CUMap;
912 const uint32_t NotIndexed = std::numeric_limits<uint32_t>::max();
914 CUMap.reserve(DCtx.getNumCompileUnits());
915 for (const auto &CU : DCtx.compile_units())
916 CUMap[CU->getOffset()] = NotIndexed;
918 unsigned NumErrors = 0;
919 for (const DWARFDebugNames::NameIndex &NI : AccelTable) {
920 if (NI.getCUCount() == 0) {
921 error() << formatv("Name Index @ {0:x} does not index any CU\n",
926 for (uint32_t CU = 0, End = NI.getCUCount(); CU < End; ++CU) {
927 uint32_t Offset = NI.getCUOffset(CU);
928 auto Iter = CUMap.find(Offset);
930 if (Iter == CUMap.end()) {
932 "Name Index @ {0:x} references a non-existing CU @ {1:x}\n",
933 NI.getUnitOffset(), Offset);
938 if (Iter->second != NotIndexed) {
939 error() << formatv("Name Index @ {0:x} references a CU @ {1:x}, but "
940 "this CU is already indexed by Name Index @ {2:x}\n",
941 NI.getUnitOffset(), Offset, Iter->second);
944 Iter->second = NI.getUnitOffset();
948 for (const auto &KV : CUMap) {
949 if (KV.second == NotIndexed)
950 warn() << formatv("CU @ {0:x} not covered by any Name Index\n", KV.first);
957 DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI,
958 const DataExtractor &StrData) {
963 constexpr BucketInfo(uint32_t Bucket, uint32_t Index)
964 : Bucket(Bucket), Index(Index) {}
965 bool operator<(const BucketInfo &RHS) const { return Index < RHS.Index; };
968 uint32_t NumErrors = 0;
969 if (NI.getBucketCount() == 0) {
970 warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n",
975 // Build up a list of (Bucket, Index) pairs. We use this later to verify that
976 // each Name is reachable from the appropriate bucket.
977 std::vector<BucketInfo> BucketStarts;
978 BucketStarts.reserve(NI.getBucketCount() + 1);
979 for (uint32_t Bucket = 0, End = NI.getBucketCount(); Bucket < End; ++Bucket) {
980 uint32_t Index = NI.getBucketArrayEntry(Bucket);
981 if (Index > NI.getNameCount()) {
982 error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid "
983 "value {2}. Valid range is [0, {3}].\n",
984 Bucket, NI.getUnitOffset(), Index, NI.getNameCount());
989 BucketStarts.emplace_back(Bucket, Index);
992 // If there were any buckets with invalid values, skip further checks as they
993 // will likely produce many errors which will only confuse the actual root
998 // Sort the list in the order of increasing "Index" entries.
999 array_pod_sort(BucketStarts.begin(), BucketStarts.end());
1001 // Insert a sentinel entry at the end, so we can check that the end of the
1002 // table is covered in the loop below.
1003 BucketStarts.emplace_back(NI.getBucketCount(), NI.getNameCount() + 1);
1005 // Loop invariant: NextUncovered is the (1-based) index of the first Name
1006 // which is not reachable by any of the buckets we processed so far (and
1007 // hasn't been reported as uncovered).
1008 uint32_t NextUncovered = 1;
1009 for (const BucketInfo &B : BucketStarts) {
1010 // Under normal circumstances B.Index be equal to NextUncovered, but it can
1011 // be less if a bucket points to names which are already known to be in some
1012 // bucket we processed earlier. In that case, we won't trigger this error,
1013 // but report the mismatched hash value error instead. (We know the hash
1014 // will not match because we have already verified that the name's hash
1015 // puts it into the previous bucket.)
1016 if (B.Index > NextUncovered) {
1017 error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] "
1018 "are not covered by the hash table.\n",
1019 NI.getUnitOffset(), NextUncovered, B.Index - 1);
1022 uint32_t Idx = B.Index;
1024 // The rest of the checks apply only to non-sentinel entries.
1025 if (B.Bucket == NI.getBucketCount())
1028 // This triggers if a non-empty bucket points to a name with a mismatched
1029 // hash. Clients are likely to interpret this as an empty bucket, because a
1030 // mismatched hash signals the end of a bucket, but if this is indeed an
1031 // empty bucket, the producer should have signalled this by marking the
1033 uint32_t FirstHash = NI.getHashArrayEntry(Idx);
1034 if (FirstHash % NI.getBucketCount() != B.Bucket) {
1036 "Name Index @ {0:x}: Bucket {1} is not empty but points to a "
1037 "mismatched hash value {2:x} (belonging to bucket {3}).\n",
1038 NI.getUnitOffset(), B.Bucket, FirstHash,
1039 FirstHash % NI.getBucketCount());
1043 // This find the end of this bucket and also verifies that all the hashes in
1044 // this bucket are correct by comparing the stored hashes to the ones we
1045 // compute ourselves.
1046 while (Idx <= NI.getNameCount()) {
1047 uint32_t Hash = NI.getHashArrayEntry(Idx);
1048 if (Hash % NI.getBucketCount() != B.Bucket)
1051 const char *Str = NI.getNameTableEntry(Idx).getString();
1052 if (caseFoldingDjbHash(Str) != Hash) {
1053 error() << formatv("Name Index @ {0:x}: String ({1}) at index {2} "
1054 "hashes to {3:x}, but "
1055 "the Name Index hash is {4:x}\n",
1056 NI.getUnitOffset(), Str, Idx,
1057 caseFoldingDjbHash(Str), Hash);
1063 NextUncovered = std::max(NextUncovered, Idx);
1068 unsigned DWARFVerifier::verifyNameIndexAttribute(
1069 const DWARFDebugNames::NameIndex &NI, const DWARFDebugNames::Abbrev &Abbr,
1070 DWARFDebugNames::AttributeEncoding AttrEnc) {
1071 StringRef FormName = dwarf::FormEncodingString(AttrEnc.Form);
1072 if (FormName.empty()) {
1073 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1074 "unknown form: {3}.\n",
1075 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1080 if (AttrEnc.Index == DW_IDX_type_hash) {
1081 if (AttrEnc.Form != dwarf::DW_FORM_data8) {
1083 "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash "
1084 "uses an unexpected form {2} (should be {3}).\n",
1085 NI.getUnitOffset(), Abbr.Code, AttrEnc.Form, dwarf::DW_FORM_data8);
1090 // A list of known index attributes and their expected form classes.
1091 // DW_IDX_type_hash is handled specially in the check above, as it has a
1092 // specific form (not just a form class) we should expect.
1093 struct FormClassTable {
1095 DWARFFormValue::FormClass Class;
1096 StringLiteral ClassName;
1098 static constexpr FormClassTable Table[] = {
1099 {dwarf::DW_IDX_compile_unit, DWARFFormValue::FC_Constant, {"constant"}},
1100 {dwarf::DW_IDX_type_unit, DWARFFormValue::FC_Constant, {"constant"}},
1101 {dwarf::DW_IDX_die_offset, DWARFFormValue::FC_Reference, {"reference"}},
1102 {dwarf::DW_IDX_parent, DWARFFormValue::FC_Constant, {"constant"}},
1105 ArrayRef<FormClassTable> TableRef(Table);
1106 auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) {
1107 return T.Index == AttrEnc.Index;
1109 if (Iter == TableRef.end()) {
1110 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an "
1111 "unknown index attribute: {2}.\n",
1112 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index);
1116 if (!DWARFFormValue(AttrEnc.Form).isFormClass(Iter->Class)) {
1117 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1118 "unexpected form {3} (expected form class {4}).\n",
1119 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1120 AttrEnc.Form, Iter->ClassName);
1127 DWARFVerifier::verifyNameIndexAbbrevs(const DWARFDebugNames::NameIndex &NI) {
1128 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) {
1129 warn() << formatv("Name Index @ {0:x}: Verifying indexes of type units is "
1130 "not currently supported.\n",
1131 NI.getUnitOffset());
1135 unsigned NumErrors = 0;
1136 for (const auto &Abbrev : NI.getAbbrevs()) {
1137 StringRef TagName = dwarf::TagString(Abbrev.Tag);
1138 if (TagName.empty()) {
1139 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an "
1140 "unknown tag: {2}.\n",
1141 NI.getUnitOffset(), Abbrev.Code, Abbrev.Tag);
1143 SmallSet<unsigned, 5> Attributes;
1144 for (const auto &AttrEnc : Abbrev.Attributes) {
1145 if (!Attributes.insert(AttrEnc.Index).second) {
1146 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains "
1147 "multiple {2} attributes.\n",
1148 NI.getUnitOffset(), Abbrev.Code, AttrEnc.Index);
1152 NumErrors += verifyNameIndexAttribute(NI, Abbrev, AttrEnc);
1155 if (NI.getCUCount() > 1 && !Attributes.count(dwarf::DW_IDX_compile_unit)) {
1156 error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units "
1157 "and abbreviation {1:x} has no {2} attribute.\n",
1158 NI.getUnitOffset(), Abbrev.Code,
1159 dwarf::DW_IDX_compile_unit);
1162 if (!Attributes.count(dwarf::DW_IDX_die_offset)) {
1164 "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n",
1165 NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset);
1172 static SmallVector<StringRef, 2> getNames(const DWARFDie &DIE,
1173 bool IncludeLinkageName = true) {
1174 SmallVector<StringRef, 2> Result;
1175 if (const char *Str = DIE.getName(DINameKind::ShortName))
1176 Result.emplace_back(Str);
1177 else if (DIE.getTag() == dwarf::DW_TAG_namespace)
1178 Result.emplace_back("(anonymous namespace)");
1180 if (IncludeLinkageName) {
1181 if (const char *Str = DIE.getName(DINameKind::LinkageName)) {
1182 if (Result.empty() || Result[0] != Str)
1183 Result.emplace_back(Str);
1190 unsigned DWARFVerifier::verifyNameIndexEntries(
1191 const DWARFDebugNames::NameIndex &NI,
1192 const DWARFDebugNames::NameTableEntry &NTE) {
1193 // Verifying type unit indexes not supported.
1194 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0)
1197 const char *CStr = NTE.getString();
1200 "Name Index @ {0:x}: Unable to get string associated with name {1}.\n",
1201 NI.getUnitOffset(), NTE.getIndex());
1204 StringRef Str(CStr);
1206 unsigned NumErrors = 0;
1207 unsigned NumEntries = 0;
1208 uint32_t EntryID = NTE.getEntryOffset();
1209 uint32_t NextEntryID = EntryID;
1210 Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&NextEntryID);
1211 for (; EntryOr; ++NumEntries, EntryID = NextEntryID,
1212 EntryOr = NI.getEntry(&NextEntryID)) {
1213 uint32_t CUIndex = *EntryOr->getCUIndex();
1214 if (CUIndex > NI.getCUCount()) {
1215 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
1216 "invalid CU index ({2}).\n",
1217 NI.getUnitOffset(), EntryID, CUIndex);
1221 uint32_t CUOffset = NI.getCUOffset(CUIndex);
1222 uint64_t DIEOffset = CUOffset + *EntryOr->getDIEUnitOffset();
1223 DWARFDie DIE = DCtx.getDIEForOffset(DIEOffset);
1225 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
1226 "non-existing DIE @ {2:x}.\n",
1227 NI.getUnitOffset(), EntryID, DIEOffset);
1231 if (DIE.getDwarfUnit()->getOffset() != CUOffset) {
1232 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of "
1233 "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n",
1234 NI.getUnitOffset(), EntryID, DIEOffset, CUOffset,
1235 DIE.getDwarfUnit()->getOffset());
1238 if (DIE.getTag() != EntryOr->tag()) {
1239 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of "
1240 "DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1241 NI.getUnitOffset(), EntryID, DIEOffset, EntryOr->tag(),
1246 auto EntryNames = getNames(DIE);
1247 if (!is_contained(EntryNames, Str)) {
1248 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name "
1249 "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1250 NI.getUnitOffset(), EntryID, DIEOffset, Str,
1251 make_range(EntryNames.begin(), EntryNames.end()));
1255 handleAllErrors(EntryOr.takeError(),
1256 [&](const DWARFDebugNames::SentinelError &) {
1259 error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
1260 "not associated with any entries.\n",
1261 NI.getUnitOffset(), NTE.getIndex(), Str);
1264 [&](const ErrorInfoBase &Info) {
1266 << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n",
1267 NI.getUnitOffset(), NTE.getIndex(), Str,
1274 static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) {
1275 Optional<DWARFFormValue> Location = Die.findRecursively(DW_AT_location);
1279 auto ContainsInterestingOperators = [&](StringRef D) {
1280 DWARFUnit *U = Die.getDwarfUnit();
1281 DataExtractor Data(D, DCtx.isLittleEndian(), U->getAddressByteSize());
1282 DWARFExpression Expression(Data, U->getVersion(), U->getAddressByteSize());
1283 return any_of(Expression, [](DWARFExpression::Operation &Op) {
1284 return !Op.isError() && (Op.getCode() == DW_OP_addr ||
1285 Op.getCode() == DW_OP_form_tls_address ||
1286 Op.getCode() == DW_OP_GNU_push_tls_address);
1290 if (Optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
1291 // Inlined location.
1292 if (ContainsInterestingOperators(toStringRef(*Expr)))
1294 } else if (Optional<uint64_t> Offset = Location->getAsSectionOffset()) {
1296 if (const DWARFDebugLoc *DebugLoc = DCtx.getDebugLoc()) {
1297 if (const DWARFDebugLoc::LocationList *LocList =
1298 DebugLoc->getLocationListAtOffset(*Offset)) {
1299 if (any_of(LocList->Entries, [&](const DWARFDebugLoc::Entry &E) {
1300 return ContainsInterestingOperators({E.Loc.data(), E.Loc.size()});
1309 unsigned DWARFVerifier::verifyNameIndexCompleteness(
1310 const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI) {
1312 // First check, if the Die should be indexed. The code follows the DWARF v5
1313 // wording as closely as possible.
1315 // "All non-defining declarations (that is, debugging information entries
1316 // with a DW_AT_declaration attribute) are excluded."
1317 if (Die.find(DW_AT_declaration))
1320 // "DW_TAG_namespace debugging information entries without a DW_AT_name
1321 // attribute are included with the name “(anonymous namespace)”.
1322 // All other debugging information entries without a DW_AT_name attribute
1324 // "If a subprogram or inlined subroutine is included, and has a
1325 // DW_AT_linkage_name attribute, there will be an additional index entry for
1326 // the linkage name."
1327 auto IncludeLinkageName = Die.getTag() == DW_TAG_subprogram ||
1328 Die.getTag() == DW_TAG_inlined_subroutine;
1329 auto EntryNames = getNames(Die, IncludeLinkageName);
1330 if (EntryNames.empty())
1333 // We deviate from the specification here, which says:
1334 // "The name index must contain an entry for each debugging information entry
1335 // that defines a named subprogram, label, variable, type, or namespace,
1337 // Instead whitelisting all TAGs representing a "type" or a "subprogram", to
1338 // make sure we catch any missing items, we instead blacklist all TAGs that we
1339 // know shouldn't be indexed.
1340 switch (Die.getTag()) {
1341 // Compile units and modules have names but shouldn't be indexed.
1342 case DW_TAG_compile_unit:
1346 // Function and template parameters are not globally visible, so we shouldn't
1348 case DW_TAG_formal_parameter:
1349 case DW_TAG_template_value_parameter:
1350 case DW_TAG_template_type_parameter:
1351 case DW_TAG_GNU_template_parameter_pack:
1352 case DW_TAG_GNU_template_template_param:
1355 // Object members aren't globally visible.
1359 // According to a strict reading of the specification, enumerators should not
1360 // be indexed (and LLVM currently does not do that). However, this causes
1361 // problems for the debuggers, so we may need to reconsider this.
1362 case DW_TAG_enumerator:
1365 // Imported declarations should not be indexed according to the specification
1366 // and LLVM currently does not do that.
1367 case DW_TAG_imported_declaration:
1370 // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging
1371 // information entries without an address attribute (DW_AT_low_pc,
1372 // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded."
1373 case DW_TAG_subprogram:
1374 case DW_TAG_inlined_subroutine:
1376 if (Die.findRecursively(
1377 {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc}))
1381 // "DW_TAG_variable debugging information entries with a DW_AT_location
1382 // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are
1383 // included; otherwise, they are excluded."
1385 // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list.
1386 case DW_TAG_variable:
1387 if (isVariableIndexable(Die, DCtx))
1395 // Now we know that our Die should be present in the Index. Let's check if
1397 unsigned NumErrors = 0;
1398 uint64_t DieUnitOffset = Die.getOffset() - Die.getDwarfUnit()->getOffset();
1399 for (StringRef Name : EntryNames) {
1400 if (none_of(NI.equal_range(Name), [&](const DWARFDebugNames::Entry &E) {
1401 return E.getDIEUnitOffset() == DieUnitOffset;
1403 error() << formatv("Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with "
1404 "name {3} missing.\n",
1405 NI.getUnitOffset(), Die.getOffset(), Die.getTag(),
1413 unsigned DWARFVerifier::verifyDebugNames(const DWARFSection &AccelSection,
1414 const DataExtractor &StrData) {
1415 unsigned NumErrors = 0;
1416 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), AccelSection,
1417 DCtx.isLittleEndian(), 0);
1418 DWARFDebugNames AccelTable(AccelSectionData, StrData);
1420 OS << "Verifying .debug_names...\n";
1422 // This verifies that we can read individual name indices and their
1423 // abbreviation tables.
1424 if (Error E = AccelTable.extract()) {
1425 error() << toString(std::move(E)) << '\n';
1429 NumErrors += verifyDebugNamesCULists(AccelTable);
1430 for (const auto &NI : AccelTable)
1431 NumErrors += verifyNameIndexBuckets(NI, StrData);
1432 for (const auto &NI : AccelTable)
1433 NumErrors += verifyNameIndexAbbrevs(NI);
1435 // Don't attempt Entry validation if any of the previous checks found errors
1438 for (const auto &NI : AccelTable)
1439 for (DWARFDebugNames::NameTableEntry NTE : NI)
1440 NumErrors += verifyNameIndexEntries(NI, NTE);
1445 for (const std::unique_ptr<DWARFUnit> &U : DCtx.compile_units()) {
1446 if (const DWARFDebugNames::NameIndex *NI =
1447 AccelTable.getCUNameIndex(U->getOffset())) {
1448 auto *CU = cast<DWARFCompileUnit>(U.get());
1449 for (const DWARFDebugInfoEntry &Die : CU->dies())
1450 NumErrors += verifyNameIndexCompleteness(DWARFDie(CU, &Die), *NI);
1456 bool DWARFVerifier::handleAccelTables() {
1457 const DWARFObject &D = DCtx.getDWARFObj();
1458 DataExtractor StrData(D.getStringSection(), DCtx.isLittleEndian(), 0);
1459 unsigned NumErrors = 0;
1460 if (!D.getAppleNamesSection().Data.empty())
1461 NumErrors += verifyAppleAccelTable(&D.getAppleNamesSection(), &StrData,
1463 if (!D.getAppleTypesSection().Data.empty())
1464 NumErrors += verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData,
1466 if (!D.getAppleNamespacesSection().Data.empty())
1467 NumErrors += verifyAppleAccelTable(&D.getAppleNamespacesSection(), &StrData,
1468 ".apple_namespaces");
1469 if (!D.getAppleObjCSection().Data.empty())
1470 NumErrors += verifyAppleAccelTable(&D.getAppleObjCSection(), &StrData,
1473 if (!D.getDebugNamesSection().Data.empty())
1474 NumErrors += verifyDebugNames(D.getDebugNamesSection(), StrData);
1475 return NumErrors == 0;
1478 raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); }
1480 raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); }
1482 raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); }
1484 raw_ostream &DWARFVerifier::dump(const DWARFDie &Die, unsigned indent) const {
1485 Die.dump(OS, indent, DumpOpts);