LLVM 19.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/STLExtras.h"
11#include "llvm/ADT/SmallSet.h"
28#include "llvm/Object/Error.h"
29#include "llvm/Support/DJB.h"
30#include "llvm/Support/Error.h"
34#include "llvm/Support/JSON.h"
37#include <map>
38#include <set>
39#include <vector>
40
41using namespace llvm;
42using namespace dwarf;
43using namespace object;
44
45namespace llvm {
47}
48
49std::optional<DWARFAddressRange>
51 auto Begin = Ranges.begin();
52 auto End = Ranges.end();
53 auto Pos = std::lower_bound(Begin, End, R);
54
55 if (Pos != End) {
56 DWARFAddressRange Range(*Pos);
57 if (Pos->merge(R))
58 return Range;
59 }
60 if (Pos != Begin) {
61 auto Iter = Pos - 1;
62 DWARFAddressRange Range(*Iter);
63 if (Iter->merge(R))
64 return Range;
65 }
66
67 Ranges.insert(Pos, R);
68 return std::nullopt;
69}
70
73 if (RI.Ranges.empty())
74 return Children.end();
75
76 auto End = Children.end();
77 auto Iter = Children.begin();
78 while (Iter != End) {
79 if (Iter->intersects(RI))
80 return Iter;
81 ++Iter;
82 }
83 Children.insert(RI);
84 return Children.end();
85}
86
88 auto I1 = Ranges.begin(), E1 = Ranges.end();
89 auto I2 = RHS.Ranges.begin(), E2 = RHS.Ranges.end();
90 if (I2 == E2)
91 return true;
92
93 DWARFAddressRange R = *I2;
94 while (I1 != E1) {
95 bool Covered = I1->LowPC <= R.LowPC;
96 if (R.LowPC == R.HighPC || (Covered && R.HighPC <= I1->HighPC)) {
97 if (++I2 == E2)
98 return true;
99 R = *I2;
100 continue;
101 }
102 if (!Covered)
103 return false;
104 if (R.LowPC < I1->HighPC)
105 R.LowPC = I1->HighPC;
106 ++I1;
107 }
108 return false;
109}
110
112 auto I1 = Ranges.begin(), E1 = Ranges.end();
113 auto I2 = RHS.Ranges.begin(), E2 = RHS.Ranges.end();
114 while (I1 != E1 && I2 != E2) {
115 if (I1->intersects(*I2))
116 return true;
117 if (I1->LowPC < I2->LowPC)
118 ++I1;
119 else
120 ++I2;
121 }
122 return false;
123}
124
125bool DWARFVerifier::verifyUnitHeader(const DWARFDataExtractor DebugInfoData,
126 uint64_t *Offset, unsigned UnitIndex,
127 uint8_t &UnitType, bool &isUnitDWARF64) {
128 uint64_t AbbrOffset, Length;
129 uint8_t AddrSize = 0;
130 uint16_t Version;
131 bool Success = true;
132
133 bool ValidLength = false;
134 bool ValidVersion = false;
135 bool ValidAddrSize = false;
136 bool ValidType = true;
137 bool ValidAbbrevOffset = true;
138
139 uint64_t OffsetStart = *Offset;
141 std::tie(Length, Format) = DebugInfoData.getInitialLength(Offset);
142 isUnitDWARF64 = Format == DWARF64;
143 Version = DebugInfoData.getU16(Offset);
144
145 if (Version >= 5) {
146 UnitType = DebugInfoData.getU8(Offset);
147 AddrSize = DebugInfoData.getU8(Offset);
148 AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
149 ValidType = dwarf::isUnitType(UnitType);
150 } else {
151 UnitType = 0;
152 AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
153 AddrSize = DebugInfoData.getU8(Offset);
154 }
155
158 if (!AbbrevSetOrErr) {
159 ValidAbbrevOffset = false;
160 // FIXME: A problematic debug_abbrev section is reported below in the form
161 // of a `note:`. We should propagate this error there (or elsewhere) to
162 // avoid losing the specific problem with the debug_abbrev section.
163 consumeError(AbbrevSetOrErr.takeError());
164 }
165
166 ValidLength = DebugInfoData.isValidOffset(OffsetStart + Length + 3);
167 ValidVersion = DWARFContext::isSupportedVersion(Version);
168 ValidAddrSize = DWARFContext::isAddressSizeSupported(AddrSize);
169 if (!ValidLength || !ValidVersion || !ValidAddrSize || !ValidAbbrevOffset ||
170 !ValidType) {
171 Success = false;
172 bool HeaderShown = false;
173 auto ShowHeaderOnce = [&]() {
174 if (!HeaderShown) {
175 error() << format("Units[%d] - start offset: 0x%08" PRIx64 " \n",
176 UnitIndex, OffsetStart);
177 HeaderShown = true;
178 }
179 };
180 if (!ValidLength)
181 ErrorCategory.Report(
182 "Unit Header Length: Unit too large for .debug_info provided", [&]() {
183 ShowHeaderOnce();
184 note() << "The length for this unit is too "
185 "large for the .debug_info provided.\n";
186 });
187 if (!ValidVersion)
188 ErrorCategory.Report(
189 "Unit Header Length: 16 bit unit header version is not valid", [&]() {
190 ShowHeaderOnce();
191 note() << "The 16 bit unit header version is not valid.\n";
192 });
193 if (!ValidType)
194 ErrorCategory.Report(
195 "Unit Header Length: Unit type encoding is not valid", [&]() {
196 ShowHeaderOnce();
197 note() << "The unit type encoding is not valid.\n";
198 });
199 if (!ValidAbbrevOffset)
200 ErrorCategory.Report(
201 "Unit Header Length: Offset into the .debug_abbrev section is not "
202 "valid",
203 [&]() {
204 ShowHeaderOnce();
205 note() << "The offset into the .debug_abbrev section is "
206 "not valid.\n";
207 });
208 if (!ValidAddrSize)
209 ErrorCategory.Report("Unit Header Length: Address size is unsupported",
210 [&]() {
211 ShowHeaderOnce();
212 note() << "The address size is unsupported.\n";
213 });
214 }
215 *Offset = OffsetStart + Length + (isUnitDWARF64 ? 12 : 4);
216 return Success;
217}
218
219bool DWARFVerifier::verifyName(const DWARFDie &Die) {
220 // FIXME Add some kind of record of which DIE names have already failed and
221 // don't bother checking a DIE that uses an already failed DIE.
222
223 std::string ReconstructedName;
224 raw_string_ostream OS(ReconstructedName);
225 std::string OriginalFullName;
226 Die.getFullName(OS, &OriginalFullName);
227 OS.flush();
228 if (OriginalFullName.empty() || OriginalFullName == ReconstructedName)
229 return false;
230
231 ErrorCategory.Report(
232 "Simplified template DW_AT_name could not be reconstituted", [&]() {
233 error()
234 << "Simplified template DW_AT_name could not be reconstituted:\n"
235 << formatv(" original: {0}\n"
236 " reconstituted: {1}\n",
237 OriginalFullName, ReconstructedName);
238 dump(Die) << '\n';
239 dump(Die.getDwarfUnit()->getUnitDIE()) << '\n';
240 });
241 return true;
242}
243
244unsigned DWARFVerifier::verifyUnitContents(DWARFUnit &Unit,
245 ReferenceMap &UnitLocalReferences,
246 ReferenceMap &CrossUnitReferences) {
247 unsigned NumUnitErrors = 0;
248 unsigned NumDies = Unit.getNumDIEs();
249 for (unsigned I = 0; I < NumDies; ++I) {
250 auto Die = Unit.getDIEAtIndex(I);
251
252 if (Die.getTag() == DW_TAG_null)
253 continue;
254
255 for (auto AttrValue : Die.attributes()) {
256 NumUnitErrors += verifyDebugInfoAttribute(Die, AttrValue);
257 NumUnitErrors += verifyDebugInfoForm(Die, AttrValue, UnitLocalReferences,
258 CrossUnitReferences);
259 }
260
261 NumUnitErrors += verifyName(Die);
262
263 if (Die.hasChildren()) {
264 if (Die.getFirstChild().isValid() &&
265 Die.getFirstChild().getTag() == DW_TAG_null) {
266 warn() << dwarf::TagString(Die.getTag())
267 << " has DW_CHILDREN_yes but DIE has no children: ";
268 Die.dump(OS);
269 }
270 }
271
272 NumUnitErrors += verifyDebugInfoCallSite(Die);
273 }
274
275 DWARFDie Die = Unit.getUnitDIE(/* ExtractUnitDIEOnly = */ false);
276 if (!Die) {
277 ErrorCategory.Report("Compilation unit missing DIE", [&]() {
278 error() << "Compilation unit without DIE.\n";
279 });
280 NumUnitErrors++;
281 return NumUnitErrors;
282 }
283
284 if (!dwarf::isUnitType(Die.getTag())) {
285 ErrorCategory.Report("Compilation unit root DIE is not a unit DIE", [&]() {
286 error() << "Compilation unit root DIE is not a unit DIE: "
287 << dwarf::TagString(Die.getTag()) << ".\n";
288 });
289 NumUnitErrors++;
290 }
291
292 uint8_t UnitType = Unit.getUnitType();
294 ErrorCategory.Report("Mismatched unit type", [&]() {
295 error() << "Compilation unit type (" << dwarf::UnitTypeString(UnitType)
296 << ") and root DIE (" << dwarf::TagString(Die.getTag())
297 << ") do not match.\n";
298 });
299 NumUnitErrors++;
300 }
301
302 // According to DWARF Debugging Information Format Version 5,
303 // 3.1.2 Skeleton Compilation Unit Entries:
304 // "A skeleton compilation unit has no children."
305 if (Die.getTag() == dwarf::DW_TAG_skeleton_unit && Die.hasChildren()) {
306 ErrorCategory.Report("Skeleton CU has children", [&]() {
307 error() << "Skeleton compilation unit has children.\n";
308 });
309 NumUnitErrors++;
310 }
311
312 DieRangeInfo RI;
313 NumUnitErrors += verifyDieRanges(Die, RI);
314
315 return NumUnitErrors;
316}
317
318unsigned DWARFVerifier::verifyDebugInfoCallSite(const DWARFDie &Die) {
319 if (Die.getTag() != DW_TAG_call_site && Die.getTag() != DW_TAG_GNU_call_site)
320 return 0;
321
322 DWARFDie Curr = Die.getParent();
323 for (; Curr.isValid() && !Curr.isSubprogramDIE(); Curr = Die.getParent()) {
324 if (Curr.getTag() == DW_TAG_inlined_subroutine) {
325 ErrorCategory.Report(
326 "Call site nested entry within inlined subroutine", [&]() {
327 error() << "Call site entry nested within inlined subroutine:";
328 Curr.dump(OS);
329 });
330 return 1;
331 }
332 }
333
334 if (!Curr.isValid()) {
335 ErrorCategory.Report(
336 "Call site entry not nested within valid subprogram", [&]() {
337 error() << "Call site entry not nested within a valid subprogram:";
338 Die.dump(OS);
339 });
340 return 1;
341 }
342
343 std::optional<DWARFFormValue> CallAttr = Curr.find(
344 {DW_AT_call_all_calls, DW_AT_call_all_source_calls,
345 DW_AT_call_all_tail_calls, DW_AT_GNU_all_call_sites,
346 DW_AT_GNU_all_source_call_sites, DW_AT_GNU_all_tail_call_sites});
347 if (!CallAttr) {
348 ErrorCategory.Report(
349 "Subprogram with call site entry has no DW_AT_call attribute", [&]() {
350 error()
351 << "Subprogram with call site entry has no DW_AT_call attribute:";
352 Curr.dump(OS);
353 Die.dump(OS, /*indent*/ 1);
354 });
355 return 1;
356 }
357
358 return 0;
359}
360
361unsigned DWARFVerifier::verifyAbbrevSection(const DWARFDebugAbbrev *Abbrev) {
362 if (!Abbrev)
363 return 0;
364
367 if (!AbbrDeclsOrErr) {
368 std::string ErrMsg = toString(AbbrDeclsOrErr.takeError());
369 ErrorCategory.Report("Abbreviation Declaration error",
370 [&]() { error() << ErrMsg << "\n"; });
371 return 1;
372 }
373
374 const auto *AbbrDecls = *AbbrDeclsOrErr;
375 unsigned NumErrors = 0;
376 for (auto AbbrDecl : *AbbrDecls) {
378 for (auto Attribute : AbbrDecl.attributes()) {
379 auto Result = AttributeSet.insert(Attribute.Attr);
380 if (!Result.second) {
381 ErrorCategory.Report(
382 "Abbreviation declartion contains multiple attributes", [&]() {
383 error() << "Abbreviation declaration contains multiple "
384 << AttributeString(Attribute.Attr) << " attributes.\n";
385 AbbrDecl.dump(OS);
386 });
387 ++NumErrors;
388 }
389 }
390 }
391 return NumErrors;
392}
393
395 OS << "Verifying .debug_abbrev...\n";
396
397 const DWARFObject &DObj = DCtx.getDWARFObj();
398 unsigned NumErrors = 0;
399 if (!DObj.getAbbrevSection().empty())
400 NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrev());
401 if (!DObj.getAbbrevDWOSection().empty())
402 NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrevDWO());
403
404 return NumErrors == 0;
405}
406
407unsigned DWARFVerifier::verifyUnits(const DWARFUnitVector &Units) {
408 unsigned NumDebugInfoErrors = 0;
409 ReferenceMap CrossUnitReferences;
410
411 unsigned Index = 1;
412 for (const auto &Unit : Units) {
413 OS << "Verifying unit: " << Index << " / " << Units.getNumUnits();
414 if (const char* Name = Unit->getUnitDIE(true).getShortName())
415 OS << ", \"" << Name << '\"';
416 OS << '\n';
417 OS.flush();
418 ReferenceMap UnitLocalReferences;
419 NumDebugInfoErrors +=
420 verifyUnitContents(*Unit, UnitLocalReferences, CrossUnitReferences);
421 NumDebugInfoErrors += verifyDebugInfoReferences(
422 UnitLocalReferences, [&](uint64_t Offset) { return Unit.get(); });
423 ++Index;
424 }
425
426 NumDebugInfoErrors += verifyDebugInfoReferences(
427 CrossUnitReferences, [&](uint64_t Offset) -> DWARFUnit * {
428 if (DWARFUnit *U = Units.getUnitForOffset(Offset))
429 return U;
430 return nullptr;
431 });
432
433 return NumDebugInfoErrors;
434}
435
436unsigned DWARFVerifier::verifyUnitSection(const DWARFSection &S) {
437 const DWARFObject &DObj = DCtx.getDWARFObj();
438 DWARFDataExtractor DebugInfoData(DObj, S, DCtx.isLittleEndian(), 0);
439 unsigned NumDebugInfoErrors = 0;
440 uint64_t Offset = 0, UnitIdx = 0;
441 uint8_t UnitType = 0;
442 bool isUnitDWARF64 = false;
443 bool isHeaderChainValid = true;
444 bool hasDIE = DebugInfoData.isValidOffset(Offset);
445 DWARFUnitVector TypeUnitVector;
446 DWARFUnitVector CompileUnitVector;
447 /// A map that tracks all references (converted absolute references) so we
448 /// can verify each reference points to a valid DIE and not an offset that
449 /// lies between to valid DIEs.
450 ReferenceMap CrossUnitReferences;
451 while (hasDIE) {
452 if (!verifyUnitHeader(DebugInfoData, &Offset, UnitIdx, UnitType,
453 isUnitDWARF64)) {
454 isHeaderChainValid = false;
455 if (isUnitDWARF64)
456 break;
457 }
458 hasDIE = DebugInfoData.isValidOffset(Offset);
459 ++UnitIdx;
460 }
461 if (UnitIdx == 0 && !hasDIE) {
462 warn() << "Section is empty.\n";
463 isHeaderChainValid = true;
464 }
465 if (!isHeaderChainValid)
466 ++NumDebugInfoErrors;
467 return NumDebugInfoErrors;
468}
469
470unsigned DWARFVerifier::verifyIndex(StringRef Name,
471 DWARFSectionKind InfoColumnKind,
472 StringRef IndexStr) {
473 if (IndexStr.empty())
474 return 0;
475 OS << "Verifying " << Name << "...\n";
476 DWARFUnitIndex Index(InfoColumnKind);
477 DataExtractor D(IndexStr, DCtx.isLittleEndian(), 0);
478 if (!Index.parse(D))
479 return 1;
480 using MapType = IntervalMap<uint64_t, uint64_t>;
481 MapType::Allocator Alloc;
482 std::vector<std::unique_ptr<MapType>> Sections(Index.getColumnKinds().size());
483 for (const DWARFUnitIndex::Entry &E : Index.getRows()) {
484 uint64_t Sig = E.getSignature();
485 if (!E.getContributions())
486 continue;
487 for (auto E : enumerate(
488 InfoColumnKind == DW_SECT_INFO
489 ? ArrayRef(E.getContributions(), Index.getColumnKinds().size())
490 : ArrayRef(E.getContribution(), 1))) {
492 int Col = E.index();
493 if (SC.getLength() == 0)
494 continue;
495 if (!Sections[Col])
496 Sections[Col] = std::make_unique<MapType>(Alloc);
497 auto &M = *Sections[Col];
498 auto I = M.find(SC.getOffset());
499 if (I != M.end() && I.start() < (SC.getOffset() + SC.getLength())) {
500 StringRef Category = InfoColumnKind == DWARFSectionKind::DW_SECT_INFO
501 ? "Overlapping CU index entries"
502 : "Overlapping TU index entries";
503 ErrorCategory.Report(Category, [&]() {
504 error() << llvm::formatv(
505 "overlapping index entries for entries {0:x16} "
506 "and {1:x16} for column {2}\n",
507 *I, Sig, toString(Index.getColumnKinds()[Col]));
508 });
509 return 1;
510 }
511 M.insert(SC.getOffset(), SC.getOffset() + SC.getLength() - 1, Sig);
512 }
513 }
514
515 return 0;
516}
517
519 return verifyIndex(".debug_cu_index", DWARFSectionKind::DW_SECT_INFO,
520 DCtx.getDWARFObj().getCUIndexSection()) == 0;
521}
522
524 return verifyIndex(".debug_tu_index", DWARFSectionKind::DW_SECT_EXT_TYPES,
525 DCtx.getDWARFObj().getTUIndexSection()) == 0;
526}
527
529 const DWARFObject &DObj = DCtx.getDWARFObj();
530 unsigned NumErrors = 0;
531
532 OS << "Verifying .debug_info Unit Header Chain...\n";
533 DObj.forEachInfoSections([&](const DWARFSection &S) {
534 NumErrors += verifyUnitSection(S);
535 });
536
537 OS << "Verifying .debug_types Unit Header Chain...\n";
538 DObj.forEachTypesSections([&](const DWARFSection &S) {
539 NumErrors += verifyUnitSection(S);
540 });
541
542 OS << "Verifying non-dwo Units...\n";
543 NumErrors += verifyUnits(DCtx.getNormalUnitsVector());
544
545 OS << "Verifying dwo Units...\n";
546 NumErrors += verifyUnits(DCtx.getDWOUnitsVector());
547 return NumErrors == 0;
548}
549
550unsigned DWARFVerifier::verifyDieRanges(const DWARFDie &Die,
551 DieRangeInfo &ParentRI) {
552 unsigned NumErrors = 0;
553
554 if (!Die.isValid())
555 return NumErrors;
556
557 DWARFUnit *Unit = Die.getDwarfUnit();
558
559 auto RangesOrError = Die.getAddressRanges();
560 if (!RangesOrError) {
561 // FIXME: Report the error.
562 if (!Unit->isDWOUnit())
563 ++NumErrors;
564 llvm::consumeError(RangesOrError.takeError());
565 return NumErrors;
566 }
567
568 const DWARFAddressRangesVector &Ranges = RangesOrError.get();
569 // Build RI for this DIE and check that ranges within this DIE do not
570 // overlap.
571 DieRangeInfo RI(Die);
572
573 // TODO support object files better
574 //
575 // Some object file formats (i.e. non-MachO) support COMDAT. ELF in
576 // particular does so by placing each function into a section. The DWARF data
577 // for the function at that point uses a section relative DW_FORM_addrp for
578 // the DW_AT_low_pc and a DW_FORM_data4 for the offset as the DW_AT_high_pc.
579 // In such a case, when the Die is the CU, the ranges will overlap, and we
580 // will flag valid conflicting ranges as invalid.
581 //
582 // For such targets, we should read the ranges from the CU and partition them
583 // by the section id. The ranges within a particular section should be
584 // disjoint, although the ranges across sections may overlap. We would map
585 // the child die to the entity that it references and the section with which
586 // it is associated. The child would then be checked against the range
587 // information for the associated section.
588 //
589 // For now, simply elide the range verification for the CU DIEs if we are
590 // processing an object file.
591
592 if (!IsObjectFile || IsMachOObject || Die.getTag() != DW_TAG_compile_unit) {
593 bool DumpDieAfterError = false;
594 for (const auto &Range : Ranges) {
595 if (!Range.valid()) {
596 ++NumErrors;
597 ErrorCategory.Report("Invalid address range", [&]() {
598 error() << "Invalid address range " << Range << "\n";
599 DumpDieAfterError = true;
600 });
601 continue;
602 }
603
604 // Verify that ranges don't intersect and also build up the DieRangeInfo
605 // address ranges. Don't break out of the loop below early, or we will
606 // think this DIE doesn't have all of the address ranges it is supposed
607 // to have. Compile units often have DW_AT_ranges that can contain one or
608 // more dead stripped address ranges which tend to all be at the same
609 // address: 0 or -1.
610 if (auto PrevRange = RI.insert(Range)) {
611 ++NumErrors;
612 ErrorCategory.Report("DIE has overlapping DW_AT_ranges", [&]() {
613 error() << "DIE has overlapping ranges in DW_AT_ranges attribute: "
614 << *PrevRange << " and " << Range << '\n';
615 DumpDieAfterError = true;
616 });
617 }
618 }
619 if (DumpDieAfterError)
620 dump(Die, 2) << '\n';
621 }
622
623 // Verify that children don't intersect.
624 const auto IntersectingChild = ParentRI.insert(RI);
625 if (IntersectingChild != ParentRI.Children.end()) {
626 ++NumErrors;
627 ErrorCategory.Report("DIEs have overlapping address ranges", [&]() {
628 error() << "DIEs have overlapping address ranges:";
629 dump(Die);
630 dump(IntersectingChild->Die) << '\n';
631 });
632 }
633
634 // Verify that ranges are contained within their parent.
635 bool ShouldBeContained = !RI.Ranges.empty() && !ParentRI.Ranges.empty() &&
636 !(Die.getTag() == DW_TAG_subprogram &&
637 ParentRI.Die.getTag() == DW_TAG_subprogram);
638 if (ShouldBeContained && !ParentRI.contains(RI)) {
639 ++NumErrors;
640 ErrorCategory.Report(
641 "DIE address ranges are not contained by parent ranges", [&]() {
642 error()
643 << "DIE address ranges are not contained in its parent's ranges:";
644 dump(ParentRI.Die);
645 dump(Die, 2) << '\n';
646 });
647 }
648
649 // Recursively check children.
650 for (DWARFDie Child : Die)
651 NumErrors += verifyDieRanges(Child, RI);
652
653 return NumErrors;
654}
655
656unsigned DWARFVerifier::verifyDebugInfoAttribute(const DWARFDie &Die,
657 DWARFAttribute &AttrValue) {
658 unsigned NumErrors = 0;
659 auto ReportError = [&](StringRef category, const Twine &TitleMsg) {
660 ++NumErrors;
661 ErrorCategory.Report(category, [&]() {
662 error() << TitleMsg << '\n';
663 dump(Die) << '\n';
664 });
665 };
666
667 const DWARFObject &DObj = DCtx.getDWARFObj();
668 DWARFUnit *U = Die.getDwarfUnit();
669 const auto Attr = AttrValue.Attr;
670 switch (Attr) {
671 case DW_AT_ranges:
672 // Make sure the offset in the DW_AT_ranges attribute is valid.
673 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
674 unsigned DwarfVersion = U->getVersion();
675 const DWARFSection &RangeSection = DwarfVersion < 5
676 ? DObj.getRangesSection()
677 : DObj.getRnglistsSection();
678 if (U->isDWOUnit() && RangeSection.Data.empty())
679 break;
680 if (*SectionOffset >= RangeSection.Data.size())
681 ReportError("DW_AT_ranges offset out of bounds",
682 "DW_AT_ranges offset is beyond " +
683 StringRef(DwarfVersion < 5 ? ".debug_ranges"
684 : ".debug_rnglists") +
685 " bounds: " + llvm::formatv("{0:x8}", *SectionOffset));
686 break;
687 }
688 ReportError("Invalid DW_AT_ranges encoding",
689 "DIE has invalid DW_AT_ranges encoding:");
690 break;
691 case DW_AT_stmt_list:
692 // Make sure the offset in the DW_AT_stmt_list attribute is valid.
693 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
694 if (*SectionOffset >= U->getLineSection().Data.size())
695 ReportError("DW_AT_stmt_list offset out of bounds",
696 "DW_AT_stmt_list offset is beyond .debug_line bounds: " +
697 llvm::formatv("{0:x8}", *SectionOffset));
698 break;
699 }
700 ReportError("Invalid DW_AT_stmt_list encoding",
701 "DIE has invalid DW_AT_stmt_list encoding:");
702 break;
703 case DW_AT_location: {
704 // FIXME: It might be nice if there's a way to walk location expressions
705 // without trying to resolve the address ranges - it'd be a more efficient
706 // API (since the API is currently unnecessarily resolving addresses for
707 // this use case which only wants to validate the expressions themselves) &
708 // then the expressions could be validated even if the addresses can't be
709 // resolved.
710 // That sort of API would probably look like a callback "for each
711 // expression" with some way to lazily resolve the address ranges when
712 // needed (& then the existing API used here could be built on top of that -
713 // using the callback API to build the data structure and return it).
714 if (Expected<std::vector<DWARFLocationExpression>> Loc =
715 Die.getLocations(DW_AT_location)) {
716 for (const auto &Entry : *Loc) {
717 DataExtractor Data(toStringRef(Entry.Expr), DCtx.isLittleEndian(), 0);
718 DWARFExpression Expression(Data, U->getAddressByteSize(),
719 U->getFormParams().Format);
720 bool Error =
722 return Op.isError();
723 });
724 if (Error || !Expression.verify(U))
725 ReportError("Invalid DWARF expressions",
726 "DIE contains invalid DWARF expression:");
727 }
728 } else if (Error Err = handleErrors(
729 Loc.takeError(), [&](std::unique_ptr<ResolverError> E) {
730 return U->isDWOUnit() ? Error::success()
731 : Error(std::move(E));
732 }))
733 ReportError("Invalid DW_AT_location", toString(std::move(Err)));
734 break;
735 }
736 case DW_AT_specification:
737 case DW_AT_abstract_origin: {
738 if (auto ReferencedDie = Die.getAttributeValueAsReferencedDie(Attr)) {
739 auto DieTag = Die.getTag();
740 auto RefTag = ReferencedDie.getTag();
741 if (DieTag == RefTag)
742 break;
743 if (DieTag == DW_TAG_inlined_subroutine && RefTag == DW_TAG_subprogram)
744 break;
745 if (DieTag == DW_TAG_variable && RefTag == DW_TAG_member)
746 break;
747 // This might be reference to a function declaration.
748 if (DieTag == DW_TAG_GNU_call_site && RefTag == DW_TAG_subprogram)
749 break;
750 ReportError("Incompatible DW_AT_abstract_origin tag reference",
751 "DIE with tag " + TagString(DieTag) + " has " +
752 AttributeString(Attr) +
753 " that points to DIE with "
754 "incompatible tag " +
755 TagString(RefTag));
756 }
757 break;
758 }
759 case DW_AT_type: {
760 DWARFDie TypeDie = Die.getAttributeValueAsReferencedDie(DW_AT_type);
761 if (TypeDie && !isType(TypeDie.getTag())) {
762 ReportError("Incompatible DW_AT_type attribute tag",
763 "DIE has " + AttributeString(Attr) +
764 " with incompatible tag " + TagString(TypeDie.getTag()));
765 }
766 break;
767 }
768 case DW_AT_call_file:
769 case DW_AT_decl_file: {
770 if (auto FileIdx = AttrValue.Value.getAsUnsignedConstant()) {
771 if (U->isDWOUnit() && !U->isTypeUnit())
772 break;
773 const auto *LT = U->getContext().getLineTableForUnit(U);
774 if (LT) {
775 if (!LT->hasFileAtIndex(*FileIdx)) {
776 bool IsZeroIndexed = LT->Prologue.getVersion() >= 5;
777 if (std::optional<uint64_t> LastFileIdx =
778 LT->getLastValidFileIndex()) {
779 ReportError("Invalid file index in DW_AT_decl_file",
780 "DIE has " + AttributeString(Attr) +
781 " with an invalid file index " +
782 llvm::formatv("{0}", *FileIdx) +
783 " (valid values are [" +
784 (IsZeroIndexed ? "0-" : "1-") +
785 llvm::formatv("{0}", *LastFileIdx) + "])");
786 } else {
787 ReportError("Invalid file index in DW_AT_decl_file",
788 "DIE has " + AttributeString(Attr) +
789 " with an invalid file index " +
790 llvm::formatv("{0}", *FileIdx) +
791 " (the file table in the prologue is empty)");
792 }
793 }
794 } else {
795 ReportError(
796 "File index in DW_AT_decl_file reference CU with no line table",
797 "DIE has " + AttributeString(Attr) +
798 " that references a file with index " +
799 llvm::formatv("{0}", *FileIdx) +
800 " and the compile unit has no line table");
801 }
802 } else {
803 ReportError("Invalid encoding in DW_AT_decl_file",
804 "DIE has " + AttributeString(Attr) +
805 " with invalid encoding");
806 }
807 break;
808 }
809 case DW_AT_call_line:
810 case DW_AT_decl_line: {
811 if (!AttrValue.Value.getAsUnsignedConstant()) {
812 ReportError(
813 Attr == DW_AT_call_line ? "Invalid file index in DW_AT_decl_line"
814 : "Invalid file index in DW_AT_call_line",
815 "DIE has " + AttributeString(Attr) + " with invalid encoding");
816 }
817 break;
818 }
819 default:
820 break;
821 }
822 return NumErrors;
823}
824
825unsigned DWARFVerifier::verifyDebugInfoForm(const DWARFDie &Die,
826 DWARFAttribute &AttrValue,
827 ReferenceMap &LocalReferences,
828 ReferenceMap &CrossUnitReferences) {
829 auto DieCU = Die.getDwarfUnit();
830 unsigned NumErrors = 0;
831 const auto Form = AttrValue.Value.getForm();
832 switch (Form) {
833 case DW_FORM_ref1:
834 case DW_FORM_ref2:
835 case DW_FORM_ref4:
836 case DW_FORM_ref8:
837 case DW_FORM_ref_udata: {
838 // Verify all CU relative references are valid CU offsets.
839 std::optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
840 assert(RefVal);
841 if (RefVal) {
842 auto CUSize = DieCU->getNextUnitOffset() - DieCU->getOffset();
843 auto CUOffset = AttrValue.Value.getRawUValue();
844 if (CUOffset >= CUSize) {
845 ++NumErrors;
846 ErrorCategory.Report("Invalid CU offset", [&]() {
847 error() << FormEncodingString(Form) << " CU offset "
848 << format("0x%08" PRIx64, CUOffset)
849 << " is invalid (must be less than CU size of "
850 << format("0x%08" PRIx64, CUSize) << "):\n";
851 Die.dump(OS, 0, DumpOpts);
852 dump(Die) << '\n';
853 });
854 } else {
855 // Valid reference, but we will verify it points to an actual
856 // DIE later.
857 LocalReferences[*RefVal].insert(Die.getOffset());
858 }
859 }
860 break;
861 }
862 case DW_FORM_ref_addr: {
863 // Verify all absolute DIE references have valid offsets in the
864 // .debug_info section.
865 std::optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
866 assert(RefVal);
867 if (RefVal) {
868 if (*RefVal >= DieCU->getInfoSection().Data.size()) {
869 ++NumErrors;
870 ErrorCategory.Report("DW_FORM_ref_addr offset out of bounds", [&]() {
871 error() << "DW_FORM_ref_addr offset beyond .debug_info "
872 "bounds:\n";
873 dump(Die) << '\n';
874 });
875 } else {
876 // Valid reference, but we will verify it points to an actual
877 // DIE later.
878 CrossUnitReferences[*RefVal].insert(Die.getOffset());
879 }
880 }
881 break;
882 }
883 case DW_FORM_strp:
884 case DW_FORM_strx:
885 case DW_FORM_strx1:
886 case DW_FORM_strx2:
887 case DW_FORM_strx3:
888 case DW_FORM_strx4:
889 case DW_FORM_line_strp: {
890 if (Error E = AttrValue.Value.getAsCString().takeError()) {
891 ++NumErrors;
892 std::string ErrMsg = toString(std::move(E));
893 ErrorCategory.Report("Invalid DW_FORM attribute", [&]() {
894 error() << ErrMsg << ":\n";
895 dump(Die) << '\n';
896 });
897 }
898 break;
899 }
900 default:
901 break;
902 }
903 return NumErrors;
904}
905
906unsigned DWARFVerifier::verifyDebugInfoReferences(
907 const ReferenceMap &References,
908 llvm::function_ref<DWARFUnit *(uint64_t)> GetUnitForOffset) {
909 auto GetDIEForOffset = [&](uint64_t Offset) {
910 if (DWARFUnit *U = GetUnitForOffset(Offset))
911 return U->getDIEForOffset(Offset);
912 return DWARFDie();
913 };
914 unsigned NumErrors = 0;
915 for (const std::pair<const uint64_t, std::set<uint64_t>> &Pair :
916 References) {
917 if (GetDIEForOffset(Pair.first))
918 continue;
919 ++NumErrors;
920 ErrorCategory.Report("Invalid DIE reference", [&]() {
921 error() << "invalid DIE reference " << format("0x%08" PRIx64, Pair.first)
922 << ". Offset is in between DIEs:\n";
923 for (auto Offset : Pair.second)
924 dump(GetDIEForOffset(Offset)) << '\n';
925 OS << "\n";
926 });
927 }
928 return NumErrors;
929}
930
931void DWARFVerifier::verifyDebugLineStmtOffsets() {
932 std::map<uint64_t, DWARFDie> StmtListToDie;
933 for (const auto &CU : DCtx.compile_units()) {
934 auto Die = CU->getUnitDIE();
935 // Get the attribute value as a section offset. No need to produce an
936 // error here if the encoding isn't correct because we validate this in
937 // the .debug_info verifier.
938 auto StmtSectionOffset = toSectionOffset(Die.find(DW_AT_stmt_list));
939 if (!StmtSectionOffset)
940 continue;
941 const uint64_t LineTableOffset = *StmtSectionOffset;
942 auto LineTable = DCtx.getLineTableForUnit(CU.get());
943 if (LineTableOffset < DCtx.getDWARFObj().getLineSection().Data.size()) {
944 if (!LineTable) {
945 ++NumDebugLineErrors;
946 ErrorCategory.Report("Unparsable .debug_line entry", [&]() {
947 error() << ".debug_line[" << format("0x%08" PRIx64, LineTableOffset)
948 << "] was not able to be parsed for CU:\n";
949 dump(Die) << '\n';
950 });
951 continue;
952 }
953 } else {
954 // Make sure we don't get a valid line table back if the offset is wrong.
955 assert(LineTable == nullptr);
956 // Skip this line table as it isn't valid. No need to create an error
957 // here because we validate this in the .debug_info verifier.
958 continue;
959 }
960 auto Iter = StmtListToDie.find(LineTableOffset);
961 if (Iter != StmtListToDie.end()) {
962 ++NumDebugLineErrors;
963 ErrorCategory.Report("Identical DW_AT_stmt_list section offset", [&]() {
964 error() << "two compile unit DIEs, "
965 << format("0x%08" PRIx64, Iter->second.getOffset()) << " and "
966 << format("0x%08" PRIx64, Die.getOffset())
967 << ", have the same DW_AT_stmt_list section offset:\n";
968 dump(Iter->second);
969 dump(Die) << '\n';
970 });
971 // Already verified this line table before, no need to do it again.
972 continue;
973 }
974 StmtListToDie[LineTableOffset] = Die;
975 }
976}
977
978void DWARFVerifier::verifyDebugLineRows() {
979 for (const auto &CU : DCtx.compile_units()) {
980 auto Die = CU->getUnitDIE();
981 auto LineTable = DCtx.getLineTableForUnit(CU.get());
982 // If there is no line table we will have created an error in the
983 // .debug_info verifier or in verifyDebugLineStmtOffsets().
984 if (!LineTable)
985 continue;
986
987 // Verify prologue.
988 bool isDWARF5 = LineTable->Prologue.getVersion() >= 5;
989 uint32_t MaxDirIndex = LineTable->Prologue.IncludeDirectories.size();
990 uint32_t MinFileIndex = isDWARF5 ? 0 : 1;
991 uint32_t FileIndex = MinFileIndex;
992 StringMap<uint16_t> FullPathMap;
993 for (const auto &FileName : LineTable->Prologue.FileNames) {
994 // Verify directory index.
995 if (FileName.DirIdx > MaxDirIndex) {
996 ++NumDebugLineErrors;
997 ErrorCategory.Report(
998 "Invalid index in .debug_line->prologue.file_names->dir_idx",
999 [&]() {
1000 error() << ".debug_line["
1001 << format("0x%08" PRIx64,
1002 *toSectionOffset(Die.find(DW_AT_stmt_list)))
1003 << "].prologue.file_names[" << FileIndex
1004 << "].dir_idx contains an invalid index: "
1005 << FileName.DirIdx << "\n";
1006 });
1007 }
1008
1009 // Check file paths for duplicates.
1010 std::string FullPath;
1011 const bool HasFullPath = LineTable->getFileNameByIndex(
1012 FileIndex, CU->getCompilationDir(),
1013 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FullPath);
1014 assert(HasFullPath && "Invalid index?");
1015 (void)HasFullPath;
1016 auto It = FullPathMap.find(FullPath);
1017 if (It == FullPathMap.end())
1018 FullPathMap[FullPath] = FileIndex;
1019 else if (It->second != FileIndex && DumpOpts.Verbose) {
1020 warn() << ".debug_line["
1021 << format("0x%08" PRIx64,
1022 *toSectionOffset(Die.find(DW_AT_stmt_list)))
1023 << "].prologue.file_names[" << FileIndex
1024 << "] is a duplicate of file_names[" << It->second << "]\n";
1025 }
1026
1027 FileIndex++;
1028 }
1029
1030 // Nothing to verify in a line table with a single row containing the end
1031 // sequence.
1032 if (LineTable->Rows.size() == 1 && LineTable->Rows.front().EndSequence)
1033 continue;
1034
1035 // Verify rows.
1036 uint64_t PrevAddress = 0;
1037 uint32_t RowIndex = 0;
1038 for (const auto &Row : LineTable->Rows) {
1039 // Verify row address.
1040 if (Row.Address.Address < PrevAddress) {
1041 ++NumDebugLineErrors;
1042 ErrorCategory.Report(
1043 "decreasing address between debug_line rows", [&]() {
1044 error() << ".debug_line["
1045 << format("0x%08" PRIx64,
1046 *toSectionOffset(Die.find(DW_AT_stmt_list)))
1047 << "] row[" << RowIndex
1048 << "] decreases in address from previous row:\n";
1049
1051 if (RowIndex > 0)
1052 LineTable->Rows[RowIndex - 1].dump(OS);
1053 Row.dump(OS);
1054 OS << '\n';
1055 });
1056 }
1057
1058 if (!LineTable->hasFileAtIndex(Row.File)) {
1059 ++NumDebugLineErrors;
1060 ErrorCategory.Report("Invalid file index in debug_line", [&]() {
1061 error() << ".debug_line["
1062 << format("0x%08" PRIx64,
1063 *toSectionOffset(Die.find(DW_AT_stmt_list)))
1064 << "][" << RowIndex << "] has invalid file index " << Row.File
1065 << " (valid values are [" << MinFileIndex << ','
1066 << LineTable->Prologue.FileNames.size()
1067 << (isDWARF5 ? ")" : "]") << "):\n";
1069 Row.dump(OS);
1070 OS << '\n';
1071 });
1072 }
1073 if (Row.EndSequence)
1074 PrevAddress = 0;
1075 else
1076 PrevAddress = Row.Address.Address;
1077 ++RowIndex;
1078 }
1079 }
1080}
1081
1083 DIDumpOptions DumpOpts)
1084 : OS(S), DCtx(D), DumpOpts(std::move(DumpOpts)), IsObjectFile(false),
1085 IsMachOObject(false) {
1086 ErrorCategory.ShowDetail(this->DumpOpts.Verbose ||
1087 !this->DumpOpts.ShowAggregateErrors);
1088 if (const auto *F = DCtx.getDWARFObj().getFile()) {
1089 IsObjectFile = F->isRelocatableObject();
1090 IsMachOObject = F->isMachO();
1091 }
1092}
1093
1095 NumDebugLineErrors = 0;
1096 OS << "Verifying .debug_line...\n";
1097 verifyDebugLineStmtOffsets();
1098 verifyDebugLineRows();
1099 return NumDebugLineErrors == 0;
1100}
1101
1102unsigned DWARFVerifier::verifyAppleAccelTable(const DWARFSection *AccelSection,
1103 DataExtractor *StrData,
1104 const char *SectionName) {
1105 unsigned NumErrors = 0;
1106 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), *AccelSection,
1107 DCtx.isLittleEndian(), 0);
1108 AppleAcceleratorTable AccelTable(AccelSectionData, *StrData);
1109
1110 OS << "Verifying " << SectionName << "...\n";
1111
1112 // Verify that the fixed part of the header is not too short.
1113 if (!AccelSectionData.isValidOffset(AccelTable.getSizeHdr())) {
1114 ErrorCategory.Report("Section is too small to fit a section header", [&]() {
1115 error() << "Section is too small to fit a section header.\n";
1116 });
1117 return 1;
1118 }
1119
1120 // Verify that the section is not too short.
1121 if (Error E = AccelTable.extract()) {
1122 std::string Msg = toString(std::move(E));
1123 ErrorCategory.Report("Section is too small to fit a section header",
1124 [&]() { error() << Msg << '\n'; });
1125 return 1;
1126 }
1127
1128 // Verify that all buckets have a valid hash index or are empty.
1129 uint32_t NumBuckets = AccelTable.getNumBuckets();
1130 uint32_t NumHashes = AccelTable.getNumHashes();
1131
1132 uint64_t BucketsOffset =
1133 AccelTable.getSizeHdr() + AccelTable.getHeaderDataLength();
1134 uint64_t HashesBase = BucketsOffset + NumBuckets * 4;
1135 uint64_t OffsetsBase = HashesBase + NumHashes * 4;
1136 for (uint32_t BucketIdx = 0; BucketIdx < NumBuckets; ++BucketIdx) {
1137 uint32_t HashIdx = AccelSectionData.getU32(&BucketsOffset);
1138 if (HashIdx >= NumHashes && HashIdx != UINT32_MAX) {
1139 ErrorCategory.Report("Invalid hash index", [&]() {
1140 error() << format("Bucket[%d] has invalid hash index: %u.\n", BucketIdx,
1141 HashIdx);
1142 });
1143 ++NumErrors;
1144 }
1145 }
1146 uint32_t NumAtoms = AccelTable.getAtomsDesc().size();
1147 if (NumAtoms == 0) {
1148 ErrorCategory.Report("No atoms", [&]() {
1149 error() << "No atoms: failed to read HashData.\n";
1150 });
1151 return 1;
1152 }
1153 if (!AccelTable.validateForms()) {
1154 ErrorCategory.Report("Unsupported form", [&]() {
1155 error() << "Unsupported form: failed to read HashData.\n";
1156 });
1157 return 1;
1158 }
1159
1160 for (uint32_t HashIdx = 0; HashIdx < NumHashes; ++HashIdx) {
1161 uint64_t HashOffset = HashesBase + 4 * HashIdx;
1162 uint64_t DataOffset = OffsetsBase + 4 * HashIdx;
1163 uint32_t Hash = AccelSectionData.getU32(&HashOffset);
1164 uint64_t HashDataOffset = AccelSectionData.getU32(&DataOffset);
1165 if (!AccelSectionData.isValidOffsetForDataOfSize(HashDataOffset,
1166 sizeof(uint64_t))) {
1167 ErrorCategory.Report("Invalid HashData offset", [&]() {
1168 error() << format("Hash[%d] has invalid HashData offset: "
1169 "0x%08" PRIx64 ".\n",
1170 HashIdx, HashDataOffset);
1171 });
1172 ++NumErrors;
1173 }
1174
1175 uint64_t StrpOffset;
1176 uint64_t StringOffset;
1177 uint32_t StringCount = 0;
1179 unsigned Tag;
1180 while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) {
1181 const uint32_t NumHashDataObjects =
1182 AccelSectionData.getU32(&HashDataOffset);
1183 for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects;
1184 ++HashDataIdx) {
1185 std::tie(Offset, Tag) = AccelTable.readAtoms(&HashDataOffset);
1186 auto Die = DCtx.getDIEForOffset(Offset);
1187 if (!Die) {
1188 const uint32_t BucketIdx =
1189 NumBuckets ? (Hash % NumBuckets) : UINT32_MAX;
1190 StringOffset = StrpOffset;
1191 const char *Name = StrData->getCStr(&StringOffset);
1192 if (!Name)
1193 Name = "<NULL>";
1194
1195 ErrorCategory.Report("Invalid DIE offset", [&]() {
1196 error() << format(
1197 "%s Bucket[%d] Hash[%d] = 0x%08x "
1198 "Str[%u] = 0x%08" PRIx64 " DIE[%d] = 0x%08" PRIx64 " "
1199 "is not a valid DIE offset for \"%s\".\n",
1200 SectionName, BucketIdx, HashIdx, Hash, StringCount, StrpOffset,
1201 HashDataIdx, Offset, Name);
1202 });
1203
1204 ++NumErrors;
1205 continue;
1206 }
1207 if ((Tag != dwarf::DW_TAG_null) && (Die.getTag() != Tag)) {
1208 ErrorCategory.Report("Mismatched Tag in accellerator table", [&]() {
1209 error() << "Tag " << dwarf::TagString(Tag)
1210 << " in accelerator table does not match Tag "
1211 << dwarf::TagString(Die.getTag()) << " of DIE["
1212 << HashDataIdx << "].\n";
1213 });
1214 ++NumErrors;
1215 }
1216 }
1217 ++StringCount;
1218 }
1219 }
1220 return NumErrors;
1221}
1222
1223unsigned
1224DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) {
1225 // A map from CU offset to the (first) Name Index offset which claims to index
1226 // this CU.
1228 const uint64_t NotIndexed = std::numeric_limits<uint64_t>::max();
1229
1230 CUMap.reserve(DCtx.getNumCompileUnits());
1231 for (const auto &CU : DCtx.compile_units())
1232 CUMap[CU->getOffset()] = NotIndexed;
1233
1234 unsigned NumErrors = 0;
1235 for (const DWARFDebugNames::NameIndex &NI : AccelTable) {
1236 if (NI.getCUCount() == 0) {
1237 ErrorCategory.Report("Name Index doesn't index any CU", [&]() {
1238 error() << formatv("Name Index @ {0:x} does not index any CU\n",
1239 NI.getUnitOffset());
1240 });
1241 ++NumErrors;
1242 continue;
1243 }
1244 for (uint32_t CU = 0, End = NI.getCUCount(); CU < End; ++CU) {
1245 uint64_t Offset = NI.getCUOffset(CU);
1246 auto Iter = CUMap.find(Offset);
1247
1248 if (Iter == CUMap.end()) {
1249 ErrorCategory.Report("Name Index references non-existing CU", [&]() {
1250 error() << formatv(
1251 "Name Index @ {0:x} references a non-existing CU @ {1:x}\n",
1252 NI.getUnitOffset(), Offset);
1253 });
1254 ++NumErrors;
1255 continue;
1256 }
1257
1258 if (Iter->second != NotIndexed) {
1259 ErrorCategory.Report("Duplicate Name Index", [&]() {
1260 error() << formatv(
1261 "Name Index @ {0:x} references a CU @ {1:x}, but "
1262 "this CU is already indexed by Name Index @ {2:x}\n",
1263 NI.getUnitOffset(), Offset, Iter->second);
1264 });
1265 continue;
1266 }
1267 Iter->second = NI.getUnitOffset();
1268 }
1269 }
1270
1271 for (const auto &KV : CUMap) {
1272 if (KV.second == NotIndexed)
1273 warn() << formatv("CU @ {0:x} not covered by any Name Index\n", KV.first);
1274 }
1275
1276 return NumErrors;
1277}
1278
1279unsigned
1280DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI,
1281 const DataExtractor &StrData) {
1282 struct BucketInfo {
1283 uint32_t Bucket;
1285
1286 constexpr BucketInfo(uint32_t Bucket, uint32_t Index)
1287 : Bucket(Bucket), Index(Index) {}
1288 bool operator<(const BucketInfo &RHS) const { return Index < RHS.Index; }
1289 };
1290
1291 uint32_t NumErrors = 0;
1292 if (NI.getBucketCount() == 0) {
1293 warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n",
1294 NI.getUnitOffset());
1295 return NumErrors;
1296 }
1297
1298 // Build up a list of (Bucket, Index) pairs. We use this later to verify that
1299 // each Name is reachable from the appropriate bucket.
1300 std::vector<BucketInfo> BucketStarts;
1301 BucketStarts.reserve(NI.getBucketCount() + 1);
1302 for (uint32_t Bucket = 0, End = NI.getBucketCount(); Bucket < End; ++Bucket) {
1303 uint32_t Index = NI.getBucketArrayEntry(Bucket);
1304 if (Index > NI.getNameCount()) {
1305 ErrorCategory.Report("Name Index Bucket contains invalid value", [&]() {
1306 error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid "
1307 "value {2}. Valid range is [0, {3}].\n",
1308 Bucket, NI.getUnitOffset(), Index,
1309 NI.getNameCount());
1310 });
1311 ++NumErrors;
1312 continue;
1313 }
1314 if (Index > 0)
1315 BucketStarts.emplace_back(Bucket, Index);
1316 }
1317
1318 // If there were any buckets with invalid values, skip further checks as they
1319 // will likely produce many errors which will only confuse the actual root
1320 // problem.
1321 if (NumErrors > 0)
1322 return NumErrors;
1323
1324 // Sort the list in the order of increasing "Index" entries.
1325 array_pod_sort(BucketStarts.begin(), BucketStarts.end());
1326
1327 // Insert a sentinel entry at the end, so we can check that the end of the
1328 // table is covered in the loop below.
1329 BucketStarts.emplace_back(NI.getBucketCount(), NI.getNameCount() + 1);
1330
1331 // Loop invariant: NextUncovered is the (1-based) index of the first Name
1332 // which is not reachable by any of the buckets we processed so far (and
1333 // hasn't been reported as uncovered).
1334 uint32_t NextUncovered = 1;
1335 for (const BucketInfo &B : BucketStarts) {
1336 // Under normal circumstances B.Index be equal to NextUncovered, but it can
1337 // be less if a bucket points to names which are already known to be in some
1338 // bucket we processed earlier. In that case, we won't trigger this error,
1339 // but report the mismatched hash value error instead. (We know the hash
1340 // will not match because we have already verified that the name's hash
1341 // puts it into the previous bucket.)
1342 if (B.Index > NextUncovered) {
1343 ErrorCategory.Report("Name table entries uncovered by hash table", [&]() {
1344 error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] "
1345 "are not covered by the hash table.\n",
1346 NI.getUnitOffset(), NextUncovered, B.Index - 1);
1347 });
1348 ++NumErrors;
1349 }
1350 uint32_t Idx = B.Index;
1351
1352 // The rest of the checks apply only to non-sentinel entries.
1353 if (B.Bucket == NI.getBucketCount())
1354 break;
1355
1356 // This triggers if a non-empty bucket points to a name with a mismatched
1357 // hash. Clients are likely to interpret this as an empty bucket, because a
1358 // mismatched hash signals the end of a bucket, but if this is indeed an
1359 // empty bucket, the producer should have signalled this by marking the
1360 // bucket as empty.
1361 uint32_t FirstHash = NI.getHashArrayEntry(Idx);
1362 if (FirstHash % NI.getBucketCount() != B.Bucket) {
1363 ErrorCategory.Report("Name Index point to mismatched hash value", [&]() {
1364 error() << formatv(
1365 "Name Index @ {0:x}: Bucket {1} is not empty but points to a "
1366 "mismatched hash value {2:x} (belonging to bucket {3}).\n",
1367 NI.getUnitOffset(), B.Bucket, FirstHash,
1368 FirstHash % NI.getBucketCount());
1369 });
1370 ++NumErrors;
1371 }
1372
1373 // This find the end of this bucket and also verifies that all the hashes in
1374 // this bucket are correct by comparing the stored hashes to the ones we
1375 // compute ourselves.
1376 while (Idx <= NI.getNameCount()) {
1377 uint32_t Hash = NI.getHashArrayEntry(Idx);
1378 if (Hash % NI.getBucketCount() != B.Bucket)
1379 break;
1380
1381 const char *Str = NI.getNameTableEntry(Idx).getString();
1382 if (caseFoldingDjbHash(Str) != Hash) {
1383 ErrorCategory.Report(
1384 "String hash doesn't match Name Index hash", [&]() {
1385 error() << formatv(
1386 "Name Index @ {0:x}: String ({1}) at index {2} "
1387 "hashes to {3:x}, but "
1388 "the Name Index hash is {4:x}\n",
1389 NI.getUnitOffset(), Str, Idx, caseFoldingDjbHash(Str), Hash);
1390 });
1391 ++NumErrors;
1392 }
1393
1394 ++Idx;
1395 }
1396 NextUncovered = std::max(NextUncovered, Idx);
1397 }
1398 return NumErrors;
1399}
1400
1401unsigned DWARFVerifier::verifyNameIndexAttribute(
1404 StringRef FormName = dwarf::FormEncodingString(AttrEnc.Form);
1405 if (FormName.empty()) {
1406 ErrorCategory.Report("Unknown NameIndex Abbreviation", [&]() {
1407 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1408 "unknown form: {3}.\n",
1409 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1410 AttrEnc.Form);
1411 });
1412 return 1;
1413 }
1414
1415 if (AttrEnc.Index == DW_IDX_type_hash) {
1416 if (AttrEnc.Form != dwarf::DW_FORM_data8) {
1417 ErrorCategory.Report("Unexpected NameIndex Abbreviation", [&]() {
1418 error() << formatv(
1419 "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash "
1420 "uses an unexpected form {2} (should be {3}).\n",
1421 NI.getUnitOffset(), Abbr.Code, AttrEnc.Form, dwarf::DW_FORM_data8);
1422 });
1423 return 1;
1424 }
1425 return 0;
1426 }
1427
1428 if (AttrEnc.Index == dwarf::DW_IDX_parent) {
1429 constexpr static auto AllowedForms = {dwarf::Form::DW_FORM_flag_present,
1430 dwarf::Form::DW_FORM_ref4};
1431 if (!is_contained(AllowedForms, AttrEnc.Form)) {
1432 ErrorCategory.Report("Unexpected NameIndex Abbreviation", [&]() {
1433 error() << formatv(
1434 "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_parent "
1435 "uses an unexpected form {2} (should be "
1436 "DW_FORM_ref4 or DW_FORM_flag_present).\n",
1437 NI.getUnitOffset(), Abbr.Code, AttrEnc.Form);
1438 });
1439 return 1;
1440 }
1441 return 0;
1442 }
1443
1444 // A list of known index attributes and their expected form classes.
1445 // DW_IDX_type_hash is handled specially in the check above, as it has a
1446 // specific form (not just a form class) we should expect.
1447 struct FormClassTable {
1450 StringLiteral ClassName;
1451 };
1452 static constexpr FormClassTable Table[] = {
1453 {dwarf::DW_IDX_compile_unit, DWARFFormValue::FC_Constant, {"constant"}},
1454 {dwarf::DW_IDX_type_unit, DWARFFormValue::FC_Constant, {"constant"}},
1455 {dwarf::DW_IDX_die_offset, DWARFFormValue::FC_Reference, {"reference"}},
1456 };
1457
1459 auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) {
1460 return T.Index == AttrEnc.Index;
1461 });
1462 if (Iter == TableRef.end()) {
1463 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an "
1464 "unknown index attribute: {2}.\n",
1465 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index);
1466 return 0;
1467 }
1468
1469 if (!DWARFFormValue(AttrEnc.Form).isFormClass(Iter->Class)) {
1470 ErrorCategory.Report("Unexpected NameIndex Abbreviation", [&]() {
1471 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1472 "unexpected form {3} (expected form class {4}).\n",
1473 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1474 AttrEnc.Form, Iter->ClassName);
1475 });
1476 return 1;
1477 }
1478 return 0;
1479}
1480
1481unsigned
1482DWARFVerifier::verifyNameIndexAbbrevs(const DWARFDebugNames::NameIndex &NI) {
1483 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) {
1484 warn() << formatv("Name Index @ {0:x}: Verifying indexes of type units is "
1485 "not currently supported.\n",
1486 NI.getUnitOffset());
1487 return 0;
1488 }
1489
1490 unsigned NumErrors = 0;
1491 for (const auto &Abbrev : NI.getAbbrevs()) {
1492 StringRef TagName = dwarf::TagString(Abbrev.Tag);
1493 if (TagName.empty()) {
1494 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an "
1495 "unknown tag: {2}.\n",
1496 NI.getUnitOffset(), Abbrev.Code, Abbrev.Tag);
1497 }
1499 for (const auto &AttrEnc : Abbrev.Attributes) {
1500 if (!Attributes.insert(AttrEnc.Index).second) {
1501 ErrorCategory.Report(
1502 "NameIndex Abbreviateion contains multiple attributes", [&]() {
1503 error() << formatv(
1504 "NameIndex @ {0:x}: Abbreviation {1:x} contains "
1505 "multiple {2} attributes.\n",
1506 NI.getUnitOffset(), Abbrev.Code, AttrEnc.Index);
1507 });
1508 ++NumErrors;
1509 continue;
1510 }
1511 NumErrors += verifyNameIndexAttribute(NI, Abbrev, AttrEnc);
1512 }
1513
1514 if (NI.getCUCount() > 1 && !Attributes.count(dwarf::DW_IDX_compile_unit)) {
1515 ErrorCategory.Report("Abbreviation contains no attribute", [&]() {
1516 error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units "
1517 "and abbreviation {1:x} has no {2} attribute.\n",
1518 NI.getUnitOffset(), Abbrev.Code,
1519 dwarf::DW_IDX_compile_unit);
1520 });
1521 ++NumErrors;
1522 }
1523 if (!Attributes.count(dwarf::DW_IDX_die_offset)) {
1524 ErrorCategory.Report("Abbreviate in NameIndex missing attribute", [&]() {
1525 error() << formatv(
1526 "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n",
1527 NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset);
1528 });
1529 ++NumErrors;
1530 }
1531 }
1532 return NumErrors;
1533}
1534
1536 bool IncludeStrippedTemplateNames,
1537 bool IncludeObjCNames = true,
1538 bool IncludeLinkageName = true) {
1540 if (const char *Str = DIE.getShortName()) {
1541 StringRef Name(Str);
1542 Result.emplace_back(Name);
1543 if (IncludeStrippedTemplateNames) {
1544 if (std::optional<StringRef> StrippedName =
1545 StripTemplateParameters(Result.back()))
1546 // Convert to std::string and push; emplacing the StringRef may trigger
1547 // a vector resize which may destroy the StringRef memory.
1548 Result.push_back(StrippedName->str());
1549 }
1550
1551 if (IncludeObjCNames) {
1552 if (std::optional<ObjCSelectorNames> ObjCNames =
1554 Result.emplace_back(ObjCNames->ClassName);
1555 Result.emplace_back(ObjCNames->Selector);
1556 if (ObjCNames->ClassNameNoCategory)
1557 Result.emplace_back(*ObjCNames->ClassNameNoCategory);
1558 if (ObjCNames->MethodNameNoCategory)
1559 Result.push_back(std::move(*ObjCNames->MethodNameNoCategory));
1560 }
1561 }
1562 } else if (DIE.getTag() == dwarf::DW_TAG_namespace)
1563 Result.emplace_back("(anonymous namespace)");
1564
1565 if (IncludeLinkageName) {
1566 if (const char *Str = DIE.getLinkageName())
1567 Result.emplace_back(Str);
1568 }
1569
1570 return Result;
1571}
1572
1573unsigned DWARFVerifier::verifyNameIndexEntries(
1576 // Verifying type unit indexes not supported.
1577 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0)
1578 return 0;
1579
1580 const char *CStr = NTE.getString();
1581 if (!CStr) {
1582 ErrorCategory.Report("Unable to get string associated with name", [&]() {
1583 error() << formatv("Name Index @ {0:x}: Unable to get string associated "
1584 "with name {1}.\n",
1585 NI.getUnitOffset(), NTE.getIndex());
1586 });
1587 return 1;
1588 }
1589 StringRef Str(CStr);
1590
1591 unsigned NumErrors = 0;
1592 unsigned NumEntries = 0;
1593 uint64_t EntryID = NTE.getEntryOffset();
1594 uint64_t NextEntryID = EntryID;
1595 Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&NextEntryID);
1596 for (; EntryOr; ++NumEntries, EntryID = NextEntryID,
1597 EntryOr = NI.getEntry(&NextEntryID)) {
1598 uint32_t CUIndex = *EntryOr->getCUIndex();
1599 if (CUIndex > NI.getCUCount()) {
1600 ErrorCategory.Report("Name Index entry contains invalid CU index", [&]() {
1601 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
1602 "invalid CU index ({2}).\n",
1603 NI.getUnitOffset(), EntryID, CUIndex);
1604 });
1605 ++NumErrors;
1606 continue;
1607 }
1608 uint64_t CUOffset = NI.getCUOffset(CUIndex);
1609 uint64_t DIEOffset = CUOffset + *EntryOr->getDIEUnitOffset();
1610 DWARFDie DIE = DCtx.getDIEForOffset(DIEOffset);
1611 if (!DIE) {
1612 ErrorCategory.Report("NameIndex references nonexistent DIE", [&]() {
1613 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
1614 "non-existing DIE @ {2:x}.\n",
1615 NI.getUnitOffset(), EntryID, DIEOffset);
1616 });
1617 ++NumErrors;
1618 continue;
1619 }
1620 if (DIE.getDwarfUnit()->getOffset() != CUOffset) {
1621 ErrorCategory.Report("Name index contains mismatched CU of DIE", [&]() {
1622 error() << formatv(
1623 "Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of "
1624 "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n",
1625 NI.getUnitOffset(), EntryID, DIEOffset, CUOffset,
1626 DIE.getDwarfUnit()->getOffset());
1627 });
1628 ++NumErrors;
1629 }
1630 if (DIE.getTag() != EntryOr->tag()) {
1631 ErrorCategory.Report("Name Index contains mismatched Tag of DIE", [&]() {
1632 error() << formatv(
1633 "Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of "
1634 "DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1635 NI.getUnitOffset(), EntryID, DIEOffset, EntryOr->tag(),
1636 DIE.getTag());
1637 });
1638 ++NumErrors;
1639 }
1640
1641 // We allow an extra name for functions: their name without any template
1642 // parameters.
1643 auto IncludeStrippedTemplateNames =
1644 DIE.getTag() == DW_TAG_subprogram ||
1645 DIE.getTag() == DW_TAG_inlined_subroutine;
1646 auto EntryNames = getNames(DIE, IncludeStrippedTemplateNames);
1647 if (!is_contained(EntryNames, Str)) {
1648 ErrorCategory.Report("Name Index contains mismatched name of DIE", [&]() {
1649 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name "
1650 "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1651 NI.getUnitOffset(), EntryID, DIEOffset, Str,
1652 make_range(EntryNames.begin(), EntryNames.end()));
1653 });
1654 ++NumErrors;
1655 }
1656 }
1658 EntryOr.takeError(),
1659 [&](const DWARFDebugNames::SentinelError &) {
1660 if (NumEntries > 0)
1661 return;
1662 ErrorCategory.Report(
1663 "NameIndex Name is not associated with any entries", [&]() {
1664 error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
1665 "not associated with any entries.\n",
1666 NI.getUnitOffset(), NTE.getIndex(), Str);
1667 });
1668 ++NumErrors;
1669 },
1670 [&](const ErrorInfoBase &Info) {
1671 ErrorCategory.Report("Uncategorized NameIndex error", [&]() {
1672 error() << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n",
1673 NI.getUnitOffset(), NTE.getIndex(), Str,
1674 Info.message());
1675 });
1676 ++NumErrors;
1677 });
1678 return NumErrors;
1679}
1680
1681static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) {
1683 Die.getLocations(DW_AT_location);
1684 if (!Loc) {
1685 consumeError(Loc.takeError());
1686 return false;
1687 }
1688 DWARFUnit *U = Die.getDwarfUnit();
1689 for (const auto &Entry : *Loc) {
1690 DataExtractor Data(toStringRef(Entry.Expr), DCtx.isLittleEndian(),
1691 U->getAddressByteSize());
1692 DWARFExpression Expression(Data, U->getAddressByteSize(),
1693 U->getFormParams().Format);
1694 bool IsInteresting =
1696 return !Op.isError() && (Op.getCode() == DW_OP_addr ||
1697 Op.getCode() == DW_OP_form_tls_address ||
1698 Op.getCode() == DW_OP_GNU_push_tls_address);
1699 });
1700 if (IsInteresting)
1701 return true;
1702 }
1703 return false;
1704}
1705
1706unsigned DWARFVerifier::verifyNameIndexCompleteness(
1707 const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI) {
1708
1709 // First check, if the Die should be indexed. The code follows the DWARF v5
1710 // wording as closely as possible.
1711
1712 // "All non-defining declarations (that is, debugging information entries
1713 // with a DW_AT_declaration attribute) are excluded."
1714 if (Die.find(DW_AT_declaration))
1715 return 0;
1716
1717 // "DW_TAG_namespace debugging information entries without a DW_AT_name
1718 // attribute are included with the name “(anonymous namespace)”.
1719 // All other debugging information entries without a DW_AT_name attribute
1720 // are excluded."
1721 // "If a subprogram or inlined subroutine is included, and has a
1722 // DW_AT_linkage_name attribute, there will be an additional index entry for
1723 // the linkage name."
1724 auto IncludeLinkageName = Die.getTag() == DW_TAG_subprogram ||
1725 Die.getTag() == DW_TAG_inlined_subroutine;
1726 // We *allow* stripped template names / ObjectiveC names as extra entries into
1727 // the table, but we don't *require* them to pass the completeness test.
1728 auto IncludeStrippedTemplateNames = false;
1729 auto IncludeObjCNames = false;
1730 auto EntryNames = getNames(Die, IncludeStrippedTemplateNames,
1731 IncludeObjCNames, IncludeLinkageName);
1732 if (EntryNames.empty())
1733 return 0;
1734
1735 // We deviate from the specification here, which says:
1736 // "The name index must contain an entry for each debugging information entry
1737 // that defines a named subprogram, label, variable, type, or namespace,
1738 // subject to ..."
1739 // Explicitly exclude all TAGs that we know shouldn't be indexed.
1740 switch (Die.getTag()) {
1741 // Compile units and modules have names but shouldn't be indexed.
1742 case DW_TAG_compile_unit:
1743 case DW_TAG_module:
1744 return 0;
1745
1746 // Function and template parameters are not globally visible, so we shouldn't
1747 // index them.
1748 case DW_TAG_formal_parameter:
1749 case DW_TAG_template_value_parameter:
1750 case DW_TAG_template_type_parameter:
1751 case DW_TAG_GNU_template_parameter_pack:
1752 case DW_TAG_GNU_template_template_param:
1753 return 0;
1754
1755 // Object members aren't globally visible.
1756 case DW_TAG_member:
1757 return 0;
1758
1759 // According to a strict reading of the specification, enumerators should not
1760 // be indexed (and LLVM currently does not do that). However, this causes
1761 // problems for the debuggers, so we may need to reconsider this.
1762 case DW_TAG_enumerator:
1763 return 0;
1764
1765 // Imported declarations should not be indexed according to the specification
1766 // and LLVM currently does not do that.
1767 case DW_TAG_imported_declaration:
1768 return 0;
1769
1770 // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging
1771 // information entries without an address attribute (DW_AT_low_pc,
1772 // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded."
1773 case DW_TAG_subprogram:
1774 case DW_TAG_inlined_subroutine:
1775 case DW_TAG_label:
1776 if (Die.findRecursively(
1777 {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc}))
1778 break;
1779 return 0;
1780
1781 // "DW_TAG_variable debugging information entries with a DW_AT_location
1782 // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are
1783 // included; otherwise, they are excluded."
1784 //
1785 // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list.
1786 case DW_TAG_variable:
1787 if (isVariableIndexable(Die, DCtx))
1788 break;
1789 return 0;
1790
1791 default:
1792 break;
1793 }
1794
1795 // Now we know that our Die should be present in the Index. Let's check if
1796 // that's the case.
1797 unsigned NumErrors = 0;
1798 uint64_t DieUnitOffset = Die.getOffset() - Die.getDwarfUnit()->getOffset();
1799 for (StringRef Name : EntryNames) {
1800 if (none_of(NI.equal_range(Name), [&](const DWARFDebugNames::Entry &E) {
1801 return E.getDIEUnitOffset() == DieUnitOffset;
1802 })) {
1803 ErrorCategory.Report("Name Index DIE entry missing name", [&]() {
1804 error() << formatv(
1805 "Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with "
1806 "name {3} missing.\n",
1807 NI.getUnitOffset(), Die.getOffset(), Die.getTag(), Name);
1808 });
1809 ++NumErrors;
1810 }
1811 }
1812 return NumErrors;
1813}
1814
1815unsigned DWARFVerifier::verifyDebugNames(const DWARFSection &AccelSection,
1816 const DataExtractor &StrData) {
1817 unsigned NumErrors = 0;
1818 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), AccelSection,
1819 DCtx.isLittleEndian(), 0);
1820 DWARFDebugNames AccelTable(AccelSectionData, StrData);
1821
1822 OS << "Verifying .debug_names...\n";
1823
1824 // This verifies that we can read individual name indices and their
1825 // abbreviation tables.
1826 if (Error E = AccelTable.extract()) {
1827 std::string Msg = toString(std::move(E));
1828 ErrorCategory.Report("Accelerator Table Error",
1829 [&]() { error() << Msg << '\n'; });
1830 return 1;
1831 }
1832
1833 NumErrors += verifyDebugNamesCULists(AccelTable);
1834 for (const auto &NI : AccelTable)
1835 NumErrors += verifyNameIndexBuckets(NI, StrData);
1836 for (const auto &NI : AccelTable)
1837 NumErrors += verifyNameIndexAbbrevs(NI);
1838
1839 // Don't attempt Entry validation if any of the previous checks found errors
1840 if (NumErrors > 0)
1841 return NumErrors;
1842 for (const auto &NI : AccelTable)
1843 for (const DWARFDebugNames::NameTableEntry &NTE : NI)
1844 NumErrors += verifyNameIndexEntries(NI, NTE);
1845
1846 if (NumErrors > 0)
1847 return NumErrors;
1848
1849 for (const std::unique_ptr<DWARFUnit> &U : DCtx.compile_units()) {
1850 if (const DWARFDebugNames::NameIndex *NI =
1851 AccelTable.getCUNameIndex(U->getOffset())) {
1852 auto *CU = cast<DWARFCompileUnit>(U.get());
1853 for (const DWARFDebugInfoEntry &Die : CU->dies())
1854 NumErrors += verifyNameIndexCompleteness(DWARFDie(CU, &Die), *NI);
1855 }
1856 }
1857 return NumErrors;
1858}
1859
1861 const DWARFObject &D = DCtx.getDWARFObj();
1862 DataExtractor StrData(D.getStrSection(), DCtx.isLittleEndian(), 0);
1863 unsigned NumErrors = 0;
1864 if (!D.getAppleNamesSection().Data.empty())
1865 NumErrors += verifyAppleAccelTable(&D.getAppleNamesSection(), &StrData,
1866 ".apple_names");
1867 if (!D.getAppleTypesSection().Data.empty())
1868 NumErrors += verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData,
1869 ".apple_types");
1870 if (!D.getAppleNamespacesSection().Data.empty())
1871 NumErrors += verifyAppleAccelTable(&D.getAppleNamespacesSection(), &StrData,
1872 ".apple_namespaces");
1873 if (!D.getAppleObjCSection().Data.empty())
1874 NumErrors += verifyAppleAccelTable(&D.getAppleObjCSection(), &StrData,
1875 ".apple_objc");
1876
1877 if (!D.getNamesSection().Data.empty())
1878 NumErrors += verifyDebugNames(D.getNamesSection(), StrData);
1879 return NumErrors == 0;
1880}
1881
1883 OS << "Verifying .debug_str_offsets...\n";
1884 const DWARFObject &DObj = DCtx.getDWARFObj();
1885 bool Success = true;
1886
1887 // dwo sections may contain the legacy debug_str_offsets format (and they
1888 // can't be mixed with dwarf 5's format). This section format contains no
1889 // header.
1890 // As such, check the version from debug_info and, if we are in the legacy
1891 // mode (Dwarf <= 4), extract Dwarf32/Dwarf64.
1892 std::optional<DwarfFormat> DwoLegacyDwarf4Format;
1893 DObj.forEachInfoDWOSections([&](const DWARFSection &S) {
1894 if (DwoLegacyDwarf4Format)
1895 return;
1896 DWARFDataExtractor DebugInfoData(DObj, S, DCtx.isLittleEndian(), 0);
1897 uint64_t Offset = 0;
1898 DwarfFormat InfoFormat = DebugInfoData.getInitialLength(&Offset).second;
1899 if (uint16_t InfoVersion = DebugInfoData.getU16(&Offset); InfoVersion <= 4)
1900 DwoLegacyDwarf4Format = InfoFormat;
1901 });
1902
1904 DwoLegacyDwarf4Format, ".debug_str_offsets.dwo",
1907 /*LegacyFormat=*/std::nullopt, ".debug_str_offsets",
1908 DObj.getStrOffsetsSection(), DObj.getStrSection());
1909 return Success;
1910}
1911
1913 std::optional<DwarfFormat> LegacyFormat, StringRef SectionName,
1914 const DWARFSection &Section, StringRef StrData) {
1915 const DWARFObject &DObj = DCtx.getDWARFObj();
1916
1917 DWARFDataExtractor DA(DObj, Section, DCtx.isLittleEndian(), 0);
1919 uint64_t NextUnit = 0;
1920 bool Success = true;
1921 while (C.seek(NextUnit), C.tell() < DA.getData().size()) {
1924 uint64_t StartOffset = C.tell();
1925 if (LegacyFormat) {
1926 Format = *LegacyFormat;
1927 Length = DA.getData().size();
1928 NextUnit = C.tell() + Length;
1929 } else {
1930 std::tie(Length, Format) = DA.getInitialLength(C);
1931 if (!C)
1932 break;
1933 if (C.tell() + Length > DA.getData().size()) {
1934 ErrorCategory.Report(
1935 "Section contribution length exceeds available space", [&]() {
1936 error() << formatv(
1937 "{0}: contribution {1:X}: length exceeds available space "
1938 "(contribution "
1939 "offset ({1:X}) + length field space ({2:X}) + length "
1940 "({3:X}) == "
1941 "{4:X} > section size {5:X})\n",
1942 SectionName, StartOffset, C.tell() - StartOffset, Length,
1943 C.tell() + Length, DA.getData().size());
1944 });
1945 Success = false;
1946 // Nothing more to do - no other contributions to try.
1947 break;
1948 }
1949 NextUnit = C.tell() + Length;
1950 uint8_t Version = DA.getU16(C);
1951 if (C && Version != 5) {
1952 ErrorCategory.Report("Invalid Section version", [&]() {
1953 error() << formatv("{0}: contribution {1:X}: invalid version {2}\n",
1954 SectionName, StartOffset, Version);
1955 });
1956 Success = false;
1957 // Can't parse the rest of this contribution, since we don't know the
1958 // version, but we can pick up with the next contribution.
1959 continue;
1960 }
1961 (void)DA.getU16(C); // padding
1962 }
1963 uint64_t OffsetByteSize = getDwarfOffsetByteSize(Format);
1964 DA.setAddressSize(OffsetByteSize);
1965 uint64_t Remainder = (Length - 4) % OffsetByteSize;
1966 if (Remainder != 0) {
1967 ErrorCategory.Report("Invalid section contribution length", [&]() {
1968 error() << formatv(
1969 "{0}: contribution {1:X}: invalid length ((length ({2:X}) "
1970 "- header (0x4)) % offset size {3:X} == {4:X} != 0)\n",
1971 SectionName, StartOffset, Length, OffsetByteSize, Remainder);
1972 });
1973 Success = false;
1974 }
1975 for (uint64_t Index = 0; C && C.tell() + OffsetByteSize <= NextUnit; ++Index) {
1976 uint64_t OffOff = C.tell();
1977 uint64_t StrOff = DA.getAddress(C);
1978 // check StrOff refers to the start of a string
1979 if (StrOff == 0)
1980 continue;
1981 if (StrData.size() <= StrOff) {
1982 ErrorCategory.Report(
1983 "String offset out of bounds of string section", [&]() {
1984 error() << formatv(
1985 "{0}: contribution {1:X}: index {2:X}: invalid string "
1986 "offset *{3:X} == {4:X}, is beyond the bounds of the string "
1987 "section of length {5:X}\n",
1988 SectionName, StartOffset, Index, OffOff, StrOff,
1989 StrData.size());
1990 });
1991 continue;
1992 }
1993 if (StrData[StrOff - 1] == '\0')
1994 continue;
1995 ErrorCategory.Report(
1996 "Section contribution contains invalid string offset", [&]() {
1997 error() << formatv(
1998 "{0}: contribution {1:X}: index {2:X}: invalid string "
1999 "offset *{3:X} == {4:X}, is neither zero nor "
2000 "immediately following a null character\n",
2001 SectionName, StartOffset, Index, OffOff, StrOff);
2002 });
2003 Success = false;
2004 }
2005 }
2006
2007 if (Error E = C.takeError()) {
2008 std::string Msg = toString(std::move(E));
2009 ErrorCategory.Report("String offset error", [&]() {
2010 error() << SectionName << ": " << Msg << '\n';
2011 return false;
2012 });
2013 }
2014 return Success;
2015}
2016
2018 StringRef s, std::function<void(void)> detailCallback) {
2019 Aggregation[std::string(s)]++;
2020 if (IncludeDetail)
2021 detailCallback();
2022}
2023
2025 std::function<void(StringRef, unsigned)> handleCounts) {
2026 for (auto &&[name, count] : Aggregation) {
2027 handleCounts(name, count);
2028 }
2029}
2030
2032 if (DumpOpts.ShowAggregateErrors && ErrorCategory.GetNumCategories()) {
2033 error() << "Aggregated error counts:\n";
2034 ErrorCategory.EnumerateResults([&](StringRef s, unsigned count) {
2035 error() << s << " occurred " << count << " time(s).\n";
2036 });
2037 }
2038 if (!DumpOpts.JsonErrSummaryFile.empty()) {
2039 std::error_code EC;
2040 raw_fd_ostream JsonStream(DumpOpts.JsonErrSummaryFile, EC,
2042 if (EC) {
2043 error() << "unable to open json summary file '"
2044 << DumpOpts.JsonErrSummaryFile
2045 << "' for writing: " << EC.message() << '\n';
2046 return;
2047 }
2048
2049 llvm::json::Object Categories;
2050 uint64_t ErrorCount = 0;
2051 ErrorCategory.EnumerateResults([&](StringRef Category, unsigned Count) {
2053 Val.try_emplace("count", Count);
2054 Categories.try_emplace(Category, std::move(Val));
2055 ErrorCount += Count;
2056 });
2057 llvm::json::Object RootNode;
2058 RootNode.try_emplace("error-categories", std::move(Categories));
2059 RootNode.try_emplace("error-count", ErrorCount);
2060
2061 JsonStream << llvm::json::Value(std::move(RootNode));
2062 }
2063}
2064
2065raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); }
2066
2067raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); }
2068
2069raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); }
2070
2071raw_ostream &DWARFVerifier::dump(const DWARFDie &Die, unsigned indent) const {
2072 Die.dump(OS, indent, DumpOpts);
2073 return OS;
2074}
#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")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx)
static SmallVector< std::string, 3 > getNames(const DWARFDie &DIE, bool IncludeStrippedTemplateNames, bool IncludeObjCNames=true, bool IncludeLinkageName=true)
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
bool End
Definition: ELF_riscv.cpp:480
This file implements a coalescing interval map for small objects.
This file supports working with JSON data.
#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())
static const char * name
Definition: SMEABIPass.cpp:49
This file contains some templates that are useful if you are working with the STL at all.
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:202
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:154
A structured debug information entry.
Definition: DIE.h:819
unsigned getOffset() const
Get the compile/type unit relative offset of this DIE.
Definition: DIE.h:857
dwarf::Tag getTag() const
Definition: DIE.h:855
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
Definition: DWARFContext.h:48
static bool isSupportedVersion(unsigned version)
Definition: DWARFContext.h:400
unsigned getNumCompileUnits()
Get the number of compile units in this context.
Definition: DWARFContext.h:235
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:188
const DWARFDebugAbbrev * getDebugAbbrev()
Get a pointer to the parsed DebugAbbrev object.
bool isLittleEndian() const
Definition: DWARFContext.h:398
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:176
static bool isAddressSizeSupported(unsigned AddressSize)
Definition: DWARFContext.h:407
const DWARFUnitVector & getDWOUnitsVector()
Definition: DWARFContext.h:208
const DWARFObject & getDWARFObj() const
Definition: DWARFContext.h:147
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...
Expected< 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:233
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:378
DWARFDie getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE as the referenced DIE.
Definition: DWARFDie.cpp:307
DWARFDie getParent() const
Get the parent of this DIE object.
Definition: DWARFDie.cpp:636
std::optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
Definition: DWARFDie.cpp:250
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:243
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:274
DWARFDie getFirstChild() const
Get the first child of this DIE object.
Definition: DWARFDie.cpp:654
dwarf::Tag getTag() const
Definition: DWARFDie.h:71
Expected< DWARFLocationExpressionsVector > getLocations(dwarf::Attribute Attr) const
Definition: DWARFDie.cpp:409
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:666
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:576
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 getStrDWOSection() const
Definition: DWARFObject.h:68
virtual StringRef getAbbrevDWOSection() const
Definition: DWARFObject.h:64
virtual StringRef getAbbrevSection() const
Definition: DWARFObject.h:40
virtual const DWARFSection & getStrOffsetsDWOSection() const
Definition: DWARFObject.h:69
virtual void forEachInfoDWOSections(function_ref< void(const DWARFSection &)> F) const
Definition: DWARFObject.h:61
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 & getStrOffsetsSection() const
Definition: DWARFObject.h:59
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 StringRef getStrSection() const
Definition: DWARFObject.h:48
virtual const object::ObjectFile * getFile() const
Definition: DWARFObject.h:32
Describe a collection of units.
Definition: DWARFUnit.h:128
DWARFDie getUnitDIE(bool ExtractUnitDIEOnly=true)
Definition: DWARFUnit.h:443
static bool isMatchingUnitTypeAndTag(uint8_t UnitType, dwarf::Tag Tag)
Definition: DWARFUnit.h:424
uint64_t getOffset() const
Definition: DWARFUnit.h:321
bool handleAccelTables()
Verify the information in accelerator tables, if they exist.
bool verifyDebugStrOffsets(std::optional< dwarf::DwarfFormat > LegacyFormat, StringRef SectionName, const DWARFSection &Section, StringRef StrData)
bool handleDebugTUIndex()
Verify the information in the .debug_tu_index section.
bool handleDebugStrOffsets()
Verify the information in the .debug_str_offsets[.dwo].
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.
void summarize()
Emits any aggregate information collected, depending on the dump options.
bool handleDebugAbbrev()
Verify the information in any of the following sections, if available: .debug_abbrev,...
A class representing a position in a DataExtractor, as well as any error encountered during extractio...
Definition: DataExtractor.h:54
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:45
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:474
Error takeError()
Take ownership of the stored error.
Definition: Error.h:601
Class representing an expression and its matching format.
void ShowDetail(bool showDetail)
Definition: DWARFVerifier.h:41
void Report(StringRef s, std::function< void()> detailCallback)
void EnumerateResults(std::function< void(StringRef, unsigned)> handleCounts)
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:1209
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition: StringRef.h:849
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
iterator end()
Definition: StringMap.h:221
iterator find(StringRef Key)
Definition: StringMap.h:234
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.
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition: JSON.h:98
std::pair< iterator, bool > try_emplace(const ObjectKey &K, Ts &&... Args)
Definition: JSON.h:126
A Value is an JSON value of unknown type.
Definition: JSON.h:288
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:470
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:660
StringRef AttributeString(unsigned Attribute)
Definition: Dwarf.cpp:72
StringRef FormEncodingString(unsigned Encoding)
Definition: Dwarf.cpp:105
StringRef UnitTypeString(unsigned)
Definition: Dwarf.cpp:611
StringRef TagString(unsigned Tag)
Definition: Dwarf.cpp:21
const CustomOperand< const MCSubtargetInfo & > Msg[]
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ 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:565
UnitType
Constants for unit types in DWARF v5.
Definition: Dwarf.h:551
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.
uint8_t getDwarfOffsetByteSize(DwarfFormat Format)
The size of a reference determined by the DWARF 32/64-bit format.
Definition: Dwarf.h:749
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:759
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:456
@ Length
Definition: DWP.cpp:456
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:2415
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:970
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition: Error.h:947
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:1738
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:1745
std::optional< StringRef > StripTemplateParameters(StringRef Name)
If Name is the name of a templated function that includes template parameters, returns a substring of...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
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
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1923
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:1858
std::optional< ObjCSelectorNames > getObjCNamesIfSelector(StringRef Name)
If Name is the AT_name of a DIE which refers to an Objective-C selector, returns an instance of ObjCS...
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:1758
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1888
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:1616
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1041
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
Container for dump options that control which debug information will be dumped.
Definition: DIContext.h:193
std::string JsonErrSummaryFile
Definition: DIContext.h:209
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 offset in the .debug_names section
Index attribute and its encoding.
A class that keeps the address range information for a single DIE.
Definition: DWARFVerifier.h:51
std::vector< DWARFAddressRange > Ranges
Sorted DWARFAddressRanges.
Definition: DWARFVerifier.h:55
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:67
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.