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