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