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