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