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