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                                    U->getFormParams().Format);
491         bool Error = any_of(Expression, [](DWARFExpression::Operation &Op) {
492           return Op.isError();
493         });
494         if (Error || !Expression.verify(U))
495           ReportError("DIE contains invalid DWARF expression:");
496       }
497     } else
498       ReportError(toString(Loc.takeError()));
499     break;
500   }
501   case DW_AT_specification:
502   case DW_AT_abstract_origin: {
503     if (auto ReferencedDie = Die.getAttributeValueAsReferencedDie(Attr)) {
504       auto DieTag = Die.getTag();
505       auto RefTag = ReferencedDie.getTag();
506       if (DieTag == RefTag)
507         break;
508       if (DieTag == DW_TAG_inlined_subroutine && RefTag == DW_TAG_subprogram)
509         break;
510       if (DieTag == DW_TAG_variable && RefTag == DW_TAG_member)
511         break;
512       // This might be reference to a function declaration.
513       if (DieTag == DW_TAG_GNU_call_site && RefTag == DW_TAG_subprogram)
514         break;
515       ReportError("DIE with tag " + TagString(DieTag) + " has " +
516                   AttributeString(Attr) +
517                   " that points to DIE with "
518                   "incompatible tag " +
519                   TagString(RefTag));
520     }
521     break;
522   }
523   case DW_AT_type: {
524     DWARFDie TypeDie = Die.getAttributeValueAsReferencedDie(DW_AT_type);
525     if (TypeDie && !isType(TypeDie.getTag())) {
526       ReportError("DIE has " + AttributeString(Attr) +
527                   " with incompatible tag " + TagString(TypeDie.getTag()));
528     }
529     break;
530   }
531   default:
532     break;
533   }
534   return NumErrors;
535 }
536 
537 unsigned DWARFVerifier::verifyDebugInfoForm(const DWARFDie &Die,
538                                             DWARFAttribute &AttrValue) {
539   const DWARFObject &DObj = DCtx.getDWARFObj();
540   auto DieCU = Die.getDwarfUnit();
541   unsigned NumErrors = 0;
542   const auto Form = AttrValue.Value.getForm();
543   switch (Form) {
544   case DW_FORM_ref1:
545   case DW_FORM_ref2:
546   case DW_FORM_ref4:
547   case DW_FORM_ref8:
548   case DW_FORM_ref_udata: {
549     // Verify all CU relative references are valid CU offsets.
550     Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
551     assert(RefVal);
552     if (RefVal) {
553       auto CUSize = DieCU->getNextUnitOffset() - DieCU->getOffset();
554       auto CUOffset = AttrValue.Value.getRawUValue();
555       if (CUOffset >= CUSize) {
556         ++NumErrors;
557         error() << FormEncodingString(Form) << " CU offset "
558                 << format("0x%08" PRIx64, CUOffset)
559                 << " is invalid (must be less than CU size of "
560                 << format("0x%08" PRIx64, CUSize) << "):\n";
561         Die.dump(OS, 0, DumpOpts);
562         dump(Die) << '\n';
563       } else {
564         // Valid reference, but we will verify it points to an actual
565         // DIE later.
566         ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
567       }
568     }
569     break;
570   }
571   case DW_FORM_ref_addr: {
572     // Verify all absolute DIE references have valid offsets in the
573     // .debug_info section.
574     Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
575     assert(RefVal);
576     if (RefVal) {
577       if (*RefVal >= DieCU->getInfoSection().Data.size()) {
578         ++NumErrors;
579         error() << "DW_FORM_ref_addr offset beyond .debug_info "
580                    "bounds:\n";
581         dump(Die) << '\n';
582       } else {
583         // Valid reference, but we will verify it points to an actual
584         // DIE later.
585         ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
586       }
587     }
588     break;
589   }
590   case DW_FORM_strp: {
591     auto SecOffset = AttrValue.Value.getAsSectionOffset();
592     assert(SecOffset); // DW_FORM_strp is a section offset.
593     if (SecOffset && *SecOffset >= DObj.getStrSection().size()) {
594       ++NumErrors;
595       error() << "DW_FORM_strp offset beyond .debug_str bounds:\n";
596       dump(Die) << '\n';
597     }
598     break;
599   }
600   case DW_FORM_strx:
601   case DW_FORM_strx1:
602   case DW_FORM_strx2:
603   case DW_FORM_strx3:
604   case DW_FORM_strx4: {
605     auto Index = AttrValue.Value.getRawUValue();
606     auto DieCU = Die.getDwarfUnit();
607     // Check that we have a valid DWARF v5 string offsets table.
608     if (!DieCU->getStringOffsetsTableContribution()) {
609       ++NumErrors;
610       error() << FormEncodingString(Form)
611               << " used without a valid string offsets table:\n";
612       dump(Die) << '\n';
613       break;
614     }
615     // Check that the index is within the bounds of the section.
616     unsigned ItemSize = DieCU->getDwarfStringOffsetsByteSize();
617     // Use a 64-bit type to calculate the offset to guard against overflow.
618     uint64_t Offset =
619         (uint64_t)DieCU->getStringOffsetsBase() + Index * ItemSize;
620     if (DObj.getStrOffsetsSection().Data.size() < Offset + ItemSize) {
621       ++NumErrors;
622       error() << FormEncodingString(Form) << " uses index "
623               << format("%" PRIu64, Index) << ", which is too large:\n";
624       dump(Die) << '\n';
625       break;
626     }
627     // Check that the string offset is valid.
628     uint64_t StringOffset = *DieCU->getStringOffsetSectionItem(Index);
629     if (StringOffset >= DObj.getStrSection().size()) {
630       ++NumErrors;
631       error() << FormEncodingString(Form) << " uses index "
632               << format("%" PRIu64, Index)
633               << ", but the referenced string"
634                  " offset is beyond .debug_str bounds:\n";
635       dump(Die) << '\n';
636     }
637     break;
638   }
639   default:
640     break;
641   }
642   return NumErrors;
643 }
644 
645 unsigned DWARFVerifier::verifyDebugInfoReferences() {
646   // Take all references and make sure they point to an actual DIE by
647   // getting the DIE by offset and emitting an error
648   OS << "Verifying .debug_info references...\n";
649   unsigned NumErrors = 0;
650   for (const std::pair<const uint64_t, std::set<uint64_t>> &Pair :
651        ReferenceToDIEOffsets) {
652     if (DCtx.getDIEForOffset(Pair.first))
653       continue;
654     ++NumErrors;
655     error() << "invalid DIE reference " << format("0x%08" PRIx64, Pair.first)
656             << ". Offset is in between DIEs:\n";
657     for (auto Offset : Pair.second)
658       dump(DCtx.getDIEForOffset(Offset)) << '\n';
659     OS << "\n";
660   }
661   return NumErrors;
662 }
663 
664 void DWARFVerifier::verifyDebugLineStmtOffsets() {
665   std::map<uint64_t, DWARFDie> StmtListToDie;
666   for (const auto &CU : DCtx.compile_units()) {
667     auto Die = CU->getUnitDIE();
668     // Get the attribute value as a section offset. No need to produce an
669     // error here if the encoding isn't correct because we validate this in
670     // the .debug_info verifier.
671     auto StmtSectionOffset = toSectionOffset(Die.find(DW_AT_stmt_list));
672     if (!StmtSectionOffset)
673       continue;
674     const uint64_t LineTableOffset = *StmtSectionOffset;
675     auto LineTable = DCtx.getLineTableForUnit(CU.get());
676     if (LineTableOffset < DCtx.getDWARFObj().getLineSection().Data.size()) {
677       if (!LineTable) {
678         ++NumDebugLineErrors;
679         error() << ".debug_line[" << format("0x%08" PRIx64, LineTableOffset)
680                 << "] was not able to be parsed for CU:\n";
681         dump(Die) << '\n';
682         continue;
683       }
684     } else {
685       // Make sure we don't get a valid line table back if the offset is wrong.
686       assert(LineTable == nullptr);
687       // Skip this line table as it isn't valid. No need to create an error
688       // here because we validate this in the .debug_info verifier.
689       continue;
690     }
691     auto Iter = StmtListToDie.find(LineTableOffset);
692     if (Iter != StmtListToDie.end()) {
693       ++NumDebugLineErrors;
694       error() << "two compile unit DIEs, "
695               << format("0x%08" PRIx64, Iter->second.getOffset()) << " and "
696               << format("0x%08" PRIx64, Die.getOffset())
697               << ", have the same DW_AT_stmt_list section offset:\n";
698       dump(Iter->second);
699       dump(Die) << '\n';
700       // Already verified this line table before, no need to do it again.
701       continue;
702     }
703     StmtListToDie[LineTableOffset] = Die;
704   }
705 }
706 
707 void DWARFVerifier::verifyDebugLineRows() {
708   for (const auto &CU : DCtx.compile_units()) {
709     auto Die = CU->getUnitDIE();
710     auto LineTable = DCtx.getLineTableForUnit(CU.get());
711     // If there is no line table we will have created an error in the
712     // .debug_info verifier or in verifyDebugLineStmtOffsets().
713     if (!LineTable)
714       continue;
715 
716     // Verify prologue.
717     uint32_t MaxDirIndex = LineTable->Prologue.IncludeDirectories.size();
718     uint32_t FileIndex = 1;
719     StringMap<uint16_t> FullPathMap;
720     for (const auto &FileName : LineTable->Prologue.FileNames) {
721       // Verify directory index.
722       if (FileName.DirIdx > MaxDirIndex) {
723         ++NumDebugLineErrors;
724         error() << ".debug_line["
725                 << format("0x%08" PRIx64,
726                           *toSectionOffset(Die.find(DW_AT_stmt_list)))
727                 << "].prologue.file_names[" << FileIndex
728                 << "].dir_idx contains an invalid index: " << FileName.DirIdx
729                 << "\n";
730       }
731 
732       // Check file paths for duplicates.
733       std::string FullPath;
734       const bool HasFullPath = LineTable->getFileNameByIndex(
735           FileIndex, CU->getCompilationDir(),
736           DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FullPath);
737       assert(HasFullPath && "Invalid index?");
738       (void)HasFullPath;
739       auto It = FullPathMap.find(FullPath);
740       if (It == FullPathMap.end())
741         FullPathMap[FullPath] = FileIndex;
742       else if (It->second != FileIndex) {
743         warn() << ".debug_line["
744                << format("0x%08" PRIx64,
745                          *toSectionOffset(Die.find(DW_AT_stmt_list)))
746                << "].prologue.file_names[" << FileIndex
747                << "] is a duplicate of file_names[" << It->second << "]\n";
748       }
749 
750       FileIndex++;
751     }
752 
753     // Verify rows.
754     uint64_t PrevAddress = 0;
755     uint32_t RowIndex = 0;
756     for (const auto &Row : LineTable->Rows) {
757       // Verify row address.
758       if (Row.Address.Address < PrevAddress) {
759         ++NumDebugLineErrors;
760         error() << ".debug_line["
761                 << format("0x%08" PRIx64,
762                           *toSectionOffset(Die.find(DW_AT_stmt_list)))
763                 << "] row[" << RowIndex
764                 << "] decreases in address from previous row:\n";
765 
766         DWARFDebugLine::Row::dumpTableHeader(OS);
767         if (RowIndex > 0)
768           LineTable->Rows[RowIndex - 1].dump(OS);
769         Row.dump(OS);
770         OS << '\n';
771       }
772 
773       // Verify file index.
774       if (!LineTable->hasFileAtIndex(Row.File)) {
775         ++NumDebugLineErrors;
776         bool isDWARF5 = LineTable->Prologue.getVersion() >= 5;
777         error() << ".debug_line["
778                 << format("0x%08" PRIx64,
779                           *toSectionOffset(Die.find(DW_AT_stmt_list)))
780                 << "][" << RowIndex << "] has invalid file index " << Row.File
781                 << " (valid values are [" << (isDWARF5 ? "0," : "1,")
782                 << LineTable->Prologue.FileNames.size()
783                 << (isDWARF5 ? ")" : "]") << "):\n";
784         DWARFDebugLine::Row::dumpTableHeader(OS);
785         Row.dump(OS);
786         OS << '\n';
787       }
788       if (Row.EndSequence)
789         PrevAddress = 0;
790       else
791         PrevAddress = Row.Address.Address;
792       ++RowIndex;
793     }
794   }
795 }
796 
797 DWARFVerifier::DWARFVerifier(raw_ostream &S, DWARFContext &D,
798                              DIDumpOptions DumpOpts)
799     : OS(S), DCtx(D), DumpOpts(std::move(DumpOpts)), IsObjectFile(false),
800       IsMachOObject(false) {
801   if (const auto *F = DCtx.getDWARFObj().getFile()) {
802     IsObjectFile = F->isRelocatableObject();
803     IsMachOObject = F->isMachO();
804   }
805 }
806 
807 bool DWARFVerifier::handleDebugLine() {
808   NumDebugLineErrors = 0;
809   OS << "Verifying .debug_line...\n";
810   verifyDebugLineStmtOffsets();
811   verifyDebugLineRows();
812   return NumDebugLineErrors == 0;
813 }
814 
815 unsigned DWARFVerifier::verifyAppleAccelTable(const DWARFSection *AccelSection,
816                                               DataExtractor *StrData,
817                                               const char *SectionName) {
818   unsigned NumErrors = 0;
819   DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), *AccelSection,
820                                       DCtx.isLittleEndian(), 0);
821   AppleAcceleratorTable AccelTable(AccelSectionData, *StrData);
822 
823   OS << "Verifying " << SectionName << "...\n";
824 
825   // Verify that the fixed part of the header is not too short.
826   if (!AccelSectionData.isValidOffset(AccelTable.getSizeHdr())) {
827     error() << "Section is too small to fit a section header.\n";
828     return 1;
829   }
830 
831   // Verify that the section is not too short.
832   if (Error E = AccelTable.extract()) {
833     error() << toString(std::move(E)) << '\n';
834     return 1;
835   }
836 
837   // Verify that all buckets have a valid hash index or are empty.
838   uint32_t NumBuckets = AccelTable.getNumBuckets();
839   uint32_t NumHashes = AccelTable.getNumHashes();
840 
841   uint64_t BucketsOffset =
842       AccelTable.getSizeHdr() + AccelTable.getHeaderDataLength();
843   uint64_t HashesBase = BucketsOffset + NumBuckets * 4;
844   uint64_t OffsetsBase = HashesBase + NumHashes * 4;
845   for (uint32_t BucketIdx = 0; BucketIdx < NumBuckets; ++BucketIdx) {
846     uint32_t HashIdx = AccelSectionData.getU32(&BucketsOffset);
847     if (HashIdx >= NumHashes && HashIdx != UINT32_MAX) {
848       error() << format("Bucket[%d] has invalid hash index: %u.\n", BucketIdx,
849                         HashIdx);
850       ++NumErrors;
851     }
852   }
853   uint32_t NumAtoms = AccelTable.getAtomsDesc().size();
854   if (NumAtoms == 0) {
855     error() << "No atoms: failed to read HashData.\n";
856     return 1;
857   }
858   if (!AccelTable.validateForms()) {
859     error() << "Unsupported form: failed to read HashData.\n";
860     return 1;
861   }
862 
863   for (uint32_t HashIdx = 0; HashIdx < NumHashes; ++HashIdx) {
864     uint64_t HashOffset = HashesBase + 4 * HashIdx;
865     uint64_t DataOffset = OffsetsBase + 4 * HashIdx;
866     uint32_t Hash = AccelSectionData.getU32(&HashOffset);
867     uint64_t HashDataOffset = AccelSectionData.getU32(&DataOffset);
868     if (!AccelSectionData.isValidOffsetForDataOfSize(HashDataOffset,
869                                                      sizeof(uint64_t))) {
870       error() << format("Hash[%d] has invalid HashData offset: "
871                         "0x%08" PRIx64 ".\n",
872                         HashIdx, HashDataOffset);
873       ++NumErrors;
874     }
875 
876     uint64_t StrpOffset;
877     uint64_t StringOffset;
878     uint32_t StringCount = 0;
879     uint64_t Offset;
880     unsigned Tag;
881     while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) {
882       const uint32_t NumHashDataObjects =
883           AccelSectionData.getU32(&HashDataOffset);
884       for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects;
885            ++HashDataIdx) {
886         std::tie(Offset, Tag) = AccelTable.readAtoms(&HashDataOffset);
887         auto Die = DCtx.getDIEForOffset(Offset);
888         if (!Die) {
889           const uint32_t BucketIdx =
890               NumBuckets ? (Hash % NumBuckets) : UINT32_MAX;
891           StringOffset = StrpOffset;
892           const char *Name = StrData->getCStr(&StringOffset);
893           if (!Name)
894             Name = "<NULL>";
895 
896           error() << format(
897               "%s Bucket[%d] Hash[%d] = 0x%08x "
898               "Str[%u] = 0x%08" PRIx64 " DIE[%d] = 0x%08" PRIx64 " "
899               "is not a valid DIE offset for \"%s\".\n",
900               SectionName, BucketIdx, HashIdx, Hash, StringCount, StrpOffset,
901               HashDataIdx, Offset, Name);
902 
903           ++NumErrors;
904           continue;
905         }
906         if ((Tag != dwarf::DW_TAG_null) && (Die.getTag() != Tag)) {
907           error() << "Tag " << dwarf::TagString(Tag)
908                   << " in accelerator table does not match Tag "
909                   << dwarf::TagString(Die.getTag()) << " of DIE[" << HashDataIdx
910                   << "].\n";
911           ++NumErrors;
912         }
913       }
914       ++StringCount;
915     }
916   }
917   return NumErrors;
918 }
919 
920 unsigned
921 DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) {
922   // A map from CU offset to the (first) Name Index offset which claims to index
923   // this CU.
924   DenseMap<uint64_t, uint64_t> CUMap;
925   const uint64_t NotIndexed = std::numeric_limits<uint64_t>::max();
926 
927   CUMap.reserve(DCtx.getNumCompileUnits());
928   for (const auto &CU : DCtx.compile_units())
929     CUMap[CU->getOffset()] = NotIndexed;
930 
931   unsigned NumErrors = 0;
932   for (const DWARFDebugNames::NameIndex &NI : AccelTable) {
933     if (NI.getCUCount() == 0) {
934       error() << formatv("Name Index @ {0:x} does not index any CU\n",
935                          NI.getUnitOffset());
936       ++NumErrors;
937       continue;
938     }
939     for (uint32_t CU = 0, End = NI.getCUCount(); CU < End; ++CU) {
940       uint64_t Offset = NI.getCUOffset(CU);
941       auto Iter = CUMap.find(Offset);
942 
943       if (Iter == CUMap.end()) {
944         error() << formatv(
945             "Name Index @ {0:x} references a non-existing CU @ {1:x}\n",
946             NI.getUnitOffset(), Offset);
947         ++NumErrors;
948         continue;
949       }
950 
951       if (Iter->second != NotIndexed) {
952         error() << formatv("Name Index @ {0:x} references a CU @ {1:x}, but "
953                            "this CU is already indexed by Name Index @ {2:x}\n",
954                            NI.getUnitOffset(), Offset, Iter->second);
955         continue;
956       }
957       Iter->second = NI.getUnitOffset();
958     }
959   }
960 
961   for (const auto &KV : CUMap) {
962     if (KV.second == NotIndexed)
963       warn() << formatv("CU @ {0:x} not covered by any Name Index\n", KV.first);
964   }
965 
966   return NumErrors;
967 }
968 
969 unsigned
970 DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI,
971                                       const DataExtractor &StrData) {
972   struct BucketInfo {
973     uint32_t Bucket;
974     uint32_t Index;
975 
976     constexpr BucketInfo(uint32_t Bucket, uint32_t Index)
977         : Bucket(Bucket), Index(Index) {}
978     bool operator<(const BucketInfo &RHS) const { return Index < RHS.Index; }
979   };
980 
981   uint32_t NumErrors = 0;
982   if (NI.getBucketCount() == 0) {
983     warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n",
984                       NI.getUnitOffset());
985     return NumErrors;
986   }
987 
988   // Build up a list of (Bucket, Index) pairs. We use this later to verify that
989   // each Name is reachable from the appropriate bucket.
990   std::vector<BucketInfo> BucketStarts;
991   BucketStarts.reserve(NI.getBucketCount() + 1);
992   for (uint32_t Bucket = 0, End = NI.getBucketCount(); Bucket < End; ++Bucket) {
993     uint32_t Index = NI.getBucketArrayEntry(Bucket);
994     if (Index > NI.getNameCount()) {
995       error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid "
996                          "value {2}. Valid range is [0, {3}].\n",
997                          Bucket, NI.getUnitOffset(), Index, NI.getNameCount());
998       ++NumErrors;
999       continue;
1000     }
1001     if (Index > 0)
1002       BucketStarts.emplace_back(Bucket, Index);
1003   }
1004 
1005   // If there were any buckets with invalid values, skip further checks as they
1006   // will likely produce many errors which will only confuse the actual root
1007   // problem.
1008   if (NumErrors > 0)
1009     return NumErrors;
1010 
1011   // Sort the list in the order of increasing "Index" entries.
1012   array_pod_sort(BucketStarts.begin(), BucketStarts.end());
1013 
1014   // Insert a sentinel entry at the end, so we can check that the end of the
1015   // table is covered in the loop below.
1016   BucketStarts.emplace_back(NI.getBucketCount(), NI.getNameCount() + 1);
1017 
1018   // Loop invariant: NextUncovered is the (1-based) index of the first Name
1019   // which is not reachable by any of the buckets we processed so far (and
1020   // hasn't been reported as uncovered).
1021   uint32_t NextUncovered = 1;
1022   for (const BucketInfo &B : BucketStarts) {
1023     // Under normal circumstances B.Index be equal to NextUncovered, but it can
1024     // be less if a bucket points to names which are already known to be in some
1025     // bucket we processed earlier. In that case, we won't trigger this error,
1026     // but report the mismatched hash value error instead. (We know the hash
1027     // will not match because we have already verified that the name's hash
1028     // puts it into the previous bucket.)
1029     if (B.Index > NextUncovered) {
1030       error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] "
1031                          "are not covered by the hash table.\n",
1032                          NI.getUnitOffset(), NextUncovered, B.Index - 1);
1033       ++NumErrors;
1034     }
1035     uint32_t Idx = B.Index;
1036 
1037     // The rest of the checks apply only to non-sentinel entries.
1038     if (B.Bucket == NI.getBucketCount())
1039       break;
1040 
1041     // This triggers if a non-empty bucket points to a name with a mismatched
1042     // hash. Clients are likely to interpret this as an empty bucket, because a
1043     // mismatched hash signals the end of a bucket, but if this is indeed an
1044     // empty bucket, the producer should have signalled this by marking the
1045     // bucket as empty.
1046     uint32_t FirstHash = NI.getHashArrayEntry(Idx);
1047     if (FirstHash % NI.getBucketCount() != B.Bucket) {
1048       error() << formatv(
1049           "Name Index @ {0:x}: Bucket {1} is not empty but points to a "
1050           "mismatched hash value {2:x} (belonging to bucket {3}).\n",
1051           NI.getUnitOffset(), B.Bucket, FirstHash,
1052           FirstHash % NI.getBucketCount());
1053       ++NumErrors;
1054     }
1055 
1056     // This find the end of this bucket and also verifies that all the hashes in
1057     // this bucket are correct by comparing the stored hashes to the ones we
1058     // compute ourselves.
1059     while (Idx <= NI.getNameCount()) {
1060       uint32_t Hash = NI.getHashArrayEntry(Idx);
1061       if (Hash % NI.getBucketCount() != B.Bucket)
1062         break;
1063 
1064       const char *Str = NI.getNameTableEntry(Idx).getString();
1065       if (caseFoldingDjbHash(Str) != Hash) {
1066         error() << formatv("Name Index @ {0:x}: String ({1}) at index {2} "
1067                            "hashes to {3:x}, but "
1068                            "the Name Index hash is {4:x}\n",
1069                            NI.getUnitOffset(), Str, Idx,
1070                            caseFoldingDjbHash(Str), Hash);
1071         ++NumErrors;
1072       }
1073 
1074       ++Idx;
1075     }
1076     NextUncovered = std::max(NextUncovered, Idx);
1077   }
1078   return NumErrors;
1079 }
1080 
1081 unsigned DWARFVerifier::verifyNameIndexAttribute(
1082     const DWARFDebugNames::NameIndex &NI, const DWARFDebugNames::Abbrev &Abbr,
1083     DWARFDebugNames::AttributeEncoding AttrEnc) {
1084   StringRef FormName = dwarf::FormEncodingString(AttrEnc.Form);
1085   if (FormName.empty()) {
1086     error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1087                        "unknown form: {3}.\n",
1088                        NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1089                        AttrEnc.Form);
1090     return 1;
1091   }
1092 
1093   if (AttrEnc.Index == DW_IDX_type_hash) {
1094     if (AttrEnc.Form != dwarf::DW_FORM_data8) {
1095       error() << formatv(
1096           "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash "
1097           "uses an unexpected form {2} (should be {3}).\n",
1098           NI.getUnitOffset(), Abbr.Code, AttrEnc.Form, dwarf::DW_FORM_data8);
1099       return 1;
1100     }
1101   }
1102 
1103   // A list of known index attributes and their expected form classes.
1104   // DW_IDX_type_hash is handled specially in the check above, as it has a
1105   // specific form (not just a form class) we should expect.
1106   struct FormClassTable {
1107     dwarf::Index Index;
1108     DWARFFormValue::FormClass Class;
1109     StringLiteral ClassName;
1110   };
1111   static constexpr FormClassTable Table[] = {
1112       {dwarf::DW_IDX_compile_unit, DWARFFormValue::FC_Constant, {"constant"}},
1113       {dwarf::DW_IDX_type_unit, DWARFFormValue::FC_Constant, {"constant"}},
1114       {dwarf::DW_IDX_die_offset, DWARFFormValue::FC_Reference, {"reference"}},
1115       {dwarf::DW_IDX_parent, DWARFFormValue::FC_Constant, {"constant"}},
1116   };
1117 
1118   ArrayRef<FormClassTable> TableRef(Table);
1119   auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) {
1120     return T.Index == AttrEnc.Index;
1121   });
1122   if (Iter == TableRef.end()) {
1123     warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an "
1124                       "unknown index attribute: {2}.\n",
1125                       NI.getUnitOffset(), Abbr.Code, AttrEnc.Index);
1126     return 0;
1127   }
1128 
1129   if (!DWARFFormValue(AttrEnc.Form).isFormClass(Iter->Class)) {
1130     error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1131                        "unexpected form {3} (expected form class {4}).\n",
1132                        NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1133                        AttrEnc.Form, Iter->ClassName);
1134     return 1;
1135   }
1136   return 0;
1137 }
1138 
1139 unsigned
1140 DWARFVerifier::verifyNameIndexAbbrevs(const DWARFDebugNames::NameIndex &NI) {
1141   if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) {
1142     warn() << formatv("Name Index @ {0:x}: Verifying indexes of type units is "
1143                       "not currently supported.\n",
1144                       NI.getUnitOffset());
1145     return 0;
1146   }
1147 
1148   unsigned NumErrors = 0;
1149   for (const auto &Abbrev : NI.getAbbrevs()) {
1150     StringRef TagName = dwarf::TagString(Abbrev.Tag);
1151     if (TagName.empty()) {
1152       warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an "
1153                         "unknown tag: {2}.\n",
1154                         NI.getUnitOffset(), Abbrev.Code, Abbrev.Tag);
1155     }
1156     SmallSet<unsigned, 5> Attributes;
1157     for (const auto &AttrEnc : Abbrev.Attributes) {
1158       if (!Attributes.insert(AttrEnc.Index).second) {
1159         error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains "
1160                            "multiple {2} attributes.\n",
1161                            NI.getUnitOffset(), Abbrev.Code, AttrEnc.Index);
1162         ++NumErrors;
1163         continue;
1164       }
1165       NumErrors += verifyNameIndexAttribute(NI, Abbrev, AttrEnc);
1166     }
1167 
1168     if (NI.getCUCount() > 1 && !Attributes.count(dwarf::DW_IDX_compile_unit)) {
1169       error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units "
1170                          "and abbreviation {1:x} has no {2} attribute.\n",
1171                          NI.getUnitOffset(), Abbrev.Code,
1172                          dwarf::DW_IDX_compile_unit);
1173       ++NumErrors;
1174     }
1175     if (!Attributes.count(dwarf::DW_IDX_die_offset)) {
1176       error() << formatv(
1177           "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n",
1178           NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset);
1179       ++NumErrors;
1180     }
1181   }
1182   return NumErrors;
1183 }
1184 
1185 static SmallVector<StringRef, 2> getNames(const DWARFDie &DIE,
1186                                           bool IncludeLinkageName = true) {
1187   SmallVector<StringRef, 2> Result;
1188   if (const char *Str = DIE.getName(DINameKind::ShortName))
1189     Result.emplace_back(Str);
1190   else if (DIE.getTag() == dwarf::DW_TAG_namespace)
1191     Result.emplace_back("(anonymous namespace)");
1192 
1193   if (IncludeLinkageName) {
1194     if (const char *Str = DIE.getName(DINameKind::LinkageName)) {
1195       if (Result.empty() || Result[0] != Str)
1196         Result.emplace_back(Str);
1197     }
1198   }
1199 
1200   return Result;
1201 }
1202 
1203 unsigned DWARFVerifier::verifyNameIndexEntries(
1204     const DWARFDebugNames::NameIndex &NI,
1205     const DWARFDebugNames::NameTableEntry &NTE) {
1206   // Verifying type unit indexes not supported.
1207   if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0)
1208     return 0;
1209 
1210   const char *CStr = NTE.getString();
1211   if (!CStr) {
1212     error() << formatv(
1213         "Name Index @ {0:x}: Unable to get string associated with name {1}.\n",
1214         NI.getUnitOffset(), NTE.getIndex());
1215     return 1;
1216   }
1217   StringRef Str(CStr);
1218 
1219   unsigned NumErrors = 0;
1220   unsigned NumEntries = 0;
1221   uint64_t EntryID = NTE.getEntryOffset();
1222   uint64_t NextEntryID = EntryID;
1223   Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&NextEntryID);
1224   for (; EntryOr; ++NumEntries, EntryID = NextEntryID,
1225                                 EntryOr = NI.getEntry(&NextEntryID)) {
1226     uint32_t CUIndex = *EntryOr->getCUIndex();
1227     if (CUIndex > NI.getCUCount()) {
1228       error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
1229                          "invalid CU index ({2}).\n",
1230                          NI.getUnitOffset(), EntryID, CUIndex);
1231       ++NumErrors;
1232       continue;
1233     }
1234     uint64_t CUOffset = NI.getCUOffset(CUIndex);
1235     uint64_t DIEOffset = CUOffset + *EntryOr->getDIEUnitOffset();
1236     DWARFDie DIE = DCtx.getDIEForOffset(DIEOffset);
1237     if (!DIE) {
1238       error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
1239                          "non-existing DIE @ {2:x}.\n",
1240                          NI.getUnitOffset(), EntryID, DIEOffset);
1241       ++NumErrors;
1242       continue;
1243     }
1244     if (DIE.getDwarfUnit()->getOffset() != CUOffset) {
1245       error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of "
1246                          "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n",
1247                          NI.getUnitOffset(), EntryID, DIEOffset, CUOffset,
1248                          DIE.getDwarfUnit()->getOffset());
1249       ++NumErrors;
1250     }
1251     if (DIE.getTag() != EntryOr->tag()) {
1252       error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of "
1253                          "DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1254                          NI.getUnitOffset(), EntryID, DIEOffset, EntryOr->tag(),
1255                          DIE.getTag());
1256       ++NumErrors;
1257     }
1258 
1259     auto EntryNames = getNames(DIE);
1260     if (!is_contained(EntryNames, Str)) {
1261       error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name "
1262                          "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1263                          NI.getUnitOffset(), EntryID, DIEOffset, Str,
1264                          make_range(EntryNames.begin(), EntryNames.end()));
1265       ++NumErrors;
1266     }
1267   }
1268   handleAllErrors(EntryOr.takeError(),
1269                   [&](const DWARFDebugNames::SentinelError &) {
1270                     if (NumEntries > 0)
1271                       return;
1272                     error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
1273                                        "not associated with any entries.\n",
1274                                        NI.getUnitOffset(), NTE.getIndex(), Str);
1275                     ++NumErrors;
1276                   },
1277                   [&](const ErrorInfoBase &Info) {
1278                     error()
1279                         << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n",
1280                                    NI.getUnitOffset(), NTE.getIndex(), Str,
1281                                    Info.message());
1282                     ++NumErrors;
1283                   });
1284   return NumErrors;
1285 }
1286 
1287 static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) {
1288   Expected<std::vector<DWARFLocationExpression>> Loc =
1289       Die.getLocations(DW_AT_location);
1290   if (!Loc) {
1291     consumeError(Loc.takeError());
1292     return false;
1293   }
1294   DWARFUnit *U = Die.getDwarfUnit();
1295   for (const auto &Entry : *Loc) {
1296     DataExtractor Data(toStringRef(Entry.Expr), DCtx.isLittleEndian(),
1297                        U->getAddressByteSize());
1298     DWARFExpression Expression(Data, U->getAddressByteSize(),
1299                                U->getFormParams().Format);
1300     bool IsInteresting = any_of(Expression, [](DWARFExpression::Operation &Op) {
1301       return !Op.isError() && (Op.getCode() == DW_OP_addr ||
1302                                Op.getCode() == DW_OP_form_tls_address ||
1303                                Op.getCode() == DW_OP_GNU_push_tls_address);
1304     });
1305     if (IsInteresting)
1306       return true;
1307   }
1308   return false;
1309 }
1310 
1311 unsigned DWARFVerifier::verifyNameIndexCompleteness(
1312     const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI) {
1313 
1314   // First check, if the Die should be indexed. The code follows the DWARF v5
1315   // wording as closely as possible.
1316 
1317   // "All non-defining declarations (that is, debugging information entries
1318   // with a DW_AT_declaration attribute) are excluded."
1319   if (Die.find(DW_AT_declaration))
1320     return 0;
1321 
1322   // "DW_TAG_namespace debugging information entries without a DW_AT_name
1323   // attribute are included with the name “(anonymous namespace)”.
1324   // All other debugging information entries without a DW_AT_name attribute
1325   // are excluded."
1326   // "If a subprogram or inlined subroutine is included, and has a
1327   // DW_AT_linkage_name attribute, there will be an additional index entry for
1328   // the linkage name."
1329   auto IncludeLinkageName = Die.getTag() == DW_TAG_subprogram ||
1330                             Die.getTag() == DW_TAG_inlined_subroutine;
1331   auto EntryNames = getNames(Die, IncludeLinkageName);
1332   if (EntryNames.empty())
1333     return 0;
1334 
1335   // We deviate from the specification here, which says:
1336   // "The name index must contain an entry for each debugging information entry
1337   // that defines a named subprogram, label, variable, type, or namespace,
1338   // subject to ..."
1339   // Instead whitelisting all TAGs representing a "type" or a "subprogram", to
1340   // make sure we catch any missing items, we instead blacklist all TAGs that we
1341   // know shouldn't be indexed.
1342   switch (Die.getTag()) {
1343   // Compile units and modules have names but shouldn't be indexed.
1344   case DW_TAG_compile_unit:
1345   case DW_TAG_module:
1346     return 0;
1347 
1348   // Function and template parameters are not globally visible, so we shouldn't
1349   // index them.
1350   case DW_TAG_formal_parameter:
1351   case DW_TAG_template_value_parameter:
1352   case DW_TAG_template_type_parameter:
1353   case DW_TAG_GNU_template_parameter_pack:
1354   case DW_TAG_GNU_template_template_param:
1355     return 0;
1356 
1357   // Object members aren't globally visible.
1358   case DW_TAG_member:
1359     return 0;
1360 
1361   // According to a strict reading of the specification, enumerators should not
1362   // be indexed (and LLVM currently does not do that). However, this causes
1363   // problems for the debuggers, so we may need to reconsider this.
1364   case DW_TAG_enumerator:
1365     return 0;
1366 
1367   // Imported declarations should not be indexed according to the specification
1368   // and LLVM currently does not do that.
1369   case DW_TAG_imported_declaration:
1370     return 0;
1371 
1372   // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging
1373   // information entries without an address attribute (DW_AT_low_pc,
1374   // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded."
1375   case DW_TAG_subprogram:
1376   case DW_TAG_inlined_subroutine:
1377   case DW_TAG_label:
1378     if (Die.findRecursively(
1379             {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc}))
1380       break;
1381     return 0;
1382 
1383   // "DW_TAG_variable debugging information entries with a DW_AT_location
1384   // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are
1385   // included; otherwise, they are excluded."
1386   //
1387   // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list.
1388   case DW_TAG_variable:
1389     if (isVariableIndexable(Die, DCtx))
1390       break;
1391     return 0;
1392 
1393   default:
1394     break;
1395   }
1396 
1397   // Now we know that our Die should be present in the Index. Let's check if
1398   // that's the case.
1399   unsigned NumErrors = 0;
1400   uint64_t DieUnitOffset = Die.getOffset() - Die.getDwarfUnit()->getOffset();
1401   for (StringRef Name : EntryNames) {
1402     if (none_of(NI.equal_range(Name), [&](const DWARFDebugNames::Entry &E) {
1403           return E.getDIEUnitOffset() == DieUnitOffset;
1404         })) {
1405       error() << formatv("Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with "
1406                          "name {3} missing.\n",
1407                          NI.getUnitOffset(), Die.getOffset(), Die.getTag(),
1408                          Name);
1409       ++NumErrors;
1410     }
1411   }
1412   return NumErrors;
1413 }
1414 
1415 unsigned DWARFVerifier::verifyDebugNames(const DWARFSection &AccelSection,
1416                                          const DataExtractor &StrData) {
1417   unsigned NumErrors = 0;
1418   DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), AccelSection,
1419                                       DCtx.isLittleEndian(), 0);
1420   DWARFDebugNames AccelTable(AccelSectionData, StrData);
1421 
1422   OS << "Verifying .debug_names...\n";
1423 
1424   // This verifies that we can read individual name indices and their
1425   // abbreviation tables.
1426   if (Error E = AccelTable.extract()) {
1427     error() << toString(std::move(E)) << '\n';
1428     return 1;
1429   }
1430 
1431   NumErrors += verifyDebugNamesCULists(AccelTable);
1432   for (const auto &NI : AccelTable)
1433     NumErrors += verifyNameIndexBuckets(NI, StrData);
1434   for (const auto &NI : AccelTable)
1435     NumErrors += verifyNameIndexAbbrevs(NI);
1436 
1437   // Don't attempt Entry validation if any of the previous checks found errors
1438   if (NumErrors > 0)
1439     return NumErrors;
1440   for (const auto &NI : AccelTable)
1441     for (DWARFDebugNames::NameTableEntry NTE : NI)
1442       NumErrors += verifyNameIndexEntries(NI, NTE);
1443 
1444   if (NumErrors > 0)
1445     return NumErrors;
1446 
1447   for (const std::unique_ptr<DWARFUnit> &U : DCtx.compile_units()) {
1448     if (const DWARFDebugNames::NameIndex *NI =
1449             AccelTable.getCUNameIndex(U->getOffset())) {
1450       auto *CU = cast<DWARFCompileUnit>(U.get());
1451       for (const DWARFDebugInfoEntry &Die : CU->dies())
1452         NumErrors += verifyNameIndexCompleteness(DWARFDie(CU, &Die), *NI);
1453     }
1454   }
1455   return NumErrors;
1456 }
1457 
1458 bool DWARFVerifier::handleAccelTables() {
1459   const DWARFObject &D = DCtx.getDWARFObj();
1460   DataExtractor StrData(D.getStrSection(), DCtx.isLittleEndian(), 0);
1461   unsigned NumErrors = 0;
1462   if (!D.getAppleNamesSection().Data.empty())
1463     NumErrors += verifyAppleAccelTable(&D.getAppleNamesSection(), &StrData,
1464                                        ".apple_names");
1465   if (!D.getAppleTypesSection().Data.empty())
1466     NumErrors += verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData,
1467                                        ".apple_types");
1468   if (!D.getAppleNamespacesSection().Data.empty())
1469     NumErrors += verifyAppleAccelTable(&D.getAppleNamespacesSection(), &StrData,
1470                                        ".apple_namespaces");
1471   if (!D.getAppleObjCSection().Data.empty())
1472     NumErrors += verifyAppleAccelTable(&D.getAppleObjCSection(), &StrData,
1473                                        ".apple_objc");
1474 
1475   if (!D.getNamesSection().Data.empty())
1476     NumErrors += verifyDebugNames(D.getNamesSection(), StrData);
1477   return NumErrors == 0;
1478 }
1479 
1480 raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); }
1481 
1482 raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); }
1483 
1484 raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); }
1485 
1486 raw_ostream &DWARFVerifier::dump(const DWARFDie &Die, unsigned indent) const {
1487   Die.dump(OS, indent, DumpOpts);
1488   return OS;
1489 }
1490