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 //===----------------------------------------------------------------------===//
8 #include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
9 #include "llvm/ADT/SmallSet.h"
10 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
11 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
12 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
13 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
14 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
15 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
16 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
17 #include "llvm/Support/DJB.h"
18 #include "llvm/Support/FormatVariadic.h"
19 #include "llvm/Support/WithColor.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <map>
22 #include <set>
23 #include <vector>
24 
25 using namespace llvm;
26 using namespace dwarf;
27 using namespace object;
28 
29 DWARFVerifier::DieRangeInfo::address_range_iterator
30 DWARFVerifier::DieRangeInfo::insert(const DWARFAddressRange &R) {
31   auto Begin = Ranges.begin();
32   auto End = Ranges.end();
33   auto Pos = std::lower_bound(Begin, End, R);
34 
35   if (Pos != End) {
36     if (Pos->intersects(R))
37       return std::move(Pos);
38     if (Pos != Begin) {
39       auto Iter = Pos - 1;
40       if (Iter->intersects(R))
41         return std::move(Iter);
42     }
43   }
44 
45   Ranges.insert(Pos, R);
46   return Ranges.end();
47 }
48 
49 DWARFVerifier::DieRangeInfo::die_range_info_iterator
50 DWARFVerifier::DieRangeInfo::insert(const DieRangeInfo &RI) {
51   auto End = Children.end();
52   auto Iter = Children.begin();
53   while (Iter != End) {
54     if (Iter->intersects(RI))
55       return Iter;
56     ++Iter;
57   }
58   Children.insert(RI);
59   return Children.end();
60 }
61 
62 bool DWARFVerifier::DieRangeInfo::contains(const DieRangeInfo &RHS) const {
63   auto I1 = Ranges.begin(), E1 = Ranges.end();
64   auto I2 = RHS.Ranges.begin(), E2 = RHS.Ranges.end();
65   if (I2 == E2)
66     return true;
67 
68   DWARFAddressRange R = *I2;
69   while (I1 != E1) {
70     bool Covered = I1->LowPC <= R.LowPC;
71     if (R.LowPC == R.HighPC || (Covered && R.HighPC <= I1->HighPC)) {
72       if (++I2 == E2)
73         return true;
74       R = *I2;
75       continue;
76     }
77     if (!Covered)
78       return false;
79     if (R.LowPC < I1->HighPC)
80       R.LowPC = I1->HighPC;
81     ++I1;
82   }
83   return false;
84 }
85 
86 bool DWARFVerifier::DieRangeInfo::intersects(const DieRangeInfo &RHS) const {
87   auto I1 = Ranges.begin(), E1 = Ranges.end();
88   auto I2 = RHS.Ranges.begin(), E2 = RHS.Ranges.end();
89   while (I1 != E1 && I2 != E2) {
90     if (I1->intersects(*I2))
91       return true;
92     if (I1->LowPC < I2->LowPC)
93       ++I1;
94     else
95       ++I2;
96   }
97   return false;
98 }
99 
100 bool DWARFVerifier::verifyUnitHeader(const DWARFDataExtractor DebugInfoData,
101                                      uint64_t *Offset, unsigned UnitIndex,
102                                      uint8_t &UnitType, bool &isUnitDWARF64) {
103   uint64_t AbbrOffset, Length;
104   uint8_t AddrSize = 0;
105   uint16_t Version;
106   bool Success = true;
107 
108   bool ValidLength = false;
109   bool ValidVersion = false;
110   bool ValidAddrSize = false;
111   bool ValidType = true;
112   bool ValidAbbrevOffset = true;
113 
114   uint64_t OffsetStart = *Offset;
115   Length = DebugInfoData.getU32(Offset);
116   if (Length == dwarf::DW_LENGTH_DWARF64) {
117     Length = DebugInfoData.getU64(Offset);
118     isUnitDWARF64 = true;
119   }
120   Version = DebugInfoData.getU16(Offset);
121 
122   if (Version >= 5) {
123     UnitType = DebugInfoData.getU8(Offset);
124     AddrSize = DebugInfoData.getU8(Offset);
125     AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
126     ValidType = dwarf::isUnitType(UnitType);
127   } else {
128     UnitType = 0;
129     AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
130     AddrSize = DebugInfoData.getU8(Offset);
131   }
132 
133   if (!DCtx.getDebugAbbrev()->getAbbreviationDeclarationSet(AbbrOffset))
134     ValidAbbrevOffset = false;
135 
136   ValidLength = DebugInfoData.isValidOffset(OffsetStart + Length + 3);
137   ValidVersion = DWARFContext::isSupportedVersion(Version);
138   ValidAddrSize = AddrSize == 4 || AddrSize == 8;
139   if (!ValidLength || !ValidVersion || !ValidAddrSize || !ValidAbbrevOffset ||
140       !ValidType) {
141     Success = false;
142     error() << format("Units[%d] - start offset: 0x%08" PRIx64 " \n", UnitIndex,
143                       OffsetStart);
144     if (!ValidLength)
145       note() << "The length for this unit is too "
146                 "large for the .debug_info provided.\n";
147     if (!ValidVersion)
148       note() << "The 16 bit unit header version is not valid.\n";
149     if (!ValidType)
150       note() << "The unit type encoding is not valid.\n";
151     if (!ValidAbbrevOffset)
152       note() << "The offset into the .debug_abbrev section is "
153                 "not valid.\n";
154     if (!ValidAddrSize)
155       note() << "The address size is unsupported.\n";
156   }
157   *Offset = OffsetStart + Length + (isUnitDWARF64 ? 12 : 4);
158   return Success;
159 }
160 
161 unsigned DWARFVerifier::verifyUnitContents(DWARFUnit &Unit) {
162   unsigned NumUnitErrors = 0;
163   unsigned NumDies = Unit.getNumDIEs();
164   for (unsigned I = 0; I < NumDies; ++I) {
165     auto Die = Unit.getDIEAtIndex(I);
166 
167     if (Die.getTag() == DW_TAG_null)
168       continue;
169 
170     for (auto AttrValue : Die.attributes()) {
171       NumUnitErrors += verifyDebugInfoAttribute(Die, AttrValue);
172       NumUnitErrors += verifyDebugInfoForm(Die, AttrValue);
173     }
174 
175     NumUnitErrors += verifyDebugInfoCallSite(Die);
176   }
177 
178   DWARFDie Die = Unit.getUnitDIE(/* ExtractUnitDIEOnly = */ false);
179   if (!Die) {
180     error() << "Compilation unit without DIE.\n";
181     NumUnitErrors++;
182     return NumUnitErrors;
183   }
184 
185   if (!dwarf::isUnitType(Die.getTag())) {
186     error() << "Compilation unit root DIE is not a unit DIE: "
187             << dwarf::TagString(Die.getTag()) << ".\n";
188     NumUnitErrors++;
189   }
190 
191   uint8_t UnitType = Unit.getUnitType();
192   if (!DWARFUnit::isMatchingUnitTypeAndTag(UnitType, Die.getTag())) {
193     error() << "Compilation unit type (" << dwarf::UnitTypeString(UnitType)
194             << ") and root DIE (" << dwarf::TagString(Die.getTag())
195             << ") do not match.\n";
196     NumUnitErrors++;
197   }
198 
199   DieRangeInfo RI;
200   NumUnitErrors += verifyDieRanges(Die, RI);
201 
202   return NumUnitErrors;
203 }
204 
205 unsigned DWARFVerifier::verifyDebugInfoCallSite(const DWARFDie &Die) {
206   if (Die.getTag() != DW_TAG_call_site && Die.getTag() != DW_TAG_GNU_call_site)
207     return 0;
208 
209   DWARFDie Curr = Die.getParent();
210   for (; Curr.isValid() && !Curr.isSubprogramDIE(); Curr = Die.getParent()) {
211     if (Curr.getTag() == DW_TAG_inlined_subroutine) {
212       error() << "Call site entry nested within inlined subroutine:";
213       Curr.dump(OS);
214       return 1;
215     }
216   }
217 
218   if (!Curr.isValid()) {
219     error() << "Call site entry not nested within a valid subprogram:";
220     Die.dump(OS);
221     return 1;
222   }
223 
224   Optional<DWARFFormValue> CallAttr =
225       Curr.find({DW_AT_call_all_calls, DW_AT_call_all_source_calls,
226                  DW_AT_call_all_tail_calls, DW_AT_GNU_all_call_sites,
227                  DW_AT_GNU_all_source_call_sites,
228                  DW_AT_GNU_all_tail_call_sites});
229   if (!CallAttr) {
230     error() << "Subprogram with call site entry has no DW_AT_call attribute:";
231     Curr.dump(OS);
232     Die.dump(OS, /*indent*/ 1);
233     return 1;
234   }
235 
236   return 0;
237 }
238 
239 unsigned DWARFVerifier::verifyAbbrevSection(const DWARFDebugAbbrev *Abbrev) {
240   unsigned NumErrors = 0;
241   if (Abbrev) {
242     const DWARFAbbreviationDeclarationSet *AbbrDecls =
243         Abbrev->getAbbreviationDeclarationSet(0);
244     for (auto AbbrDecl : *AbbrDecls) {
245       SmallDenseSet<uint16_t> AttributeSet;
246       for (auto Attribute : AbbrDecl.attributes()) {
247         auto Result = AttributeSet.insert(Attribute.Attr);
248         if (!Result.second) {
249           error() << "Abbreviation declaration contains multiple "
250                   << AttributeString(Attribute.Attr) << " attributes.\n";
251           AbbrDecl.dump(OS);
252           ++NumErrors;
253         }
254       }
255     }
256   }
257   return NumErrors;
258 }
259 
260 bool DWARFVerifier::handleDebugAbbrev() {
261   OS << "Verifying .debug_abbrev...\n";
262 
263   const DWARFObject &DObj = DCtx.getDWARFObj();
264   unsigned NumErrors = 0;
265   if (!DObj.getAbbrevSection().empty())
266     NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrev());
267   if (!DObj.getAbbrevDWOSection().empty())
268     NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrevDWO());
269 
270   return NumErrors == 0;
271 }
272 
273 unsigned DWARFVerifier::verifyUnitSection(const DWARFSection &S,
274                                           DWARFSectionKind SectionKind) {
275   const DWARFObject &DObj = DCtx.getDWARFObj();
276   DWARFDataExtractor DebugInfoData(DObj, S, DCtx.isLittleEndian(), 0);
277   unsigned NumDebugInfoErrors = 0;
278   uint64_t OffsetStart = 0, Offset = 0, UnitIdx = 0;
279   uint8_t UnitType = 0;
280   bool isUnitDWARF64 = false;
281   bool isHeaderChainValid = true;
282   bool hasDIE = DebugInfoData.isValidOffset(Offset);
283   DWARFUnitVector TypeUnitVector;
284   DWARFUnitVector CompileUnitVector;
285   while (hasDIE) {
286     OffsetStart = Offset;
287     if (!verifyUnitHeader(DebugInfoData, &Offset, UnitIdx, UnitType,
288                           isUnitDWARF64)) {
289       isHeaderChainValid = false;
290       if (isUnitDWARF64)
291         break;
292     } else {
293       DWARFUnitHeader Header;
294       Header.extract(DCtx, DebugInfoData, &OffsetStart, SectionKind);
295       DWARFUnit *Unit;
296       switch (UnitType) {
297       case dwarf::DW_UT_type:
298       case dwarf::DW_UT_split_type: {
299         Unit = TypeUnitVector.addUnit(std::make_unique<DWARFTypeUnit>(
300             DCtx, S, Header, DCtx.getDebugAbbrev(), &DObj.getRangesSection(),
301             &DObj.getLocSection(), DObj.getStrSection(),
302             DObj.getStrOffsetsSection(), &DObj.getAppleObjCSection(),
303             DObj.getLineSection(), DCtx.isLittleEndian(), false,
304             TypeUnitVector));
305         break;
306       }
307       case dwarf::DW_UT_skeleton:
308       case dwarf::DW_UT_split_compile:
309       case dwarf::DW_UT_compile:
310       case dwarf::DW_UT_partial:
311       // UnitType = 0 means that we are verifying a compile unit in DWARF v4.
312       case 0: {
313         Unit = CompileUnitVector.addUnit(std::make_unique<DWARFCompileUnit>(
314             DCtx, S, Header, DCtx.getDebugAbbrev(), &DObj.getRangesSection(),
315             &DObj.getLocSection(), DObj.getStrSection(),
316             DObj.getStrOffsetsSection(), &DObj.getAppleObjCSection(),
317             DObj.getLineSection(), DCtx.isLittleEndian(), false,
318             CompileUnitVector));
319         break;
320       }
321       default: { llvm_unreachable("Invalid UnitType."); }
322       }
323       NumDebugInfoErrors += verifyUnitContents(*Unit);
324     }
325     hasDIE = DebugInfoData.isValidOffset(Offset);
326     ++UnitIdx;
327   }
328   if (UnitIdx == 0 && !hasDIE) {
329     warn() << "Section is empty.\n";
330     isHeaderChainValid = true;
331   }
332   if (!isHeaderChainValid)
333     ++NumDebugInfoErrors;
334   NumDebugInfoErrors += verifyDebugInfoReferences();
335   return NumDebugInfoErrors;
336 }
337 
338 bool DWARFVerifier::handleDebugInfo() {
339   const DWARFObject &DObj = DCtx.getDWARFObj();
340   unsigned NumErrors = 0;
341 
342   OS << "Verifying .debug_info Unit Header Chain...\n";
343   DObj.forEachInfoSections([&](const DWARFSection &S) {
344     NumErrors += verifyUnitSection(S, DW_SECT_INFO);
345   });
346 
347   OS << "Verifying .debug_types Unit Header Chain...\n";
348   DObj.forEachTypesSections([&](const DWARFSection &S) {
349     NumErrors += verifyUnitSection(S, DW_SECT_TYPES);
350   });
351   return NumErrors == 0;
352 }
353 
354 unsigned DWARFVerifier::verifyDieRanges(const DWARFDie &Die,
355                                         DieRangeInfo &ParentRI) {
356   unsigned NumErrors = 0;
357 
358   if (!Die.isValid())
359     return NumErrors;
360 
361   auto RangesOrError = Die.getAddressRanges();
362   if (!RangesOrError) {
363     // FIXME: Report the error.
364     ++NumErrors;
365     llvm::consumeError(RangesOrError.takeError());
366     return NumErrors;
367   }
368 
369   DWARFAddressRangesVector Ranges = RangesOrError.get();
370   // Build RI for this DIE and check that ranges within this DIE do not
371   // overlap.
372   DieRangeInfo RI(Die);
373 
374   // TODO support object files better
375   //
376   // Some object file formats (i.e. non-MachO) support COMDAT.  ELF in
377   // particular does so by placing each function into a section.  The DWARF data
378   // for the function at that point uses a section relative DW_FORM_addrp for
379   // the DW_AT_low_pc and a DW_FORM_data4 for the offset as the DW_AT_high_pc.
380   // In such a case, when the Die is the CU, the ranges will overlap, and we
381   // will flag valid conflicting ranges as invalid.
382   //
383   // For such targets, we should read the ranges from the CU and partition them
384   // by the section id.  The ranges within a particular section should be
385   // disjoint, although the ranges across sections may overlap.  We would map
386   // the child die to the entity that it references and the section with which
387   // it is associated.  The child would then be checked against the range
388   // information for the associated section.
389   //
390   // For now, simply elide the range verification for the CU DIEs if we are
391   // processing an object file.
392 
393   if (!IsObjectFile || IsMachOObject || Die.getTag() != DW_TAG_compile_unit) {
394     for (auto Range : Ranges) {
395       if (!Range.valid()) {
396         ++NumErrors;
397         error() << "Invalid address range " << Range << "\n";
398         continue;
399       }
400 
401       // Verify that ranges don't intersect.
402       const auto IntersectingRange = RI.insert(Range);
403       if (IntersectingRange != RI.Ranges.end()) {
404         ++NumErrors;
405         error() << "DIE has overlapping address ranges: " << Range << " and "
406                 << *IntersectingRange << "\n";
407         break;
408       }
409     }
410   }
411 
412   // Verify that children don't intersect.
413   const auto IntersectingChild = ParentRI.insert(RI);
414   if (IntersectingChild != ParentRI.Children.end()) {
415     ++NumErrors;
416     error() << "DIEs have overlapping address ranges:";
417     dump(Die);
418     dump(IntersectingChild->Die) << '\n';
419   }
420 
421   // Verify that ranges are contained within their parent.
422   bool ShouldBeContained = !Ranges.empty() && !ParentRI.Ranges.empty() &&
423                            !(Die.getTag() == DW_TAG_subprogram &&
424                              ParentRI.Die.getTag() == DW_TAG_subprogram);
425   if (ShouldBeContained && !ParentRI.contains(RI)) {
426     ++NumErrors;
427     error() << "DIE address ranges are not contained in its parent's ranges:";
428     dump(ParentRI.Die);
429     dump(Die, 2) << '\n';
430   }
431 
432   // Recursively check children.
433   for (DWARFDie Child : Die)
434     NumErrors += verifyDieRanges(Child, RI);
435 
436   return NumErrors;
437 }
438 
439 unsigned DWARFVerifier::verifyDebugInfoAttribute(const DWARFDie &Die,
440                                                  DWARFAttribute &AttrValue) {
441   unsigned NumErrors = 0;
442   auto ReportError = [&](const Twine &TitleMsg) {
443     ++NumErrors;
444     error() << TitleMsg << '\n';
445     dump(Die) << '\n';
446   };
447 
448   const DWARFObject &DObj = DCtx.getDWARFObj();
449   const auto Attr = AttrValue.Attr;
450   switch (Attr) {
451   case DW_AT_ranges:
452     // Make sure the offset in the DW_AT_ranges attribute is valid.
453     if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
454       if (*SectionOffset >= DObj.getRangesSection().Data.size())
455         ReportError("DW_AT_ranges offset is beyond .debug_ranges bounds:");
456       break;
457     }
458     ReportError("DIE has invalid DW_AT_ranges encoding:");
459     break;
460   case DW_AT_stmt_list:
461     // Make sure the offset in the DW_AT_stmt_list attribute is valid.
462     if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
463       if (*SectionOffset >= DObj.getLineSection().Data.size())
464         ReportError("DW_AT_stmt_list offset is beyond .debug_line bounds: " +
465                     llvm::formatv("{0:x8}", *SectionOffset));
466       break;
467     }
468     ReportError("DIE has invalid DW_AT_stmt_list encoding:");
469     break;
470   case DW_AT_location: {
471     if (Expected<std::vector<DWARFLocationExpression>> Loc =
472             Die.getLocations(DW_AT_location)) {
473       DWARFUnit *U = Die.getDwarfUnit();
474       for (const auto &Entry : *Loc) {
475         DataExtractor Data(toStringRef(Entry.Expr), DCtx.isLittleEndian(), 0);
476         DWARFExpression Expression(Data, U->getVersion(),
477                                    U->getAddressByteSize());
478         bool Error = any_of(Expression, [](DWARFExpression::Operation &Op) {
479           return Op.isError();
480         });
481         if (Error || !Expression.verify(U))
482           ReportError("DIE contains invalid DWARF expression:");
483       }
484     } else
485       ReportError(toString(Loc.takeError()));
486     break;
487   }
488   case DW_AT_specification:
489   case DW_AT_abstract_origin: {
490     if (auto ReferencedDie = Die.getAttributeValueAsReferencedDie(Attr)) {
491       auto DieTag = Die.getTag();
492       auto RefTag = ReferencedDie.getTag();
493       if (DieTag == RefTag)
494         break;
495       if (DieTag == DW_TAG_inlined_subroutine && RefTag == DW_TAG_subprogram)
496         break;
497       if (DieTag == DW_TAG_variable && RefTag == DW_TAG_member)
498         break;
499       // This might be reference to a function declaration.
500       if (DieTag == DW_TAG_GNU_call_site && RefTag == DW_TAG_subprogram)
501         break;
502       ReportError("DIE with tag " + TagString(DieTag) + " has " +
503                   AttributeString(Attr) +
504                   " that points to DIE with "
505                   "incompatible tag " +
506                   TagString(RefTag));
507     }
508     break;
509   }
510   case DW_AT_type: {
511     DWARFDie TypeDie = Die.getAttributeValueAsReferencedDie(DW_AT_type);
512     if (TypeDie && !isType(TypeDie.getTag())) {
513       ReportError("DIE has " + AttributeString(Attr) +
514                   " with incompatible tag " + TagString(TypeDie.getTag()));
515     }
516     break;
517   }
518   default:
519     break;
520   }
521   return NumErrors;
522 }
523 
524 unsigned DWARFVerifier::verifyDebugInfoForm(const DWARFDie &Die,
525                                             DWARFAttribute &AttrValue) {
526   const DWARFObject &DObj = DCtx.getDWARFObj();
527   auto DieCU = Die.getDwarfUnit();
528   unsigned NumErrors = 0;
529   const auto Form = AttrValue.Value.getForm();
530   switch (Form) {
531   case DW_FORM_ref1:
532   case DW_FORM_ref2:
533   case DW_FORM_ref4:
534   case DW_FORM_ref8:
535   case DW_FORM_ref_udata: {
536     // Verify all CU relative references are valid CU offsets.
537     Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
538     assert(RefVal);
539     if (RefVal) {
540       auto CUSize = DieCU->getNextUnitOffset() - DieCU->getOffset();
541       auto CUOffset = AttrValue.Value.getRawUValue();
542       if (CUOffset >= CUSize) {
543         ++NumErrors;
544         error() << FormEncodingString(Form) << " CU offset "
545                 << format("0x%08" PRIx64, CUOffset)
546                 << " is invalid (must be less than CU size of "
547                 << format("0x%08" PRIx64, CUSize) << "):\n";
548         Die.dump(OS, 0, DumpOpts);
549         dump(Die) << '\n';
550       } else {
551         // Valid reference, but we will verify it points to an actual
552         // DIE later.
553         ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
554       }
555     }
556     break;
557   }
558   case DW_FORM_ref_addr: {
559     // Verify all absolute DIE references have valid offsets in the
560     // .debug_info section.
561     Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
562     assert(RefVal);
563     if (RefVal) {
564       if (*RefVal >= DieCU->getInfoSection().Data.size()) {
565         ++NumErrors;
566         error() << "DW_FORM_ref_addr offset beyond .debug_info "
567                    "bounds:\n";
568         dump(Die) << '\n';
569       } else {
570         // Valid reference, but we will verify it points to an actual
571         // DIE later.
572         ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
573       }
574     }
575     break;
576   }
577   case DW_FORM_strp: {
578     auto SecOffset = AttrValue.Value.getAsSectionOffset();
579     assert(SecOffset); // DW_FORM_strp is a section offset.
580     if (SecOffset && *SecOffset >= DObj.getStrSection().size()) {
581       ++NumErrors;
582       error() << "DW_FORM_strp offset beyond .debug_str bounds:\n";
583       dump(Die) << '\n';
584     }
585     break;
586   }
587   case DW_FORM_strx:
588   case DW_FORM_strx1:
589   case DW_FORM_strx2:
590   case DW_FORM_strx3:
591   case DW_FORM_strx4: {
592     auto Index = AttrValue.Value.getRawUValue();
593     auto DieCU = Die.getDwarfUnit();
594     // Check that we have a valid DWARF v5 string offsets table.
595     if (!DieCU->getStringOffsetsTableContribution()) {
596       ++NumErrors;
597       error() << FormEncodingString(Form)
598               << " used without a valid string offsets table:\n";
599       dump(Die) << '\n';
600       break;
601     }
602     // Check that the index is within the bounds of the section.
603     unsigned ItemSize = DieCU->getDwarfStringOffsetsByteSize();
604     // Use a 64-bit type to calculate the offset to guard against overflow.
605     uint64_t Offset =
606         (uint64_t)DieCU->getStringOffsetsBase() + Index * ItemSize;
607     if (DObj.getStrOffsetsSection().Data.size() < Offset + ItemSize) {
608       ++NumErrors;
609       error() << FormEncodingString(Form) << " uses index "
610               << format("%" PRIu64, Index) << ", which is too large:\n";
611       dump(Die) << '\n';
612       break;
613     }
614     // Check that the string offset is valid.
615     uint64_t StringOffset = *DieCU->getStringOffsetSectionItem(Index);
616     if (StringOffset >= DObj.getStrSection().size()) {
617       ++NumErrors;
618       error() << FormEncodingString(Form) << " uses index "
619               << format("%" PRIu64, Index)
620               << ", but the referenced string"
621                  " offset is beyond .debug_str bounds:\n";
622       dump(Die) << '\n';
623     }
624     break;
625   }
626   default:
627     break;
628   }
629   return NumErrors;
630 }
631 
632 unsigned DWARFVerifier::verifyDebugInfoReferences() {
633   // Take all references and make sure they point to an actual DIE by
634   // getting the DIE by offset and emitting an error
635   OS << "Verifying .debug_info references...\n";
636   unsigned NumErrors = 0;
637   for (const std::pair<uint64_t, std::set<uint64_t>> &Pair :
638        ReferenceToDIEOffsets) {
639     if (DCtx.getDIEForOffset(Pair.first))
640       continue;
641     ++NumErrors;
642     error() << "invalid DIE reference " << format("0x%08" PRIx64, Pair.first)
643             << ". Offset is in between DIEs:\n";
644     for (auto Offset : Pair.second)
645       dump(DCtx.getDIEForOffset(Offset)) << '\n';
646     OS << "\n";
647   }
648   return NumErrors;
649 }
650 
651 void DWARFVerifier::verifyDebugLineStmtOffsets() {
652   std::map<uint64_t, DWARFDie> StmtListToDie;
653   for (const auto &CU : DCtx.compile_units()) {
654     auto Die = CU->getUnitDIE();
655     // Get the attribute value as a section offset. No need to produce an
656     // error here if the encoding isn't correct because we validate this in
657     // the .debug_info verifier.
658     auto StmtSectionOffset = toSectionOffset(Die.find(DW_AT_stmt_list));
659     if (!StmtSectionOffset)
660       continue;
661     const uint64_t LineTableOffset = *StmtSectionOffset;
662     auto LineTable = DCtx.getLineTableForUnit(CU.get());
663     if (LineTableOffset < DCtx.getDWARFObj().getLineSection().Data.size()) {
664       if (!LineTable) {
665         ++NumDebugLineErrors;
666         error() << ".debug_line[" << format("0x%08" PRIx64, LineTableOffset)
667                 << "] was not able to be parsed for CU:\n";
668         dump(Die) << '\n';
669         continue;
670       }
671     } else {
672       // Make sure we don't get a valid line table back if the offset is wrong.
673       assert(LineTable == nullptr);
674       // Skip this line table as it isn't valid. No need to create an error
675       // here because we validate this in the .debug_info verifier.
676       continue;
677     }
678     auto Iter = StmtListToDie.find(LineTableOffset);
679     if (Iter != StmtListToDie.end()) {
680       ++NumDebugLineErrors;
681       error() << "two compile unit DIEs, "
682               << format("0x%08" PRIx64, Iter->second.getOffset()) << " and "
683               << format("0x%08" PRIx64, Die.getOffset())
684               << ", have the same DW_AT_stmt_list section offset:\n";
685       dump(Iter->second);
686       dump(Die) << '\n';
687       // Already verified this line table before, no need to do it again.
688       continue;
689     }
690     StmtListToDie[LineTableOffset] = Die;
691   }
692 }
693 
694 void DWARFVerifier::verifyDebugLineRows() {
695   for (const auto &CU : DCtx.compile_units()) {
696     auto Die = CU->getUnitDIE();
697     auto LineTable = DCtx.getLineTableForUnit(CU.get());
698     // If there is no line table we will have created an error in the
699     // .debug_info verifier or in verifyDebugLineStmtOffsets().
700     if (!LineTable)
701       continue;
702 
703     // Verify prologue.
704     uint32_t MaxDirIndex = LineTable->Prologue.IncludeDirectories.size();
705     uint32_t FileIndex = 1;
706     StringMap<uint16_t> FullPathMap;
707     for (const auto &FileName : LineTable->Prologue.FileNames) {
708       // Verify directory index.
709       if (FileName.DirIdx > MaxDirIndex) {
710         ++NumDebugLineErrors;
711         error() << ".debug_line["
712                 << format("0x%08" PRIx64,
713                           *toSectionOffset(Die.find(DW_AT_stmt_list)))
714                 << "].prologue.file_names[" << FileIndex
715                 << "].dir_idx contains an invalid index: " << FileName.DirIdx
716                 << "\n";
717       }
718 
719       // Check file paths for duplicates.
720       std::string FullPath;
721       const bool HasFullPath = LineTable->getFileNameByIndex(
722           FileIndex, CU->getCompilationDir(),
723           DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FullPath);
724       assert(HasFullPath && "Invalid index?");
725       (void)HasFullPath;
726       auto It = FullPathMap.find(FullPath);
727       if (It == FullPathMap.end())
728         FullPathMap[FullPath] = FileIndex;
729       else if (It->second != FileIndex) {
730         warn() << ".debug_line["
731                << format("0x%08" PRIx64,
732                          *toSectionOffset(Die.find(DW_AT_stmt_list)))
733                << "].prologue.file_names[" << FileIndex
734                << "] is a duplicate of file_names[" << It->second << "]\n";
735       }
736 
737       FileIndex++;
738     }
739 
740     // Verify rows.
741     uint64_t PrevAddress = 0;
742     uint32_t RowIndex = 0;
743     for (const auto &Row : LineTable->Rows) {
744       // Verify row address.
745       if (Row.Address.Address < PrevAddress) {
746         ++NumDebugLineErrors;
747         error() << ".debug_line["
748                 << format("0x%08" PRIx64,
749                           *toSectionOffset(Die.find(DW_AT_stmt_list)))
750                 << "] row[" << RowIndex
751                 << "] decreases in address from previous row:\n";
752 
753         DWARFDebugLine::Row::dumpTableHeader(OS);
754         if (RowIndex > 0)
755           LineTable->Rows[RowIndex - 1].dump(OS);
756         Row.dump(OS);
757         OS << '\n';
758       }
759 
760       // Verify file index.
761       if (!LineTable->hasFileAtIndex(Row.File)) {
762         ++NumDebugLineErrors;
763         bool isDWARF5 = LineTable->Prologue.getVersion() >= 5;
764         error() << ".debug_line["
765                 << format("0x%08" PRIx64,
766                           *toSectionOffset(Die.find(DW_AT_stmt_list)))
767                 << "][" << RowIndex << "] has invalid file index " << Row.File
768                 << " (valid values are [" << (isDWARF5 ? "0," : "1,")
769                 << LineTable->Prologue.FileNames.size()
770                 << (isDWARF5 ? ")" : "]") << "):\n";
771         DWARFDebugLine::Row::dumpTableHeader(OS);
772         Row.dump(OS);
773         OS << '\n';
774       }
775       if (Row.EndSequence)
776         PrevAddress = 0;
777       else
778         PrevAddress = Row.Address.Address;
779       ++RowIndex;
780     }
781   }
782 }
783 
784 DWARFVerifier::DWARFVerifier(raw_ostream &S, DWARFContext &D,
785                              DIDumpOptions DumpOpts)
786     : OS(S), DCtx(D), DumpOpts(std::move(DumpOpts)), IsObjectFile(false),
787       IsMachOObject(false) {
788   if (const auto *F = DCtx.getDWARFObj().getFile()) {
789     IsObjectFile = F->isRelocatableObject();
790     IsMachOObject = F->isMachO();
791   }
792 }
793 
794 bool DWARFVerifier::handleDebugLine() {
795   NumDebugLineErrors = 0;
796   OS << "Verifying .debug_line...\n";
797   verifyDebugLineStmtOffsets();
798   verifyDebugLineRows();
799   return NumDebugLineErrors == 0;
800 }
801 
802 unsigned DWARFVerifier::verifyAppleAccelTable(const DWARFSection *AccelSection,
803                                               DataExtractor *StrData,
804                                               const char *SectionName) {
805   unsigned NumErrors = 0;
806   DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), *AccelSection,
807                                       DCtx.isLittleEndian(), 0);
808   AppleAcceleratorTable AccelTable(AccelSectionData, *StrData);
809 
810   OS << "Verifying " << SectionName << "...\n";
811 
812   // Verify that the fixed part of the header is not too short.
813   if (!AccelSectionData.isValidOffset(AccelTable.getSizeHdr())) {
814     error() << "Section is too small to fit a section header.\n";
815     return 1;
816   }
817 
818   // Verify that the section is not too short.
819   if (Error E = AccelTable.extract()) {
820     error() << toString(std::move(E)) << '\n';
821     return 1;
822   }
823 
824   // Verify that all buckets have a valid hash index or are empty.
825   uint32_t NumBuckets = AccelTable.getNumBuckets();
826   uint32_t NumHashes = AccelTable.getNumHashes();
827 
828   uint64_t BucketsOffset =
829       AccelTable.getSizeHdr() + AccelTable.getHeaderDataLength();
830   uint64_t HashesBase = BucketsOffset + NumBuckets * 4;
831   uint64_t OffsetsBase = HashesBase + NumHashes * 4;
832   for (uint32_t BucketIdx = 0; BucketIdx < NumBuckets; ++BucketIdx) {
833     uint32_t HashIdx = AccelSectionData.getU32(&BucketsOffset);
834     if (HashIdx >= NumHashes && HashIdx != UINT32_MAX) {
835       error() << format("Bucket[%d] has invalid hash index: %u.\n", BucketIdx,
836                         HashIdx);
837       ++NumErrors;
838     }
839   }
840   uint32_t NumAtoms = AccelTable.getAtomsDesc().size();
841   if (NumAtoms == 0) {
842     error() << "No atoms: failed to read HashData.\n";
843     return 1;
844   }
845   if (!AccelTable.validateForms()) {
846     error() << "Unsupported form: failed to read HashData.\n";
847     return 1;
848   }
849 
850   for (uint32_t HashIdx = 0; HashIdx < NumHashes; ++HashIdx) {
851     uint64_t HashOffset = HashesBase + 4 * HashIdx;
852     uint64_t DataOffset = OffsetsBase + 4 * HashIdx;
853     uint32_t Hash = AccelSectionData.getU32(&HashOffset);
854     uint64_t HashDataOffset = AccelSectionData.getU32(&DataOffset);
855     if (!AccelSectionData.isValidOffsetForDataOfSize(HashDataOffset,
856                                                      sizeof(uint64_t))) {
857       error() << format("Hash[%d] has invalid HashData offset: "
858                         "0x%08" PRIx64 ".\n",
859                         HashIdx, HashDataOffset);
860       ++NumErrors;
861     }
862 
863     uint64_t StrpOffset;
864     uint64_t StringOffset;
865     uint32_t StringCount = 0;
866     uint64_t Offset;
867     unsigned Tag;
868     while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) {
869       const uint32_t NumHashDataObjects =
870           AccelSectionData.getU32(&HashDataOffset);
871       for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects;
872            ++HashDataIdx) {
873         std::tie(Offset, Tag) = AccelTable.readAtoms(&HashDataOffset);
874         auto Die = DCtx.getDIEForOffset(Offset);
875         if (!Die) {
876           const uint32_t BucketIdx =
877               NumBuckets ? (Hash % NumBuckets) : UINT32_MAX;
878           StringOffset = StrpOffset;
879           const char *Name = StrData->getCStr(&StringOffset);
880           if (!Name)
881             Name = "<NULL>";
882 
883           error() << format(
884               "%s Bucket[%d] Hash[%d] = 0x%08x "
885               "Str[%u] = 0x%08" PRIx64 " DIE[%d] = 0x%08" PRIx64 " "
886               "is not a valid DIE offset for \"%s\".\n",
887               SectionName, BucketIdx, HashIdx, Hash, StringCount, StrpOffset,
888               HashDataIdx, Offset, Name);
889 
890           ++NumErrors;
891           continue;
892         }
893         if ((Tag != dwarf::DW_TAG_null) && (Die.getTag() != Tag)) {
894           error() << "Tag " << dwarf::TagString(Tag)
895                   << " in accelerator table does not match Tag "
896                   << dwarf::TagString(Die.getTag()) << " of DIE[" << HashDataIdx
897                   << "].\n";
898           ++NumErrors;
899         }
900       }
901       ++StringCount;
902     }
903   }
904   return NumErrors;
905 }
906 
907 unsigned
908 DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) {
909   // A map from CU offset to the (first) Name Index offset which claims to index
910   // this CU.
911   DenseMap<uint64_t, uint64_t> CUMap;
912   const uint64_t NotIndexed = std::numeric_limits<uint64_t>::max();
913 
914   CUMap.reserve(DCtx.getNumCompileUnits());
915   for (const auto &CU : DCtx.compile_units())
916     CUMap[CU->getOffset()] = NotIndexed;
917 
918   unsigned NumErrors = 0;
919   for (const DWARFDebugNames::NameIndex &NI : AccelTable) {
920     if (NI.getCUCount() == 0) {
921       error() << formatv("Name Index @ {0:x} does not index any CU\n",
922                          NI.getUnitOffset());
923       ++NumErrors;
924       continue;
925     }
926     for (uint32_t CU = 0, End = NI.getCUCount(); CU < End; ++CU) {
927       uint64_t Offset = NI.getCUOffset(CU);
928       auto Iter = CUMap.find(Offset);
929 
930       if (Iter == CUMap.end()) {
931         error() << formatv(
932             "Name Index @ {0:x} references a non-existing CU @ {1:x}\n",
933             NI.getUnitOffset(), Offset);
934         ++NumErrors;
935         continue;
936       }
937 
938       if (Iter->second != NotIndexed) {
939         error() << formatv("Name Index @ {0:x} references a CU @ {1:x}, but "
940                            "this CU is already indexed by Name Index @ {2:x}\n",
941                            NI.getUnitOffset(), Offset, Iter->second);
942         continue;
943       }
944       Iter->second = NI.getUnitOffset();
945     }
946   }
947 
948   for (const auto &KV : CUMap) {
949     if (KV.second == NotIndexed)
950       warn() << formatv("CU @ {0:x} not covered by any Name Index\n", KV.first);
951   }
952 
953   return NumErrors;
954 }
955 
956 unsigned
957 DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI,
958                                       const DataExtractor &StrData) {
959   struct BucketInfo {
960     uint32_t Bucket;
961     uint32_t Index;
962 
963     constexpr BucketInfo(uint32_t Bucket, uint32_t Index)
964         : Bucket(Bucket), Index(Index) {}
965     bool operator<(const BucketInfo &RHS) const { return Index < RHS.Index; }
966   };
967 
968   uint32_t NumErrors = 0;
969   if (NI.getBucketCount() == 0) {
970     warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n",
971                       NI.getUnitOffset());
972     return NumErrors;
973   }
974 
975   // Build up a list of (Bucket, Index) pairs. We use this later to verify that
976   // each Name is reachable from the appropriate bucket.
977   std::vector<BucketInfo> BucketStarts;
978   BucketStarts.reserve(NI.getBucketCount() + 1);
979   for (uint32_t Bucket = 0, End = NI.getBucketCount(); Bucket < End; ++Bucket) {
980     uint32_t Index = NI.getBucketArrayEntry(Bucket);
981     if (Index > NI.getNameCount()) {
982       error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid "
983                          "value {2}. Valid range is [0, {3}].\n",
984                          Bucket, NI.getUnitOffset(), Index, NI.getNameCount());
985       ++NumErrors;
986       continue;
987     }
988     if (Index > 0)
989       BucketStarts.emplace_back(Bucket, Index);
990   }
991 
992   // If there were any buckets with invalid values, skip further checks as they
993   // will likely produce many errors which will only confuse the actual root
994   // problem.
995   if (NumErrors > 0)
996     return NumErrors;
997 
998   // Sort the list in the order of increasing "Index" entries.
999   array_pod_sort(BucketStarts.begin(), BucketStarts.end());
1000 
1001   // Insert a sentinel entry at the end, so we can check that the end of the
1002   // table is covered in the loop below.
1003   BucketStarts.emplace_back(NI.getBucketCount(), NI.getNameCount() + 1);
1004 
1005   // Loop invariant: NextUncovered is the (1-based) index of the first Name
1006   // which is not reachable by any of the buckets we processed so far (and
1007   // hasn't been reported as uncovered).
1008   uint32_t NextUncovered = 1;
1009   for (const BucketInfo &B : BucketStarts) {
1010     // Under normal circumstances B.Index be equal to NextUncovered, but it can
1011     // be less if a bucket points to names which are already known to be in some
1012     // bucket we processed earlier. In that case, we won't trigger this error,
1013     // but report the mismatched hash value error instead. (We know the hash
1014     // will not match because we have already verified that the name's hash
1015     // puts it into the previous bucket.)
1016     if (B.Index > NextUncovered) {
1017       error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] "
1018                          "are not covered by the hash table.\n",
1019                          NI.getUnitOffset(), NextUncovered, B.Index - 1);
1020       ++NumErrors;
1021     }
1022     uint32_t Idx = B.Index;
1023 
1024     // The rest of the checks apply only to non-sentinel entries.
1025     if (B.Bucket == NI.getBucketCount())
1026       break;
1027 
1028     // This triggers if a non-empty bucket points to a name with a mismatched
1029     // hash. Clients are likely to interpret this as an empty bucket, because a
1030     // mismatched hash signals the end of a bucket, but if this is indeed an
1031     // empty bucket, the producer should have signalled this by marking the
1032     // bucket as empty.
1033     uint32_t FirstHash = NI.getHashArrayEntry(Idx);
1034     if (FirstHash % NI.getBucketCount() != B.Bucket) {
1035       error() << formatv(
1036           "Name Index @ {0:x}: Bucket {1} is not empty but points to a "
1037           "mismatched hash value {2:x} (belonging to bucket {3}).\n",
1038           NI.getUnitOffset(), B.Bucket, FirstHash,
1039           FirstHash % NI.getBucketCount());
1040       ++NumErrors;
1041     }
1042 
1043     // This find the end of this bucket and also verifies that all the hashes in
1044     // this bucket are correct by comparing the stored hashes to the ones we
1045     // compute ourselves.
1046     while (Idx <= NI.getNameCount()) {
1047       uint32_t Hash = NI.getHashArrayEntry(Idx);
1048       if (Hash % NI.getBucketCount() != B.Bucket)
1049         break;
1050 
1051       const char *Str = NI.getNameTableEntry(Idx).getString();
1052       if (caseFoldingDjbHash(Str) != Hash) {
1053         error() << formatv("Name Index @ {0:x}: String ({1}) at index {2} "
1054                            "hashes to {3:x}, but "
1055                            "the Name Index hash is {4:x}\n",
1056                            NI.getUnitOffset(), Str, Idx,
1057                            caseFoldingDjbHash(Str), Hash);
1058         ++NumErrors;
1059       }
1060 
1061       ++Idx;
1062     }
1063     NextUncovered = std::max(NextUncovered, Idx);
1064   }
1065   return NumErrors;
1066 }
1067 
1068 unsigned DWARFVerifier::verifyNameIndexAttribute(
1069     const DWARFDebugNames::NameIndex &NI, const DWARFDebugNames::Abbrev &Abbr,
1070     DWARFDebugNames::AttributeEncoding AttrEnc) {
1071   StringRef FormName = dwarf::FormEncodingString(AttrEnc.Form);
1072   if (FormName.empty()) {
1073     error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1074                        "unknown form: {3}.\n",
1075                        NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1076                        AttrEnc.Form);
1077     return 1;
1078   }
1079 
1080   if (AttrEnc.Index == DW_IDX_type_hash) {
1081     if (AttrEnc.Form != dwarf::DW_FORM_data8) {
1082       error() << formatv(
1083           "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash "
1084           "uses an unexpected form {2} (should be {3}).\n",
1085           NI.getUnitOffset(), Abbr.Code, AttrEnc.Form, dwarf::DW_FORM_data8);
1086       return 1;
1087     }
1088   }
1089 
1090   // A list of known index attributes and their expected form classes.
1091   // DW_IDX_type_hash is handled specially in the check above, as it has a
1092   // specific form (not just a form class) we should expect.
1093   struct FormClassTable {
1094     dwarf::Index Index;
1095     DWARFFormValue::FormClass Class;
1096     StringLiteral ClassName;
1097   };
1098   static constexpr FormClassTable Table[] = {
1099       {dwarf::DW_IDX_compile_unit, DWARFFormValue::FC_Constant, {"constant"}},
1100       {dwarf::DW_IDX_type_unit, DWARFFormValue::FC_Constant, {"constant"}},
1101       {dwarf::DW_IDX_die_offset, DWARFFormValue::FC_Reference, {"reference"}},
1102       {dwarf::DW_IDX_parent, DWARFFormValue::FC_Constant, {"constant"}},
1103   };
1104 
1105   ArrayRef<FormClassTable> TableRef(Table);
1106   auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) {
1107     return T.Index == AttrEnc.Index;
1108   });
1109   if (Iter == TableRef.end()) {
1110     warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an "
1111                       "unknown index attribute: {2}.\n",
1112                       NI.getUnitOffset(), Abbr.Code, AttrEnc.Index);
1113     return 0;
1114   }
1115 
1116   if (!DWARFFormValue(AttrEnc.Form).isFormClass(Iter->Class)) {
1117     error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1118                        "unexpected form {3} (expected form class {4}).\n",
1119                        NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1120                        AttrEnc.Form, Iter->ClassName);
1121     return 1;
1122   }
1123   return 0;
1124 }
1125 
1126 unsigned
1127 DWARFVerifier::verifyNameIndexAbbrevs(const DWARFDebugNames::NameIndex &NI) {
1128   if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) {
1129     warn() << formatv("Name Index @ {0:x}: Verifying indexes of type units is "
1130                       "not currently supported.\n",
1131                       NI.getUnitOffset());
1132     return 0;
1133   }
1134 
1135   unsigned NumErrors = 0;
1136   for (const auto &Abbrev : NI.getAbbrevs()) {
1137     StringRef TagName = dwarf::TagString(Abbrev.Tag);
1138     if (TagName.empty()) {
1139       warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an "
1140                         "unknown tag: {2}.\n",
1141                         NI.getUnitOffset(), Abbrev.Code, Abbrev.Tag);
1142     }
1143     SmallSet<unsigned, 5> Attributes;
1144     for (const auto &AttrEnc : Abbrev.Attributes) {
1145       if (!Attributes.insert(AttrEnc.Index).second) {
1146         error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains "
1147                            "multiple {2} attributes.\n",
1148                            NI.getUnitOffset(), Abbrev.Code, AttrEnc.Index);
1149         ++NumErrors;
1150         continue;
1151       }
1152       NumErrors += verifyNameIndexAttribute(NI, Abbrev, AttrEnc);
1153     }
1154 
1155     if (NI.getCUCount() > 1 && !Attributes.count(dwarf::DW_IDX_compile_unit)) {
1156       error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units "
1157                          "and abbreviation {1:x} has no {2} attribute.\n",
1158                          NI.getUnitOffset(), Abbrev.Code,
1159                          dwarf::DW_IDX_compile_unit);
1160       ++NumErrors;
1161     }
1162     if (!Attributes.count(dwarf::DW_IDX_die_offset)) {
1163       error() << formatv(
1164           "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n",
1165           NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset);
1166       ++NumErrors;
1167     }
1168   }
1169   return NumErrors;
1170 }
1171 
1172 static SmallVector<StringRef, 2> getNames(const DWARFDie &DIE,
1173                                           bool IncludeLinkageName = true) {
1174   SmallVector<StringRef, 2> Result;
1175   if (const char *Str = DIE.getName(DINameKind::ShortName))
1176     Result.emplace_back(Str);
1177   else if (DIE.getTag() == dwarf::DW_TAG_namespace)
1178     Result.emplace_back("(anonymous namespace)");
1179 
1180   if (IncludeLinkageName) {
1181     if (const char *Str = DIE.getName(DINameKind::LinkageName)) {
1182       if (Result.empty() || Result[0] != Str)
1183         Result.emplace_back(Str);
1184     }
1185   }
1186 
1187   return Result;
1188 }
1189 
1190 unsigned DWARFVerifier::verifyNameIndexEntries(
1191     const DWARFDebugNames::NameIndex &NI,
1192     const DWARFDebugNames::NameTableEntry &NTE) {
1193   // Verifying type unit indexes not supported.
1194   if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0)
1195     return 0;
1196 
1197   const char *CStr = NTE.getString();
1198   if (!CStr) {
1199     error() << formatv(
1200         "Name Index @ {0:x}: Unable to get string associated with name {1}.\n",
1201         NI.getUnitOffset(), NTE.getIndex());
1202     return 1;
1203   }
1204   StringRef Str(CStr);
1205 
1206   unsigned NumErrors = 0;
1207   unsigned NumEntries = 0;
1208   uint64_t EntryID = NTE.getEntryOffset();
1209   uint64_t NextEntryID = EntryID;
1210   Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&NextEntryID);
1211   for (; EntryOr; ++NumEntries, EntryID = NextEntryID,
1212                                 EntryOr = NI.getEntry(&NextEntryID)) {
1213     uint32_t CUIndex = *EntryOr->getCUIndex();
1214     if (CUIndex > NI.getCUCount()) {
1215       error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
1216                          "invalid CU index ({2}).\n",
1217                          NI.getUnitOffset(), EntryID, CUIndex);
1218       ++NumErrors;
1219       continue;
1220     }
1221     uint64_t CUOffset = NI.getCUOffset(CUIndex);
1222     uint64_t DIEOffset = CUOffset + *EntryOr->getDIEUnitOffset();
1223     DWARFDie DIE = DCtx.getDIEForOffset(DIEOffset);
1224     if (!DIE) {
1225       error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
1226                          "non-existing DIE @ {2:x}.\n",
1227                          NI.getUnitOffset(), EntryID, DIEOffset);
1228       ++NumErrors;
1229       continue;
1230     }
1231     if (DIE.getDwarfUnit()->getOffset() != CUOffset) {
1232       error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of "
1233                          "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n",
1234                          NI.getUnitOffset(), EntryID, DIEOffset, CUOffset,
1235                          DIE.getDwarfUnit()->getOffset());
1236       ++NumErrors;
1237     }
1238     if (DIE.getTag() != EntryOr->tag()) {
1239       error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of "
1240                          "DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1241                          NI.getUnitOffset(), EntryID, DIEOffset, EntryOr->tag(),
1242                          DIE.getTag());
1243       ++NumErrors;
1244     }
1245 
1246     auto EntryNames = getNames(DIE);
1247     if (!is_contained(EntryNames, Str)) {
1248       error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name "
1249                          "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1250                          NI.getUnitOffset(), EntryID, DIEOffset, Str,
1251                          make_range(EntryNames.begin(), EntryNames.end()));
1252       ++NumErrors;
1253     }
1254   }
1255   handleAllErrors(EntryOr.takeError(),
1256                   [&](const DWARFDebugNames::SentinelError &) {
1257                     if (NumEntries > 0)
1258                       return;
1259                     error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
1260                                        "not associated with any entries.\n",
1261                                        NI.getUnitOffset(), NTE.getIndex(), Str);
1262                     ++NumErrors;
1263                   },
1264                   [&](const ErrorInfoBase &Info) {
1265                     error()
1266                         << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n",
1267                                    NI.getUnitOffset(), NTE.getIndex(), Str,
1268                                    Info.message());
1269                     ++NumErrors;
1270                   });
1271   return NumErrors;
1272 }
1273 
1274 static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) {
1275   Expected<std::vector<DWARFLocationExpression>> Loc =
1276       Die.getLocations(DW_AT_location);
1277   if (!Loc) {
1278     consumeError(Loc.takeError());
1279     return false;
1280   }
1281   DWARFUnit *U = Die.getDwarfUnit();
1282   for (const auto &Entry : *Loc) {
1283     DataExtractor Data(toStringRef(Entry.Expr), DCtx.isLittleEndian(),
1284                        U->getAddressByteSize());
1285     DWARFExpression Expression(Data, U->getVersion(), U->getAddressByteSize());
1286     bool IsInteresting = any_of(Expression, [](DWARFExpression::Operation &Op) {
1287       return !Op.isError() && (Op.getCode() == DW_OP_addr ||
1288                                Op.getCode() == DW_OP_form_tls_address ||
1289                                Op.getCode() == DW_OP_GNU_push_tls_address);
1290     });
1291     if (IsInteresting)
1292       return true;
1293   }
1294   return false;
1295 }
1296 
1297 unsigned DWARFVerifier::verifyNameIndexCompleteness(
1298     const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI) {
1299 
1300   // First check, if the Die should be indexed. The code follows the DWARF v5
1301   // wording as closely as possible.
1302 
1303   // "All non-defining declarations (that is, debugging information entries
1304   // with a DW_AT_declaration attribute) are excluded."
1305   if (Die.find(DW_AT_declaration))
1306     return 0;
1307 
1308   // "DW_TAG_namespace debugging information entries without a DW_AT_name
1309   // attribute are included with the name “(anonymous namespace)”.
1310   // All other debugging information entries without a DW_AT_name attribute
1311   // are excluded."
1312   // "If a subprogram or inlined subroutine is included, and has a
1313   // DW_AT_linkage_name attribute, there will be an additional index entry for
1314   // the linkage name."
1315   auto IncludeLinkageName = Die.getTag() == DW_TAG_subprogram ||
1316                             Die.getTag() == DW_TAG_inlined_subroutine;
1317   auto EntryNames = getNames(Die, IncludeLinkageName);
1318   if (EntryNames.empty())
1319     return 0;
1320 
1321   // We deviate from the specification here, which says:
1322   // "The name index must contain an entry for each debugging information entry
1323   // that defines a named subprogram, label, variable, type, or namespace,
1324   // subject to ..."
1325   // Instead whitelisting all TAGs representing a "type" or a "subprogram", to
1326   // make sure we catch any missing items, we instead blacklist all TAGs that we
1327   // know shouldn't be indexed.
1328   switch (Die.getTag()) {
1329   // Compile units and modules have names but shouldn't be indexed.
1330   case DW_TAG_compile_unit:
1331   case DW_TAG_module:
1332     return 0;
1333 
1334   // Function and template parameters are not globally visible, so we shouldn't
1335   // index them.
1336   case DW_TAG_formal_parameter:
1337   case DW_TAG_template_value_parameter:
1338   case DW_TAG_template_type_parameter:
1339   case DW_TAG_GNU_template_parameter_pack:
1340   case DW_TAG_GNU_template_template_param:
1341     return 0;
1342 
1343   // Object members aren't globally visible.
1344   case DW_TAG_member:
1345     return 0;
1346 
1347   // According to a strict reading of the specification, enumerators should not
1348   // be indexed (and LLVM currently does not do that). However, this causes
1349   // problems for the debuggers, so we may need to reconsider this.
1350   case DW_TAG_enumerator:
1351     return 0;
1352 
1353   // Imported declarations should not be indexed according to the specification
1354   // and LLVM currently does not do that.
1355   case DW_TAG_imported_declaration:
1356     return 0;
1357 
1358   // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging
1359   // information entries without an address attribute (DW_AT_low_pc,
1360   // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded."
1361   case DW_TAG_subprogram:
1362   case DW_TAG_inlined_subroutine:
1363   case DW_TAG_label:
1364     if (Die.findRecursively(
1365             {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc}))
1366       break;
1367     return 0;
1368 
1369   // "DW_TAG_variable debugging information entries with a DW_AT_location
1370   // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are
1371   // included; otherwise, they are excluded."
1372   //
1373   // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list.
1374   case DW_TAG_variable:
1375     if (isVariableIndexable(Die, DCtx))
1376       break;
1377     return 0;
1378 
1379   default:
1380     break;
1381   }
1382 
1383   // Now we know that our Die should be present in the Index. Let's check if
1384   // that's the case.
1385   unsigned NumErrors = 0;
1386   uint64_t DieUnitOffset = Die.getOffset() - Die.getDwarfUnit()->getOffset();
1387   for (StringRef Name : EntryNames) {
1388     if (none_of(NI.equal_range(Name), [&](const DWARFDebugNames::Entry &E) {
1389           return E.getDIEUnitOffset() == DieUnitOffset;
1390         })) {
1391       error() << formatv("Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with "
1392                          "name {3} missing.\n",
1393                          NI.getUnitOffset(), Die.getOffset(), Die.getTag(),
1394                          Name);
1395       ++NumErrors;
1396     }
1397   }
1398   return NumErrors;
1399 }
1400 
1401 unsigned DWARFVerifier::verifyDebugNames(const DWARFSection &AccelSection,
1402                                          const DataExtractor &StrData) {
1403   unsigned NumErrors = 0;
1404   DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), AccelSection,
1405                                       DCtx.isLittleEndian(), 0);
1406   DWARFDebugNames AccelTable(AccelSectionData, StrData);
1407 
1408   OS << "Verifying .debug_names...\n";
1409 
1410   // This verifies that we can read individual name indices and their
1411   // abbreviation tables.
1412   if (Error E = AccelTable.extract()) {
1413     error() << toString(std::move(E)) << '\n';
1414     return 1;
1415   }
1416 
1417   NumErrors += verifyDebugNamesCULists(AccelTable);
1418   for (const auto &NI : AccelTable)
1419     NumErrors += verifyNameIndexBuckets(NI, StrData);
1420   for (const auto &NI : AccelTable)
1421     NumErrors += verifyNameIndexAbbrevs(NI);
1422 
1423   // Don't attempt Entry validation if any of the previous checks found errors
1424   if (NumErrors > 0)
1425     return NumErrors;
1426   for (const auto &NI : AccelTable)
1427     for (DWARFDebugNames::NameTableEntry NTE : NI)
1428       NumErrors += verifyNameIndexEntries(NI, NTE);
1429 
1430   if (NumErrors > 0)
1431     return NumErrors;
1432 
1433   for (const std::unique_ptr<DWARFUnit> &U : DCtx.compile_units()) {
1434     if (const DWARFDebugNames::NameIndex *NI =
1435             AccelTable.getCUNameIndex(U->getOffset())) {
1436       auto *CU = cast<DWARFCompileUnit>(U.get());
1437       for (const DWARFDebugInfoEntry &Die : CU->dies())
1438         NumErrors += verifyNameIndexCompleteness(DWARFDie(CU, &Die), *NI);
1439     }
1440   }
1441   return NumErrors;
1442 }
1443 
1444 bool DWARFVerifier::handleAccelTables() {
1445   const DWARFObject &D = DCtx.getDWARFObj();
1446   DataExtractor StrData(D.getStrSection(), DCtx.isLittleEndian(), 0);
1447   unsigned NumErrors = 0;
1448   if (!D.getAppleNamesSection().Data.empty())
1449     NumErrors += verifyAppleAccelTable(&D.getAppleNamesSection(), &StrData,
1450                                        ".apple_names");
1451   if (!D.getAppleTypesSection().Data.empty())
1452     NumErrors += verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData,
1453                                        ".apple_types");
1454   if (!D.getAppleNamespacesSection().Data.empty())
1455     NumErrors += verifyAppleAccelTable(&D.getAppleNamespacesSection(), &StrData,
1456                                        ".apple_namespaces");
1457   if (!D.getAppleObjCSection().Data.empty())
1458     NumErrors += verifyAppleAccelTable(&D.getAppleObjCSection(), &StrData,
1459                                        ".apple_objc");
1460 
1461   if (!D.getNamesSection().Data.empty())
1462     NumErrors += verifyDebugNames(D.getNamesSection(), StrData);
1463   return NumErrors == 0;
1464 }
1465 
1466 raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); }
1467 
1468 raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); }
1469 
1470 raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); }
1471 
1472 raw_ostream &DWARFVerifier::dump(const DWARFDie &Die, unsigned indent) const {
1473   Die.dump(OS, indent, DumpOpts);
1474   return OS;
1475 }
1476