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/IntervalMap.h"
10 #include "llvm/ADT/SmallSet.h"
11 #include "llvm/BinaryFormat/Dwarf.h"
12 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
13 #include "llvm/DebugInfo/DWARF/DWARFAttribute.h"
14 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
15 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
16 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
17 #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
20 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
21 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
22 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
23 #include "llvm/DebugInfo/DWARF/DWARFLocationExpression.h"
24 #include "llvm/DebugInfo/DWARF/DWARFObject.h"
25 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
26 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
27 #include "llvm/Object/Error.h"
28 #include "llvm/Support/DJB.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormatVariadic.h"
32 #include "llvm/Support/WithColor.h"
33 #include "llvm/Support/raw_ostream.h"
39 using namespace dwarf
;
40 using namespace object
;
43 class DWARFDebugInfoEntry
;
46 std::optional
<DWARFAddressRange
>
47 DWARFVerifier::DieRangeInfo::insert(const DWARFAddressRange
&R
) {
48 auto Begin
= Ranges
.begin();
49 auto End
= Ranges
.end();
50 auto Pos
= std::lower_bound(Begin
, End
, R
);
53 DWARFAddressRange
Range(*Pos
);
59 DWARFAddressRange
Range(*Iter
);
64 Ranges
.insert(Pos
, R
);
68 DWARFVerifier::DieRangeInfo::die_range_info_iterator
69 DWARFVerifier::DieRangeInfo::insert(const DieRangeInfo
&RI
) {
70 if (RI
.Ranges
.empty())
71 return Children
.end();
73 auto End
= Children
.end();
74 auto Iter
= Children
.begin();
76 if (Iter
->intersects(RI
))
81 return Children
.end();
84 bool DWARFVerifier::DieRangeInfo::contains(const DieRangeInfo
&RHS
) const {
85 auto I1
= Ranges
.begin(), E1
= Ranges
.end();
86 auto I2
= RHS
.Ranges
.begin(), E2
= RHS
.Ranges
.end();
90 DWARFAddressRange R
= *I2
;
92 bool Covered
= I1
->LowPC
<= R
.LowPC
;
93 if (R
.LowPC
== R
.HighPC
|| (Covered
&& R
.HighPC
<= I1
->HighPC
)) {
101 if (R
.LowPC
< I1
->HighPC
)
102 R
.LowPC
= I1
->HighPC
;
108 bool DWARFVerifier::DieRangeInfo::intersects(const DieRangeInfo
&RHS
) const {
109 auto I1
= Ranges
.begin(), E1
= Ranges
.end();
110 auto I2
= RHS
.Ranges
.begin(), E2
= RHS
.Ranges
.end();
111 while (I1
!= E1
&& I2
!= E2
) {
112 if (I1
->intersects(*I2
))
114 if (I1
->LowPC
< I2
->LowPC
)
122 bool DWARFVerifier::verifyUnitHeader(const DWARFDataExtractor DebugInfoData
,
123 uint64_t *Offset
, unsigned UnitIndex
,
124 uint8_t &UnitType
, bool &isUnitDWARF64
) {
125 uint64_t AbbrOffset
, Length
;
126 uint8_t AddrSize
= 0;
130 bool ValidLength
= false;
131 bool ValidVersion
= false;
132 bool ValidAddrSize
= false;
133 bool ValidType
= true;
134 bool ValidAbbrevOffset
= true;
136 uint64_t OffsetStart
= *Offset
;
138 std::tie(Length
, Format
) = DebugInfoData
.getInitialLength(Offset
);
139 isUnitDWARF64
= Format
== DWARF64
;
140 Version
= DebugInfoData
.getU16(Offset
);
143 UnitType
= DebugInfoData
.getU8(Offset
);
144 AddrSize
= DebugInfoData
.getU8(Offset
);
145 AbbrOffset
= isUnitDWARF64
? DebugInfoData
.getU64(Offset
) : DebugInfoData
.getU32(Offset
);
146 ValidType
= dwarf::isUnitType(UnitType
);
149 AbbrOffset
= isUnitDWARF64
? DebugInfoData
.getU64(Offset
) : DebugInfoData
.getU32(Offset
);
150 AddrSize
= DebugInfoData
.getU8(Offset
);
153 if (!DCtx
.getDebugAbbrev()->getAbbreviationDeclarationSet(AbbrOffset
))
154 ValidAbbrevOffset
= false;
156 ValidLength
= DebugInfoData
.isValidOffset(OffsetStart
+ Length
+ 3);
157 ValidVersion
= DWARFContext::isSupportedVersion(Version
);
158 ValidAddrSize
= DWARFContext::isAddressSizeSupported(AddrSize
);
159 if (!ValidLength
|| !ValidVersion
|| !ValidAddrSize
|| !ValidAbbrevOffset
||
162 error() << format("Units[%d] - start offset: 0x%08" PRIx64
" \n", UnitIndex
,
165 note() << "The length for this unit is too "
166 "large for the .debug_info provided.\n";
168 note() << "The 16 bit unit header version is not valid.\n";
170 note() << "The unit type encoding is not valid.\n";
171 if (!ValidAbbrevOffset
)
172 note() << "The offset into the .debug_abbrev section is "
175 note() << "The address size is unsupported.\n";
177 *Offset
= OffsetStart
+ Length
+ (isUnitDWARF64
? 12 : 4);
181 bool DWARFVerifier::verifyName(const DWARFDie
&Die
) {
182 // FIXME Add some kind of record of which DIE names have already failed and
183 // don't bother checking a DIE that uses an already failed DIE.
185 std::string ReconstructedName
;
186 raw_string_ostream
OS(ReconstructedName
);
187 std::string OriginalFullName
;
188 Die
.getFullName(OS
, &OriginalFullName
);
190 if (OriginalFullName
.empty() || OriginalFullName
== ReconstructedName
)
193 error() << "Simplified template DW_AT_name could not be reconstituted:\n"
194 << formatv(" original: {0}\n"
195 " reconstituted: {1}\n",
196 OriginalFullName
, ReconstructedName
);
198 dump(Die
.getDwarfUnit()->getUnitDIE()) << '\n';
202 unsigned DWARFVerifier::verifyUnitContents(DWARFUnit
&Unit
,
203 ReferenceMap
&UnitLocalReferences
,
204 ReferenceMap
&CrossUnitReferences
) {
205 unsigned NumUnitErrors
= 0;
206 unsigned NumDies
= Unit
.getNumDIEs();
207 for (unsigned I
= 0; I
< NumDies
; ++I
) {
208 auto Die
= Unit
.getDIEAtIndex(I
);
210 if (Die
.getTag() == DW_TAG_null
)
213 for (auto AttrValue
: Die
.attributes()) {
214 NumUnitErrors
+= verifyDebugInfoAttribute(Die
, AttrValue
);
215 NumUnitErrors
+= verifyDebugInfoForm(Die
, AttrValue
, UnitLocalReferences
,
216 CrossUnitReferences
);
219 NumUnitErrors
+= verifyName(Die
);
221 if (Die
.hasChildren()) {
222 if (Die
.getFirstChild().isValid() &&
223 Die
.getFirstChild().getTag() == DW_TAG_null
) {
224 warn() << dwarf::TagString(Die
.getTag())
225 << " has DW_CHILDREN_yes but DIE has no children: ";
230 NumUnitErrors
+= verifyDebugInfoCallSite(Die
);
233 DWARFDie Die
= Unit
.getUnitDIE(/* ExtractUnitDIEOnly = */ false);
235 error() << "Compilation unit without DIE.\n";
237 return NumUnitErrors
;
240 if (!dwarf::isUnitType(Die
.getTag())) {
241 error() << "Compilation unit root DIE is not a unit DIE: "
242 << dwarf::TagString(Die
.getTag()) << ".\n";
246 uint8_t UnitType
= Unit
.getUnitType();
247 if (!DWARFUnit::isMatchingUnitTypeAndTag(UnitType
, Die
.getTag())) {
248 error() << "Compilation unit type (" << dwarf::UnitTypeString(UnitType
)
249 << ") and root DIE (" << dwarf::TagString(Die
.getTag())
250 << ") do not match.\n";
254 // According to DWARF Debugging Information Format Version 5,
255 // 3.1.2 Skeleton Compilation Unit Entries:
256 // "A skeleton compilation unit has no children."
257 if (Die
.getTag() == dwarf::DW_TAG_skeleton_unit
&& Die
.hasChildren()) {
258 error() << "Skeleton compilation unit has children.\n";
263 NumUnitErrors
+= verifyDieRanges(Die
, RI
);
265 return NumUnitErrors
;
268 unsigned DWARFVerifier::verifyDebugInfoCallSite(const DWARFDie
&Die
) {
269 if (Die
.getTag() != DW_TAG_call_site
&& Die
.getTag() != DW_TAG_GNU_call_site
)
272 DWARFDie Curr
= Die
.getParent();
273 for (; Curr
.isValid() && !Curr
.isSubprogramDIE(); Curr
= Die
.getParent()) {
274 if (Curr
.getTag() == DW_TAG_inlined_subroutine
) {
275 error() << "Call site entry nested within inlined subroutine:";
281 if (!Curr
.isValid()) {
282 error() << "Call site entry not nested within a valid subprogram:";
287 std::optional
<DWARFFormValue
> CallAttr
= Curr
.find(
288 {DW_AT_call_all_calls
, DW_AT_call_all_source_calls
,
289 DW_AT_call_all_tail_calls
, DW_AT_GNU_all_call_sites
,
290 DW_AT_GNU_all_source_call_sites
, DW_AT_GNU_all_tail_call_sites
});
292 error() << "Subprogram with call site entry has no DW_AT_call attribute:";
294 Die
.dump(OS
, /*indent*/ 1);
301 unsigned DWARFVerifier::verifyAbbrevSection(const DWARFDebugAbbrev
*Abbrev
) {
302 unsigned NumErrors
= 0;
304 const DWARFAbbreviationDeclarationSet
*AbbrDecls
=
305 Abbrev
->getAbbreviationDeclarationSet(0);
306 for (auto AbbrDecl
: *AbbrDecls
) {
307 SmallDenseSet
<uint16_t> AttributeSet
;
308 for (auto Attribute
: AbbrDecl
.attributes()) {
309 auto Result
= AttributeSet
.insert(Attribute
.Attr
);
310 if (!Result
.second
) {
311 error() << "Abbreviation declaration contains multiple "
312 << AttributeString(Attribute
.Attr
) << " attributes.\n";
322 bool DWARFVerifier::handleDebugAbbrev() {
323 OS
<< "Verifying .debug_abbrev...\n";
325 const DWARFObject
&DObj
= DCtx
.getDWARFObj();
326 unsigned NumErrors
= 0;
327 if (!DObj
.getAbbrevSection().empty())
328 NumErrors
+= verifyAbbrevSection(DCtx
.getDebugAbbrev());
329 if (!DObj
.getAbbrevDWOSection().empty())
330 NumErrors
+= verifyAbbrevSection(DCtx
.getDebugAbbrevDWO());
332 return NumErrors
== 0;
335 unsigned DWARFVerifier::verifyUnits(const DWARFUnitVector
&Units
) {
336 unsigned NumDebugInfoErrors
= 0;
337 ReferenceMap CrossUnitReferences
;
340 for (const auto &Unit
: Units
) {
341 OS
<< "Verifying unit: " << Index
<< " / " << Units
.getNumUnits();
342 if (const char* Name
= Unit
->getUnitDIE(true).getShortName())
343 OS
<< ", \"" << Name
<< '\"';
346 ReferenceMap UnitLocalReferences
;
347 NumDebugInfoErrors
+=
348 verifyUnitContents(*Unit
, UnitLocalReferences
, CrossUnitReferences
);
349 NumDebugInfoErrors
+= verifyDebugInfoReferences(
350 UnitLocalReferences
, [&](uint64_t Offset
) { return Unit
.get(); });
354 NumDebugInfoErrors
+= verifyDebugInfoReferences(
355 CrossUnitReferences
, [&](uint64_t Offset
) -> DWARFUnit
* {
356 if (DWARFUnit
*U
= Units
.getUnitForOffset(Offset
))
361 return NumDebugInfoErrors
;
364 unsigned DWARFVerifier::verifyUnitSection(const DWARFSection
&S
) {
365 const DWARFObject
&DObj
= DCtx
.getDWARFObj();
366 DWARFDataExtractor
DebugInfoData(DObj
, S
, DCtx
.isLittleEndian(), 0);
367 unsigned NumDebugInfoErrors
= 0;
368 uint64_t Offset
= 0, UnitIdx
= 0;
369 uint8_t UnitType
= 0;
370 bool isUnitDWARF64
= false;
371 bool isHeaderChainValid
= true;
372 bool hasDIE
= DebugInfoData
.isValidOffset(Offset
);
373 DWARFUnitVector TypeUnitVector
;
374 DWARFUnitVector CompileUnitVector
;
375 /// A map that tracks all references (converted absolute references) so we
376 /// can verify each reference points to a valid DIE and not an offset that
377 /// lies between to valid DIEs.
378 ReferenceMap CrossUnitReferences
;
380 if (!verifyUnitHeader(DebugInfoData
, &Offset
, UnitIdx
, UnitType
,
382 isHeaderChainValid
= false;
386 hasDIE
= DebugInfoData
.isValidOffset(Offset
);
389 if (UnitIdx
== 0 && !hasDIE
) {
390 warn() << "Section is empty.\n";
391 isHeaderChainValid
= true;
393 if (!isHeaderChainValid
)
394 ++NumDebugInfoErrors
;
395 return NumDebugInfoErrors
;
398 unsigned DWARFVerifier::verifyIndex(StringRef Name
,
399 DWARFSectionKind InfoColumnKind
,
400 StringRef IndexStr
) {
401 if (IndexStr
.empty())
403 OS
<< "Verifying " << Name
<< "...\n";
404 DWARFUnitIndex
Index(InfoColumnKind
);
405 DataExtractor
D(IndexStr
, DCtx
.isLittleEndian(), 0);
408 using MapType
= IntervalMap
<uint64_t, uint64_t>;
409 MapType::Allocator Alloc
;
410 std::vector
<std::unique_ptr
<MapType
>> Sections(Index
.getColumnKinds().size());
411 for (const DWARFUnitIndex::Entry
&E
: Index
.getRows()) {
412 uint64_t Sig
= E
.getSignature();
413 if (!E
.getContributions())
415 for (auto E
: enumerate(
416 InfoColumnKind
== DW_SECT_INFO
417 ? ArrayRef(E
.getContributions(), Index
.getColumnKinds().size())
418 : ArrayRef(E
.getContribution(), 1))) {
419 const DWARFUnitIndex::Entry::SectionContribution
&SC
= E
.value();
421 if (SC
.getLength() == 0)
424 Sections
[Col
] = std::make_unique
<MapType
>(Alloc
);
425 auto &M
= *Sections
[Col
];
426 auto I
= M
.find(SC
.getOffset());
427 if (I
!= M
.end() && I
.start() < (SC
.getOffset() + SC
.getLength())) {
428 error() << llvm::formatv(
429 "overlapping index entries for entries {0:x16} "
430 "and {1:x16} for column {2}\n",
431 *I
, Sig
, toString(Index
.getColumnKinds()[Col
]));
434 M
.insert(SC
.getOffset(), SC
.getOffset() + SC
.getLength() - 1, Sig
);
441 bool DWARFVerifier::handleDebugCUIndex() {
442 return verifyIndex(".debug_cu_index", DWARFSectionKind::DW_SECT_INFO
,
443 DCtx
.getDWARFObj().getCUIndexSection()) == 0;
446 bool DWARFVerifier::handleDebugTUIndex() {
447 return verifyIndex(".debug_tu_index", DWARFSectionKind::DW_SECT_EXT_TYPES
,
448 DCtx
.getDWARFObj().getTUIndexSection()) == 0;
451 bool DWARFVerifier::handleDebugInfo() {
452 const DWARFObject
&DObj
= DCtx
.getDWARFObj();
453 unsigned NumErrors
= 0;
455 OS
<< "Verifying .debug_info Unit Header Chain...\n";
456 DObj
.forEachInfoSections([&](const DWARFSection
&S
) {
457 NumErrors
+= verifyUnitSection(S
);
460 OS
<< "Verifying .debug_types Unit Header Chain...\n";
461 DObj
.forEachTypesSections([&](const DWARFSection
&S
) {
462 NumErrors
+= verifyUnitSection(S
);
465 OS
<< "Verifying non-dwo Units...\n";
466 NumErrors
+= verifyUnits(DCtx
.getNormalUnitsVector());
468 OS
<< "Verifying dwo Units...\n";
469 NumErrors
+= verifyUnits(DCtx
.getDWOUnitsVector());
470 return NumErrors
== 0;
473 unsigned DWARFVerifier::verifyDieRanges(const DWARFDie
&Die
,
474 DieRangeInfo
&ParentRI
) {
475 unsigned NumErrors
= 0;
480 DWARFUnit
*Unit
= Die
.getDwarfUnit();
482 auto RangesOrError
= Die
.getAddressRanges();
483 if (!RangesOrError
) {
484 // FIXME: Report the error.
485 if (!Unit
->isDWOUnit())
487 llvm::consumeError(RangesOrError
.takeError());
491 const DWARFAddressRangesVector
&Ranges
= RangesOrError
.get();
492 // Build RI for this DIE and check that ranges within this DIE do not
494 DieRangeInfo
RI(Die
);
496 // TODO support object files better
498 // Some object file formats (i.e. non-MachO) support COMDAT. ELF in
499 // particular does so by placing each function into a section. The DWARF data
500 // for the function at that point uses a section relative DW_FORM_addrp for
501 // the DW_AT_low_pc and a DW_FORM_data4 for the offset as the DW_AT_high_pc.
502 // In such a case, when the Die is the CU, the ranges will overlap, and we
503 // will flag valid conflicting ranges as invalid.
505 // For such targets, we should read the ranges from the CU and partition them
506 // by the section id. The ranges within a particular section should be
507 // disjoint, although the ranges across sections may overlap. We would map
508 // the child die to the entity that it references and the section with which
509 // it is associated. The child would then be checked against the range
510 // information for the associated section.
512 // For now, simply elide the range verification for the CU DIEs if we are
513 // processing an object file.
515 if (!IsObjectFile
|| IsMachOObject
|| Die
.getTag() != DW_TAG_compile_unit
) {
516 bool DumpDieAfterError
= false;
517 for (const auto &Range
: Ranges
) {
518 if (!Range
.valid()) {
520 error() << "Invalid address range " << Range
<< "\n";
521 DumpDieAfterError
= true;
525 // Verify that ranges don't intersect and also build up the DieRangeInfo
526 // address ranges. Don't break out of the loop below early, or we will
527 // think this DIE doesn't have all of the address ranges it is supposed
528 // to have. Compile units often have DW_AT_ranges that can contain one or
529 // more dead stripped address ranges which tend to all be at the same
531 if (auto PrevRange
= RI
.insert(Range
)) {
533 error() << "DIE has overlapping ranges in DW_AT_ranges attribute: "
534 << *PrevRange
<< " and " << Range
<< '\n';
535 DumpDieAfterError
= true;
538 if (DumpDieAfterError
)
539 dump(Die
, 2) << '\n';
542 // Verify that children don't intersect.
543 const auto IntersectingChild
= ParentRI
.insert(RI
);
544 if (IntersectingChild
!= ParentRI
.Children
.end()) {
546 error() << "DIEs have overlapping address ranges:";
548 dump(IntersectingChild
->Die
) << '\n';
551 // Verify that ranges are contained within their parent.
552 bool ShouldBeContained
= !RI
.Ranges
.empty() && !ParentRI
.Ranges
.empty() &&
553 !(Die
.getTag() == DW_TAG_subprogram
&&
554 ParentRI
.Die
.getTag() == DW_TAG_subprogram
);
555 if (ShouldBeContained
&& !ParentRI
.contains(RI
)) {
557 error() << "DIE address ranges are not contained in its parent's ranges:";
559 dump(Die
, 2) << '\n';
562 // Recursively check children.
563 for (DWARFDie Child
: Die
)
564 NumErrors
+= verifyDieRanges(Child
, RI
);
569 unsigned DWARFVerifier::verifyDebugInfoAttribute(const DWARFDie
&Die
,
570 DWARFAttribute
&AttrValue
) {
571 unsigned NumErrors
= 0;
572 auto ReportError
= [&](const Twine
&TitleMsg
) {
574 error() << TitleMsg
<< '\n';
578 const DWARFObject
&DObj
= DCtx
.getDWARFObj();
579 DWARFUnit
*U
= Die
.getDwarfUnit();
580 const auto Attr
= AttrValue
.Attr
;
583 // Make sure the offset in the DW_AT_ranges attribute is valid.
584 if (auto SectionOffset
= AttrValue
.Value
.getAsSectionOffset()) {
585 unsigned DwarfVersion
= U
->getVersion();
586 const DWARFSection
&RangeSection
= DwarfVersion
< 5
587 ? DObj
.getRangesSection()
588 : DObj
.getRnglistsSection();
589 if (U
->isDWOUnit() && RangeSection
.Data
.empty())
591 if (*SectionOffset
>= RangeSection
.Data
.size())
593 "DW_AT_ranges offset is beyond " +
594 StringRef(DwarfVersion
< 5 ? ".debug_ranges" : ".debug_rnglists") +
595 " bounds: " + llvm::formatv("{0:x8}", *SectionOffset
));
598 ReportError("DIE has invalid DW_AT_ranges encoding:");
600 case DW_AT_stmt_list
:
601 // Make sure the offset in the DW_AT_stmt_list attribute is valid.
602 if (auto SectionOffset
= AttrValue
.Value
.getAsSectionOffset()) {
603 if (*SectionOffset
>= U
->getLineSection().Data
.size())
604 ReportError("DW_AT_stmt_list offset is beyond .debug_line bounds: " +
605 llvm::formatv("{0:x8}", *SectionOffset
));
608 ReportError("DIE has invalid DW_AT_stmt_list encoding:");
610 case DW_AT_location
: {
611 // FIXME: It might be nice if there's a way to walk location expressions
612 // without trying to resolve the address ranges - it'd be a more efficient
613 // API (since the API is currently unnecessarily resolving addresses for
614 // this use case which only wants to validate the expressions themselves) &
615 // then the expressions could be validated even if the addresses can't be
617 // That sort of API would probably look like a callback "for each
618 // expression" with some way to lazily resolve the address ranges when
619 // needed (& then the existing API used here could be built on top of that -
620 // using the callback API to build the data structure and return it).
621 if (Expected
<std::vector
<DWARFLocationExpression
>> Loc
=
622 Die
.getLocations(DW_AT_location
)) {
623 for (const auto &Entry
: *Loc
) {
624 DataExtractor
Data(toStringRef(Entry
.Expr
), DCtx
.isLittleEndian(), 0);
625 DWARFExpression
Expression(Data
, U
->getAddressByteSize(),
626 U
->getFormParams().Format
);
628 any_of(Expression
, [](const DWARFExpression::Operation
&Op
) {
631 if (Error
|| !Expression
.verify(U
))
632 ReportError("DIE contains invalid DWARF expression:");
634 } else if (Error Err
= handleErrors(
635 Loc
.takeError(), [&](std::unique_ptr
<ResolverError
> E
) {
636 return U
->isDWOUnit() ? Error::success()
637 : Error(std::move(E
));
639 ReportError(toString(std::move(Err
)));
642 case DW_AT_specification
:
643 case DW_AT_abstract_origin
: {
644 if (auto ReferencedDie
= Die
.getAttributeValueAsReferencedDie(Attr
)) {
645 auto DieTag
= Die
.getTag();
646 auto RefTag
= ReferencedDie
.getTag();
647 if (DieTag
== RefTag
)
649 if (DieTag
== DW_TAG_inlined_subroutine
&& RefTag
== DW_TAG_subprogram
)
651 if (DieTag
== DW_TAG_variable
&& RefTag
== DW_TAG_member
)
653 // This might be reference to a function declaration.
654 if (DieTag
== DW_TAG_GNU_call_site
&& RefTag
== DW_TAG_subprogram
)
656 ReportError("DIE with tag " + TagString(DieTag
) + " has " +
657 AttributeString(Attr
) +
658 " that points to DIE with "
659 "incompatible tag " +
665 DWARFDie TypeDie
= Die
.getAttributeValueAsReferencedDie(DW_AT_type
);
666 if (TypeDie
&& !isType(TypeDie
.getTag())) {
667 ReportError("DIE has " + AttributeString(Attr
) +
668 " with incompatible tag " + TagString(TypeDie
.getTag()));
672 case DW_AT_call_file
:
673 case DW_AT_decl_file
: {
674 if (auto FileIdx
= AttrValue
.Value
.getAsUnsignedConstant()) {
675 if (U
->isDWOUnit() && !U
->isTypeUnit())
677 const auto *LT
= U
->getContext().getLineTableForUnit(U
);
679 if (!LT
->hasFileAtIndex(*FileIdx
)) {
680 bool IsZeroIndexed
= LT
->Prologue
.getVersion() >= 5;
681 if (std::optional
<uint64_t> LastFileIdx
=
682 LT
->getLastValidFileIndex()) {
683 ReportError("DIE has " + AttributeString(Attr
) +
684 " with an invalid file index " +
685 llvm::formatv("{0}", *FileIdx
) +
686 " (valid values are [" + (IsZeroIndexed
? "0-" : "1-") +
687 llvm::formatv("{0}", *LastFileIdx
) + "])");
689 ReportError("DIE has " + AttributeString(Attr
) +
690 " with an invalid file index " +
691 llvm::formatv("{0}", *FileIdx
) +
692 " (the file table in the prologue is empty)");
696 ReportError("DIE has " + AttributeString(Attr
) +
697 " that references a file with index " +
698 llvm::formatv("{0}", *FileIdx
) +
699 " and the compile unit has no line table");
702 ReportError("DIE has " + AttributeString(Attr
) +
703 " with invalid encoding");
707 case DW_AT_call_line
:
708 case DW_AT_decl_line
: {
709 if (!AttrValue
.Value
.getAsUnsignedConstant()) {
710 ReportError("DIE has " + AttributeString(Attr
) +
711 " with invalid encoding");
721 unsigned DWARFVerifier::verifyDebugInfoForm(const DWARFDie
&Die
,
722 DWARFAttribute
&AttrValue
,
723 ReferenceMap
&LocalReferences
,
724 ReferenceMap
&CrossUnitReferences
) {
725 auto DieCU
= Die
.getDwarfUnit();
726 unsigned NumErrors
= 0;
727 const auto Form
= AttrValue
.Value
.getForm();
733 case DW_FORM_ref_udata
: {
734 // Verify all CU relative references are valid CU offsets.
735 std::optional
<uint64_t> RefVal
= AttrValue
.Value
.getAsReference();
738 auto CUSize
= DieCU
->getNextUnitOffset() - DieCU
->getOffset();
739 auto CUOffset
= AttrValue
.Value
.getRawUValue();
740 if (CUOffset
>= CUSize
) {
742 error() << FormEncodingString(Form
) << " CU offset "
743 << format("0x%08" PRIx64
, CUOffset
)
744 << " is invalid (must be less than CU size of "
745 << format("0x%08" PRIx64
, CUSize
) << "):\n";
746 Die
.dump(OS
, 0, DumpOpts
);
749 // Valid reference, but we will verify it points to an actual
751 LocalReferences
[*RefVal
].insert(Die
.getOffset());
756 case DW_FORM_ref_addr
: {
757 // Verify all absolute DIE references have valid offsets in the
758 // .debug_info section.
759 std::optional
<uint64_t> RefVal
= AttrValue
.Value
.getAsReference();
762 if (*RefVal
>= DieCU
->getInfoSection().Data
.size()) {
764 error() << "DW_FORM_ref_addr offset beyond .debug_info "
768 // Valid reference, but we will verify it points to an actual
770 CrossUnitReferences
[*RefVal
].insert(Die
.getOffset());
781 case DW_FORM_line_strp
: {
782 if (Error E
= AttrValue
.Value
.getAsCString().takeError()) {
784 error() << toString(std::move(E
)) << ":\n";
795 unsigned DWARFVerifier::verifyDebugInfoReferences(
796 const ReferenceMap
&References
,
797 llvm::function_ref
<DWARFUnit
*(uint64_t)> GetUnitForOffset
) {
798 auto GetDIEForOffset
= [&](uint64_t Offset
) {
799 if (DWARFUnit
*U
= GetUnitForOffset(Offset
))
800 return U
->getDIEForOffset(Offset
);
803 unsigned NumErrors
= 0;
804 for (const std::pair
<const uint64_t, std::set
<uint64_t>> &Pair
:
806 if (GetDIEForOffset(Pair
.first
))
809 error() << "invalid DIE reference " << format("0x%08" PRIx64
, Pair
.first
)
810 << ". Offset is in between DIEs:\n";
811 for (auto Offset
: Pair
.second
)
812 dump(GetDIEForOffset(Offset
)) << '\n';
818 void DWARFVerifier::verifyDebugLineStmtOffsets() {
819 std::map
<uint64_t, DWARFDie
> StmtListToDie
;
820 for (const auto &CU
: DCtx
.compile_units()) {
821 auto Die
= CU
->getUnitDIE();
822 // Get the attribute value as a section offset. No need to produce an
823 // error here if the encoding isn't correct because we validate this in
824 // the .debug_info verifier.
825 auto StmtSectionOffset
= toSectionOffset(Die
.find(DW_AT_stmt_list
));
826 if (!StmtSectionOffset
)
828 const uint64_t LineTableOffset
= *StmtSectionOffset
;
829 auto LineTable
= DCtx
.getLineTableForUnit(CU
.get());
830 if (LineTableOffset
< DCtx
.getDWARFObj().getLineSection().Data
.size()) {
832 ++NumDebugLineErrors
;
833 error() << ".debug_line[" << format("0x%08" PRIx64
, LineTableOffset
)
834 << "] was not able to be parsed for CU:\n";
839 // Make sure we don't get a valid line table back if the offset is wrong.
840 assert(LineTable
== nullptr);
841 // Skip this line table as it isn't valid. No need to create an error
842 // here because we validate this in the .debug_info verifier.
845 auto Iter
= StmtListToDie
.find(LineTableOffset
);
846 if (Iter
!= StmtListToDie
.end()) {
847 ++NumDebugLineErrors
;
848 error() << "two compile unit DIEs, "
849 << format("0x%08" PRIx64
, Iter
->second
.getOffset()) << " and "
850 << format("0x%08" PRIx64
, Die
.getOffset())
851 << ", have the same DW_AT_stmt_list section offset:\n";
854 // Already verified this line table before, no need to do it again.
857 StmtListToDie
[LineTableOffset
] = Die
;
861 void DWARFVerifier::verifyDebugLineRows() {
862 for (const auto &CU
: DCtx
.compile_units()) {
863 auto Die
= CU
->getUnitDIE();
864 auto LineTable
= DCtx
.getLineTableForUnit(CU
.get());
865 // If there is no line table we will have created an error in the
866 // .debug_info verifier or in verifyDebugLineStmtOffsets().
871 bool isDWARF5
= LineTable
->Prologue
.getVersion() >= 5;
872 uint32_t MaxDirIndex
= LineTable
->Prologue
.IncludeDirectories
.size();
873 uint32_t MinFileIndex
= isDWARF5
? 0 : 1;
874 uint32_t FileIndex
= MinFileIndex
;
875 StringMap
<uint16_t> FullPathMap
;
876 for (const auto &FileName
: LineTable
->Prologue
.FileNames
) {
877 // Verify directory index.
878 if (FileName
.DirIdx
> MaxDirIndex
) {
879 ++NumDebugLineErrors
;
880 error() << ".debug_line["
881 << format("0x%08" PRIx64
,
882 *toSectionOffset(Die
.find(DW_AT_stmt_list
)))
883 << "].prologue.file_names[" << FileIndex
884 << "].dir_idx contains an invalid index: " << FileName
.DirIdx
888 // Check file paths for duplicates.
889 std::string FullPath
;
890 const bool HasFullPath
= LineTable
->getFileNameByIndex(
891 FileIndex
, CU
->getCompilationDir(),
892 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath
, FullPath
);
893 assert(HasFullPath
&& "Invalid index?");
895 auto It
= FullPathMap
.find(FullPath
);
896 if (It
== FullPathMap
.end())
897 FullPathMap
[FullPath
] = FileIndex
;
898 else if (It
->second
!= FileIndex
) {
899 warn() << ".debug_line["
900 << format("0x%08" PRIx64
,
901 *toSectionOffset(Die
.find(DW_AT_stmt_list
)))
902 << "].prologue.file_names[" << FileIndex
903 << "] is a duplicate of file_names[" << It
->second
<< "]\n";
910 uint64_t PrevAddress
= 0;
911 uint32_t RowIndex
= 0;
912 for (const auto &Row
: LineTable
->Rows
) {
913 // Verify row address.
914 if (Row
.Address
.Address
< PrevAddress
) {
915 ++NumDebugLineErrors
;
916 error() << ".debug_line["
917 << format("0x%08" PRIx64
,
918 *toSectionOffset(Die
.find(DW_AT_stmt_list
)))
919 << "] row[" << RowIndex
920 << "] decreases in address from previous row:\n";
922 DWARFDebugLine::Row::dumpTableHeader(OS
, 0);
924 LineTable
->Rows
[RowIndex
- 1].dump(OS
);
929 // Verify file index.
930 if (!LineTable
->hasFileAtIndex(Row
.File
)) {
931 ++NumDebugLineErrors
;
932 error() << ".debug_line["
933 << format("0x%08" PRIx64
,
934 *toSectionOffset(Die
.find(DW_AT_stmt_list
)))
935 << "][" << RowIndex
<< "] has invalid file index " << Row
.File
936 << " (valid values are [" << MinFileIndex
<< ','
937 << LineTable
->Prologue
.FileNames
.size()
938 << (isDWARF5
? ")" : "]") << "):\n";
939 DWARFDebugLine::Row::dumpTableHeader(OS
, 0);
946 PrevAddress
= Row
.Address
.Address
;
952 DWARFVerifier::DWARFVerifier(raw_ostream
&S
, DWARFContext
&D
,
953 DIDumpOptions DumpOpts
)
954 : OS(S
), DCtx(D
), DumpOpts(std::move(DumpOpts
)), IsObjectFile(false),
955 IsMachOObject(false) {
956 if (const auto *F
= DCtx
.getDWARFObj().getFile()) {
957 IsObjectFile
= F
->isRelocatableObject();
958 IsMachOObject
= F
->isMachO();
962 bool DWARFVerifier::handleDebugLine() {
963 NumDebugLineErrors
= 0;
964 OS
<< "Verifying .debug_line...\n";
965 verifyDebugLineStmtOffsets();
966 verifyDebugLineRows();
967 return NumDebugLineErrors
== 0;
970 unsigned DWARFVerifier::verifyAppleAccelTable(const DWARFSection
*AccelSection
,
971 DataExtractor
*StrData
,
972 const char *SectionName
) {
973 unsigned NumErrors
= 0;
974 DWARFDataExtractor
AccelSectionData(DCtx
.getDWARFObj(), *AccelSection
,
975 DCtx
.isLittleEndian(), 0);
976 AppleAcceleratorTable
AccelTable(AccelSectionData
, *StrData
);
978 OS
<< "Verifying " << SectionName
<< "...\n";
980 // Verify that the fixed part of the header is not too short.
981 if (!AccelSectionData
.isValidOffset(AccelTable
.getSizeHdr())) {
982 error() << "Section is too small to fit a section header.\n";
986 // Verify that the section is not too short.
987 if (Error E
= AccelTable
.extract()) {
988 error() << toString(std::move(E
)) << '\n';
992 // Verify that all buckets have a valid hash index or are empty.
993 uint32_t NumBuckets
= AccelTable
.getNumBuckets();
994 uint32_t NumHashes
= AccelTable
.getNumHashes();
996 uint64_t BucketsOffset
=
997 AccelTable
.getSizeHdr() + AccelTable
.getHeaderDataLength();
998 uint64_t HashesBase
= BucketsOffset
+ NumBuckets
* 4;
999 uint64_t OffsetsBase
= HashesBase
+ NumHashes
* 4;
1000 for (uint32_t BucketIdx
= 0; BucketIdx
< NumBuckets
; ++BucketIdx
) {
1001 uint32_t HashIdx
= AccelSectionData
.getU32(&BucketsOffset
);
1002 if (HashIdx
>= NumHashes
&& HashIdx
!= UINT32_MAX
) {
1003 error() << format("Bucket[%d] has invalid hash index: %u.\n", BucketIdx
,
1008 uint32_t NumAtoms
= AccelTable
.getAtomsDesc().size();
1009 if (NumAtoms
== 0) {
1010 error() << "No atoms: failed to read HashData.\n";
1013 if (!AccelTable
.validateForms()) {
1014 error() << "Unsupported form: failed to read HashData.\n";
1018 for (uint32_t HashIdx
= 0; HashIdx
< NumHashes
; ++HashIdx
) {
1019 uint64_t HashOffset
= HashesBase
+ 4 * HashIdx
;
1020 uint64_t DataOffset
= OffsetsBase
+ 4 * HashIdx
;
1021 uint32_t Hash
= AccelSectionData
.getU32(&HashOffset
);
1022 uint64_t HashDataOffset
= AccelSectionData
.getU32(&DataOffset
);
1023 if (!AccelSectionData
.isValidOffsetForDataOfSize(HashDataOffset
,
1024 sizeof(uint64_t))) {
1025 error() << format("Hash[%d] has invalid HashData offset: "
1026 "0x%08" PRIx64
".\n",
1027 HashIdx
, HashDataOffset
);
1031 uint64_t StrpOffset
;
1032 uint64_t StringOffset
;
1033 uint32_t StringCount
= 0;
1036 while ((StrpOffset
= AccelSectionData
.getU32(&HashDataOffset
)) != 0) {
1037 const uint32_t NumHashDataObjects
=
1038 AccelSectionData
.getU32(&HashDataOffset
);
1039 for (uint32_t HashDataIdx
= 0; HashDataIdx
< NumHashDataObjects
;
1041 std::tie(Offset
, Tag
) = AccelTable
.readAtoms(&HashDataOffset
);
1042 auto Die
= DCtx
.getDIEForOffset(Offset
);
1044 const uint32_t BucketIdx
=
1045 NumBuckets
? (Hash
% NumBuckets
) : UINT32_MAX
;
1046 StringOffset
= StrpOffset
;
1047 const char *Name
= StrData
->getCStr(&StringOffset
);
1052 "%s Bucket[%d] Hash[%d] = 0x%08x "
1053 "Str[%u] = 0x%08" PRIx64
" DIE[%d] = 0x%08" PRIx64
" "
1054 "is not a valid DIE offset for \"%s\".\n",
1055 SectionName
, BucketIdx
, HashIdx
, Hash
, StringCount
, StrpOffset
,
1056 HashDataIdx
, Offset
, Name
);
1061 if ((Tag
!= dwarf::DW_TAG_null
) && (Die
.getTag() != Tag
)) {
1062 error() << "Tag " << dwarf::TagString(Tag
)
1063 << " in accelerator table does not match Tag "
1064 << dwarf::TagString(Die
.getTag()) << " of DIE[" << HashDataIdx
1076 DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames
&AccelTable
) {
1077 // A map from CU offset to the (first) Name Index offset which claims to index
1079 DenseMap
<uint64_t, uint64_t> CUMap
;
1080 const uint64_t NotIndexed
= std::numeric_limits
<uint64_t>::max();
1082 CUMap
.reserve(DCtx
.getNumCompileUnits());
1083 for (const auto &CU
: DCtx
.compile_units())
1084 CUMap
[CU
->getOffset()] = NotIndexed
;
1086 unsigned NumErrors
= 0;
1087 for (const DWARFDebugNames::NameIndex
&NI
: AccelTable
) {
1088 if (NI
.getCUCount() == 0) {
1089 error() << formatv("Name Index @ {0:x} does not index any CU\n",
1090 NI
.getUnitOffset());
1094 for (uint32_t CU
= 0, End
= NI
.getCUCount(); CU
< End
; ++CU
) {
1095 uint64_t Offset
= NI
.getCUOffset(CU
);
1096 auto Iter
= CUMap
.find(Offset
);
1098 if (Iter
== CUMap
.end()) {
1100 "Name Index @ {0:x} references a non-existing CU @ {1:x}\n",
1101 NI
.getUnitOffset(), Offset
);
1106 if (Iter
->second
!= NotIndexed
) {
1107 error() << formatv("Name Index @ {0:x} references a CU @ {1:x}, but "
1108 "this CU is already indexed by Name Index @ {2:x}\n",
1109 NI
.getUnitOffset(), Offset
, Iter
->second
);
1112 Iter
->second
= NI
.getUnitOffset();
1116 for (const auto &KV
: CUMap
) {
1117 if (KV
.second
== NotIndexed
)
1118 warn() << formatv("CU @ {0:x} not covered by any Name Index\n", KV
.first
);
1125 DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex
&NI
,
1126 const DataExtractor
&StrData
) {
1131 constexpr BucketInfo(uint32_t Bucket
, uint32_t Index
)
1132 : Bucket(Bucket
), Index(Index
) {}
1133 bool operator<(const BucketInfo
&RHS
) const { return Index
< RHS
.Index
; }
1136 uint32_t NumErrors
= 0;
1137 if (NI
.getBucketCount() == 0) {
1138 warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n",
1139 NI
.getUnitOffset());
1143 // Build up a list of (Bucket, Index) pairs. We use this later to verify that
1144 // each Name is reachable from the appropriate bucket.
1145 std::vector
<BucketInfo
> BucketStarts
;
1146 BucketStarts
.reserve(NI
.getBucketCount() + 1);
1147 for (uint32_t Bucket
= 0, End
= NI
.getBucketCount(); Bucket
< End
; ++Bucket
) {
1148 uint32_t Index
= NI
.getBucketArrayEntry(Bucket
);
1149 if (Index
> NI
.getNameCount()) {
1150 error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid "
1151 "value {2}. Valid range is [0, {3}].\n",
1152 Bucket
, NI
.getUnitOffset(), Index
, NI
.getNameCount());
1157 BucketStarts
.emplace_back(Bucket
, Index
);
1160 // If there were any buckets with invalid values, skip further checks as they
1161 // will likely produce many errors which will only confuse the actual root
1166 // Sort the list in the order of increasing "Index" entries.
1167 array_pod_sort(BucketStarts
.begin(), BucketStarts
.end());
1169 // Insert a sentinel entry at the end, so we can check that the end of the
1170 // table is covered in the loop below.
1171 BucketStarts
.emplace_back(NI
.getBucketCount(), NI
.getNameCount() + 1);
1173 // Loop invariant: NextUncovered is the (1-based) index of the first Name
1174 // which is not reachable by any of the buckets we processed so far (and
1175 // hasn't been reported as uncovered).
1176 uint32_t NextUncovered
= 1;
1177 for (const BucketInfo
&B
: BucketStarts
) {
1178 // Under normal circumstances B.Index be equal to NextUncovered, but it can
1179 // be less if a bucket points to names which are already known to be in some
1180 // bucket we processed earlier. In that case, we won't trigger this error,
1181 // but report the mismatched hash value error instead. (We know the hash
1182 // will not match because we have already verified that the name's hash
1183 // puts it into the previous bucket.)
1184 if (B
.Index
> NextUncovered
) {
1185 error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] "
1186 "are not covered by the hash table.\n",
1187 NI
.getUnitOffset(), NextUncovered
, B
.Index
- 1);
1190 uint32_t Idx
= B
.Index
;
1192 // The rest of the checks apply only to non-sentinel entries.
1193 if (B
.Bucket
== NI
.getBucketCount())
1196 // This triggers if a non-empty bucket points to a name with a mismatched
1197 // hash. Clients are likely to interpret this as an empty bucket, because a
1198 // mismatched hash signals the end of a bucket, but if this is indeed an
1199 // empty bucket, the producer should have signalled this by marking the
1201 uint32_t FirstHash
= NI
.getHashArrayEntry(Idx
);
1202 if (FirstHash
% NI
.getBucketCount() != B
.Bucket
) {
1204 "Name Index @ {0:x}: Bucket {1} is not empty but points to a "
1205 "mismatched hash value {2:x} (belonging to bucket {3}).\n",
1206 NI
.getUnitOffset(), B
.Bucket
, FirstHash
,
1207 FirstHash
% NI
.getBucketCount());
1211 // This find the end of this bucket and also verifies that all the hashes in
1212 // this bucket are correct by comparing the stored hashes to the ones we
1213 // compute ourselves.
1214 while (Idx
<= NI
.getNameCount()) {
1215 uint32_t Hash
= NI
.getHashArrayEntry(Idx
);
1216 if (Hash
% NI
.getBucketCount() != B
.Bucket
)
1219 const char *Str
= NI
.getNameTableEntry(Idx
).getString();
1220 if (caseFoldingDjbHash(Str
) != Hash
) {
1221 error() << formatv("Name Index @ {0:x}: String ({1}) at index {2} "
1222 "hashes to {3:x}, but "
1223 "the Name Index hash is {4:x}\n",
1224 NI
.getUnitOffset(), Str
, Idx
,
1225 caseFoldingDjbHash(Str
), Hash
);
1231 NextUncovered
= std::max(NextUncovered
, Idx
);
1236 unsigned DWARFVerifier::verifyNameIndexAttribute(
1237 const DWARFDebugNames::NameIndex
&NI
, const DWARFDebugNames::Abbrev
&Abbr
,
1238 DWARFDebugNames::AttributeEncoding AttrEnc
) {
1239 StringRef FormName
= dwarf::FormEncodingString(AttrEnc
.Form
);
1240 if (FormName
.empty()) {
1241 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1242 "unknown form: {3}.\n",
1243 NI
.getUnitOffset(), Abbr
.Code
, AttrEnc
.Index
,
1248 if (AttrEnc
.Index
== DW_IDX_type_hash
) {
1249 if (AttrEnc
.Form
!= dwarf::DW_FORM_data8
) {
1251 "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash "
1252 "uses an unexpected form {2} (should be {3}).\n",
1253 NI
.getUnitOffset(), Abbr
.Code
, AttrEnc
.Form
, dwarf::DW_FORM_data8
);
1258 // A list of known index attributes and their expected form classes.
1259 // DW_IDX_type_hash is handled specially in the check above, as it has a
1260 // specific form (not just a form class) we should expect.
1261 struct FormClassTable
{
1263 DWARFFormValue::FormClass Class
;
1264 StringLiteral ClassName
;
1266 static constexpr FormClassTable Table
[] = {
1267 {dwarf::DW_IDX_compile_unit
, DWARFFormValue::FC_Constant
, {"constant"}},
1268 {dwarf::DW_IDX_type_unit
, DWARFFormValue::FC_Constant
, {"constant"}},
1269 {dwarf::DW_IDX_die_offset
, DWARFFormValue::FC_Reference
, {"reference"}},
1270 {dwarf::DW_IDX_parent
, DWARFFormValue::FC_Constant
, {"constant"}},
1273 ArrayRef
<FormClassTable
> TableRef(Table
);
1274 auto Iter
= find_if(TableRef
, [AttrEnc
](const FormClassTable
&T
) {
1275 return T
.Index
== AttrEnc
.Index
;
1277 if (Iter
== TableRef
.end()) {
1278 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an "
1279 "unknown index attribute: {2}.\n",
1280 NI
.getUnitOffset(), Abbr
.Code
, AttrEnc
.Index
);
1284 if (!DWARFFormValue(AttrEnc
.Form
).isFormClass(Iter
->Class
)) {
1285 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1286 "unexpected form {3} (expected form class {4}).\n",
1287 NI
.getUnitOffset(), Abbr
.Code
, AttrEnc
.Index
,
1288 AttrEnc
.Form
, Iter
->ClassName
);
1295 DWARFVerifier::verifyNameIndexAbbrevs(const DWARFDebugNames::NameIndex
&NI
) {
1296 if (NI
.getLocalTUCount() + NI
.getForeignTUCount() > 0) {
1297 warn() << formatv("Name Index @ {0:x}: Verifying indexes of type units is "
1298 "not currently supported.\n",
1299 NI
.getUnitOffset());
1303 unsigned NumErrors
= 0;
1304 for (const auto &Abbrev
: NI
.getAbbrevs()) {
1305 StringRef TagName
= dwarf::TagString(Abbrev
.Tag
);
1306 if (TagName
.empty()) {
1307 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an "
1308 "unknown tag: {2}.\n",
1309 NI
.getUnitOffset(), Abbrev
.Code
, Abbrev
.Tag
);
1311 SmallSet
<unsigned, 5> Attributes
;
1312 for (const auto &AttrEnc
: Abbrev
.Attributes
) {
1313 if (!Attributes
.insert(AttrEnc
.Index
).second
) {
1314 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains "
1315 "multiple {2} attributes.\n",
1316 NI
.getUnitOffset(), Abbrev
.Code
, AttrEnc
.Index
);
1320 NumErrors
+= verifyNameIndexAttribute(NI
, Abbrev
, AttrEnc
);
1323 if (NI
.getCUCount() > 1 && !Attributes
.count(dwarf::DW_IDX_compile_unit
)) {
1324 error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units "
1325 "and abbreviation {1:x} has no {2} attribute.\n",
1326 NI
.getUnitOffset(), Abbrev
.Code
,
1327 dwarf::DW_IDX_compile_unit
);
1330 if (!Attributes
.count(dwarf::DW_IDX_die_offset
)) {
1332 "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n",
1333 NI
.getUnitOffset(), Abbrev
.Code
, dwarf::DW_IDX_die_offset
);
1340 static SmallVector
<StringRef
, 2> getNames(const DWARFDie
&DIE
,
1341 bool IncludeLinkageName
= true) {
1342 SmallVector
<StringRef
, 2> Result
;
1343 if (const char *Str
= DIE
.getShortName())
1344 Result
.emplace_back(Str
);
1345 else if (DIE
.getTag() == dwarf::DW_TAG_namespace
)
1346 Result
.emplace_back("(anonymous namespace)");
1348 if (IncludeLinkageName
) {
1349 if (const char *Str
= DIE
.getLinkageName())
1350 Result
.emplace_back(Str
);
1356 unsigned DWARFVerifier::verifyNameIndexEntries(
1357 const DWARFDebugNames::NameIndex
&NI
,
1358 const DWARFDebugNames::NameTableEntry
&NTE
) {
1359 // Verifying type unit indexes not supported.
1360 if (NI
.getLocalTUCount() + NI
.getForeignTUCount() > 0)
1363 const char *CStr
= NTE
.getString();
1366 "Name Index @ {0:x}: Unable to get string associated with name {1}.\n",
1367 NI
.getUnitOffset(), NTE
.getIndex());
1370 StringRef
Str(CStr
);
1372 unsigned NumErrors
= 0;
1373 unsigned NumEntries
= 0;
1374 uint64_t EntryID
= NTE
.getEntryOffset();
1375 uint64_t NextEntryID
= EntryID
;
1376 Expected
<DWARFDebugNames::Entry
> EntryOr
= NI
.getEntry(&NextEntryID
);
1377 for (; EntryOr
; ++NumEntries
, EntryID
= NextEntryID
,
1378 EntryOr
= NI
.getEntry(&NextEntryID
)) {
1379 uint32_t CUIndex
= *EntryOr
->getCUIndex();
1380 if (CUIndex
> NI
.getCUCount()) {
1381 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
1382 "invalid CU index ({2}).\n",
1383 NI
.getUnitOffset(), EntryID
, CUIndex
);
1387 uint64_t CUOffset
= NI
.getCUOffset(CUIndex
);
1388 uint64_t DIEOffset
= CUOffset
+ *EntryOr
->getDIEUnitOffset();
1389 DWARFDie DIE
= DCtx
.getDIEForOffset(DIEOffset
);
1391 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
1392 "non-existing DIE @ {2:x}.\n",
1393 NI
.getUnitOffset(), EntryID
, DIEOffset
);
1397 if (DIE
.getDwarfUnit()->getOffset() != CUOffset
) {
1398 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of "
1399 "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n",
1400 NI
.getUnitOffset(), EntryID
, DIEOffset
, CUOffset
,
1401 DIE
.getDwarfUnit()->getOffset());
1404 if (DIE
.getTag() != EntryOr
->tag()) {
1405 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of "
1406 "DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1407 NI
.getUnitOffset(), EntryID
, DIEOffset
, EntryOr
->tag(),
1412 auto EntryNames
= getNames(DIE
);
1413 if (!is_contained(EntryNames
, Str
)) {
1414 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name "
1415 "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1416 NI
.getUnitOffset(), EntryID
, DIEOffset
, Str
,
1417 make_range(EntryNames
.begin(), EntryNames
.end()));
1421 handleAllErrors(EntryOr
.takeError(),
1422 [&](const DWARFDebugNames::SentinelError
&) {
1425 error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
1426 "not associated with any entries.\n",
1427 NI
.getUnitOffset(), NTE
.getIndex(), Str
);
1430 [&](const ErrorInfoBase
&Info
) {
1432 << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n",
1433 NI
.getUnitOffset(), NTE
.getIndex(), Str
,
1440 static bool isVariableIndexable(const DWARFDie
&Die
, DWARFContext
&DCtx
) {
1441 Expected
<std::vector
<DWARFLocationExpression
>> Loc
=
1442 Die
.getLocations(DW_AT_location
);
1444 consumeError(Loc
.takeError());
1447 DWARFUnit
*U
= Die
.getDwarfUnit();
1448 for (const auto &Entry
: *Loc
) {
1449 DataExtractor
Data(toStringRef(Entry
.Expr
), DCtx
.isLittleEndian(),
1450 U
->getAddressByteSize());
1451 DWARFExpression
Expression(Data
, U
->getAddressByteSize(),
1452 U
->getFormParams().Format
);
1453 bool IsInteresting
=
1454 any_of(Expression
, [](const DWARFExpression::Operation
&Op
) {
1455 return !Op
.isError() && (Op
.getCode() == DW_OP_addr
||
1456 Op
.getCode() == DW_OP_form_tls_address
||
1457 Op
.getCode() == DW_OP_GNU_push_tls_address
);
1465 unsigned DWARFVerifier::verifyNameIndexCompleteness(
1466 const DWARFDie
&Die
, const DWARFDebugNames::NameIndex
&NI
) {
1468 // First check, if the Die should be indexed. The code follows the DWARF v5
1469 // wording as closely as possible.
1471 // "All non-defining declarations (that is, debugging information entries
1472 // with a DW_AT_declaration attribute) are excluded."
1473 if (Die
.find(DW_AT_declaration
))
1476 // "DW_TAG_namespace debugging information entries without a DW_AT_name
1477 // attribute are included with the name “(anonymous namespace)”.
1478 // All other debugging information entries without a DW_AT_name attribute
1480 // "If a subprogram or inlined subroutine is included, and has a
1481 // DW_AT_linkage_name attribute, there will be an additional index entry for
1482 // the linkage name."
1483 auto IncludeLinkageName
= Die
.getTag() == DW_TAG_subprogram
||
1484 Die
.getTag() == DW_TAG_inlined_subroutine
;
1485 auto EntryNames
= getNames(Die
, IncludeLinkageName
);
1486 if (EntryNames
.empty())
1489 // We deviate from the specification here, which says:
1490 // "The name index must contain an entry for each debugging information entry
1491 // that defines a named subprogram, label, variable, type, or namespace,
1493 // Explicitly exclude all TAGs that we know shouldn't be indexed.
1494 switch (Die
.getTag()) {
1495 // Compile units and modules have names but shouldn't be indexed.
1496 case DW_TAG_compile_unit
:
1500 // Function and template parameters are not globally visible, so we shouldn't
1502 case DW_TAG_formal_parameter
:
1503 case DW_TAG_template_value_parameter
:
1504 case DW_TAG_template_type_parameter
:
1505 case DW_TAG_GNU_template_parameter_pack
:
1506 case DW_TAG_GNU_template_template_param
:
1509 // Object members aren't globally visible.
1513 // According to a strict reading of the specification, enumerators should not
1514 // be indexed (and LLVM currently does not do that). However, this causes
1515 // problems for the debuggers, so we may need to reconsider this.
1516 case DW_TAG_enumerator
:
1519 // Imported declarations should not be indexed according to the specification
1520 // and LLVM currently does not do that.
1521 case DW_TAG_imported_declaration
:
1524 // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging
1525 // information entries without an address attribute (DW_AT_low_pc,
1526 // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded."
1527 case DW_TAG_subprogram
:
1528 case DW_TAG_inlined_subroutine
:
1530 if (Die
.findRecursively(
1531 {DW_AT_low_pc
, DW_AT_high_pc
, DW_AT_ranges
, DW_AT_entry_pc
}))
1535 // "DW_TAG_variable debugging information entries with a DW_AT_location
1536 // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are
1537 // included; otherwise, they are excluded."
1539 // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list.
1540 case DW_TAG_variable
:
1541 if (isVariableIndexable(Die
, DCtx
))
1549 // Now we know that our Die should be present in the Index. Let's check if
1551 unsigned NumErrors
= 0;
1552 uint64_t DieUnitOffset
= Die
.getOffset() - Die
.getDwarfUnit()->getOffset();
1553 for (StringRef Name
: EntryNames
) {
1554 if (none_of(NI
.equal_range(Name
), [&](const DWARFDebugNames::Entry
&E
) {
1555 return E
.getDIEUnitOffset() == DieUnitOffset
;
1557 error() << formatv("Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with "
1558 "name {3} missing.\n",
1559 NI
.getUnitOffset(), Die
.getOffset(), Die
.getTag(),
1567 unsigned DWARFVerifier::verifyDebugNames(const DWARFSection
&AccelSection
,
1568 const DataExtractor
&StrData
) {
1569 unsigned NumErrors
= 0;
1570 DWARFDataExtractor
AccelSectionData(DCtx
.getDWARFObj(), AccelSection
,
1571 DCtx
.isLittleEndian(), 0);
1572 DWARFDebugNames
AccelTable(AccelSectionData
, StrData
);
1574 OS
<< "Verifying .debug_names...\n";
1576 // This verifies that we can read individual name indices and their
1577 // abbreviation tables.
1578 if (Error E
= AccelTable
.extract()) {
1579 error() << toString(std::move(E
)) << '\n';
1583 NumErrors
+= verifyDebugNamesCULists(AccelTable
);
1584 for (const auto &NI
: AccelTable
)
1585 NumErrors
+= verifyNameIndexBuckets(NI
, StrData
);
1586 for (const auto &NI
: AccelTable
)
1587 NumErrors
+= verifyNameIndexAbbrevs(NI
);
1589 // Don't attempt Entry validation if any of the previous checks found errors
1592 for (const auto &NI
: AccelTable
)
1593 for (const DWARFDebugNames::NameTableEntry
&NTE
: NI
)
1594 NumErrors
+= verifyNameIndexEntries(NI
, NTE
);
1599 for (const std::unique_ptr
<DWARFUnit
> &U
: DCtx
.compile_units()) {
1600 if (const DWARFDebugNames::NameIndex
*NI
=
1601 AccelTable
.getCUNameIndex(U
->getOffset())) {
1602 auto *CU
= cast
<DWARFCompileUnit
>(U
.get());
1603 for (const DWARFDebugInfoEntry
&Die
: CU
->dies())
1604 NumErrors
+= verifyNameIndexCompleteness(DWARFDie(CU
, &Die
), *NI
);
1610 bool DWARFVerifier::handleAccelTables() {
1611 const DWARFObject
&D
= DCtx
.getDWARFObj();
1612 DataExtractor
StrData(D
.getStrSection(), DCtx
.isLittleEndian(), 0);
1613 unsigned NumErrors
= 0;
1614 if (!D
.getAppleNamesSection().Data
.empty())
1615 NumErrors
+= verifyAppleAccelTable(&D
.getAppleNamesSection(), &StrData
,
1617 if (!D
.getAppleTypesSection().Data
.empty())
1618 NumErrors
+= verifyAppleAccelTable(&D
.getAppleTypesSection(), &StrData
,
1620 if (!D
.getAppleNamespacesSection().Data
.empty())
1621 NumErrors
+= verifyAppleAccelTable(&D
.getAppleNamespacesSection(), &StrData
,
1622 ".apple_namespaces");
1623 if (!D
.getAppleObjCSection().Data
.empty())
1624 NumErrors
+= verifyAppleAccelTable(&D
.getAppleObjCSection(), &StrData
,
1627 if (!D
.getNamesSection().Data
.empty())
1628 NumErrors
+= verifyDebugNames(D
.getNamesSection(), StrData
);
1629 return NumErrors
== 0;
1632 raw_ostream
&DWARFVerifier::error() const { return WithColor::error(OS
); }
1634 raw_ostream
&DWARFVerifier::warn() const { return WithColor::warning(OS
); }
1636 raw_ostream
&DWARFVerifier::note() const { return WithColor::note(OS
); }
1638 raw_ostream
&DWARFVerifier::dump(const DWARFDie
&Die
, unsigned indent
) const {
1639 Die
.dump(OS
, indent
, DumpOpts
);