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