LLVM 17.0.0git
DWARFVerifier.cpp
Go to the documentation of this file.
1//===- DWARFVerifier.cpp --------------------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
10#include "llvm/ADT/SmallSet.h"
27#include "llvm/Object/Error.h"
28#include "llvm/Support/DJB.h"
29#include "llvm/Support/Error.h"
34#include <map>
35#include <set>
36#include <vector>
37
38using namespace llvm;
39using namespace dwarf;
40using namespace object;
41
42namespace llvm {
44}
45
46std::optional<DWARFAddressRange>
48 auto Begin = Ranges.begin();
49 auto End = Ranges.end();
50 auto Pos = std::lower_bound(Begin, End, R);
51
52 if (Pos != End) {
53 DWARFAddressRange Range(*Pos);
54 if (Pos->merge(R))
55 return Range;
56 }
57 if (Pos != Begin) {
58 auto Iter = Pos - 1;
59 DWARFAddressRange Range(*Iter);
60 if (Iter->merge(R))
61 return Range;
62 }
63
64 Ranges.insert(Pos, R);
65 return std::nullopt;
66}
67
70 if (RI.Ranges.empty())
71 return Children.end();
72
73 auto End = Children.end();
74 auto Iter = Children.begin();
75 while (Iter != End) {
76 if (Iter->intersects(RI))
77 return Iter;
78 ++Iter;
79 }
80 Children.insert(RI);
81 return Children.end();
82}
83
85 auto I1 = Ranges.begin(), E1 = Ranges.end();
86 auto I2 = RHS.Ranges.begin(), E2 = RHS.Ranges.end();
87 if (I2 == E2)
88 return true;
89
90 DWARFAddressRange R = *I2;
91 while (I1 != E1) {
92 bool Covered = I1->LowPC <= R.LowPC;
93 if (R.LowPC == R.HighPC || (Covered && R.HighPC <= I1->HighPC)) {
94 if (++I2 == E2)
95 return true;
96 R = *I2;
97 continue;
98 }
99 if (!Covered)
100 return false;
101 if (R.LowPC < I1->HighPC)
102 R.LowPC = I1->HighPC;
103 ++I1;
104 }
105 return false;
106}
107
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))
113 return true;
114 if (I1->LowPC < I2->LowPC)
115 ++I1;
116 else
117 ++I2;
118 }
119 return false;
120}
121
122bool 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;
127 uint16_t Version;
128 bool Success = true;
129
130 bool ValidLength = false;
131 bool ValidVersion = false;
132 bool ValidAddrSize = false;
133 bool ValidType = true;
134 bool ValidAbbrevOffset = true;
135
136 uint64_t OffsetStart = *Offset;
138 std::tie(Length, Format) = DebugInfoData.getInitialLength(Offset);
139 isUnitDWARF64 = Format == DWARF64;
140 Version = DebugInfoData.getU16(Offset);
141
142 if (Version >= 5) {
143 UnitType = DebugInfoData.getU8(Offset);
144 AddrSize = DebugInfoData.getU8(Offset);
145 AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
146 ValidType = dwarf::isUnitType(UnitType);
147 } else {
148 UnitType = 0;
149 AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
150 AddrSize = DebugInfoData.getU8(Offset);
151 }
152
153 if (!DCtx.getDebugAbbrev()->getAbbreviationDeclarationSet(AbbrOffset))
154 ValidAbbrevOffset = false;
155
156 ValidLength = DebugInfoData.isValidOffset(OffsetStart + Length + 3);
157 ValidVersion = DWARFContext::isSupportedVersion(Version);
158 ValidAddrSize = DWARFContext::isAddressSizeSupported(AddrSize);
159 if (!ValidLength || !ValidVersion || !ValidAddrSize || !ValidAbbrevOffset ||
160 !ValidType) {
161 Success = false;
162 error() << format("Units[%d] - start offset: 0x%08" PRIx64 " \n", UnitIndex,
163 OffsetStart);
164 if (!ValidLength)
165 note() << "The length for this unit is too "
166 "large for the .debug_info provided.\n";
167 if (!ValidVersion)
168 note() << "The 16 bit unit header version is not valid.\n";
169 if (!ValidType)
170 note() << "The unit type encoding is not valid.\n";
171 if (!ValidAbbrevOffset)
172 note() << "The offset into the .debug_abbrev section is "
173 "not valid.\n";
174 if (!ValidAddrSize)
175 note() << "The address size is unsupported.\n";
176 }
177 *Offset = OffsetStart + Length + (isUnitDWARF64 ? 12 : 4);
178 return Success;
179}
180
181bool 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.
184
185 std::string ReconstructedName;
186 raw_string_ostream OS(ReconstructedName);
187 std::string OriginalFullName;
188 Die.getFullName(OS, &OriginalFullName);
189 OS.flush();
190 if (OriginalFullName.empty() || OriginalFullName == ReconstructedName)
191 return false;
192
193 error() << "Simplified template DW_AT_name could not be reconstituted:\n"
194 << formatv(" original: {0}\n"
195 " reconstituted: {1}\n",
196 OriginalFullName, ReconstructedName);
197 dump(Die) << '\n';
198 dump(Die.getDwarfUnit()->getUnitDIE()) << '\n';
199 return true;
200}
201
202unsigned 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);
209
210 if (Die.getTag() == DW_TAG_null)
211 continue;
212
213 for (auto AttrValue : Die.attributes()) {
214 NumUnitErrors += verifyDebugInfoAttribute(Die, AttrValue);
215 NumUnitErrors += verifyDebugInfoForm(Die, AttrValue, UnitLocalReferences,
216 CrossUnitReferences);
217 }
218
219 NumUnitErrors += verifyName(Die);
220
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: ";
226 Die.dump(OS);
227 }
228 }
229
230 NumUnitErrors += verifyDebugInfoCallSite(Die);
231 }
232
233 DWARFDie Die = Unit.getUnitDIE(/* ExtractUnitDIEOnly = */ false);
234 if (!Die) {
235 error() << "Compilation unit without DIE.\n";
236 NumUnitErrors++;
237 return NumUnitErrors;
238 }
239
240 if (!dwarf::isUnitType(Die.getTag())) {
241 error() << "Compilation unit root DIE is not a unit DIE: "
242 << dwarf::TagString(Die.getTag()) << ".\n";
243 NumUnitErrors++;
244 }
245
246 uint8_t UnitType = Unit.getUnitType();
248 error() << "Compilation unit type (" << dwarf::UnitTypeString(UnitType)
249 << ") and root DIE (" << dwarf::TagString(Die.getTag())
250 << ") do not match.\n";
251 NumUnitErrors++;
252 }
253
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";
259 NumUnitErrors++;
260 }
261
262 DieRangeInfo RI;
263 NumUnitErrors += verifyDieRanges(Die, RI);
264
265 return NumUnitErrors;
266}
267
268unsigned DWARFVerifier::verifyDebugInfoCallSite(const DWARFDie &Die) {
269 if (Die.getTag() != DW_TAG_call_site && Die.getTag() != DW_TAG_GNU_call_site)
270 return 0;
271
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:";
276 Curr.dump(OS);
277 return 1;
278 }
279 }
280
281 if (!Curr.isValid()) {
282 error() << "Call site entry not nested within a valid subprogram:";
283 Die.dump(OS);
284 return 1;
285 }
286
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});
291 if (!CallAttr) {
292 error() << "Subprogram with call site entry has no DW_AT_call attribute:";
293 Curr.dump(OS);
294 Die.dump(OS, /*indent*/ 1);
295 return 1;
296 }
297
298 return 0;
299}
300
301unsigned DWARFVerifier::verifyAbbrevSection(const DWARFDebugAbbrev *Abbrev) {
302 unsigned NumErrors = 0;
303 if (Abbrev) {
304 const DWARFAbbreviationDeclarationSet *AbbrDecls =
306 for (auto AbbrDecl : *AbbrDecls) {
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";
313 AbbrDecl.dump(OS);
314 ++NumErrors;
315 }
316 }
317 }
318 }
319 return NumErrors;
320}
321
323 OS << "Verifying .debug_abbrev...\n";
324
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());
331
332 return NumErrors == 0;
333}
334
335unsigned DWARFVerifier::verifyUnits(const DWARFUnitVector &Units) {
336 unsigned NumDebugInfoErrors = 0;
337 ReferenceMap CrossUnitReferences;
338
339 unsigned Index = 1;
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 << '\"';
344 OS << '\n';
345 OS.flush();
346 ReferenceMap UnitLocalReferences;
347 NumDebugInfoErrors +=
348 verifyUnitContents(*Unit, UnitLocalReferences, CrossUnitReferences);
349 NumDebugInfoErrors += verifyDebugInfoReferences(
350 UnitLocalReferences, [&](uint64_t Offset) { return Unit.get(); });
351 ++Index;
352 }
353
354 NumDebugInfoErrors += verifyDebugInfoReferences(
355 CrossUnitReferences, [&](uint64_t Offset) -> DWARFUnit * {
356 if (DWARFUnit *U = Units.getUnitForOffset(Offset))
357 return U;
358 return nullptr;
359 });
360
361 return NumDebugInfoErrors;
362}
363
364unsigned 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;
379 while (hasDIE) {
380 if (!verifyUnitHeader(DebugInfoData, &Offset, UnitIdx, UnitType,
381 isUnitDWARF64)) {
382 isHeaderChainValid = false;
383 if (isUnitDWARF64)
384 break;
385 }
386 hasDIE = DebugInfoData.isValidOffset(Offset);
387 ++UnitIdx;
388 }
389 if (UnitIdx == 0 && !hasDIE) {
390 warn() << "Section is empty.\n";
391 isHeaderChainValid = true;
392 }
393 if (!isHeaderChainValid)
394 ++NumDebugInfoErrors;
395 return NumDebugInfoErrors;
396}
397
398unsigned DWARFVerifier::verifyIndex(StringRef Name,
399 DWARFSectionKind InfoColumnKind,
400 StringRef IndexStr) {
401 if (IndexStr.empty())
402 return 0;
403 OS << "Verifying " << Name << "...\n";
404 DWARFUnitIndex Index(InfoColumnKind);
405 DataExtractor D(IndexStr, DCtx.isLittleEndian(), 0);
406 if (!Index.parse(D))
407 return 1;
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())
414 continue;
415 for (auto E : enumerate(
416 InfoColumnKind == DW_SECT_INFO
417 ? ArrayRef(E.getContributions(), Index.getColumnKinds().size())
418 : ArrayRef(E.getContribution(), 1))) {
420 int Col = E.index();
421 if (SC.getLength() == 0)
422 continue;
423 if (!Sections[Col])
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]));
432 return 1;
433 }
434 M.insert(SC.getOffset(), SC.getOffset() + SC.getLength() - 1, Sig);
435 }
436 }
437
438 return 0;
439}
440
442 return verifyIndex(".debug_cu_index", DWARFSectionKind::DW_SECT_INFO,
443 DCtx.getDWARFObj().getCUIndexSection()) == 0;
444}
445
447 return verifyIndex(".debug_tu_index", DWARFSectionKind::DW_SECT_EXT_TYPES,
448 DCtx.getDWARFObj().getTUIndexSection()) == 0;
449}
450
452 const DWARFObject &DObj = DCtx.getDWARFObj();
453 unsigned NumErrors = 0;
454
455 OS << "Verifying .debug_info Unit Header Chain...\n";
456 DObj.forEachInfoSections([&](const DWARFSection &S) {
457 NumErrors += verifyUnitSection(S);
458 });
459
460 OS << "Verifying .debug_types Unit Header Chain...\n";
461 DObj.forEachTypesSections([&](const DWARFSection &S) {
462 NumErrors += verifyUnitSection(S);
463 });
464
465 OS << "Verifying non-dwo Units...\n";
466 NumErrors += verifyUnits(DCtx.getNormalUnitsVector());
467
468 OS << "Verifying dwo Units...\n";
469 NumErrors += verifyUnits(DCtx.getDWOUnitsVector());
470 return NumErrors == 0;
471}
472
473unsigned DWARFVerifier::verifyDieRanges(const DWARFDie &Die,
474 DieRangeInfo &ParentRI) {
475 unsigned NumErrors = 0;
476
477 if (!Die.isValid())
478 return NumErrors;
479
480 DWARFUnit *Unit = Die.getDwarfUnit();
481
482 auto RangesOrError = Die.getAddressRanges();
483 if (!RangesOrError) {
484 // FIXME: Report the error.
485 if (!Unit->isDWOUnit())
486 ++NumErrors;
487 llvm::consumeError(RangesOrError.takeError());
488 return NumErrors;
489 }
490
491 const DWARFAddressRangesVector &Ranges = RangesOrError.get();
492 // Build RI for this DIE and check that ranges within this DIE do not
493 // overlap.
494 DieRangeInfo RI(Die);
495
496 // TODO support object files better
497 //
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.
504 //
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.
511 //
512 // For now, simply elide the range verification for the CU DIEs if we are
513 // processing an object file.
514
515 if (!IsObjectFile || IsMachOObject || Die.getTag() != DW_TAG_compile_unit) {
516 bool DumpDieAfterError = false;
517 for (const auto &Range : Ranges) {
518 if (!Range.valid()) {
519 ++NumErrors;
520 error() << "Invalid address range " << Range << "\n";
521 DumpDieAfterError = true;
522 continue;
523 }
524
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
530 // address: 0 or -1.
531 if (auto PrevRange = RI.insert(Range)) {
532 ++NumErrors;
533 error() << "DIE has overlapping ranges in DW_AT_ranges attribute: "
534 << *PrevRange << " and " << Range << '\n';
535 DumpDieAfterError = true;
536 }
537 }
538 if (DumpDieAfterError)
539 dump(Die, 2) << '\n';
540 }
541
542 // Verify that children don't intersect.
543 const auto IntersectingChild = ParentRI.insert(RI);
544 if (IntersectingChild != ParentRI.Children.end()) {
545 ++NumErrors;
546 error() << "DIEs have overlapping address ranges:";
547 dump(Die);
548 dump(IntersectingChild->Die) << '\n';
549 }
550
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)) {
556 ++NumErrors;
557 error() << "DIE address ranges are not contained in its parent's ranges:";
558 dump(ParentRI.Die);
559 dump(Die, 2) << '\n';
560 }
561
562 // Recursively check children.
563 for (DWARFDie Child : Die)
564 NumErrors += verifyDieRanges(Child, RI);
565
566 return NumErrors;
567}
568
569unsigned DWARFVerifier::verifyDebugInfoAttribute(const DWARFDie &Die,
570 DWARFAttribute &AttrValue) {
571 unsigned NumErrors = 0;
572 auto ReportError = [&](const Twine &TitleMsg) {
573 ++NumErrors;
574 error() << TitleMsg << '\n';
575 dump(Die) << '\n';
576 };
577
578 const DWARFObject &DObj = DCtx.getDWARFObj();
579 DWARFUnit *U = Die.getDwarfUnit();
580 const auto Attr = AttrValue.Attr;
581 switch (Attr) {
582 case DW_AT_ranges:
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())
590 break;
591 if (*SectionOffset >= RangeSection.Data.size())
592 ReportError(
593 "DW_AT_ranges offset is beyond " +
594 StringRef(DwarfVersion < 5 ? ".debug_ranges" : ".debug_rnglists") +
595 " bounds: " + llvm::formatv("{0:x8}", *SectionOffset));
596 break;
597 }
598 ReportError("DIE has invalid DW_AT_ranges encoding:");
599 break;
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));
606 break;
607 }
608 ReportError("DIE has invalid DW_AT_stmt_list encoding:");
609 break;
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
616 // resolved.
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);
627 bool Error =
629 return Op.isError();
630 });
631 if (Error || !Expression.verify(U))
632 ReportError("DIE contains invalid DWARF expression:");
633 }
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));
638 }))
639 ReportError(toString(std::move(Err)));
640 break;
641 }
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)
648 break;
649 if (DieTag == DW_TAG_inlined_subroutine && RefTag == DW_TAG_subprogram)
650 break;
651 if (DieTag == DW_TAG_variable && RefTag == DW_TAG_member)
652 break;
653 // This might be reference to a function declaration.
654 if (DieTag == DW_TAG_GNU_call_site && RefTag == DW_TAG_subprogram)
655 break;
656 ReportError("DIE with tag " + TagString(DieTag) + " has " +
657 AttributeString(Attr) +
658 " that points to DIE with "
659 "incompatible tag " +
660 TagString(RefTag));
661 }
662 break;
663 }
664 case DW_AT_type: {
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()));
669 }
670 break;
671 }
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())
676 break;
677 const auto *LT = U->getContext().getLineTableForUnit(U);
678 if (LT) {
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) + "])");
688 } else {
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)");
693 }
694 }
695 } else {
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");
700 }
701 } else {
702 ReportError("DIE has " + AttributeString(Attr) +
703 " with invalid encoding");
704 }
705 break;
706 }
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");
712 }
713 break;
714 }
715 default:
716 break;
717 }
718 return NumErrors;
719}
720
721unsigned 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();
728 switch (Form) {
729 case DW_FORM_ref1:
730 case DW_FORM_ref2:
731 case DW_FORM_ref4:
732 case DW_FORM_ref8:
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();
736 assert(RefVal);
737 if (RefVal) {
738 auto CUSize = DieCU->getNextUnitOffset() - DieCU->getOffset();
739 auto CUOffset = AttrValue.Value.getRawUValue();
740 if (CUOffset >= CUSize) {
741 ++NumErrors;
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);
747 dump(Die) << '\n';
748 } else {
749 // Valid reference, but we will verify it points to an actual
750 // DIE later.
751 LocalReferences[*RefVal].insert(Die.getOffset());
752 }
753 }
754 break;
755 }
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();
760 assert(RefVal);
761 if (RefVal) {
762 if (*RefVal >= DieCU->getInfoSection().Data.size()) {
763 ++NumErrors;
764 error() << "DW_FORM_ref_addr offset beyond .debug_info "
765 "bounds:\n";
766 dump(Die) << '\n';
767 } else {
768 // Valid reference, but we will verify it points to an actual
769 // DIE later.
770 CrossUnitReferences[*RefVal].insert(Die.getOffset());
771 }
772 }
773 break;
774 }
775 case DW_FORM_strp:
776 case DW_FORM_strx:
777 case DW_FORM_strx1:
778 case DW_FORM_strx2:
779 case DW_FORM_strx3:
780 case DW_FORM_strx4:
781 case DW_FORM_line_strp: {
782 if (Error E = AttrValue.Value.getAsCString().takeError()) {
783 ++NumErrors;
784 error() << toString(std::move(E)) << ":\n";
785 dump(Die) << '\n';
786 }
787 break;
788 }
789 default:
790 break;
791 }
792 return NumErrors;
793}
794
795unsigned 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);
801 return DWARFDie();
802 };
803 unsigned NumErrors = 0;
804 for (const std::pair<const uint64_t, std::set<uint64_t>> &Pair :
805 References) {
806 if (GetDIEForOffset(Pair.first))
807 continue;
808 ++NumErrors;
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';
813 OS << "\n";
814 }
815 return NumErrors;
816}
817
818void 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)
827 continue;
828 const uint64_t LineTableOffset = *StmtSectionOffset;
829 auto LineTable = DCtx.getLineTableForUnit(CU.get());
830 if (LineTableOffset < DCtx.getDWARFObj().getLineSection().Data.size()) {
831 if (!LineTable) {
832 ++NumDebugLineErrors;
833 error() << ".debug_line[" << format("0x%08" PRIx64, LineTableOffset)
834 << "] was not able to be parsed for CU:\n";
835 dump(Die) << '\n';
836 continue;
837 }
838 } else {
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.
843 continue;
844 }
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";
852 dump(Iter->second);
853 dump(Die) << '\n';
854 // Already verified this line table before, no need to do it again.
855 continue;
856 }
857 StmtListToDie[LineTableOffset] = Die;
858 }
859}
860
861void 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().
867 if (!LineTable)
868 continue;
869
870 // Verify prologue.
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
885 << "\n";
886 }
887
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?");
894 (void)HasFullPath;
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";
904 }
905
906 FileIndex++;
907 }
908
909 // Verify rows.
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";
921
923 if (RowIndex > 0)
924 LineTable->Rows[RowIndex - 1].dump(OS);
925 Row.dump(OS);
926 OS << '\n';
927 }
928
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";
940 Row.dump(OS);
941 OS << '\n';
942 }
943 if (Row.EndSequence)
944 PrevAddress = 0;
945 else
946 PrevAddress = Row.Address.Address;
947 ++RowIndex;
948 }
949 }
950}
951
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();
959 }
960}
961
963 NumDebugLineErrors = 0;
964 OS << "Verifying .debug_line...\n";
965 verifyDebugLineStmtOffsets();
966 verifyDebugLineRows();
967 return NumDebugLineErrors == 0;
968}
969
970unsigned 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);
977
978 OS << "Verifying " << SectionName << "...\n";
979
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";
983 return 1;
984 }
985
986 // Verify that the section is not too short.
987 if (Error E = AccelTable.extract()) {
988 error() << toString(std::move(E)) << '\n';
989 return 1;
990 }
991
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();
995
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,
1004 HashIdx);
1005 ++NumErrors;
1006 }
1007 }
1008 uint32_t NumAtoms = AccelTable.getAtomsDesc().size();
1009 if (NumAtoms == 0) {
1010 error() << "No atoms: failed to read HashData.\n";
1011 return 1;
1012 }
1013 if (!AccelTable.validateForms()) {
1014 error() << "Unsupported form: failed to read HashData.\n";
1015 return 1;
1016 }
1017
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);
1028 ++NumErrors;
1029 }
1030
1031 uint64_t StrpOffset;
1032 uint64_t StringOffset;
1033 uint32_t StringCount = 0;
1035 unsigned Tag;
1036 while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) {
1037 const uint32_t NumHashDataObjects =
1038 AccelSectionData.getU32(&HashDataOffset);
1039 for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects;
1040 ++HashDataIdx) {
1041 std::tie(Offset, Tag) = AccelTable.readAtoms(&HashDataOffset);
1042 auto Die = DCtx.getDIEForOffset(Offset);
1043 if (!Die) {
1044 const uint32_t BucketIdx =
1045 NumBuckets ? (Hash % NumBuckets) : UINT32_MAX;
1046 StringOffset = StrpOffset;
1047 const char *Name = StrData->getCStr(&StringOffset);
1048 if (!Name)
1049 Name = "<NULL>";
1050
1051 error() << format(
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);
1057
1058 ++NumErrors;
1059 continue;
1060 }
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
1065 << "].\n";
1066 ++NumErrors;
1067 }
1068 }
1069 ++StringCount;
1070 }
1071 }
1072 return NumErrors;
1073}
1074
1075unsigned
1076DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) {
1077 // A map from CU offset to the (first) Name Index offset which claims to index
1078 // this CU.
1080 const uint64_t NotIndexed = std::numeric_limits<uint64_t>::max();
1081
1082 CUMap.reserve(DCtx.getNumCompileUnits());
1083 for (const auto &CU : DCtx.compile_units())
1084 CUMap[CU->getOffset()] = NotIndexed;
1085
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());
1091 ++NumErrors;
1092 continue;
1093 }
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);
1097
1098 if (Iter == CUMap.end()) {
1099 error() << formatv(
1100 "Name Index @ {0:x} references a non-existing CU @ {1:x}\n",
1101 NI.getUnitOffset(), Offset);
1102 ++NumErrors;
1103 continue;
1104 }
1105
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);
1110 continue;
1111 }
1112 Iter->second = NI.getUnitOffset();
1113 }
1114 }
1115
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);
1119 }
1120
1121 return NumErrors;
1122}
1123
1124unsigned
1125DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI,
1126 const DataExtractor &StrData) {
1127 struct BucketInfo {
1128 uint32_t Bucket;
1130
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; }
1134 };
1135
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());
1140 return NumErrors;
1141 }
1142
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());
1153 ++NumErrors;
1154 continue;
1155 }
1156 if (Index > 0)
1157 BucketStarts.emplace_back(Bucket, Index);
1158 }
1159
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
1162 // problem.
1163 if (NumErrors > 0)
1164 return NumErrors;
1165
1166 // Sort the list in the order of increasing "Index" entries.
1167 array_pod_sort(BucketStarts.begin(), BucketStarts.end());
1168
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);
1172
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);
1188 ++NumErrors;
1189 }
1190 uint32_t Idx = B.Index;
1191
1192 // The rest of the checks apply only to non-sentinel entries.
1193 if (B.Bucket == NI.getBucketCount())
1194 break;
1195
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
1200 // bucket as empty.
1201 uint32_t FirstHash = NI.getHashArrayEntry(Idx);
1202 if (FirstHash % NI.getBucketCount() != B.Bucket) {
1203 error() << formatv(
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());
1208 ++NumErrors;
1209 }
1210
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)
1217 break;
1218
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);
1226 ++NumErrors;
1227 }
1228
1229 ++Idx;
1230 }
1231 NextUncovered = std::max(NextUncovered, Idx);
1232 }
1233 return NumErrors;
1234}
1235
1236unsigned DWARFVerifier::verifyNameIndexAttribute(
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,
1244 AttrEnc.Form);
1245 return 1;
1246 }
1247
1248 if (AttrEnc.Index == DW_IDX_type_hash) {
1249 if (AttrEnc.Form != dwarf::DW_FORM_data8) {
1250 error() << formatv(
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);
1254 return 1;
1255 }
1256 }
1257
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 {
1264 StringLiteral ClassName;
1265 };
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"}},
1271 };
1272
1274 auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) {
1275 return T.Index == AttrEnc.Index;
1276 });
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);
1281 return 0;
1282 }
1283
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);
1289 return 1;
1290 }
1291 return 0;
1292}
1293
1294unsigned
1295DWARFVerifier::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());
1300 return 0;
1301 }
1302
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);
1310 }
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);
1317 ++NumErrors;
1318 continue;
1319 }
1320 NumErrors += verifyNameIndexAttribute(NI, Abbrev, AttrEnc);
1321 }
1322
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);
1328 ++NumErrors;
1329 }
1330 if (!Attributes.count(dwarf::DW_IDX_die_offset)) {
1331 error() << formatv(
1332 "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n",
1333 NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset);
1334 ++NumErrors;
1335 }
1336 }
1337 return NumErrors;
1338}
1339
1341 bool IncludeLinkageName = true) {
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)");
1347
1348 if (IncludeLinkageName) {
1349 if (const char *Str = DIE.getLinkageName())
1350 Result.emplace_back(Str);
1351 }
1352
1353 return Result;
1354}
1355
1356unsigned DWARFVerifier::verifyNameIndexEntries(
1359 // Verifying type unit indexes not supported.
1360 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0)
1361 return 0;
1362
1363 const char *CStr = NTE.getString();
1364 if (!CStr) {
1365 error() << formatv(
1366 "Name Index @ {0:x}: Unable to get string associated with name {1}.\n",
1367 NI.getUnitOffset(), NTE.getIndex());
1368 return 1;
1369 }
1370 StringRef Str(CStr);
1371
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);
1384 ++NumErrors;
1385 continue;
1386 }
1387 uint64_t CUOffset = NI.getCUOffset(CUIndex);
1388 uint64_t DIEOffset = CUOffset + *EntryOr->getDIEUnitOffset();
1389 DWARFDie DIE = DCtx.getDIEForOffset(DIEOffset);
1390 if (!DIE) {
1391 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
1392 "non-existing DIE @ {2:x}.\n",
1393 NI.getUnitOffset(), EntryID, DIEOffset);
1394 ++NumErrors;
1395 continue;
1396 }
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());
1402 ++NumErrors;
1403 }
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(),
1408 DIE.getTag());
1409 ++NumErrors;
1410 }
1411
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()));
1418 ++NumErrors;
1419 }
1420 }
1421 handleAllErrors(EntryOr.takeError(),
1422 [&](const DWARFDebugNames::SentinelError &) {
1423 if (NumEntries > 0)
1424 return;
1425 error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
1426 "not associated with any entries.\n",
1427 NI.getUnitOffset(), NTE.getIndex(), Str);
1428 ++NumErrors;
1429 },
1430 [&](const ErrorInfoBase &Info) {
1431 error()
1432 << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n",
1433 NI.getUnitOffset(), NTE.getIndex(), Str,
1434 Info.message());
1435 ++NumErrors;
1436 });
1437 return NumErrors;
1438}
1439
1440static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) {
1442 Die.getLocations(DW_AT_location);
1443 if (!Loc) {
1444 consumeError(Loc.takeError());
1445 return false;
1446 }
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 =
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);
1458 });
1459 if (IsInteresting)
1460 return true;
1461 }
1462 return false;
1463}
1464
1465unsigned DWARFVerifier::verifyNameIndexCompleteness(
1466 const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI) {
1467
1468 // First check, if the Die should be indexed. The code follows the DWARF v5
1469 // wording as closely as possible.
1470
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))
1474 return 0;
1475
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
1479 // are excluded."
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())
1487 return 0;
1488
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,
1492 // subject to ..."
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:
1497 case DW_TAG_module:
1498 return 0;
1499
1500 // Function and template parameters are not globally visible, so we shouldn't
1501 // index them.
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:
1507 return 0;
1508
1509 // Object members aren't globally visible.
1510 case DW_TAG_member:
1511 return 0;
1512
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:
1517 return 0;
1518
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:
1522 return 0;
1523
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:
1529 case DW_TAG_label:
1530 if (Die.findRecursively(
1531 {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc}))
1532 break;
1533 return 0;
1534
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."
1538 //
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))
1542 break;
1543 return 0;
1544
1545 default:
1546 break;
1547 }
1548
1549 // Now we know that our Die should be present in the Index. Let's check if
1550 // that's the case.
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;
1556 })) {
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(),
1560 Name);
1561 ++NumErrors;
1562 }
1563 }
1564 return NumErrors;
1565}
1566
1567unsigned 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);
1573
1574 OS << "Verifying .debug_names...\n";
1575
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';
1580 return 1;
1581 }
1582
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);
1588
1589 // Don't attempt Entry validation if any of the previous checks found errors
1590 if (NumErrors > 0)
1591 return NumErrors;
1592 for (const auto &NI : AccelTable)
1593 for (const DWARFDebugNames::NameTableEntry &NTE : NI)
1594 NumErrors += verifyNameIndexEntries(NI, NTE);
1595
1596 if (NumErrors > 0)
1597 return NumErrors;
1598
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);
1605 }
1606 }
1607 return NumErrors;
1608}
1609
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,
1616 ".apple_names");
1617 if (!D.getAppleTypesSection().Data.empty())
1618 NumErrors += verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData,
1619 ".apple_types");
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,
1625 ".apple_objc");
1626
1627 if (!D.getNamesSection().Data.empty())
1628 NumErrors += verifyDebugNames(D.getNamesSection(), StrData);
1629 return NumErrors == 0;
1630}
1631
1632raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); }
1633
1634raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); }
1635
1636raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); }
1637
1638raw_ostream &DWARFVerifier::dump(const DWARFDie &Die, unsigned indent) const {
1639 Die.dump(OS, indent, DumpOpts);
1640 return OS;
1641}
#define Success
ArrayRef< TableEntry > TableRef
AMDGPU Kernel Attributes
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static SmallVector< StringRef, 2 > getNames(const DWARFDie &DIE, bool IncludeLinkageName=true)
static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx)
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file contains constants used for implementing Dwarf debug support.
std::string Name
This file implements a coalescing interval map for small objects.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallSet class.
#define error(X)
Value * RHS
This class holds an abstract representation of an Accelerator Table, consisting of a sequence of buck...
Definition: AccelTable.h:195
This implements the Apple accelerator table format, a precursor of the DWARF 5 accelerator table form...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:152
A structured debug information entry.
Definition: DIE.h:744
unsigned getOffset() const
Get the compile/type unit relative offset of this DIE.
Definition: DIE.h:782
dwarf::Tag getTag() const
Definition: DIE.h:780
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
Definition: DWARFContext.h:46
static bool isSupportedVersion(unsigned version)
Definition: DWARFContext.h:381
unsigned getNumCompileUnits()
Get the number of compile units in this context.
Definition: DWARFContext.h:216
DWARFDie getDIEForOffset(uint64_t Offset)
Get a DIE given an exact offset.
const DWARFDebugAbbrev * getDebugAbbrevDWO()
Get a pointer to the parsed dwo abbreviations object.
compile_unit_range compile_units()
Get compile units in this context.
Definition: DWARFContext.h:168
const DWARFDebugAbbrev * getDebugAbbrev()
Get a pointer to the parsed DebugAbbrev object.
bool isLittleEndian() const
Definition: DWARFContext.h:379
const DWARFDebugLine::LineTable * getLineTableForUnit(DWARFUnit *U)
Get a pointer to a parsed line table corresponding to a compile unit.
const DWARFUnitVector & getNormalUnitsVector()
Definition: DWARFContext.h:155
static bool isAddressSizeSupported(unsigned AddressSize)
Definition: DWARFContext.h:388
const DWARFUnitVector & getDWOUnitsVector()
Definition: DWARFContext.h:188
const DWARFObject & getDWARFObj() const
Definition: DWARFContext.h:126
A DataExtractor (typically for an in-memory copy of an object-file section) plus a relocation map for...
std::pair< uint64_t, dwarf::DwarfFormat > getInitialLength(uint64_t *Off, Error *Err=nullptr) const
Extracts the DWARF "initial length" field, which can either be a 32-bit value smaller than 0xfffffff0...
const DWARFAbbreviationDeclarationSet * getAbbreviationDeclarationSet(uint64_t CUAbbrOffset) const
DWARFDebugInfoEntry - A DIE with only the minimum required data.
DWARF v5-specific implementation of an Accelerator Entry.
Represents a single accelerator table within the DWARF v5 .debug_names section.
uint32_t getHashArrayEntry(uint32_t Index) const
Reads an entry in the Hash Array for the given Index.
uint32_t getBucketArrayEntry(uint32_t Bucket) const
Reads an entry in the Bucket Array for the given Bucket.
iterator_range< ValueIterator > equal_range(StringRef Key) const
Look up all entries in this Name Index matching Key.
uint64_t getCUOffset(uint32_t CU) const
Reads offset of compilation unit CU. CU is 0-based.
Expected< Entry > getEntry(uint64_t *Offset) const
NameTableEntry getNameTableEntry(uint32_t Index) const
Reads an entry in the Name Table for the given Index.
const DenseSet< Abbrev, AbbrevMapInfo > & getAbbrevs() const
A single entry in the Name Table (DWARF v5 sect.
uint64_t getEntryOffset() const
Returns the offset of the first Entry in the list.
const char * getString() const
Return the string referenced by this name table entry or nullptr if the string offset is not valid.
uint32_t getIndex() const
Return the index of this name in the parent Name Index.
Error returned by NameIndex::getEntry to report it has reached the end of the entry list.
.debug_names section consists of one or more units.
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
Definition: DWARFDie.h:42
void getFullName(raw_string_ostream &, std::string *OriginalFullName=nullptr) const
Definition: DWARFDie.cpp:230
uint64_t getOffset() const
Get the absolute offset into the debug info or types section.
Definition: DWARFDie.h:66
Expected< DWARFAddressRangesVector > getAddressRanges() const
Get the address ranges for this DIE.
Definition: DWARFDie.cpp:375
DWARFDie getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE as the referenced DIE.
Definition: DWARFDie.cpp:304
DWARFDie getParent() const
Get the parent of this DIE object.
Definition: DWARFDie.cpp:622
std::optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
Definition: DWARFDie.cpp:247
DWARFUnit * getDwarfUnit() const
Definition: DWARFDie.h:53
bool hasChildren() const
Definition: DWARFDie.h:78
bool isSubprogramDIE() const
Returns true if DIE represents a subprogram (not inlined).
Definition: DWARFDie.cpp:240
std::optional< DWARFFormValue > findRecursively(ArrayRef< dwarf::Attribute > Attrs) const
Extract the first value of any attribute in Attrs from this DIE and recurse into any DW_AT_specificat...
Definition: DWARFDie.cpp:271
DWARFDie getFirstChild() const
Get the first child of this DIE object.
Definition: DWARFDie.cpp:640
dwarf::Tag getTag() const
Definition: DWARFDie.h:71
Expected< DWARFLocationExpressionsVector > getLocations(dwarf::Attribute Attr) const
Definition: DWARFDie.cpp:406
bool isValid() const
Definition: DWARFDie.h:50
iterator_range< attribute_iterator > attributes() const
Get an iterator range to all attributes in the current DIE only.
Definition: DWARFDie.cpp:652
void dump(raw_ostream &OS, unsigned indent=0, DIDumpOptions DumpOpts=DIDumpOptions()) const
Dump the DIE and all of its attributes to the supplied stream.
Definition: DWARFDie.cpp:562
This class represents an Operation in the Expression.
std::optional< uint64_t > getAsSectionOffset() const
std::optional< uint64_t > getAsReference() const
getAsFoo functions below return the extracted value as Foo if only DWARFFormValue has form class is s...
bool isFormClass(FormClass FC) const
std::optional< uint64_t > getAsUnsignedConstant() const
Expected< const char * > getAsCString() const
dwarf::Form getForm() const
uint64_t getRawUValue() const
virtual StringRef getAbbrevDWOSection() const
Definition: DWARFObject.h:64
virtual StringRef getAbbrevSection() const
Definition: DWARFObject.h:40
virtual void forEachInfoSections(function_ref< void(const DWARFSection &)> F) const
Definition: DWARFObject.h:37
virtual const DWARFSection & getRangesSection() const
Definition: DWARFObject.h:49
virtual StringRef getTUIndexSection() const
Definition: DWARFObject.h:84
virtual void forEachTypesSections(function_ref< void(const DWARFSection &)> F) const
Definition: DWARFObject.h:39
virtual const DWARFSection & getLineSection() const
Definition: DWARFObject.h:46
virtual const DWARFSection & getRnglistsSection() const
Definition: DWARFObject.h:50
virtual StringRef getCUIndexSection() const
Definition: DWARFObject.h:82
virtual const object::ObjectFile * getFile() const
Definition: DWARFObject.h:32
Describe a collection of units.
Definition: DWARFUnit.h:123
DWARFDie getUnitDIE(bool ExtractUnitDIEOnly=true)
Definition: DWARFUnit.h:426
static bool isMatchingUnitTypeAndTag(uint8_t UnitType, dwarf::Tag Tag)
Definition: DWARFUnit.h:407
uint64_t getOffset() const
Definition: DWARFUnit.h:314
bool handleAccelTables()
Verify the information in accelerator tables, if they exist.
bool handleDebugTUIndex()
Verify the information in the .debug_tu_index section.
bool handleDebugCUIndex()
Verify the information in the .debug_cu_index section.
DWARFVerifier(raw_ostream &S, DWARFContext &D, DIDumpOptions DumpOpts=DIDumpOptions::getForSingleDIE())
bool handleDebugInfo()
Verify the information in the .debug_info and .debug_types sections.
bool handleDebugLine()
Verify the information in the .debug_line section.
bool handleDebugAbbrev()
Verify the information in any of the following sections, if available: .debug_abbrev,...
uint32_t getU32(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint32_t value from *offset_ptr.
const char * getCStr(uint64_t *OffsetPtr, Error *Err=nullptr) const
Extract a C string from *offset_ptr.
uint8_t getU8(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint8_t value from *offset_ptr.
uint16_t getU16(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint16_t value from *offset_ptr.
uint64_t getU64(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint64_t value from *offset_ptr.
bool isValidOffset(uint64_t offset) const
Test the validity of offset.
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
iterator end()
Definition: DenseMap.h:84
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition: DenseMap.h:103
Base class for error info classes.
Definition: Error.h:47
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
Tagged union holding either a T or a Error.
Definition: Error.h:470
Error takeError()
Take ownership of the stored error.
Definition: Error.h:597
Class representing an expression and its matching format.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:290
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition: StringRef.h:840
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:111
iterator end()
Definition: StringMap.h:204
iterator find(StringRef Key)
Definition: StringMap.h:217
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
static raw_ostream & warning()
Convenience method for printing "warning: " to stderr.
Definition: WithColor.cpp:85
static raw_ostream & error()
Convenience method for printing "error: " to stderr.
Definition: WithColor.cpp:83
static raw_ostream & note()
Convenience method for printing "note: " to stderr.
Definition: WithColor.cpp:87
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:642
StringRef AttributeString(unsigned Attribute)
Definition: Dwarf.cpp:72
StringRef FormEncodingString(unsigned Encoding)
Definition: Dwarf.cpp:105
StringRef UnitTypeString(unsigned)
Definition: Dwarf.cpp:577
StringRef TagString(unsigned Tag)
Definition: Dwarf.cpp:21
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
bool isUnitType(uint8_t UnitType)
Definition: Dwarf.h:557
UnitType
Constants for unit types in DWARF v5.
Definition: Dwarf.h:543
bool isType(Tag T)
Definition: Dwarf.h:111
DwarfFormat
Constants that define the DWARF format as 32 or 64 bit.
Definition: Dwarf.h:91
@ DWARF64
Definition: Dwarf.h:91
std::optional< uint64_t > toSectionOffset(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an section offset.
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition: DWP.cpp:406
@ Length
Definition: DWP.cpp:406
bool operator<(int64_t V1, const APSInt &V2)
Definition: APSInt.h:361
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are are tuples (A,...
Definition: STLExtras.h:2430
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:966
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition: Error.h:943
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::vector< DWARFAddressRange > DWARFAddressRangesVector
DWARFAddressRangesVector - represents a set of absolute address ranges.
DWARFSectionKind
The enum of section identifiers to be used in internal interfaces.
@ DW_SECT_EXT_TYPES
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1826
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1833
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
uint32_t caseFoldingDjbHash(StringRef Buffer, uint32_t H=5381)
Computes the Bernstein hash after folding the input according to the Dwarf 5 standard case folding ru...
Definition: DJB.cpp:72
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1946
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1846
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1976
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition: STLExtras.h:1704
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1043
Definition: BitVector.h:858
Container for dump options that control which debug information will be dumped.
Definition: DIContext.h:189
Encapsulates a DWARF attribute value and all of the data required to describe the attribute value.
DWARFFormValue Value
The form and value for this attribute.
dwarf::Attribute Attr
The attribute enumeration of this attribute.
static void dumpTableHeader(raw_ostream &OS, unsigned Indent)
Abbreviation describing the encoding of Name Index entries.
uint32_t Code
Abbreviation code.
Index attribute and its encoding.
A class that keeps the address range information for a single DIE.
Definition: DWARFVerifier.h:37
std::vector< DWARFAddressRange > Ranges
Sorted DWARFAddressRanges.
Definition: DWARFVerifier.h:41
bool contains(const DieRangeInfo &RHS) const
Return true if ranges in this object contains all ranges within RHS.
std::set< DieRangeInfo >::const_iterator die_range_info_iterator
Definition: DWARFVerifier.h:53
bool intersects(const DieRangeInfo &RHS) const
Return true if any range in this object intersects with any range in RHS.
std::optional< DWARFAddressRange > insert(const DWARFAddressRange &R)
Inserts the address range.