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 while (hasDIE) {
515 if (!verifyUnitHeader(DebugInfoData, &Offset, UnitIdx, UnitType,
516 isUnitDWARF64)) {
517 isHeaderChainValid = false;
518 if (isUnitDWARF64)
519 break;
520 }
521 hasDIE = DebugInfoData.isValidOffset(Offset);
522 ++UnitIdx;
523 }
524 if (UnitIdx == 0 && !hasDIE) {
525 warn() << "Section is empty.\n";
526 isHeaderChainValid = true;
527 }
528 if (!isHeaderChainValid)
529 ++NumDebugInfoErrors;
530 return NumDebugInfoErrors;
531}
532
533unsigned DWARFVerifier::verifyIndex(StringRef Name,
534 DWARFSectionKind InfoColumnKind,
535 StringRef IndexStr) {
536 if (IndexStr.empty())
537 return 0;
538 OS << "Verifying " << Name << "...\n";
539 DWARFUnitIndex Index(InfoColumnKind);
540 DataExtractor D(IndexStr, DCtx.isLittleEndian());
541 if (!Index.parse(D))
542 return 1;
543 using MapType = IntervalMap<uint64_t, uint64_t>;
544 MapType::Allocator Alloc;
545 std::vector<std::unique_ptr<MapType>> Sections(Index.getColumnKinds().size());
546 for (const DWARFUnitIndex::Entry &E : Index.getRows()) {
547 uint64_t Sig = E.getSignature();
548 if (!E.getContributions())
549 continue;
550 for (auto E : enumerate(
551 InfoColumnKind == DW_SECT_INFO
552 ? ArrayRef(E.getContributions(), Index.getColumnKinds().size())
553 : ArrayRef(E.getContribution(), 1))) {
554 const DWARFUnitIndex::Entry::SectionContribution &SC = E.value();
555 int Col = E.index();
556 if (SC.getLength() == 0)
557 continue;
558 if (!Sections[Col])
559 Sections[Col] = std::make_unique<MapType>(Alloc);
560 auto &M = *Sections[Col];
561 auto I = M.find(SC.getOffset());
562 if (I != M.end() && I.start() < (SC.getOffset() + SC.getLength())) {
563 StringRef Category = InfoColumnKind == DWARFSectionKind::DW_SECT_INFO
564 ? "Overlapping CU index entries"
565 : "Overlapping TU index entries";
566 ErrorCategory.Report(Category, [&]() {
567 error() << llvm::formatv(
568 "overlapping index entries for entries {0:x16} "
569 "and {1:x16} for column {2}\n",
570 *I, Sig, toString(Index.getColumnKinds()[Col]));
571 });
572 return 1;
573 }
574 M.insert(SC.getOffset(), SC.getOffset() + SC.getLength() - 1, Sig);
575 }
576 }
577
578 return 0;
579}
580
582 return verifyIndex(".debug_cu_index", DWARFSectionKind::DW_SECT_INFO,
583 DCtx.getDWARFObj().getCUIndexSection()) == 0;
584}
585
587 return verifyIndex(".debug_tu_index", DWARFSectionKind::DW_SECT_EXT_TYPES,
588 DCtx.getDWARFObj().getTUIndexSection()) == 0;
589}
590
592 const DWARFObject &DObj = DCtx.getDWARFObj();
593 unsigned NumErrors = 0;
594
595 OS << "Verifying .debug_info Unit Header Chain...\n";
597 [&](const DWARFSection &S) { NumErrors += verifyUnitSection(S); });
598
599 OS << "Verifying .debug_types Unit Header Chain...\n";
601 [&](const DWARFSection &S) { NumErrors += verifyUnitSection(S); });
602
603 OS << "Verifying non-dwo Units...\n";
604 NumErrors += verifyUnits(DCtx.getNormalUnitsVector());
605
606 OS << "Verifying dwo Units...\n";
607 NumErrors += verifyUnits(DCtx.getDWOUnitsVector());
608 return NumErrors == 0;
609}
610
611unsigned DWARFVerifier::verifyDieRanges(const DWARFDie &Die,
612 DieRangeInfo &ParentRI) {
613 unsigned NumErrors = 0;
614
615 if (!Die.isValid())
616 return NumErrors;
617
618 DWARFUnit *Unit = Die.getDwarfUnit();
619
620 auto RangesOrError = Die.getAddressRanges();
621 if (!RangesOrError) {
622 // FIXME: Report the error.
623 if (!Unit->isDWOUnit())
624 ++NumErrors;
625 llvm::consumeError(RangesOrError.takeError());
626 return NumErrors;
627 }
628
629 const DWARFAddressRangesVector &Ranges = RangesOrError.get();
630 // Build RI for this DIE and check that ranges within this DIE do not
631 // overlap.
632 DieRangeInfo RI(Die);
633
634 // TODO support object files better
635 //
636 // Some object file formats (i.e. non-MachO) support COMDAT. ELF in
637 // particular does so by placing each function into a section. The DWARF data
638 // for the function at that point uses a section relative DW_FORM_addrp for
639 // the DW_AT_low_pc and a DW_FORM_data4 for the offset as the DW_AT_high_pc.
640 // In such a case, when the Die is the CU, the ranges will overlap, and we
641 // will flag valid conflicting ranges as invalid.
642 //
643 // For such targets, we should read the ranges from the CU and partition them
644 // by the section id. The ranges within a particular section should be
645 // disjoint, although the ranges across sections may overlap. We would map
646 // the child die to the entity that it references and the section with which
647 // it is associated. The child would then be checked against the range
648 // information for the associated section.
649 //
650 // For now, simply elide the range verification for the CU DIEs if we are
651 // processing an object file.
652
653 if (!IsObjectFile || IsMachOObject || Die.getTag() != DW_TAG_compile_unit) {
654 bool DumpDieAfterError = false;
655 for (const auto &Range : Ranges) {
656 if (!Range.valid()) {
657 ++NumErrors;
658 ErrorCategory.Report("Invalid address range", [&]() {
659 error() << formatv("Invalid address range {0}\n", Range);
660 DumpDieAfterError = true;
661 });
662 continue;
663 }
664
665 // Verify that ranges don't intersect and also build up the DieRangeInfo
666 // address ranges. Don't break out of the loop below early, or we will
667 // think this DIE doesn't have all of the address ranges it is supposed
668 // to have. Compile units often have DW_AT_ranges that can contain one or
669 // more dead stripped address ranges which tend to all be at the same
670 // address: 0 or -1.
671 if (auto PrevRange = RI.insert(Range)) {
672 ++NumErrors;
673 ErrorCategory.Report("DIE has overlapping DW_AT_ranges", [&]() {
674 error() << formatv("DIE has overlapping ranges in DW_AT_ranges "
675 "attribute: {0} and {1}\n",
676 *PrevRange, Range);
677 DumpDieAfterError = true;
678 });
679 }
680 }
681 if (DumpDieAfterError)
682 dump(Die, 2) << '\n';
683 }
684
685 // Verify that children don't intersect.
686 const auto IntersectingChild = ParentRI.insert(RI);
687 if (IntersectingChild != ParentRI.Children.end()) {
688 ++NumErrors;
689 ErrorCategory.Report("DIEs have overlapping address ranges", [&]() {
690 error() << "DIEs have overlapping address ranges:";
691 dump(Die);
692 dump(IntersectingChild->Die) << '\n';
693 });
694 }
695
696 // Verify that ranges are contained within their parent.
697 bool ShouldBeContained = !RI.Ranges.empty() && !ParentRI.Ranges.empty() &&
698 !(Die.getTag() == DW_TAG_subprogram &&
699 ParentRI.Die.getTag() == DW_TAG_subprogram);
700 if (ShouldBeContained && !ParentRI.contains(RI)) {
701 ++NumErrors;
702 ErrorCategory.Report(
703 "DIE address ranges are not contained by parent ranges", [&]() {
704 error()
705 << "DIE address ranges are not contained in its parent's ranges:";
706 dump(ParentRI.Die);
707 dump(Die, 2) << '\n';
708 });
709 }
710
711 // Recursively check children.
712 for (DWARFDie Child : Die)
713 NumErrors += verifyDieRanges(Child, RI);
714
715 return NumErrors;
716}
717
718bool DWARFVerifier::verifyExpressionOp(const DWARFExpression::Operation &Op,
719 DWARFUnit *U) {
720 for (unsigned Operand = 0; Operand < Op.Desc.Op.size(); ++Operand) {
721 unsigned Size = Op.Desc.Op[Operand];
722
724 // For DW_OP_convert the operand may be 0 to indicate that conversion to
725 // the generic type should be done, so don't look up a base type in that
726 // case. The same holds for DW_OP_reinterpret, which is currently not
727 // supported.
728 if (Op.Opcode == DW_OP_convert && Op.Operands[Operand] == 0)
729 continue;
730 auto Die = U->getDIEForOffset(U->getOffset() + Op.Operands[Operand]);
731 if (!Die || Die.getTag() != dwarf::DW_TAG_base_type)
732 return false;
733 }
734 }
735
736 return true;
737}
738
739bool DWARFVerifier::verifyExpression(const DWARFExpression &E, DWARFUnit *U) {
740 for (auto &Op : E)
741 if (!verifyExpressionOp(Op, U))
742 return false;
743
744 return true;
745}
746
747unsigned DWARFVerifier::verifyDebugInfoAttribute(const DWARFDie &Die,
748 DWARFAttribute &AttrValue) {
749 unsigned NumErrors = 0;
750 auto ReportError = [&](StringRef category, const Twine &TitleMsg) {
751 ++NumErrors;
752 ErrorCategory.Report(category, [&]() {
753 error() << formatv("{0}\n", TitleMsg);
754 dump(Die) << '\n';
755 });
756 };
757
758 const DWARFObject &DObj = DCtx.getDWARFObj();
759 DWARFUnit *U = Die.getDwarfUnit();
760 const auto Attr = AttrValue.Attr;
761 switch (Attr) {
762 case DW_AT_ranges:
763 // Make sure the offset in the DW_AT_ranges attribute is valid.
764 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
765 unsigned DwarfVersion = U->getVersion();
766 const DWARFSection &RangeSection = DwarfVersion < 5
767 ? DObj.getRangesSection()
768 : DObj.getRnglistsSection();
769 if (U->isDWOUnit() && RangeSection.Data.empty())
770 break;
771 if (*SectionOffset >= RangeSection.Data.size())
772 ReportError(
773 "DW_AT_ranges offset out of bounds",
774 llvm::formatv("DW_AT_ranges offset is beyond {0} bounds: {1:x8}",
775 StringRef(DwarfVersion < 5 ? ".debug_ranges"
776 : ".debug_rnglists"),
777 *SectionOffset));
778 break;
779 }
780 ReportError("Invalid DW_AT_ranges encoding",
781 "DIE has invalid DW_AT_ranges encoding:");
782 break;
783 case DW_AT_stmt_list:
784 // Make sure the offset in the DW_AT_stmt_list attribute is valid.
785 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
786 if (*SectionOffset >= U->getLineSection().Data.size())
787 ReportError(
788 "DW_AT_stmt_list offset out of bounds",
790 "DW_AT_stmt_list offset is beyond .debug_line bounds: {0:x8}",
791 *SectionOffset));
792 break;
793 }
794 ReportError("Invalid DW_AT_stmt_list encoding",
795 "DIE has invalid DW_AT_stmt_list encoding:");
796 break;
797 case DW_AT_location: {
798 // FIXME: It might be nice if there's a way to walk location expressions
799 // without trying to resolve the address ranges - it'd be a more efficient
800 // API (since the API is currently unnecessarily resolving addresses for
801 // this use case which only wants to validate the expressions themselves) &
802 // then the expressions could be validated even if the addresses can't be
803 // resolved.
804 // That sort of API would probably look like a callback "for each
805 // expression" with some way to lazily resolve the address ranges when
806 // needed (& then the existing API used here could be built on top of that -
807 // using the callback API to build the data structure and return it).
808 if (Expected<std::vector<DWARFLocationExpression>> Loc =
809 Die.getLocations(DW_AT_location)) {
810 for (const auto &Entry : *Loc) {
811 DataExtractor Data(Entry.Expr, DCtx.isLittleEndian());
812 DWARFExpression Expression(Data, U->getAddressByteSize(),
813 U->getFormParams().Format);
814 bool Error =
815 any_of(Expression, [](const DWARFExpression::Operation &Op) {
816 return Op.isError();
817 });
818 if (Error || !verifyExpression(Expression, U))
819 ReportError("Invalid DWARF expressions",
820 "DIE contains invalid DWARF expression:");
821 }
822 } else if (Error Err = handleErrors(
823 Loc.takeError(), [&](std::unique_ptr<ResolverError> E) {
824 return U->isDWOUnit() ? Error::success()
825 : Error(std::move(E));
826 }))
827 ReportError("Invalid DW_AT_location", toString(std::move(Err)));
828 break;
829 }
830 case DW_AT_specification:
831 case DW_AT_abstract_origin: {
832 if (auto ReferencedDie = Die.getAttributeValueAsReferencedDie(Attr)) {
833 auto DieTag = Die.getTag();
834 auto RefTag = ReferencedDie.getTag();
835 if (DieTag == RefTag)
836 break;
837 if (DieTag == DW_TAG_inlined_subroutine && RefTag == DW_TAG_subprogram)
838 break;
839 if (DieTag == DW_TAG_variable && RefTag == DW_TAG_member)
840 break;
841 // This might be reference to a function declaration.
842 if (DieTag == DW_TAG_GNU_call_site && RefTag == DW_TAG_subprogram)
843 break;
844 ReportError("Incompatible DW_AT_abstract_origin tag reference",
845 formatv("DIE with tag {0} has {1} that points to DIE with "
846 "incompatible tag {2}",
847 TagString(DieTag), AttributeString(Attr),
848 TagString(RefTag)));
849 }
850 break;
851 }
852 case DW_AT_type: {
853 DWARFDie TypeDie = Die.getAttributeValueAsReferencedDie(DW_AT_type);
854 if (TypeDie && !isType(TypeDie.getTag())) {
855 ReportError("Incompatible DW_AT_type attribute tag",
856 formatv("DIE has {0} with incompatible tag {1}",
857 AttributeString(Attr), TagString(TypeDie.getTag())));
858 }
859 break;
860 }
861 case DW_AT_call_file:
862 case DW_AT_decl_file: {
863 if (auto FileIdx = AttrValue.Value.getAsUnsignedConstant()) {
864 if (U->isDWOUnit() && !U->isTypeUnit())
865 break;
866 const auto *LT = U->getContext().getLineTableForUnit(U);
867 if (LT) {
868 if (!LT->hasFileAtIndex(*FileIdx)) {
869 bool IsZeroIndexed = LT->Prologue.getVersion() >= 5;
870 if (std::optional<uint64_t> LastFileIdx =
871 LT->getLastValidFileIndex()) {
872 ReportError("Invalid file index in DW_AT_decl_file",
873 llvm::formatv("DIE has {0} with an invalid file index "
874 "{1} (valid values are [{2}-{3}])",
875 AttributeString(Attr), *FileIdx,
876 (IsZeroIndexed ? "0" : "1"),
877 *LastFileIdx));
878 } else {
879 ReportError(
880 "Invalid file index in DW_AT_decl_file",
881 llvm::formatv("DIE has {0} with an invalid file index {1} (the "
882 "file table in the prologue is empty)",
883 AttributeString(Attr), *FileIdx));
884 }
885 }
886 } else {
887 ReportError(
888 "File index in DW_AT_decl_file reference CU with no line table",
889 llvm::formatv("DIE has {0} that references a file with index {1} "
890 "and the compile unit has no line table",
891 AttributeString(Attr), *FileIdx));
892 }
893 } else {
894 ReportError("Invalid encoding in DW_AT_decl_file",
895 llvm::formatv("DIE has {0} with invalid encoding",
896 AttributeString(Attr)));
897 }
898 break;
899 }
900 case DW_AT_call_line:
901 case DW_AT_decl_line: {
902 if (!AttrValue.Value.getAsUnsignedConstant()) {
903 ReportError(
904 Attr == DW_AT_call_line ? "Invalid file index in DW_AT_decl_line"
905 : "Invalid file index in DW_AT_call_line",
906 formatv("DIE has {0} with invalid encoding", AttributeString(Attr)));
907 }
908 break;
909 }
910 case DW_AT_LLVM_stmt_sequence: {
911 // Make sure the offset in the DW_AT_LLVM_stmt_sequence attribute is valid
912 // and points to a valid sequence offset in the line table.
913 auto SectionOffset = AttrValue.Value.getAsSectionOffset();
914 if (!SectionOffset) {
915 ReportError("Invalid DW_AT_LLVM_stmt_sequence encoding",
916 "DIE has invalid DW_AT_LLVM_stmt_sequence encoding");
917 break;
918 }
919 if (*SectionOffset >= U->getLineSection().Data.size()) {
920 ReportError(
921 "DW_AT_LLVM_stmt_sequence offset out of bounds",
922 "DW_AT_LLVM_stmt_sequence offset is beyond .debug_line bounds: " +
923 llvm::formatv("{0:x8}", *SectionOffset));
924 break;
925 }
926
927 // Get the line table for this unit to validate bounds
928 const auto *LineTable = DCtx.getLineTableForUnit(U);
929 if (!LineTable) {
930 ReportError("DW_AT_LLVM_stmt_sequence without line table",
931 "DIE has DW_AT_LLVM_stmt_sequence but compile unit has no "
932 "line table");
933 break;
934 }
935
936 // Get the DW_AT_stmt_list offset from the compile unit DIE
937 DWARFDie CUDie = U->getUnitDIE();
938 auto StmtListOffset = toSectionOffset(CUDie.find(DW_AT_stmt_list));
939 if (!StmtListOffset) {
940 ReportError("DW_AT_LLVM_stmt_sequence without DW_AT_stmt_list",
941 "DIE has DW_AT_LLVM_stmt_sequence but compile unit has no "
942 "DW_AT_stmt_list");
943 break;
944 }
945
946 const int8_t DwarfOffset =
947 LineTable->Prologue.getFormParams().getDwarfOffsetByteSize();
948 // Calculate the bounds of this specific line table
949 uint64_t LineTableStart = *StmtListOffset;
950 uint64_t PrologueLength = LineTable->Prologue.PrologueLength;
951 uint64_t TotalLength = LineTable->Prologue.TotalLength;
952 uint64_t LineTableEnd = LineTableStart + TotalLength + DwarfOffset;
953
954 // See DWARF definition for this, the following three do not
955 // count toward prologue length. Calculate SequencesStart correctly
956 // according to DWARF specification:
957 uint64_t InitialLengthSize = DwarfOffset;
958 // Version field is always 2 bytes
959 uint64_t VersionSize = 2;
960 uint64_t PrologueLengthSize = DwarfOffset;
961 uint64_t SequencesStart = LineTableStart + InitialLengthSize + VersionSize +
962 PrologueLengthSize + PrologueLength;
963
964 // Check if the offset is within the bounds of this specific line table
965 if (*SectionOffset < SequencesStart || *SectionOffset >= LineTableEnd) {
966 ReportError("DW_AT_LLVM_stmt_sequence offset out of line table bounds",
967 llvm::formatv("DW_AT_LLVM_stmt_sequence offset {0:x8} is not "
968 "within the line table bounds [{1:x8}, {2:x8})",
969 *SectionOffset, SequencesStart, LineTableEnd));
970 break;
971 }
972
973 // Check if the offset matches any of the sequence offset.
974 auto It = llvm::find_if(LineTable->Sequences,
975 [SectionOffset](const auto &Sequence) {
976 return Sequence.StmtSeqOffset == *SectionOffset;
977 });
978
979 if (It == LineTable->Sequences.end())
980 ReportError(
981 "Invalid DW_AT_LLVM_stmt_sequence offset",
982 llvm::formatv("DW_AT_LLVM_stmt_sequence offset {0:x8} does not point "
983 "to a valid sequence offset in the line table",
984 *SectionOffset));
985 break;
986 }
987 default:
988 break;
989 }
990 return NumErrors;
991}
992
993unsigned DWARFVerifier::verifyDebugInfoForm(const DWARFDie &Die,
994 DWARFAttribute &AttrValue,
995 ReferenceMap &LocalReferences,
996 ReferenceMap &CrossUnitReferences) {
997 auto DieCU = Die.getDwarfUnit();
998 unsigned NumErrors = 0;
999 const auto Form = AttrValue.Value.getForm();
1000 switch (Form) {
1001 case DW_FORM_ref1:
1002 case DW_FORM_ref2:
1003 case DW_FORM_ref4:
1004 case DW_FORM_ref8:
1005 case DW_FORM_ref_udata: {
1006 // Verify all CU relative references are valid CU offsets.
1007 std::optional<uint64_t> RefVal = AttrValue.Value.getAsRelativeReference();
1008 assert(RefVal);
1009 if (RefVal) {
1010 auto CUSize = DieCU->getNextUnitOffset() - DieCU->getOffset();
1011 auto CUOffset = AttrValue.Value.getRawUValue();
1012 if (CUOffset >= CUSize) {
1013 ++NumErrors;
1014 ErrorCategory.Report("Invalid CU offset", [&]() {
1015 error() << formatv("{0} CU offset {1:x+8} is invalid (must be less "
1016 "than CU size of {2:x+8}):\n",
1017 FormEncodingString(Form), CUOffset, CUSize);
1018 Die.dump(OS, 0, DumpOpts);
1019 dump(Die) << '\n';
1020 });
1021 } else {
1022 // Valid reference, but we will verify it points to an actual
1023 // DIE later.
1024 LocalReferences[AttrValue.Value.getUnit()->getOffset() + *RefVal]
1025 .insert(Die.getOffset());
1026 }
1027 }
1028 break;
1029 }
1030 case DW_FORM_ref_addr: {
1031 // Verify all absolute DIE references have valid offsets in the
1032 // .debug_info section.
1033 std::optional<uint64_t> RefVal = AttrValue.Value.getAsDebugInfoReference();
1034 assert(RefVal);
1035 if (RefVal) {
1036 if (*RefVal >= DieCU->getInfoSection().Data.size()) {
1037 ++NumErrors;
1038 ErrorCategory.Report("DW_FORM_ref_addr offset out of bounds", [&]() {
1039 error() << "DW_FORM_ref_addr offset beyond .debug_info "
1040 "bounds:\n";
1041 dump(Die) << '\n';
1042 });
1043 } else {
1044 // Valid reference, but we will verify it points to an actual
1045 // DIE later.
1046 CrossUnitReferences[*RefVal].insert(Die.getOffset());
1047 }
1048 }
1049 break;
1050 }
1051 case DW_FORM_strp:
1052 case DW_FORM_strx:
1053 case DW_FORM_strx1:
1054 case DW_FORM_strx2:
1055 case DW_FORM_strx3:
1056 case DW_FORM_strx4:
1057 case DW_FORM_line_strp: {
1058 if (Error E = AttrValue.Value.getAsCString().takeError()) {
1059 ++NumErrors;
1060 std::string ErrMsg = toString(std::move(E));
1061 ErrorCategory.Report("Invalid DW_FORM attribute", [&]() {
1062 error() << formatv("{0}:\n", ErrMsg);
1063 dump(Die) << '\n';
1064 });
1065 }
1066 break;
1067 }
1068 default:
1069 break;
1070 }
1071 return NumErrors;
1072}
1073
1074unsigned DWARFVerifier::verifyDebugInfoReferences(
1075 const ReferenceMap &References,
1076 llvm::function_ref<DWARFUnit *(uint64_t)> GetUnitForOffset) {
1077 auto GetDIEForOffset = [&](uint64_t Offset) {
1078 if (DWARFUnit *U = GetUnitForOffset(Offset))
1079 return U->getDIEForOffset(Offset);
1080 return DWARFDie();
1081 };
1082 unsigned NumErrors = 0;
1083 for (const std::pair<const uint64_t, std::set<uint64_t>> &Pair : References) {
1084 if (GetDIEForOffset(Pair.first))
1085 continue;
1086 ++NumErrors;
1087 ErrorCategory.Report("Invalid DIE reference", [&]() {
1088 error() << formatv(
1089 "invalid DIE reference {0:x+8}. Offset is in between DIEs:\n",
1090 Pair.first);
1091 for (auto Offset : Pair.second)
1092 dump(GetDIEForOffset(Offset)) << '\n';
1093 OS << "\n";
1094 });
1095 }
1096 return NumErrors;
1097}
1098
1099void DWARFVerifier::verifyDebugLineStmtOffsets() {
1100 std::map<uint64_t, DWARFDie> StmtListToDie;
1101 for (const auto &CU : DCtx.compile_units()) {
1102 auto Die = CU->getUnitDIE();
1103 // Get the attribute value as a section offset. No need to produce an
1104 // error here if the encoding isn't correct because we validate this in
1105 // the .debug_info verifier.
1106 auto StmtSectionOffset = toSectionOffset(Die.find(DW_AT_stmt_list));
1107 if (!StmtSectionOffset)
1108 continue;
1109 const uint64_t LineTableOffset = *StmtSectionOffset;
1110 auto LineTable = DCtx.getLineTableForUnit(CU.get());
1111 if (LineTableOffset < DCtx.getDWARFObj().getLineSection().Data.size()) {
1112 if (!LineTable) {
1113 ++NumDebugLineErrors;
1114 ErrorCategory.Report("Unparsable .debug_line entry", [&]() {
1115 error() << formatv(
1116 ".debug_line[{0:x+8}] was not able to be parsed for CU:\n",
1117 LineTableOffset);
1118 dump(Die) << '\n';
1119 });
1120 continue;
1121 }
1122 } else {
1123 // Make sure we don't get a valid line table back if the offset is wrong.
1124 assert(LineTable == nullptr);
1125 // Skip this line table as it isn't valid. No need to create an error
1126 // here because we validate this in the .debug_info verifier.
1127 continue;
1128 }
1129 auto [Iter, Inserted] = StmtListToDie.try_emplace(LineTableOffset, Die);
1130 if (!Inserted) {
1131 ++NumDebugLineErrors;
1132 const auto &OldDie = Iter->second;
1133 ErrorCategory.Report("Identical DW_AT_stmt_list section offset", [&]() {
1134 error() << formatv("two compile unit DIEs, {0:x+8} and {1:x+8}, have "
1135 "the same DW_AT_stmt_list section offset:\n",
1136 OldDie.getOffset(), Die.getOffset());
1137 dump(OldDie);
1138 dump(Die) << '\n';
1139 });
1140 // Already verified this line table before, no need to do it again.
1141 }
1142 }
1143}
1144
1145void DWARFVerifier::verifyDebugLineRows() {
1146 for (const auto &CU : DCtx.compile_units()) {
1147 auto Die = CU->getUnitDIE();
1148 auto LineTable = DCtx.getLineTableForUnit(CU.get());
1149 // If there is no line table we will have created an error in the
1150 // .debug_info verifier or in verifyDebugLineStmtOffsets().
1151 if (!LineTable)
1152 continue;
1153
1154 // Verify prologue.
1155 bool isDWARF5 = LineTable->Prologue.getVersion() >= 5;
1156 uint32_t MaxDirIndex = LineTable->Prologue.IncludeDirectories.size();
1157 uint32_t MinFileIndex = isDWARF5 ? 0 : 1;
1158 uint32_t FileIndex = MinFileIndex;
1159 StringMap<uint16_t> FullPathMap;
1160 for (const auto &FileName : LineTable->Prologue.FileNames) {
1161 // Verify directory index.
1162 if (FileName.DirIdx > MaxDirIndex) {
1163 ++NumDebugLineErrors;
1164 ErrorCategory.Report(
1165 "Invalid index in .debug_line->prologue.file_names->dir_idx",
1166 [&]() {
1167 error() << formatv(".debug_line[{0:x+8}].prologue.file_names[{1}]"
1168 ".dir_idx contains an invalid index: {2}\n",
1169 *toSectionOffset(Die.find(DW_AT_stmt_list)),
1170 FileIndex, FileName.DirIdx);
1171 });
1172 }
1173
1174 // Check file paths for duplicates.
1175 std::string FullPath;
1176 const bool HasFullPath = LineTable->getFileNameByIndex(
1177 FileIndex, CU->getCompilationDir(),
1179 assert(HasFullPath && "Invalid index?");
1180 (void)HasFullPath;
1181 auto [It, Inserted] = FullPathMap.try_emplace(FullPath, FileIndex);
1182 if (!Inserted && It->second != FileIndex && DumpOpts.Verbose) {
1183 warn() << formatv(".debug_line[{0:x+8}].prologue.file_names[{1}] is a "
1184 "duplicate of file_names[{2}]\n",
1185 *toSectionOffset(Die.find(DW_AT_stmt_list)),
1186 FileIndex, It->second);
1187 }
1188
1189 FileIndex++;
1190 }
1191
1192 // Nothing to verify in a line table with a single row containing the end
1193 // sequence.
1194 if (LineTable->Rows.size() == 1 && LineTable->Rows.front().EndSequence)
1195 continue;
1196
1197 // Verify rows.
1198 uint64_t PrevAddress = 0;
1199 uint32_t RowIndex = 0;
1200 for (const auto &Row : LineTable->Rows) {
1201 // Verify row address.
1202 if (Row.Address.Address < PrevAddress) {
1203 ++NumDebugLineErrors;
1204 ErrorCategory.Report(
1205 "decreasing address between debug_line rows", [&]() {
1206 error() << formatv(".debug_line[{0:x+8}] row[{1}] decreases in "
1207 "address from previous row:\n",
1208 *toSectionOffset(Die.find(DW_AT_stmt_list)),
1209 RowIndex);
1210
1212 if (RowIndex > 0)
1213 LineTable->Rows[RowIndex - 1].dump(OS);
1214 Row.dump(OS);
1215 OS << '\n';
1216 });
1217 }
1218
1219 if (!LineTable->hasFileAtIndex(Row.File)) {
1220 ++NumDebugLineErrors;
1221 ErrorCategory.Report("Invalid file index in debug_line", [&]() {
1222 error() << formatv(".debug_line[{0:x+8}][{1}] has invalid file index "
1223 "{2} (valid values are [{3},{4}{5}):\n",
1224 *toSectionOffset(Die.find(DW_AT_stmt_list)),
1225 RowIndex, Row.File, MinFileIndex,
1226 LineTable->Prologue.FileNames.size(),
1227 (isDWARF5 ? ")" : "]"));
1229 Row.dump(OS);
1230 OS << '\n';
1231 });
1232 }
1233 if (Row.EndSequence)
1234 PrevAddress = 0;
1235 else
1236 PrevAddress = Row.Address.Address;
1237 ++RowIndex;
1238 }
1239 }
1240}
1241
1243 DIDumpOptions DumpOpts)
1244 : OS(S), DCtx(D), DumpOpts(std::move(DumpOpts)), IsObjectFile(false),
1245 IsMachOObject(false) {
1246 ErrorCategory.ShowDetail(this->DumpOpts.Verbose ||
1247 !this->DumpOpts.ShowAggregateErrors);
1248 if (const auto *F = DCtx.getDWARFObj().getFile()) {
1249 IsObjectFile = F->isRelocatableObject();
1250 IsMachOObject = F->isMachO();
1251 }
1252}
1253
1255 NumDebugLineErrors = 0;
1256 OS << "Verifying .debug_line...\n";
1257 verifyDebugLineStmtOffsets();
1258 verifyDebugLineRows();
1259 return NumDebugLineErrors == 0;
1260}
1261
1262void DWARFVerifier::verifyAppleAccelTable(const DWARFSection *AccelSection,
1263 DataExtractor *StrData,
1264 const char *SectionName) {
1265 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), *AccelSection,
1266 DCtx.isLittleEndian(), 0);
1267 AppleAcceleratorTable AccelTable(AccelSectionData, *StrData);
1268
1269 OS << "Verifying " << SectionName << "...\n";
1270
1271 // Verify that the fixed part of the header is not too short.
1272 if (!AccelSectionData.isValidOffset(AccelTable.getSizeHdr())) {
1273 ErrorCategory.Report("Section is too small to fit a section header", [&]() {
1274 error() << "Section is too small to fit a section header.\n";
1275 });
1276 return;
1277 }
1278
1279 // Verify that the section is not too short.
1280 if (Error E = AccelTable.extract()) {
1281 std::string Msg = toString(std::move(E));
1282 ErrorCategory.Report("Section is too small to fit a section header",
1283 [&]() { error() << Msg << '\n'; });
1284 return;
1285 }
1286
1287 // Verify that all buckets have a valid hash index or are empty.
1288 uint32_t NumBuckets = AccelTable.getNumBuckets();
1289 uint32_t NumHashes = AccelTable.getNumHashes();
1290
1291 uint64_t BucketsOffset =
1292 AccelTable.getSizeHdr() + AccelTable.getHeaderDataLength();
1293 uint64_t HashesBase = BucketsOffset + NumBuckets * 4;
1294 uint64_t OffsetsBase = HashesBase + NumHashes * 4;
1295 for (uint32_t BucketIdx = 0; BucketIdx < NumBuckets; ++BucketIdx) {
1296 uint32_t HashIdx = AccelSectionData.getU32(&BucketsOffset);
1297 if (HashIdx >= NumHashes && HashIdx != UINT32_MAX) {
1298 ErrorCategory.Report("Invalid hash index", [&]() {
1299 error() << formatv("Bucket[{0}] has invalid hash index: {1}.\n",
1300 BucketIdx, HashIdx);
1301 });
1302 }
1303 }
1304 uint32_t NumAtoms = AccelTable.getAtomsDesc().size();
1305 if (NumAtoms == 0) {
1306 ErrorCategory.Report("No atoms", [&]() {
1307 error() << "No atoms: failed to read HashData.\n";
1308 });
1309 return;
1310 }
1311 if (!AccelTable.validateForms()) {
1312 ErrorCategory.Report("Unsupported form", [&]() {
1313 error() << "Unsupported form: failed to read HashData.\n";
1314 });
1315 return;
1316 }
1317
1318 for (uint32_t HashIdx = 0; HashIdx < NumHashes; ++HashIdx) {
1319 uint64_t HashOffset = HashesBase + 4 * HashIdx;
1320 uint64_t DataOffset = OffsetsBase + 4 * HashIdx;
1321 uint32_t Hash = AccelSectionData.getU32(&HashOffset);
1322 uint64_t HashDataOffset = AccelSectionData.getU32(&DataOffset);
1323 if (!AccelSectionData.isValidOffsetForDataOfSize(HashDataOffset,
1324 sizeof(uint64_t))) {
1325 ErrorCategory.Report("Invalid HashData offset", [&]() {
1326 error() << formatv("Hash[{0}] has invalid HashData offset: {1:x+8}.\n",
1327 HashIdx, HashDataOffset);
1328 });
1329 }
1330
1331 uint64_t StrpOffset;
1332 uint64_t StringOffset;
1333 uint32_t StringCount = 0;
1335 unsigned Tag;
1336 while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) {
1337 const uint32_t NumHashDataObjects =
1338 AccelSectionData.getU32(&HashDataOffset);
1339 for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects;
1340 ++HashDataIdx) {
1341 std::tie(Offset, Tag) = AccelTable.readAtoms(&HashDataOffset);
1342 auto Die = DCtx.getDIEForOffset(Offset);
1343 if (!Die) {
1344 const uint32_t BucketIdx =
1345 NumBuckets ? (Hash % NumBuckets) : UINT32_MAX;
1346 StringOffset = StrpOffset;
1347 const char *Name = StrData->getCStr(&StringOffset);
1348 if (!Name)
1349 Name = "<NULL>";
1350
1351 ErrorCategory.Report("Invalid DIE offset", [&]() {
1352 error() << formatv("{0} Bucket[{1}] Hash[{2}] = {3:x+8} "
1353 "Str[{4}] = {5:x+8} DIE[{6}] = {7:x+8} "
1354 "is not a valid DIE offset for \"{8}\".\n",
1355 SectionName, BucketIdx, HashIdx, Hash,
1356 StringCount, StrpOffset, HashDataIdx, Offset,
1357 Name);
1358 });
1359 continue;
1360 }
1361 if ((Tag != dwarf::DW_TAG_null) && (Die.getTag() != Tag)) {
1362 ErrorCategory.Report("Mismatched Tag in accellerator table", [&]() {
1363 error() << formatv("Tag {0} in accelerator table does not match "
1364 "Tag {1} of DIE[{2}].\n",
1366 dwarf::TagString(Die.getTag()), HashDataIdx);
1367 });
1368 }
1369 }
1370 }
1371 }
1372}
1373
1374void DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) {
1375 // A map from CU offset to the (first) Name Index offset which claims to index
1376 // this CU.
1377 DenseMap<uint64_t, uint64_t> CUMap;
1378 CUMap.reserve(DCtx.getNumCompileUnits());
1379
1380 DenseSet<uint64_t> CUOffsets;
1381 for (const auto &CU : DCtx.compile_units())
1382 CUOffsets.insert(CU->getOffset());
1383
1384 parallelForEach(AccelTable, [&](const DWARFDebugNames::NameIndex &NI) {
1385 if (NI.getCUCount() == 0) {
1386 ErrorCategory.Report("Name Index doesn't index any CU", [&]() {
1387 error() << formatv("Name Index @ {0:x} does not index any CU\n",
1388 NI.getUnitOffset());
1389 });
1390 return;
1391 }
1392 for (uint32_t CU = 0, End = NI.getCUCount(); CU < End; ++CU) {
1393 uint64_t Offset = NI.getCUOffset(CU);
1394 if (!CUOffsets.count(Offset)) {
1395 ErrorCategory.Report("Name Index references non-existing CU", [&]() {
1396 error() << formatv(
1397 "Name Index @ {0:x} references a non-existing CU @ {1:x}\n",
1398 NI.getUnitOffset(), Offset);
1399 });
1400 continue;
1401 }
1402 uint64_t DuplicateCUOffset = 0;
1403 {
1404 std::lock_guard<std::mutex> Lock(AccessMutex);
1405 auto Iter = CUMap.find(Offset);
1406 if (Iter != CUMap.end())
1407 DuplicateCUOffset = Iter->second;
1408 else
1409 CUMap[Offset] = NI.getUnitOffset();
1410 }
1411 if (DuplicateCUOffset) {
1412 ErrorCategory.Report("Duplicate Name Index", [&]() {
1413 error() << formatv(
1414 "Name Index @ {0:x} references a CU @ {1:x}, but "
1415 "this CU is already indexed by Name Index @ {2:x}\n",
1416 NI.getUnitOffset(), Offset, DuplicateCUOffset);
1417 });
1418 continue;
1419 }
1420 }
1421 });
1422
1423 for (const auto &CU : DCtx.compile_units()) {
1424 if (CUMap.count(CU->getOffset()) == 0)
1425 warn() << formatv("CU @ {0:x} not covered by any Name Index\n",
1426 CU->getOffset());
1427 }
1428}
1429
1430void DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI,
1431 const DataExtractor &StrData) {
1432 struct BucketInfo {
1433 uint32_t Bucket;
1434 uint32_t Index;
1435
1436 constexpr BucketInfo(uint32_t Bucket, uint32_t Index)
1437 : Bucket(Bucket), Index(Index) {}
1438 bool operator<(const BucketInfo &RHS) const { return Index < RHS.Index; }
1439 };
1440
1441 if (NI.getBucketCount() == 0) {
1442 warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n",
1443 NI.getUnitOffset());
1444 return;
1445 }
1446
1447 // Build up a list of (Bucket, Index) pairs. We use this later to verify that
1448 // each Name is reachable from the appropriate bucket.
1449 std::vector<BucketInfo> BucketStarts;
1450 BucketStarts.reserve(NI.getBucketCount() + 1);
1451 const uint64_t OrigNumberOfErrors = ErrorCategory.GetNumErrors();
1452 for (uint32_t Bucket = 0, End = NI.getBucketCount(); Bucket < End; ++Bucket) {
1453 uint32_t Index = NI.getBucketArrayEntry(Bucket);
1454 if (Index > NI.getNameCount()) {
1455 ErrorCategory.Report("Name Index Bucket contains invalid value", [&]() {
1456 error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid "
1457 "value {2}. Valid range is [0, {3}].\n",
1458 Bucket, NI.getUnitOffset(), Index,
1459 NI.getNameCount());
1460 });
1461 continue;
1462 }
1463 if (Index > 0)
1464 BucketStarts.emplace_back(Bucket, Index);
1465 }
1466
1467 // If there were any buckets with invalid values, skip further checks as they
1468 // will likely produce many errors which will only confuse the actual root
1469 // problem.
1470 if (OrigNumberOfErrors != ErrorCategory.GetNumErrors())
1471 return;
1472
1473 // Sort the list in the order of increasing "Index" entries.
1474 array_pod_sort(BucketStarts.begin(), BucketStarts.end());
1475
1476 // Insert a sentinel entry at the end, so we can check that the end of the
1477 // table is covered in the loop below.
1478 BucketStarts.emplace_back(NI.getBucketCount(), NI.getNameCount() + 1);
1479
1480 // Loop invariant: NextUncovered is the (1-based) index of the first Name
1481 // which is not reachable by any of the buckets we processed so far (and
1482 // hasn't been reported as uncovered).
1483 uint32_t NextUncovered = 1;
1484 for (const BucketInfo &B : BucketStarts) {
1485 // Under normal circumstances B.Index be equal to NextUncovered, but it can
1486 // be less if a bucket points to names which are already known to be in some
1487 // bucket we processed earlier. In that case, we won't trigger this error,
1488 // but report the mismatched hash value error instead. (We know the hash
1489 // will not match because we have already verified that the name's hash
1490 // puts it into the previous bucket.)
1491 if (B.Index > NextUncovered) {
1492 ErrorCategory.Report("Name table entries uncovered by hash table", [&]() {
1493 error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] "
1494 "are not covered by the hash table.\n",
1495 NI.getUnitOffset(), NextUncovered, B.Index - 1);
1496 });
1497 }
1498 uint32_t Idx = B.Index;
1499
1500 // The rest of the checks apply only to non-sentinel entries.
1501 if (B.Bucket == NI.getBucketCount())
1502 break;
1503
1504 // This triggers if a non-empty bucket points to a name with a mismatched
1505 // hash. Clients are likely to interpret this as an empty bucket, because a
1506 // mismatched hash signals the end of a bucket, but if this is indeed an
1507 // empty bucket, the producer should have signalled this by marking the
1508 // bucket as empty.
1509 uint32_t FirstHash = NI.getHashArrayEntry(Idx);
1510 if (FirstHash % NI.getBucketCount() != B.Bucket) {
1511 ErrorCategory.Report("Name Index point to mismatched hash value", [&]() {
1512 error() << formatv(
1513 "Name Index @ {0:x}: Bucket {1} is not empty but points to a "
1514 "mismatched hash value {2:x} (belonging to bucket {3}).\n",
1515 NI.getUnitOffset(), B.Bucket, FirstHash,
1516 FirstHash % NI.getBucketCount());
1517 });
1518 }
1519
1520 // This find the end of this bucket and also verifies that all the hashes in
1521 // this bucket are correct by comparing the stored hashes to the ones we
1522 // compute ourselves.
1523 while (Idx <= NI.getNameCount()) {
1524 uint32_t Hash = NI.getHashArrayEntry(Idx);
1525 if (Hash % NI.getBucketCount() != B.Bucket)
1526 break;
1527
1528 const char *Str = NI.getNameTableEntry(Idx).getString();
1529 if (caseFoldingDjbHash(Str) != Hash) {
1530 ErrorCategory.Report(
1531 "String hash doesn't match Name Index hash", [&]() {
1532 error() << formatv(
1533 "Name Index @ {0:x}: String ({1}) at index {2} "
1534 "hashes to {3:x}, but "
1535 "the Name Index hash is {4:x}\n",
1536 NI.getUnitOffset(), Str, Idx, caseFoldingDjbHash(Str), Hash);
1537 });
1538 }
1539 ++Idx;
1540 }
1541 NextUncovered = std::max(NextUncovered, Idx);
1542 }
1543}
1544
1545void DWARFVerifier::verifyNameIndexAttribute(
1548 StringRef FormName = dwarf::FormEncodingString(AttrEnc.Form);
1549 if (FormName.empty()) {
1550 ErrorCategory.Report("Unknown NameIndex Abbreviation", [&]() {
1551 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1552 "unknown form: {3}.\n",
1553 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1554 AttrEnc.Form);
1555 });
1556 return;
1557 }
1558
1559 if (AttrEnc.Index == DW_IDX_type_hash) {
1560 if (AttrEnc.Form != dwarf::DW_FORM_data8) {
1561 ErrorCategory.Report("Unexpected NameIndex Abbreviation", [&]() {
1562 error() << formatv(
1563 "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash "
1564 "uses an unexpected form {2} (should be {3}).\n",
1565 NI.getUnitOffset(), Abbr.Code, AttrEnc.Form, dwarf::DW_FORM_data8);
1566 });
1567 return;
1568 }
1569 return;
1570 }
1571
1572 if (AttrEnc.Index == dwarf::DW_IDX_parent) {
1573 constexpr static auto AllowedForms = {dwarf::Form::DW_FORM_flag_present,
1574 dwarf::Form::DW_FORM_ref4};
1575 if (!is_contained(AllowedForms, AttrEnc.Form)) {
1576 ErrorCategory.Report("Unexpected NameIndex Abbreviation", [&]() {
1577 error() << formatv(
1578 "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_parent "
1579 "uses an unexpected form {2} (should be "
1580 "DW_FORM_ref4 or DW_FORM_flag_present).\n",
1581 NI.getUnitOffset(), Abbr.Code, AttrEnc.Form);
1582 });
1583 return;
1584 }
1585 return;
1586 }
1587
1588 // A list of known index attributes and their expected form classes.
1589 // DW_IDX_type_hash is handled specially in the check above, as it has a
1590 // specific form (not just a form class) we should expect.
1591 struct FormClassTable {
1594 StringLiteral ClassName;
1595 };
1596 static constexpr FormClassTable Table[] = {
1597 {dwarf::DW_IDX_compile_unit, DWARFFormValue::FC_Constant, {"constant"}},
1598 {dwarf::DW_IDX_type_unit, DWARFFormValue::FC_Constant, {"constant"}},
1599 {dwarf::DW_IDX_die_offset, DWARFFormValue::FC_Reference, {"reference"}},
1600 };
1601
1603 auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) {
1604 return T.Index == AttrEnc.Index;
1605 });
1606 if (Iter == TableRef.end()) {
1607 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an "
1608 "unknown index attribute: {2}.\n",
1609 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index);
1610 return;
1611 }
1612
1613 if (!DWARFFormValue(AttrEnc.Form).isFormClass(Iter->Class)) {
1614 ErrorCategory.Report("Unexpected NameIndex Abbreviation", [&]() {
1615 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1616 "unexpected form {3} (expected form class {4}).\n",
1617 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1618 AttrEnc.Form, Iter->ClassName);
1619 });
1620 return;
1621 }
1622}
1623
1624void DWARFVerifier::verifyNameIndexAbbrevs(
1625 const DWARFDebugNames::NameIndex &NI) {
1626 for (const auto &Abbrev : NI.getAbbrevs()) {
1627 StringRef TagName = dwarf::TagString(Abbrev.Tag);
1628 if (TagName.empty()) {
1629 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an "
1630 "unknown tag: {2}.\n",
1631 NI.getUnitOffset(), Abbrev.Code, Abbrev.Tag);
1632 }
1633 SmallSet<unsigned, 5> Attributes;
1634 for (const auto &AttrEnc : Abbrev.Attributes) {
1635 if (!Attributes.insert(AttrEnc.Index).second) {
1636 ErrorCategory.Report(
1637 "NameIndex Abbreviateion contains multiple attributes", [&]() {
1638 error() << formatv(
1639 "NameIndex @ {0:x}: Abbreviation {1:x} contains "
1640 "multiple {2} attributes.\n",
1641 NI.getUnitOffset(), Abbrev.Code, AttrEnc.Index);
1642 });
1643 continue;
1644 }
1645 verifyNameIndexAttribute(NI, Abbrev, AttrEnc);
1646 }
1647
1648 if (NI.getCUCount() > 1 && !Attributes.count(dwarf::DW_IDX_compile_unit) &&
1649 !Attributes.count(dwarf::DW_IDX_type_unit)) {
1650 ErrorCategory.Report("Abbreviation contains no attribute", [&]() {
1651 error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units "
1652 "and abbreviation {1:x} has no DW_IDX_compile_unit "
1653 "or DW_IDX_type_unit attribute.\n",
1654 NI.getUnitOffset(), Abbrev.Code);
1655 });
1656 }
1657 if (!Attributes.count(dwarf::DW_IDX_die_offset)) {
1658 ErrorCategory.Report("Abbreviate in NameIndex missing attribute", [&]() {
1659 error() << formatv(
1660 "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n",
1661 NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset);
1662 });
1663 }
1664 }
1665}
1666
1667/// Constructs a full name for a DIE. Potentially it does recursive lookup on
1668/// DIEs. This can lead to extraction of DIEs in a different CU or TU.
1670 bool IncludeStrippedTemplateNames,
1671 bool IncludeObjCNames = true,
1672 bool IncludeLinkageName = true) {
1674 if (const char *Str = DIE.getShortName()) {
1675 StringRef Name(Str);
1676 Result.emplace_back(Name);
1677 if (IncludeStrippedTemplateNames) {
1678 if (std::optional<StringRef> StrippedName =
1679 StripTemplateParameters(Result.back()))
1680 // Convert to std::string and push; emplacing the StringRef may trigger
1681 // a vector resize which may destroy the StringRef memory.
1682 Result.push_back(StrippedName->str());
1683 }
1684
1685 if (IncludeObjCNames) {
1686 if (std::optional<ObjCSelectorNames> ObjCNames =
1687 getObjCNamesIfSelector(Name)) {
1688 Result.emplace_back(ObjCNames->ClassName);
1689 Result.emplace_back(ObjCNames->Selector);
1690 if (ObjCNames->ClassNameNoCategory)
1691 Result.emplace_back(*ObjCNames->ClassNameNoCategory);
1692 if (ObjCNames->MethodNameNoCategory)
1693 Result.push_back(std::move(*ObjCNames->MethodNameNoCategory));
1694 }
1695 }
1696 } else if (DIE.getTag() == dwarf::DW_TAG_namespace)
1697 Result.emplace_back("(anonymous namespace)");
1698
1699 if (IncludeLinkageName) {
1700 if (const char *Str = DIE.getLinkageName())
1701 Result.emplace_back(Str);
1702 }
1703
1704 return Result;
1705}
1706
1707void DWARFVerifier::verifyNameIndexEntries(
1710 const DenseMap<uint64_t, DWARFUnit *> &CUOffsetsToDUMap) {
1711 const char *CStr = NTE.getString();
1712 if (!CStr) {
1713 ErrorCategory.Report("Unable to get string associated with name", [&]() {
1714 error() << formatv("Name Index @ {0:x}: Unable to get string associated "
1715 "with name {1}.\n",
1716 NI.getUnitOffset(), NTE.getIndex());
1717 });
1718 return;
1719 }
1720 StringRef Str(CStr);
1721 unsigned NumEntries = 0;
1722 uint64_t EntryID = NTE.getEntryOffset();
1723 uint64_t NextEntryID = EntryID;
1724 Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&NextEntryID);
1725 for (; EntryOr; ++NumEntries, EntryID = NextEntryID,
1726 EntryOr = NI.getEntry(&NextEntryID)) {
1727
1728 std::optional<uint64_t> CUIndex = EntryOr->getRelatedCUIndex();
1729 std::optional<uint64_t> TUIndex = EntryOr->getTUIndex();
1730 if (CUIndex && *CUIndex >= NI.getCUCount()) {
1731 ErrorCategory.Report("Name Index entry contains invalid CU index", [&]() {
1732 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
1733 "invalid CU index ({2}).\n",
1734 NI.getUnitOffset(), EntryID, *CUIndex);
1735 });
1736 continue;
1737 }
1738 const uint32_t NumLocalTUs = NI.getLocalTUCount();
1739 const uint32_t NumForeignTUs = NI.getForeignTUCount();
1740 if (TUIndex && *TUIndex >= (NumLocalTUs + NumForeignTUs)) {
1741 ErrorCategory.Report("Name Index entry contains invalid TU index", [&]() {
1742 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
1743 "invalid TU index ({2}).\n",
1744 NI.getUnitOffset(), EntryID, *TUIndex);
1745 });
1746 continue;
1747 }
1748 std::optional<uint64_t> UnitOffset;
1749 if (TUIndex) {
1750 // We have a local or foreign type unit.
1751 if (*TUIndex >= NumLocalTUs) {
1752 // This is a foreign type unit, we will find the right type unit by
1753 // type unit signature later in this function.
1754
1755 // Foreign type units must have a valid CU index, either from a
1756 // DW_IDX_comp_unit attribute value or from the .debug_names table only
1757 // having a single compile unit. We need the originating compile unit
1758 // because foreign type units can come from any .dwo file, yet only one
1759 // copy of the type unit will end up in the .dwp file.
1760 if (CUIndex) {
1761 // We need the local skeleton unit offset for the code below.
1762 UnitOffset = NI.getCUOffset(*CUIndex);
1763 } else {
1764 ErrorCategory.Report(
1765 "Name Index entry contains foreign TU index with invalid CU "
1766 "index",
1767 [&]() {
1768 error() << formatv(
1769 "Name Index @ {0:x}: Entry @ {1:x} contains an "
1770 "foreign TU index ({2}) with no CU index.\n",
1771 NI.getUnitOffset(), EntryID, *TUIndex);
1772 });
1773 continue;
1774 }
1775 } else {
1776 // Local type unit, get the DWARF unit offset for the type unit.
1777 UnitOffset = NI.getLocalTUOffset(*TUIndex);
1778 }
1779 } else if (CUIndex) {
1780 // Local CU entry, get the DWARF unit offset for the CU.
1781 UnitOffset = NI.getCUOffset(*CUIndex);
1782 }
1783
1784 // Watch for tombstoned type unit entries.
1785 if (!UnitOffset || UnitOffset == UINT32_MAX)
1786 continue;
1787 // For split DWARF entries we need to make sure we find the non skeleton
1788 // DWARF unit that is needed and use that's DWARF unit offset as the
1789 // DIE offset to add the DW_IDX_die_offset to.
1790 DWARFUnit *DU = DCtx.getUnitForOffset(*UnitOffset);
1791 if (DU == nullptr || DU->getOffset() != *UnitOffset) {
1792 // If we didn't find a DWARF Unit from the UnitOffset, or if the offset
1793 // of the unit doesn't match exactly, report an error.
1794 ErrorCategory.Report(
1795 "Name Index entry contains invalid CU or TU offset", [&]() {
1796 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
1797 "invalid CU or TU offset {2:x}.\n",
1798 NI.getUnitOffset(), EntryID, *UnitOffset);
1799 });
1800 continue;
1801 }
1802 // This function will try to get the non skeleton unit DIE, but if it is
1803 // unable to load the .dwo file from the .dwo or .dwp, it will return the
1804 // unit DIE of the DWARFUnit in "DU". So we need to check if the DWARFUnit
1805 // has a .dwo file, but we couldn't load it.
1806
1807 // FIXME: Need a follow up patch to fix usage of
1808 // DWARFUnit::getNonSkeletonUnitDIE() so that it returns an empty DWARFDie
1809 // if the .dwo file isn't available and clean up other uses of this function
1810 // call to properly deal with it. It isn't clear that getNonSkeletonUnitDIE
1811 // will return the unit DIE of DU if we aren't able to get the .dwo file,
1812 // but that is what the function currently does.
1813 // A CU is a skeleton CU only when DWARF 5+ tags it as DW_TAG_skeleton_unit,
1814 // or when, in older DWARF, the CU has no children.
1815 DWARFDie UnitDie = DU->getUnitDIE();
1816 auto IsSkeletonCU = [&]() {
1817 if (DU->getVersion() >= 5)
1818 return UnitDie.getTag() == dwarf::DW_TAG_skeleton_unit;
1819 return !UnitDie.hasChildren();
1820 };
1821 bool IsSkeleton = DU->getDWOId() && IsSkeletonCU();
1822 DWARFUnit *NonSkeletonUnit = nullptr;
1823 if (IsSkeleton) {
1824 auto Iter = CUOffsetsToDUMap.find(DU->getOffset());
1825 NonSkeletonUnit = Iter->second;
1826 } else {
1827 NonSkeletonUnit = DU;
1828 }
1829 if (IsSkeleton && !NonSkeletonUnit->isDWOUnit()) {
1830 ErrorCategory.Report("Unable to get load .dwo file", [&]() {
1831 error() << formatv(
1832 "Name Index @ {0:x}: Entry @ {1:x} unable to load "
1833 ".dwo file \"{2}\" for DWARF unit @ {3:x}.\n",
1834 NI.getUnitOffset(), EntryID,
1835 dwarf::toString(UnitDie.find({DW_AT_dwo_name, DW_AT_GNU_dwo_name})),
1836 *UnitOffset);
1837 });
1838 continue;
1839 }
1840
1841 if (TUIndex && *TUIndex >= NumLocalTUs) {
1842 // We have a foreign TU index, which either means we have a .dwo file
1843 // that has one or more type units, or we have a .dwp file with one or
1844 // more type units. We need to get the type unit from the DWARFContext
1845 // of the .dwo. We got the NonSkeletonUnitDie above that has the .dwo
1846 // or .dwp DWARF context, so we have to get the type unit from that file.
1847 // We have also verified that NonSkeletonUnitDie points to a DWO file
1848 // above, so we know we have the right file.
1849 const uint32_t ForeignTUIdx = *TUIndex - NumLocalTUs;
1850 const uint64_t TypeSig = NI.getForeignTUSignature(ForeignTUIdx);
1851 llvm::DWARFContext &NonSkeletonDCtx = NonSkeletonUnit->getContext();
1852 // Now find the type unit from the type signature and then update the
1853 // NonSkeletonUnitDie to point to the actual type unit in the .dwo/.dwp.
1854 NonSkeletonUnit =
1855 NonSkeletonDCtx.getTypeUnitForHash(TypeSig, /*IsDWO=*/true);
1856 // If we have foreign type unit in a DWP file, then we need to ignore
1857 // any entries from type units that don't match the one that made it into
1858 // the .dwp file.
1859 if (NonSkeletonDCtx.isDWP()) {
1860 DWARFDie NonSkeletonUnitDie = NonSkeletonUnit->getUnitDIE(true);
1861 StringRef DUDwoName = dwarf::toStringRef(
1862 UnitDie.find({DW_AT_dwo_name, DW_AT_GNU_dwo_name}));
1863 StringRef TUDwoName = dwarf::toStringRef(
1864 NonSkeletonUnitDie.find({DW_AT_dwo_name, DW_AT_GNU_dwo_name}));
1865 if (DUDwoName != TUDwoName)
1866 continue; // Skip this TU, it isn't the one in the .dwp file.
1867 }
1868 }
1869 uint64_t DIEOffset =
1870 NonSkeletonUnit->getOffset() + *EntryOr->getDIEUnitOffset();
1871 const uint64_t NextUnitOffset = NonSkeletonUnit->getNextUnitOffset();
1872 // DIE offsets are relative to the specified CU or TU. Make sure the DIE
1873 // offsets is a valid relative offset.
1874 if (DIEOffset >= NextUnitOffset) {
1875 ErrorCategory.Report("NameIndex relative DIE offset too large", [&]() {
1876 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
1877 "DIE @ {2:x} when CU or TU ends at {3:x}.\n",
1878 NI.getUnitOffset(), EntryID, DIEOffset,
1879 NextUnitOffset);
1880 });
1881 continue;
1882 }
1883 DWARFDie DIE = NonSkeletonUnit->getDIEForOffset(DIEOffset);
1884 if (!DIE) {
1885 ErrorCategory.Report("NameIndex references nonexistent DIE", [&]() {
1886 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
1887 "non-existing DIE @ {2:x}.\n",
1888 NI.getUnitOffset(), EntryID, DIEOffset);
1889 });
1890 continue;
1891 }
1892 // Only compare the DIE we found's DWARFUnit offset if the DIE lives in
1893 // the DWARFUnit from the DW_IDX_comp_unit or DW_IDX_type_unit. If we are
1894 // using split DWARF, then the DIE's DWARFUnit doesn't need to match the
1895 // skeleton unit.
1896 if (DIE.getDwarfUnit() == DU &&
1897 DIE.getDwarfUnit()->getOffset() != *UnitOffset) {
1898 ErrorCategory.Report("Name index contains mismatched CU of DIE", [&]() {
1899 error() << formatv(
1900 "Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of "
1901 "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n",
1902 NI.getUnitOffset(), EntryID, DIEOffset, *UnitOffset,
1903 DIE.getDwarfUnit()->getOffset());
1904 });
1905 }
1906 if (DIE.getTag() != EntryOr->tag()) {
1907 ErrorCategory.Report("Name Index contains mismatched Tag of DIE", [&]() {
1908 error() << formatv(
1909 "Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of "
1910 "DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1911 NI.getUnitOffset(), EntryID, DIEOffset, EntryOr->tag(),
1912 DIE.getTag());
1913 });
1914 }
1915
1916 // We allow an extra name for functions: their name without any template
1917 // parameters.
1918 auto IncludeStrippedTemplateNames =
1919 DIE.getTag() == DW_TAG_subprogram ||
1920 DIE.getTag() == DW_TAG_inlined_subroutine;
1921 auto EntryNames = getNames(DIE, IncludeStrippedTemplateNames);
1922 if (!is_contained(EntryNames, Str)) {
1923 ErrorCategory.Report("Name Index contains mismatched name of DIE", [&]() {
1924 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name "
1925 "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1926 NI.getUnitOffset(), EntryID, DIEOffset, Str,
1927 make_range(EntryNames.begin(), EntryNames.end()));
1928 });
1929 }
1930 }
1932 EntryOr.takeError(),
1933 [&](const DWARFDebugNames::SentinelError &) {
1934 if (NumEntries > 0)
1935 return;
1936 ErrorCategory.Report(
1937 "NameIndex Name is not associated with any entries", [&]() {
1938 error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
1939 "not associated with any entries.\n",
1940 NI.getUnitOffset(), NTE.getIndex(), Str);
1941 });
1942 },
1943 [&](const ErrorInfoBase &Info) {
1944 ErrorCategory.Report("Uncategorized NameIndex error", [&]() {
1945 error() << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n",
1946 NI.getUnitOffset(), NTE.getIndex(), Str,
1947 Info.message());
1948 });
1949 });
1950}
1951
1952static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) {
1954 Die.getLocations(DW_AT_location);
1955 if (!Loc) {
1956 consumeError(Loc.takeError());
1957 return false;
1958 }
1959 DWARFUnit *U = Die.getDwarfUnit();
1960 for (const auto &Entry : *Loc) {
1961 DataExtractor Data(Entry.Expr, DCtx.isLittleEndian());
1962 DWARFExpression Expression(Data, U->getAddressByteSize(),
1963 U->getFormParams().Format);
1964 bool IsInteresting =
1965 Expression.isMemoryLocation() &&
1967 return !Op.isError() && (Op.getCode() == DW_OP_addr ||
1968 Op.getCode() == DW_OP_form_tls_address ||
1969 Op.getCode() == DW_OP_GNU_push_tls_address);
1970 });
1971 if (IsInteresting)
1972 return true;
1973 }
1974 return false;
1975}
1976
1977void DWARFVerifier::verifyNameIndexCompleteness(
1978 const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI,
1979 const StringMap<DenseSet<uint64_t>> &NamesToDieOffsets) {
1980
1981 // First check, if the Die should be indexed. The code follows the DWARF v5
1982 // wording as closely as possible.
1983
1984 // "All non-defining declarations (that is, debugging information entries
1985 // with a DW_AT_declaration attribute) are excluded."
1986 if (Die.find(DW_AT_declaration))
1987 return;
1988
1989 // "DW_TAG_namespace debugging information entries without a DW_AT_name
1990 // attribute are included with the name “(anonymous namespace)”.
1991 // All other debugging information entries without a DW_AT_name attribute
1992 // are excluded."
1993 // "If a subprogram or inlined subroutine is included, and has a
1994 // DW_AT_linkage_name attribute, there will be an additional index entry for
1995 // the linkage name."
1996 auto IncludeLinkageName = Die.getTag() == DW_TAG_subprogram ||
1997 Die.getTag() == DW_TAG_inlined_subroutine;
1998 // We *allow* stripped template names / ObjectiveC names as extra entries into
1999 // the table, but we don't *require* them to pass the completeness test.
2000 auto IncludeStrippedTemplateNames = false;
2001 auto IncludeObjCNames = false;
2002 auto EntryNames = getNames(Die, IncludeStrippedTemplateNames,
2003 IncludeObjCNames, IncludeLinkageName);
2004 if (EntryNames.empty())
2005 return;
2006
2007 // We deviate from the specification here, which says:
2008 // "The name index must contain an entry for each debugging information entry
2009 // that defines a named subprogram, label, variable, type, or namespace,
2010 // subject to ..."
2011 // Explicitly exclude all TAGs that we know shouldn't be indexed.
2012 switch (Die.getTag()) {
2013 // Compile units and modules have names but shouldn't be indexed.
2014 case DW_TAG_compile_unit:
2015 case DW_TAG_module:
2016 return;
2017
2018 // Function and template parameters are not globally visible, so we shouldn't
2019 // index them.
2020 case DW_TAG_formal_parameter:
2021 case DW_TAG_template_value_parameter:
2022 case DW_TAG_template_type_parameter:
2023 case DW_TAG_GNU_template_parameter_pack:
2024 case DW_TAG_GNU_template_template_param:
2025 return;
2026
2027 // Object members aren't globally visible. Properties are accessed through
2028 // their containing subprogram/type, not looked up globally by name, so
2029 // they belong in the same category.
2030 case DW_TAG_member:
2031 case DW_TAG_property:
2032 return;
2033
2034 // DW_TAG_LLVM_annotation DIEs attach metadata to other DIEs.
2035 // Their DW_AT_name carries the annotation kind, not a globally visible
2036 // symbol, so they should not be indexed.
2037 case DW_TAG_LLVM_annotation:
2038 return;
2039
2040 // According to a strict reading of the specification, enumerators should not
2041 // be indexed (and LLVM currently does not do that). However, this causes
2042 // problems for the debuggers, so we may need to reconsider this.
2043 case DW_TAG_enumerator:
2044 return;
2045
2046 // Imported declarations should not be indexed according to the specification
2047 // and LLVM currently does not do that.
2048 case DW_TAG_imported_declaration:
2049 return;
2050
2051 // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging
2052 // information entries without an address attribute (DW_AT_low_pc,
2053 // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded."
2054 case DW_TAG_subprogram:
2055 case DW_TAG_inlined_subroutine:
2056 case DW_TAG_label:
2057 if (Die.findRecursively(
2058 {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc}))
2059 break;
2060 return;
2061
2062 // "DW_TAG_variable debugging information entries with a DW_AT_location
2063 // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are
2064 // included; otherwise, they are excluded."
2065 //
2066 // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list.
2067 case DW_TAG_variable:
2068 if (isVariableIndexable(Die, DCtx))
2069 break;
2070 return;
2071
2072 default:
2073 break;
2074 }
2075
2076 // Now we know that our Die should be present in the Index. Let's check if
2077 // that's the case.
2078 uint64_t DieUnitOffset = Die.getOffset() - Die.getDwarfUnit()->getOffset();
2079 for (StringRef Name : EntryNames) {
2080 auto iter = NamesToDieOffsets.find(Name);
2081 if (iter == NamesToDieOffsets.end() || !iter->second.count(DieUnitOffset)) {
2082 ErrorCategory.Report(
2083 "Name Index DIE entry missing name",
2084 llvm::dwarf::TagString(Die.getTag()), [&]() {
2085 error() << formatv(
2086 "Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with "
2087 "name {3} missing.\n",
2088 NI.getUnitOffset(), Die.getOffset(), Die.getTag(), Name);
2089 });
2090 }
2091 }
2092}
2093
2094/// Extracts all the data for CU/TUs so we can access it in parallel without
2095/// locks.
2096static void extractCUsTus(DWARFContext &DCtx) {
2097 // Abbrev DeclSet is shared beween the units.
2098 for (auto &CUTU : DCtx.normal_units()) {
2099 CUTU->getUnitDIE();
2100 CUTU->getBaseAddress();
2101 }
2102 parallelForEach(DCtx.normal_units(), [&](const auto &CUTU) {
2103 if (Error E = CUTU->tryExtractDIEsIfNeeded(false))
2104 DCtx.getRecoverableErrorHandler()(std::move(E));
2105 });
2106
2107 // Invoking getNonSkeletonUnitDIE() sets up all the base pointers for DWO
2108 // Units. This is needed for getBaseAddress().
2109 for (const auto &CU : DCtx.compile_units()) {
2110 if (!CU->getDWOId())
2111 continue;
2112 DWARFContext &NonSkeletonContext =
2113 CU->getNonSkeletonUnitDIE().getDwarfUnit()->getContext();
2114 // Iterates over CUs and TUs.
2115 for (auto &CUTU : NonSkeletonContext.dwo_units()) {
2116 CUTU->getUnitDIE();
2117 CUTU->getBaseAddress();
2118 }
2119 parallelForEach(NonSkeletonContext.dwo_units(), [&](const auto &CUTU) {
2120 if (Error E = CUTU->tryExtractDIEsIfNeeded(false))
2121 DCtx.getRecoverableErrorHandler()(std::move(E));
2122 });
2123 // If context is for DWP we only need to extract once.
2124 if (NonSkeletonContext.isDWP())
2125 break;
2126 }
2127}
2128
2129void DWARFVerifier::verifyDebugNames(const DWARFSection &AccelSection,
2130 const DataExtractor &StrData) {
2131 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), AccelSection,
2132 DCtx.isLittleEndian(), 0);
2133 DWARFDebugNames AccelTable(AccelSectionData, StrData);
2134
2135 OS << "Verifying .debug_names...\n";
2136
2137 // This verifies that we can read individual name indices and their
2138 // abbreviation tables.
2139 if (Error E = AccelTable.extract()) {
2140 std::string Msg = toString(std::move(E));
2141 ErrorCategory.Report("Accelerator Table Error",
2142 [&]() { error() << Msg << '\n'; });
2143 return;
2144 }
2145 const uint64_t OriginalNumErrors = ErrorCategory.GetNumErrors();
2146 verifyDebugNamesCULists(AccelTable);
2147 for (const auto &NI : AccelTable)
2148 verifyNameIndexBuckets(NI, StrData);
2149 parallelForEach(AccelTable, [&](const DWARFDebugNames::NameIndex &NI) {
2150 verifyNameIndexAbbrevs(NI);
2151 });
2152
2153 // Don't attempt Entry validation if any of the previous checks found errors
2154 if (OriginalNumErrors != ErrorCategory.GetNumErrors())
2155 return;
2156 DenseMap<uint64_t, DWARFUnit *> CUOffsetsToDUMap;
2157 for (const auto &CU : DCtx.compile_units()) {
2158 if (!(CU->getVersion() >= 5 && CU->getDWOId()))
2159 continue;
2160 CUOffsetsToDUMap[CU->getOffset()] =
2161 CU->getNonSkeletonUnitDIE().getDwarfUnit();
2162 }
2163 extractCUsTus(DCtx);
2164 for (const DWARFDebugNames::NameIndex &NI : AccelTable) {
2165 parallelForEach(NI, [&](DWARFDebugNames::NameTableEntry NTE) {
2166 verifyNameIndexEntries(NI, NTE, CUOffsetsToDUMap);
2167 });
2168 }
2169
2170 auto populateNameToOffset =
2171 [&](const DWARFDebugNames::NameIndex &NI,
2172 StringMap<DenseSet<uint64_t>> &NamesToDieOffsets) {
2173 for (const DWARFDebugNames::NameTableEntry &NTE : NI) {
2174 const char *tName = NTE.getString();
2175 const std::string Name = tName ? std::string(tName) : "";
2176 uint64_t EntryID = NTE.getEntryOffset();
2177 Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&EntryID);
2178 auto Iter = NamesToDieOffsets.insert({Name, DenseSet<uint64_t>(3)});
2179 for (; EntryOr; EntryOr = NI.getEntry(&EntryID)) {
2180 if (std::optional<uint64_t> DieOffset = EntryOr->getDIEUnitOffset())
2181 Iter.first->second.insert(*DieOffset);
2182 }
2184 EntryOr.takeError(),
2185 [&](const DWARFDebugNames::SentinelError &) {
2186 if (!NamesToDieOffsets.empty())
2187 return;
2188 ErrorCategory.Report(
2189 "NameIndex Name is not associated with any entries", [&]() {
2190 error()
2191 << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
2192 "not associated with any entries.\n",
2193 NI.getUnitOffset(), NTE.getIndex(), Name);
2194 });
2195 },
2196 [&](const ErrorInfoBase &Info) {
2197 ErrorCategory.Report("Uncategorized NameIndex error", [&]() {
2198 error() << formatv(
2199 "Name Index @ {0:x}: Name {1} ({2}): {3}\n",
2200 NI.getUnitOffset(), NTE.getIndex(), Name, Info.message());
2201 });
2202 });
2203 }
2204 };
2205 // NameIndex can have multiple CUs. For example if it was created by BOLT.
2206 // So better to iterate over NI, and then over CUs in it.
2207 for (const DWARFDebugNames::NameIndex &NI : AccelTable) {
2208 StringMap<DenseSet<uint64_t>> NamesToDieOffsets(NI.getNameCount());
2209 populateNameToOffset(NI, NamesToDieOffsets);
2210 for (uint32_t i = 0, iEnd = NI.getCUCount(); i < iEnd; ++i) {
2211 const uint64_t CUOffset = NI.getCUOffset(i);
2212 DWARFUnit *U = DCtx.getUnitForOffset(CUOffset);
2214 if (CU) {
2215 if (CU->getDWOId()) {
2216 DWARFDie CUDie = CU->getUnitDIE(true);
2217 DWARFDie NonSkeletonUnitDie =
2218 CUDie.getDwarfUnit()->getNonSkeletonUnitDIE(false);
2219 if (CUDie != NonSkeletonUnitDie) {
2221 NonSkeletonUnitDie.getDwarfUnit()->dies(),
2222 [&](const DWARFDebugInfoEntry &Die) {
2223 verifyNameIndexCompleteness(
2224 DWARFDie(NonSkeletonUnitDie.getDwarfUnit(), &Die), NI,
2225 NamesToDieOffsets);
2226 });
2227 }
2228 } else {
2229 parallelForEach(CU->dies(), [&](const DWARFDebugInfoEntry &Die) {
2230 verifyNameIndexCompleteness(DWARFDie(CU, &Die), NI,
2231 NamesToDieOffsets);
2232 });
2233 }
2234 }
2235 }
2236 }
2237}
2238
2240 const DWARFObject &D = DCtx.getDWARFObj();
2241 DataExtractor StrData(D.getStrSection(), DCtx.isLittleEndian());
2242 if (!D.getAppleNamesSection().Data.empty())
2243 verifyAppleAccelTable(&D.getAppleNamesSection(), &StrData, ".apple_names");
2244 if (!D.getAppleTypesSection().Data.empty())
2245 verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData, ".apple_types");
2246 if (!D.getAppleNamespacesSection().Data.empty())
2247 verifyAppleAccelTable(&D.getAppleNamespacesSection(), &StrData,
2248 ".apple_namespaces");
2249 if (!D.getAppleObjCSection().Data.empty())
2250 verifyAppleAccelTable(&D.getAppleObjCSection(), &StrData, ".apple_objc");
2251
2252 if (!D.getNamesSection().Data.empty())
2253 verifyDebugNames(D.getNamesSection(), StrData);
2254 return ErrorCategory.GetNumErrors() == 0;
2255}
2256
2258 OS << "Verifying .debug_str_offsets...\n";
2259 const DWARFObject &DObj = DCtx.getDWARFObj();
2260 bool Success = true;
2261
2262 // dwo sections may contain the legacy debug_str_offsets format (and they
2263 // can't be mixed with dwarf 5's format). This section format contains no
2264 // header.
2265 // As such, check the version from debug_info and, if we are in the legacy
2266 // mode (Dwarf <= 4), extract Dwarf32/Dwarf64.
2267 std::optional<DwarfFormat> DwoLegacyDwarf4Format;
2268 DObj.forEachInfoDWOSections([&](const DWARFSection &S) {
2269 if (DwoLegacyDwarf4Format)
2270 return;
2271 DWARFDataExtractor DebugInfoData(DObj, S, DCtx.isLittleEndian(), 0);
2272 uint64_t Offset = 0;
2273 DwarfFormat InfoFormat = DebugInfoData.getInitialLength(&Offset).second;
2274 if (uint16_t InfoVersion = DebugInfoData.getU16(&Offset); InfoVersion <= 4)
2275 DwoLegacyDwarf4Format = InfoFormat;
2276 });
2277
2279 DwoLegacyDwarf4Format, ".debug_str_offsets.dwo",
2282 /*LegacyFormat=*/std::nullopt, ".debug_str_offsets",
2283 DObj.getStrOffsetsSection(), DObj.getStrSection());
2284 return Success;
2285}
2286
2288 std::optional<DwarfFormat> LegacyFormat, StringRef SectionName,
2289 const DWARFSection &Section, StringRef StrData) {
2290 const DWARFObject &DObj = DCtx.getDWARFObj();
2291
2292 DWARFDataExtractor DA(DObj, Section, DCtx.isLittleEndian(), 0);
2294 uint64_t NextUnit = 0;
2295 bool Success = true;
2296 while (C.seek(NextUnit), C.tell() < DA.getData().size()) {
2298 uint64_t Length;
2299 uint64_t StartOffset = C.tell();
2300 if (LegacyFormat) {
2301 Format = *LegacyFormat;
2302 Length = DA.getData().size();
2303 NextUnit = C.tell() + Length;
2304 } else {
2305 std::tie(Length, Format) = DA.getInitialLength(C);
2306 if (!C)
2307 break;
2308 if (C.tell() + Length > DA.getData().size()) {
2309 ErrorCategory.Report(
2310 "Section contribution length exceeds available space", [&]() {
2311 error() << formatv(
2312 "{0}: contribution {1:X}: length exceeds available space "
2313 "(contribution "
2314 "offset ({1:X}) + length field space ({2:X}) + length "
2315 "({3:X}) == "
2316 "{4:X} > section size {5:X})\n",
2317 SectionName, StartOffset, C.tell() - StartOffset, Length,
2318 C.tell() + Length, DA.getData().size());
2319 });
2320 Success = false;
2321 // Nothing more to do - no other contributions to try.
2322 break;
2323 }
2324 NextUnit = C.tell() + Length;
2325 uint8_t Version = DA.getU16(C);
2326 if (C && Version != 5) {
2327 ErrorCategory.Report("Invalid Section version", [&]() {
2328 error() << formatv("{0}: contribution {1:X}: invalid version {2}\n",
2329 SectionName, StartOffset, Version);
2330 });
2331 Success = false;
2332 // Can't parse the rest of this contribution, since we don't know the
2333 // version, but we can pick up with the next contribution.
2334 continue;
2335 }
2336 (void)DA.getU16(C); // padding
2337 }
2338 uint64_t OffsetByteSize = getDwarfOffsetByteSize(Format);
2339 DA.setAddressSize(OffsetByteSize);
2340 uint64_t Remainder = (Length - 4) % OffsetByteSize;
2341 if (Remainder != 0) {
2342 ErrorCategory.Report("Invalid section contribution length", [&]() {
2343 error() << formatv(
2344 "{0}: contribution {1:X}: invalid length ((length ({2:X}) "
2345 "- header (0x4)) % offset size {3:X} == {4:X} != 0)\n",
2346 SectionName, StartOffset, Length, OffsetByteSize, Remainder);
2347 });
2348 Success = false;
2349 }
2350 for (uint64_t Index = 0; C && C.tell() + OffsetByteSize <= NextUnit;
2351 ++Index) {
2352 uint64_t OffOff = C.tell();
2353 uint64_t StrOff = DA.getAddress(C);
2354 // check StrOff refers to the start of a string
2355 if (StrOff == 0)
2356 continue;
2357 if (StrData.size() <= StrOff) {
2358 ErrorCategory.Report(
2359 "String offset out of bounds of string section", [&]() {
2360 error() << formatv(
2361 "{0}: contribution {1:X}: index {2:X}: invalid string "
2362 "offset *{3:X} == {4:X}, is beyond the bounds of the string "
2363 "section of length {5:X}\n",
2364 SectionName, StartOffset, Index, OffOff, StrOff,
2365 StrData.size());
2366 });
2367 continue;
2368 }
2369 if (StrData[StrOff - 1] == '\0')
2370 continue;
2371 ErrorCategory.Report(
2372 "Section contribution contains invalid string offset", [&]() {
2373 error() << formatv(
2374 "{0}: contribution {1:X}: index {2:X}: invalid string "
2375 "offset *{3:X} == {4:X}, is neither zero nor "
2376 "immediately following a null character\n",
2377 SectionName, StartOffset, Index, OffOff, StrOff);
2378 });
2379 Success = false;
2380 }
2381 }
2382
2383 if (Error E = C.takeError()) {
2384 std::string Msg = toString(std::move(E));
2385 ErrorCategory.Report("String offset error", [&]() {
2386 error() << formatv("{0}: {1}\n", SectionName, Msg);
2387 });
2388 }
2389 return Success;
2390}
2391
2393 function_ref<void(void)> detailCallback) {
2394 Report(s, "", detailCallback);
2395}
2396
2398 StringRef sub_category,
2399 function_ref<void(void)> detailCallback) {
2400 std::lock_guard<std::mutex> Lock(WriteMutex);
2401 ++NumErrors;
2402 std::string category_str = std::string(category);
2403 AggregationData &Agg = Aggregation[category_str];
2404 Agg.OverallCount++;
2405 if (!sub_category.empty()) {
2406 Agg.DetailedCounts[std::string(sub_category)]++;
2407 }
2408 if (IncludeDetail)
2409 detailCallback();
2410}
2411
2413 function_ref<void(StringRef, unsigned)> handleCounts) {
2414 for (const auto &[name, aggData] : Aggregation) {
2415 handleCounts(name, aggData.OverallCount);
2416 }
2417}
2419 StringRef category, function_ref<void(StringRef, unsigned)> handleCounts) {
2420 const auto Agg = Aggregation.find(category);
2421 if (Agg != Aggregation.end()) {
2422 for (const auto &[name, aggData] : Agg->second.DetailedCounts) {
2423 handleCounts(name, aggData);
2424 }
2425 }
2426}
2427
2429 if (DumpOpts.ShowAggregateErrors && ErrorCategory.GetNumCategories()) {
2430 error() << "Aggregated error counts:\n";
2431 ErrorCategory.EnumerateResults([&](StringRef s, unsigned count) {
2432 error() << formatv("{0} occurred {1} time(s).\n", s, count);
2433 });
2434 }
2435 if (!DumpOpts.JsonErrSummaryFile.empty()) {
2436 std::error_code EC;
2437 raw_fd_ostream JsonStream(DumpOpts.JsonErrSummaryFile, EC,
2439 if (EC) {
2440 error() << formatv(
2441 "unable to open json summary file {0} for writing: {1}\n",
2442 DumpOpts.JsonErrSummaryFile, EC.message());
2443 return;
2444 }
2445
2446 llvm::json::Object Categories;
2447 uint64_t ErrorCount = 0;
2448 ErrorCategory.EnumerateResults([&](StringRef Category, unsigned Count) {
2450 Val.try_emplace("count", Count);
2451 llvm::json::Object Details;
2452 ErrorCategory.EnumerateDetailedResultsFor(
2453 Category, [&](StringRef SubCategory, unsigned SubCount) {
2454 Details.try_emplace(SubCategory, SubCount);
2455 });
2456 Val.try_emplace("details", std::move(Details));
2457 Categories.try_emplace(Category, std::move(Val));
2458 ErrorCount += Count;
2459 });
2460 llvm::json::Object RootNode;
2461 RootNode.try_emplace("error-categories", std::move(Categories));
2462 RootNode.try_emplace("error-count", ErrorCount);
2463
2464 JsonStream << llvm::json::Value(std::move(RootNode));
2465 }
2466}
2467
2468raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); }
2469
2470raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); }
2471
2472raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); }
2473
2474raw_ostream &DWARFVerifier::dump(const DWARFDie &Die, unsigned indent) const {
2475 Die.dump(OS, indent, DumpOpts);
2476 return OS;
2477}
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:320
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.