Thanks to visit codestin.com
Credit goes to llvm.org

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