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