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