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