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