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 uint32_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 uint32_t OffsetStart = *Offset; 115 Length = DebugInfoData.getU32(Offset); 116 if (Length == UINT32_MAX) { 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%08x \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 uint32_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(llvm::make_unique<DWARFTypeUnit>( 298 DCtx, S, Header, DCtx.getDebugAbbrev(), &DObj.getRangeSection(), 299 &DObj.getLocSection(), DObj.getStringSection(), 300 DObj.getStringOffsetSection(), &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(llvm::make_unique<DWARFCompileUnit>( 312 DCtx, S, Header, DCtx.getDebugAbbrev(), &DObj.getRangeSection(), 313 &DObj.getLocSection(), DObj.getStringSection(), 314 DObj.getStringOffsetSection(), &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.getRangeSection().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.data(), Entry.Loc.size()}); 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" PRIx32, 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.getStringSection().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.getStringOffsetSection().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.getStringSection().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<uint32_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 uint32_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" PRIx32, 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" PRIx32, Iter->second.getOffset()) << " and " 684 << format("0x%08" PRIx32, 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 uint32_t BucketsOffset = 830 AccelTable.getSizeHdr() + AccelTable.getHeaderDataLength(); 831 uint32_t HashesBase = BucketsOffset + NumBuckets * 4; 832 uint32_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 uint32_t HashOffset = HashesBase + 4 * HashIdx; 853 uint32_t DataOffset = OffsetsBase + 4 * HashIdx; 854 uint32_t Hash = AccelSectionData.getU32(&HashOffset); 855 uint32_t HashDataOffset = AccelSectionData.getU32(&DataOffset); 856 if (!AccelSectionData.isValidOffsetForDataOfSize(HashDataOffset, 857 sizeof(uint64_t))) { 858 error() << format("Hash[%d] has invalid HashData offset: 0x%08x.\n", 859 HashIdx, HashDataOffset); 860 ++NumErrors; 861 } 862 863 uint32_t StrpOffset; 864 uint32_t StringOffset; 865 uint32_t StringCount = 0; 866 unsigned Offset; 867 unsigned Tag; 868 while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) { 869 const uint32_t NumHashDataObjects = 870 AccelSectionData.getU32(&HashDataOffset); 871 for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects; 872 ++HashDataIdx) { 873 std::tie(Offset, Tag) = AccelTable.readAtoms(HashDataOffset); 874 auto Die = DCtx.getDIEForOffset(Offset); 875 if (!Die) { 876 const uint32_t BucketIdx = 877 NumBuckets ? (Hash % NumBuckets) : UINT32_MAX; 878 StringOffset = StrpOffset; 879 const char *Name = StrData->getCStr(&StringOffset); 880 if (!Name) 881 Name = "<NULL>"; 882 883 error() << format( 884 "%s Bucket[%d] Hash[%d] = 0x%08x " 885 "Str[%u] = 0x%08x " 886 "DIE[%d] = 0x%08x is not a valid DIE offset for \"%s\".\n", 887 SectionName, BucketIdx, HashIdx, Hash, StringCount, StrpOffset, 888 HashDataIdx, Offset, Name); 889 890 ++NumErrors; 891 continue; 892 } 893 if ((Tag != dwarf::DW_TAG_null) && (Die.getTag() != Tag)) { 894 error() << "Tag " << dwarf::TagString(Tag) 895 << " in accelerator table does not match Tag " 896 << dwarf::TagString(Die.getTag()) << " of DIE[" << HashDataIdx 897 << "].\n"; 898 ++NumErrors; 899 } 900 } 901 ++StringCount; 902 } 903 } 904 return NumErrors; 905 } 906 907 unsigned 908 DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) { 909 // A map from CU offset to the (first) Name Index offset which claims to index 910 // this CU. 911 DenseMap<uint32_t, uint32_t> CUMap; 912 const uint32_t NotIndexed = std::numeric_limits<uint32_t>::max(); 913 914 CUMap.reserve(DCtx.getNumCompileUnits()); 915 for (const auto &CU : DCtx.compile_units()) 916 CUMap[CU->getOffset()] = NotIndexed; 917 918 unsigned NumErrors = 0; 919 for (const DWARFDebugNames::NameIndex &NI : AccelTable) { 920 if (NI.getCUCount() == 0) { 921 error() << formatv("Name Index @ {0:x} does not index any CU\n", 922 NI.getUnitOffset()); 923 ++NumErrors; 924 continue; 925 } 926 for (uint32_t CU = 0, End = NI.getCUCount(); CU < End; ++CU) { 927 uint32_t Offset = NI.getCUOffset(CU); 928 auto Iter = CUMap.find(Offset); 929 930 if (Iter == CUMap.end()) { 931 error() << formatv( 932 "Name Index @ {0:x} references a non-existing CU @ {1:x}\n", 933 NI.getUnitOffset(), Offset); 934 ++NumErrors; 935 continue; 936 } 937 938 if (Iter->second != NotIndexed) { 939 error() << formatv("Name Index @ {0:x} references a CU @ {1:x}, but " 940 "this CU is already indexed by Name Index @ {2:x}\n", 941 NI.getUnitOffset(), Offset, Iter->second); 942 continue; 943 } 944 Iter->second = NI.getUnitOffset(); 945 } 946 } 947 948 for (const auto &KV : CUMap) { 949 if (KV.second == NotIndexed) 950 warn() << formatv("CU @ {0:x} not covered by any Name Index\n", KV.first); 951 } 952 953 return NumErrors; 954 } 955 956 unsigned 957 DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI, 958 const DataExtractor &StrData) { 959 struct BucketInfo { 960 uint32_t Bucket; 961 uint32_t Index; 962 963 constexpr BucketInfo(uint32_t Bucket, uint32_t Index) 964 : Bucket(Bucket), Index(Index) {} 965 bool operator<(const BucketInfo &RHS) const { return Index < RHS.Index; }; 966 }; 967 968 uint32_t NumErrors = 0; 969 if (NI.getBucketCount() == 0) { 970 warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n", 971 NI.getUnitOffset()); 972 return NumErrors; 973 } 974 975 // Build up a list of (Bucket, Index) pairs. We use this later to verify that 976 // each Name is reachable from the appropriate bucket. 977 std::vector<BucketInfo> BucketStarts; 978 BucketStarts.reserve(NI.getBucketCount() + 1); 979 for (uint32_t Bucket = 0, End = NI.getBucketCount(); Bucket < End; ++Bucket) { 980 uint32_t Index = NI.getBucketArrayEntry(Bucket); 981 if (Index > NI.getNameCount()) { 982 error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid " 983 "value {2}. Valid range is [0, {3}].\n", 984 Bucket, NI.getUnitOffset(), Index, NI.getNameCount()); 985 ++NumErrors; 986 continue; 987 } 988 if (Index > 0) 989 BucketStarts.emplace_back(Bucket, Index); 990 } 991 992 // If there were any buckets with invalid values, skip further checks as they 993 // will likely produce many errors which will only confuse the actual root 994 // problem. 995 if (NumErrors > 0) 996 return NumErrors; 997 998 // Sort the list in the order of increasing "Index" entries. 999 array_pod_sort(BucketStarts.begin(), BucketStarts.end()); 1000 1001 // Insert a sentinel entry at the end, so we can check that the end of the 1002 // table is covered in the loop below. 1003 BucketStarts.emplace_back(NI.getBucketCount(), NI.getNameCount() + 1); 1004 1005 // Loop invariant: NextUncovered is the (1-based) index of the first Name 1006 // which is not reachable by any of the buckets we processed so far (and 1007 // hasn't been reported as uncovered). 1008 uint32_t NextUncovered = 1; 1009 for (const BucketInfo &B : BucketStarts) { 1010 // Under normal circumstances B.Index be equal to NextUncovered, but it can 1011 // be less if a bucket points to names which are already known to be in some 1012 // bucket we processed earlier. In that case, we won't trigger this error, 1013 // but report the mismatched hash value error instead. (We know the hash 1014 // will not match because we have already verified that the name's hash 1015 // puts it into the previous bucket.) 1016 if (B.Index > NextUncovered) { 1017 error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] " 1018 "are not covered by the hash table.\n", 1019 NI.getUnitOffset(), NextUncovered, B.Index - 1); 1020 ++NumErrors; 1021 } 1022 uint32_t Idx = B.Index; 1023 1024 // The rest of the checks apply only to non-sentinel entries. 1025 if (B.Bucket == NI.getBucketCount()) 1026 break; 1027 1028 // This triggers if a non-empty bucket points to a name with a mismatched 1029 // hash. Clients are likely to interpret this as an empty bucket, because a 1030 // mismatched hash signals the end of a bucket, but if this is indeed an 1031 // empty bucket, the producer should have signalled this by marking the 1032 // bucket as empty. 1033 uint32_t FirstHash = NI.getHashArrayEntry(Idx); 1034 if (FirstHash % NI.getBucketCount() != B.Bucket) { 1035 error() << formatv( 1036 "Name Index @ {0:x}: Bucket {1} is not empty but points to a " 1037 "mismatched hash value {2:x} (belonging to bucket {3}).\n", 1038 NI.getUnitOffset(), B.Bucket, FirstHash, 1039 FirstHash % NI.getBucketCount()); 1040 ++NumErrors; 1041 } 1042 1043 // This find the end of this bucket and also verifies that all the hashes in 1044 // this bucket are correct by comparing the stored hashes to the ones we 1045 // compute ourselves. 1046 while (Idx <= NI.getNameCount()) { 1047 uint32_t Hash = NI.getHashArrayEntry(Idx); 1048 if (Hash % NI.getBucketCount() != B.Bucket) 1049 break; 1050 1051 const char *Str = NI.getNameTableEntry(Idx).getString(); 1052 if (caseFoldingDjbHash(Str) != Hash) { 1053 error() << formatv("Name Index @ {0:x}: String ({1}) at index {2} " 1054 "hashes to {3:x}, but " 1055 "the Name Index hash is {4:x}\n", 1056 NI.getUnitOffset(), Str, Idx, 1057 caseFoldingDjbHash(Str), Hash); 1058 ++NumErrors; 1059 } 1060 1061 ++Idx; 1062 } 1063 NextUncovered = std::max(NextUncovered, Idx); 1064 } 1065 return NumErrors; 1066 } 1067 1068 unsigned DWARFVerifier::verifyNameIndexAttribute( 1069 const DWARFDebugNames::NameIndex &NI, const DWARFDebugNames::Abbrev &Abbr, 1070 DWARFDebugNames::AttributeEncoding AttrEnc) { 1071 StringRef FormName = dwarf::FormEncodingString(AttrEnc.Form); 1072 if (FormName.empty()) { 1073 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an " 1074 "unknown form: {3}.\n", 1075 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index, 1076 AttrEnc.Form); 1077 return 1; 1078 } 1079 1080 if (AttrEnc.Index == DW_IDX_type_hash) { 1081 if (AttrEnc.Form != dwarf::DW_FORM_data8) { 1082 error() << formatv( 1083 "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash " 1084 "uses an unexpected form {2} (should be {3}).\n", 1085 NI.getUnitOffset(), Abbr.Code, AttrEnc.Form, dwarf::DW_FORM_data8); 1086 return 1; 1087 } 1088 } 1089 1090 // A list of known index attributes and their expected form classes. 1091 // DW_IDX_type_hash is handled specially in the check above, as it has a 1092 // specific form (not just a form class) we should expect. 1093 struct FormClassTable { 1094 dwarf::Index Index; 1095 DWARFFormValue::FormClass Class; 1096 StringLiteral ClassName; 1097 }; 1098 static constexpr FormClassTable Table[] = { 1099 {dwarf::DW_IDX_compile_unit, DWARFFormValue::FC_Constant, {"constant"}}, 1100 {dwarf::DW_IDX_type_unit, DWARFFormValue::FC_Constant, {"constant"}}, 1101 {dwarf::DW_IDX_die_offset, DWARFFormValue::FC_Reference, {"reference"}}, 1102 {dwarf::DW_IDX_parent, DWARFFormValue::FC_Constant, {"constant"}}, 1103 }; 1104 1105 ArrayRef<FormClassTable> TableRef(Table); 1106 auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) { 1107 return T.Index == AttrEnc.Index; 1108 }); 1109 if (Iter == TableRef.end()) { 1110 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an " 1111 "unknown index attribute: {2}.\n", 1112 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index); 1113 return 0; 1114 } 1115 1116 if (!DWARFFormValue(AttrEnc.Form).isFormClass(Iter->Class)) { 1117 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an " 1118 "unexpected form {3} (expected form class {4}).\n", 1119 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index, 1120 AttrEnc.Form, Iter->ClassName); 1121 return 1; 1122 } 1123 return 0; 1124 } 1125 1126 unsigned 1127 DWARFVerifier::verifyNameIndexAbbrevs(const DWARFDebugNames::NameIndex &NI) { 1128 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) { 1129 warn() << formatv("Name Index @ {0:x}: Verifying indexes of type units is " 1130 "not currently supported.\n", 1131 NI.getUnitOffset()); 1132 return 0; 1133 } 1134 1135 unsigned NumErrors = 0; 1136 for (const auto &Abbrev : NI.getAbbrevs()) { 1137 StringRef TagName = dwarf::TagString(Abbrev.Tag); 1138 if (TagName.empty()) { 1139 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an " 1140 "unknown tag: {2}.\n", 1141 NI.getUnitOffset(), Abbrev.Code, Abbrev.Tag); 1142 } 1143 SmallSet<unsigned, 5> Attributes; 1144 for (const auto &AttrEnc : Abbrev.Attributes) { 1145 if (!Attributes.insert(AttrEnc.Index).second) { 1146 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains " 1147 "multiple {2} attributes.\n", 1148 NI.getUnitOffset(), Abbrev.Code, AttrEnc.Index); 1149 ++NumErrors; 1150 continue; 1151 } 1152 NumErrors += verifyNameIndexAttribute(NI, Abbrev, AttrEnc); 1153 } 1154 1155 if (NI.getCUCount() > 1 && !Attributes.count(dwarf::DW_IDX_compile_unit)) { 1156 error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units " 1157 "and abbreviation {1:x} has no {2} attribute.\n", 1158 NI.getUnitOffset(), Abbrev.Code, 1159 dwarf::DW_IDX_compile_unit); 1160 ++NumErrors; 1161 } 1162 if (!Attributes.count(dwarf::DW_IDX_die_offset)) { 1163 error() << formatv( 1164 "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n", 1165 NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset); 1166 ++NumErrors; 1167 } 1168 } 1169 return NumErrors; 1170 } 1171 1172 static SmallVector<StringRef, 2> getNames(const DWARFDie &DIE, 1173 bool IncludeLinkageName = true) { 1174 SmallVector<StringRef, 2> Result; 1175 if (const char *Str = DIE.getName(DINameKind::ShortName)) 1176 Result.emplace_back(Str); 1177 else if (DIE.getTag() == dwarf::DW_TAG_namespace) 1178 Result.emplace_back("(anonymous namespace)"); 1179 1180 if (IncludeLinkageName) { 1181 if (const char *Str = DIE.getName(DINameKind::LinkageName)) { 1182 if (Result.empty() || Result[0] != Str) 1183 Result.emplace_back(Str); 1184 } 1185 } 1186 1187 return Result; 1188 } 1189 1190 unsigned DWARFVerifier::verifyNameIndexEntries( 1191 const DWARFDebugNames::NameIndex &NI, 1192 const DWARFDebugNames::NameTableEntry &NTE) { 1193 // Verifying type unit indexes not supported. 1194 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) 1195 return 0; 1196 1197 const char *CStr = NTE.getString(); 1198 if (!CStr) { 1199 error() << formatv( 1200 "Name Index @ {0:x}: Unable to get string associated with name {1}.\n", 1201 NI.getUnitOffset(), NTE.getIndex()); 1202 return 1; 1203 } 1204 StringRef Str(CStr); 1205 1206 unsigned NumErrors = 0; 1207 unsigned NumEntries = 0; 1208 uint32_t EntryID = NTE.getEntryOffset(); 1209 uint32_t NextEntryID = EntryID; 1210 Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&NextEntryID); 1211 for (; EntryOr; ++NumEntries, EntryID = NextEntryID, 1212 EntryOr = NI.getEntry(&NextEntryID)) { 1213 uint32_t CUIndex = *EntryOr->getCUIndex(); 1214 if (CUIndex > NI.getCUCount()) { 1215 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an " 1216 "invalid CU index ({2}).\n", 1217 NI.getUnitOffset(), EntryID, CUIndex); 1218 ++NumErrors; 1219 continue; 1220 } 1221 uint32_t CUOffset = NI.getCUOffset(CUIndex); 1222 uint64_t DIEOffset = CUOffset + *EntryOr->getDIEUnitOffset(); 1223 DWARFDie DIE = DCtx.getDIEForOffset(DIEOffset); 1224 if (!DIE) { 1225 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a " 1226 "non-existing DIE @ {2:x}.\n", 1227 NI.getUnitOffset(), EntryID, DIEOffset); 1228 ++NumErrors; 1229 continue; 1230 } 1231 if (DIE.getDwarfUnit()->getOffset() != CUOffset) { 1232 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of " 1233 "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n", 1234 NI.getUnitOffset(), EntryID, DIEOffset, CUOffset, 1235 DIE.getDwarfUnit()->getOffset()); 1236 ++NumErrors; 1237 } 1238 if (DIE.getTag() != EntryOr->tag()) { 1239 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of " 1240 "DIE @ {2:x}: index - {3}; debug_info - {4}.\n", 1241 NI.getUnitOffset(), EntryID, DIEOffset, EntryOr->tag(), 1242 DIE.getTag()); 1243 ++NumErrors; 1244 } 1245 1246 auto EntryNames = getNames(DIE); 1247 if (!is_contained(EntryNames, Str)) { 1248 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name " 1249 "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n", 1250 NI.getUnitOffset(), EntryID, DIEOffset, Str, 1251 make_range(EntryNames.begin(), EntryNames.end())); 1252 ++NumErrors; 1253 } 1254 } 1255 handleAllErrors(EntryOr.takeError(), 1256 [&](const DWARFDebugNames::SentinelError &) { 1257 if (NumEntries > 0) 1258 return; 1259 error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is " 1260 "not associated with any entries.\n", 1261 NI.getUnitOffset(), NTE.getIndex(), Str); 1262 ++NumErrors; 1263 }, 1264 [&](const ErrorInfoBase &Info) { 1265 error() 1266 << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n", 1267 NI.getUnitOffset(), NTE.getIndex(), Str, 1268 Info.message()); 1269 ++NumErrors; 1270 }); 1271 return NumErrors; 1272 } 1273 1274 static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) { 1275 Optional<DWARFFormValue> Location = Die.findRecursively(DW_AT_location); 1276 if (!Location) 1277 return false; 1278 1279 auto ContainsInterestingOperators = [&](StringRef D) { 1280 DWARFUnit *U = Die.getDwarfUnit(); 1281 DataExtractor Data(D, DCtx.isLittleEndian(), U->getAddressByteSize()); 1282 DWARFExpression Expression(Data, U->getVersion(), U->getAddressByteSize()); 1283 return any_of(Expression, [](DWARFExpression::Operation &Op) { 1284 return !Op.isError() && (Op.getCode() == DW_OP_addr || 1285 Op.getCode() == DW_OP_form_tls_address || 1286 Op.getCode() == DW_OP_GNU_push_tls_address); 1287 }); 1288 }; 1289 1290 if (Optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) { 1291 // Inlined location. 1292 if (ContainsInterestingOperators(toStringRef(*Expr))) 1293 return true; 1294 } else if (Optional<uint64_t> Offset = Location->getAsSectionOffset()) { 1295 // Location list. 1296 if (const DWARFDebugLoc *DebugLoc = DCtx.getDebugLoc()) { 1297 if (const DWARFDebugLoc::LocationList *LocList = 1298 DebugLoc->getLocationListAtOffset(*Offset)) { 1299 if (any_of(LocList->Entries, [&](const DWARFDebugLoc::Entry &E) { 1300 return ContainsInterestingOperators({E.Loc.data(), E.Loc.size()}); 1301 })) 1302 return true; 1303 } 1304 } 1305 } 1306 return false; 1307 } 1308 1309 unsigned DWARFVerifier::verifyNameIndexCompleteness( 1310 const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI) { 1311 1312 // First check, if the Die should be indexed. The code follows the DWARF v5 1313 // wording as closely as possible. 1314 1315 // "All non-defining declarations (that is, debugging information entries 1316 // with a DW_AT_declaration attribute) are excluded." 1317 if (Die.find(DW_AT_declaration)) 1318 return 0; 1319 1320 // "DW_TAG_namespace debugging information entries without a DW_AT_name 1321 // attribute are included with the name “(anonymous namespace)”. 1322 // All other debugging information entries without a DW_AT_name attribute 1323 // are excluded." 1324 // "If a subprogram or inlined subroutine is included, and has a 1325 // DW_AT_linkage_name attribute, there will be an additional index entry for 1326 // the linkage name." 1327 auto IncludeLinkageName = Die.getTag() == DW_TAG_subprogram || 1328 Die.getTag() == DW_TAG_inlined_subroutine; 1329 auto EntryNames = getNames(Die, IncludeLinkageName); 1330 if (EntryNames.empty()) 1331 return 0; 1332 1333 // We deviate from the specification here, which says: 1334 // "The name index must contain an entry for each debugging information entry 1335 // that defines a named subprogram, label, variable, type, or namespace, 1336 // subject to ..." 1337 // Instead whitelisting all TAGs representing a "type" or a "subprogram", to 1338 // make sure we catch any missing items, we instead blacklist all TAGs that we 1339 // know shouldn't be indexed. 1340 switch (Die.getTag()) { 1341 // Compile units and modules have names but shouldn't be indexed. 1342 case DW_TAG_compile_unit: 1343 case DW_TAG_module: 1344 return 0; 1345 1346 // Function and template parameters are not globally visible, so we shouldn't 1347 // index them. 1348 case DW_TAG_formal_parameter: 1349 case DW_TAG_template_value_parameter: 1350 case DW_TAG_template_type_parameter: 1351 case DW_TAG_GNU_template_parameter_pack: 1352 case DW_TAG_GNU_template_template_param: 1353 return 0; 1354 1355 // Object members aren't globally visible. 1356 case DW_TAG_member: 1357 return 0; 1358 1359 // According to a strict reading of the specification, enumerators should not 1360 // be indexed (and LLVM currently does not do that). However, this causes 1361 // problems for the debuggers, so we may need to reconsider this. 1362 case DW_TAG_enumerator: 1363 return 0; 1364 1365 // Imported declarations should not be indexed according to the specification 1366 // and LLVM currently does not do that. 1367 case DW_TAG_imported_declaration: 1368 return 0; 1369 1370 // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging 1371 // information entries without an address attribute (DW_AT_low_pc, 1372 // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded." 1373 case DW_TAG_subprogram: 1374 case DW_TAG_inlined_subroutine: 1375 case DW_TAG_label: 1376 if (Die.findRecursively( 1377 {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc})) 1378 break; 1379 return 0; 1380 1381 // "DW_TAG_variable debugging information entries with a DW_AT_location 1382 // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are 1383 // included; otherwise, they are excluded." 1384 // 1385 // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list. 1386 case DW_TAG_variable: 1387 if (isVariableIndexable(Die, DCtx)) 1388 break; 1389 return 0; 1390 1391 default: 1392 break; 1393 } 1394 1395 // Now we know that our Die should be present in the Index. Let's check if 1396 // that's the case. 1397 unsigned NumErrors = 0; 1398 uint64_t DieUnitOffset = Die.getOffset() - Die.getDwarfUnit()->getOffset(); 1399 for (StringRef Name : EntryNames) { 1400 if (none_of(NI.equal_range(Name), [&](const DWARFDebugNames::Entry &E) { 1401 return E.getDIEUnitOffset() == DieUnitOffset; 1402 })) { 1403 error() << formatv("Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with " 1404 "name {3} missing.\n", 1405 NI.getUnitOffset(), Die.getOffset(), Die.getTag(), 1406 Name); 1407 ++NumErrors; 1408 } 1409 } 1410 return NumErrors; 1411 } 1412 1413 unsigned DWARFVerifier::verifyDebugNames(const DWARFSection &AccelSection, 1414 const DataExtractor &StrData) { 1415 unsigned NumErrors = 0; 1416 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), AccelSection, 1417 DCtx.isLittleEndian(), 0); 1418 DWARFDebugNames AccelTable(AccelSectionData, StrData); 1419 1420 OS << "Verifying .debug_names...\n"; 1421 1422 // This verifies that we can read individual name indices and their 1423 // abbreviation tables. 1424 if (Error E = AccelTable.extract()) { 1425 error() << toString(std::move(E)) << '\n'; 1426 return 1; 1427 } 1428 1429 NumErrors += verifyDebugNamesCULists(AccelTable); 1430 for (const auto &NI : AccelTable) 1431 NumErrors += verifyNameIndexBuckets(NI, StrData); 1432 for (const auto &NI : AccelTable) 1433 NumErrors += verifyNameIndexAbbrevs(NI); 1434 1435 // Don't attempt Entry validation if any of the previous checks found errors 1436 if (NumErrors > 0) 1437 return NumErrors; 1438 for (const auto &NI : AccelTable) 1439 for (DWARFDebugNames::NameTableEntry NTE : NI) 1440 NumErrors += verifyNameIndexEntries(NI, NTE); 1441 1442 if (NumErrors > 0) 1443 return NumErrors; 1444 1445 for (const std::unique_ptr<DWARFUnit> &U : DCtx.compile_units()) { 1446 if (const DWARFDebugNames::NameIndex *NI = 1447 AccelTable.getCUNameIndex(U->getOffset())) { 1448 auto *CU = cast<DWARFCompileUnit>(U.get()); 1449 for (const DWARFDebugInfoEntry &Die : CU->dies()) 1450 NumErrors += verifyNameIndexCompleteness(DWARFDie(CU, &Die), *NI); 1451 } 1452 } 1453 return NumErrors; 1454 } 1455 1456 bool DWARFVerifier::handleAccelTables() { 1457 const DWARFObject &D = DCtx.getDWARFObj(); 1458 DataExtractor StrData(D.getStringSection(), DCtx.isLittleEndian(), 0); 1459 unsigned NumErrors = 0; 1460 if (!D.getAppleNamesSection().Data.empty()) 1461 NumErrors += verifyAppleAccelTable(&D.getAppleNamesSection(), &StrData, 1462 ".apple_names"); 1463 if (!D.getAppleTypesSection().Data.empty()) 1464 NumErrors += verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData, 1465 ".apple_types"); 1466 if (!D.getAppleNamespacesSection().Data.empty()) 1467 NumErrors += verifyAppleAccelTable(&D.getAppleNamespacesSection(), &StrData, 1468 ".apple_namespaces"); 1469 if (!D.getAppleObjCSection().Data.empty()) 1470 NumErrors += verifyAppleAccelTable(&D.getAppleObjCSection(), &StrData, 1471 ".apple_objc"); 1472 1473 if (!D.getDebugNamesSection().Data.empty()) 1474 NumErrors += verifyDebugNames(D.getDebugNamesSection(), StrData); 1475 return NumErrors == 0; 1476 } 1477 1478 raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); } 1479 1480 raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); } 1481 1482 raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); } 1483 1484 raw_ostream &DWARFVerifier::dump(const DWARFDie &Die, unsigned indent) const { 1485 Die.dump(OS, indent, DumpOpts); 1486 return OS; 1487 } 1488