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