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 case DW_AT_call_file: 542 case DW_AT_decl_file: { 543 if (auto FileIdx = AttrValue.Value.getAsUnsignedConstant()) { 544 DWARFUnit *U = Die.getDwarfUnit(); 545 const auto *LT = U->getContext().getLineTableForUnit(U); 546 if (LT) { 547 if (!LT->hasFileAtIndex(*FileIdx)) { 548 bool IsZeroIndexed = LT->Prologue.getVersion() >= 5; 549 if (Optional<uint64_t> LastFileIdx = LT->getLastValidFileIndex()) { 550 ReportError("DIE has " + AttributeString(Attr) + 551 " with an invalid file index " + 552 llvm::formatv("{0}", *FileIdx) + 553 " (valid values are [" + (IsZeroIndexed ? "0-" : "1-") + 554 llvm::formatv("{0}", *LastFileIdx) + "])"); 555 } else { 556 ReportError("DIE has " + AttributeString(Attr) + 557 " with an invalid file index " + 558 llvm::formatv("{0}", *FileIdx) + 559 " (the file table in the prologue is empty)"); 560 } 561 } 562 } else { 563 ReportError("DIE has " + AttributeString(Attr) + 564 " that references a file with index " + 565 llvm::formatv("{0}", *FileIdx) + 566 " and the compile unit has no line table"); 567 } 568 } else { 569 ReportError("DIE has " + AttributeString(Attr) + 570 " with invalid encoding"); 571 } 572 break; 573 } 574 default: 575 break; 576 } 577 return NumErrors; 578 } 579 580 unsigned DWARFVerifier::verifyDebugInfoForm(const DWARFDie &Die, 581 DWARFAttribute &AttrValue) { 582 const DWARFObject &DObj = DCtx.getDWARFObj(); 583 auto DieCU = Die.getDwarfUnit(); 584 unsigned NumErrors = 0; 585 const auto Form = AttrValue.Value.getForm(); 586 switch (Form) { 587 case DW_FORM_ref1: 588 case DW_FORM_ref2: 589 case DW_FORM_ref4: 590 case DW_FORM_ref8: 591 case DW_FORM_ref_udata: { 592 // Verify all CU relative references are valid CU offsets. 593 Optional<uint64_t> RefVal = AttrValue.Value.getAsReference(); 594 assert(RefVal); 595 if (RefVal) { 596 auto CUSize = DieCU->getNextUnitOffset() - DieCU->getOffset(); 597 auto CUOffset = AttrValue.Value.getRawUValue(); 598 if (CUOffset >= CUSize) { 599 ++NumErrors; 600 error() << FormEncodingString(Form) << " CU offset " 601 << format("0x%08" PRIx64, CUOffset) 602 << " is invalid (must be less than CU size of " 603 << format("0x%08" PRIx64, CUSize) << "):\n"; 604 Die.dump(OS, 0, DumpOpts); 605 dump(Die) << '\n'; 606 } else { 607 // Valid reference, but we will verify it points to an actual 608 // DIE later. 609 ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset()); 610 } 611 } 612 break; 613 } 614 case DW_FORM_ref_addr: { 615 // Verify all absolute DIE references have valid offsets in the 616 // .debug_info section. 617 Optional<uint64_t> RefVal = AttrValue.Value.getAsReference(); 618 assert(RefVal); 619 if (RefVal) { 620 if (*RefVal >= DieCU->getInfoSection().Data.size()) { 621 ++NumErrors; 622 error() << "DW_FORM_ref_addr offset beyond .debug_info " 623 "bounds:\n"; 624 dump(Die) << '\n'; 625 } else { 626 // Valid reference, but we will verify it points to an actual 627 // DIE later. 628 ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset()); 629 } 630 } 631 break; 632 } 633 case DW_FORM_strp: { 634 auto SecOffset = AttrValue.Value.getAsSectionOffset(); 635 assert(SecOffset); // DW_FORM_strp is a section offset. 636 if (SecOffset && *SecOffset >= DObj.getStrSection().size()) { 637 ++NumErrors; 638 error() << "DW_FORM_strp offset beyond .debug_str bounds:\n"; 639 dump(Die) << '\n'; 640 } 641 break; 642 } 643 case DW_FORM_strx: 644 case DW_FORM_strx1: 645 case DW_FORM_strx2: 646 case DW_FORM_strx3: 647 case DW_FORM_strx4: { 648 auto Index = AttrValue.Value.getRawUValue(); 649 auto DieCU = Die.getDwarfUnit(); 650 // Check that we have a valid DWARF v5 string offsets table. 651 if (!DieCU->getStringOffsetsTableContribution()) { 652 ++NumErrors; 653 error() << FormEncodingString(Form) 654 << " used without a valid string offsets table:\n"; 655 dump(Die) << '\n'; 656 break; 657 } 658 // Check that the index is within the bounds of the section. 659 unsigned ItemSize = DieCU->getDwarfStringOffsetsByteSize(); 660 // Use a 64-bit type to calculate the offset to guard against overflow. 661 uint64_t Offset = 662 (uint64_t)DieCU->getStringOffsetsBase() + Index * ItemSize; 663 if (DObj.getStrOffsetsSection().Data.size() < Offset + ItemSize) { 664 ++NumErrors; 665 error() << FormEncodingString(Form) << " uses index " 666 << format("%" PRIu64, Index) << ", which is too large:\n"; 667 dump(Die) << '\n'; 668 break; 669 } 670 // Check that the string offset is valid. 671 uint64_t StringOffset = *DieCU->getStringOffsetSectionItem(Index); 672 if (StringOffset >= DObj.getStrSection().size()) { 673 ++NumErrors; 674 error() << FormEncodingString(Form) << " uses index " 675 << format("%" PRIu64, Index) 676 << ", but the referenced string" 677 " offset is beyond .debug_str bounds:\n"; 678 dump(Die) << '\n'; 679 } 680 break; 681 } 682 default: 683 break; 684 } 685 return NumErrors; 686 } 687 688 unsigned DWARFVerifier::verifyDebugInfoReferences() { 689 // Take all references and make sure they point to an actual DIE by 690 // getting the DIE by offset and emitting an error 691 OS << "Verifying .debug_info references...\n"; 692 unsigned NumErrors = 0; 693 for (const std::pair<const uint64_t, std::set<uint64_t>> &Pair : 694 ReferenceToDIEOffsets) { 695 if (DCtx.getDIEForOffset(Pair.first)) 696 continue; 697 ++NumErrors; 698 error() << "invalid DIE reference " << format("0x%08" PRIx64, Pair.first) 699 << ". Offset is in between DIEs:\n"; 700 for (auto Offset : Pair.second) 701 dump(DCtx.getDIEForOffset(Offset)) << '\n'; 702 OS << "\n"; 703 } 704 return NumErrors; 705 } 706 707 void DWARFVerifier::verifyDebugLineStmtOffsets() { 708 std::map<uint64_t, DWARFDie> StmtListToDie; 709 for (const auto &CU : DCtx.compile_units()) { 710 auto Die = CU->getUnitDIE(); 711 // Get the attribute value as a section offset. No need to produce an 712 // error here if the encoding isn't correct because we validate this in 713 // the .debug_info verifier. 714 auto StmtSectionOffset = toSectionOffset(Die.find(DW_AT_stmt_list)); 715 if (!StmtSectionOffset) 716 continue; 717 const uint64_t LineTableOffset = *StmtSectionOffset; 718 auto LineTable = DCtx.getLineTableForUnit(CU.get()); 719 if (LineTableOffset < DCtx.getDWARFObj().getLineSection().Data.size()) { 720 if (!LineTable) { 721 ++NumDebugLineErrors; 722 error() << ".debug_line[" << format("0x%08" PRIx64, LineTableOffset) 723 << "] was not able to be parsed for CU:\n"; 724 dump(Die) << '\n'; 725 continue; 726 } 727 } else { 728 // Make sure we don't get a valid line table back if the offset is wrong. 729 assert(LineTable == nullptr); 730 // Skip this line table as it isn't valid. No need to create an error 731 // here because we validate this in the .debug_info verifier. 732 continue; 733 } 734 auto Iter = StmtListToDie.find(LineTableOffset); 735 if (Iter != StmtListToDie.end()) { 736 ++NumDebugLineErrors; 737 error() << "two compile unit DIEs, " 738 << format("0x%08" PRIx64, Iter->second.getOffset()) << " and " 739 << format("0x%08" PRIx64, Die.getOffset()) 740 << ", have the same DW_AT_stmt_list section offset:\n"; 741 dump(Iter->second); 742 dump(Die) << '\n'; 743 // Already verified this line table before, no need to do it again. 744 continue; 745 } 746 StmtListToDie[LineTableOffset] = Die; 747 } 748 } 749 750 void DWARFVerifier::verifyDebugLineRows() { 751 for (const auto &CU : DCtx.compile_units()) { 752 auto Die = CU->getUnitDIE(); 753 auto LineTable = DCtx.getLineTableForUnit(CU.get()); 754 // If there is no line table we will have created an error in the 755 // .debug_info verifier or in verifyDebugLineStmtOffsets(). 756 if (!LineTable) 757 continue; 758 759 // Verify prologue. 760 uint32_t MaxDirIndex = LineTable->Prologue.IncludeDirectories.size(); 761 uint32_t FileIndex = 1; 762 StringMap<uint16_t> FullPathMap; 763 for (const auto &FileName : LineTable->Prologue.FileNames) { 764 // Verify directory index. 765 if (FileName.DirIdx > MaxDirIndex) { 766 ++NumDebugLineErrors; 767 error() << ".debug_line[" 768 << format("0x%08" PRIx64, 769 *toSectionOffset(Die.find(DW_AT_stmt_list))) 770 << "].prologue.file_names[" << FileIndex 771 << "].dir_idx contains an invalid index: " << FileName.DirIdx 772 << "\n"; 773 } 774 775 // Check file paths for duplicates. 776 std::string FullPath; 777 const bool HasFullPath = LineTable->getFileNameByIndex( 778 FileIndex, CU->getCompilationDir(), 779 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FullPath); 780 assert(HasFullPath && "Invalid index?"); 781 (void)HasFullPath; 782 auto It = FullPathMap.find(FullPath); 783 if (It == FullPathMap.end()) 784 FullPathMap[FullPath] = FileIndex; 785 else if (It->second != FileIndex) { 786 warn() << ".debug_line[" 787 << format("0x%08" PRIx64, 788 *toSectionOffset(Die.find(DW_AT_stmt_list))) 789 << "].prologue.file_names[" << FileIndex 790 << "] is a duplicate of file_names[" << It->second << "]\n"; 791 } 792 793 FileIndex++; 794 } 795 796 // Verify rows. 797 uint64_t PrevAddress = 0; 798 uint32_t RowIndex = 0; 799 for (const auto &Row : LineTable->Rows) { 800 // Verify row address. 801 if (Row.Address.Address < PrevAddress) { 802 ++NumDebugLineErrors; 803 error() << ".debug_line[" 804 << format("0x%08" PRIx64, 805 *toSectionOffset(Die.find(DW_AT_stmt_list))) 806 << "] row[" << RowIndex 807 << "] decreases in address from previous row:\n"; 808 809 DWARFDebugLine::Row::dumpTableHeader(OS, 0); 810 if (RowIndex > 0) 811 LineTable->Rows[RowIndex - 1].dump(OS); 812 Row.dump(OS); 813 OS << '\n'; 814 } 815 816 // Verify file index. 817 if (!LineTable->hasFileAtIndex(Row.File)) { 818 ++NumDebugLineErrors; 819 bool isDWARF5 = LineTable->Prologue.getVersion() >= 5; 820 error() << ".debug_line[" 821 << format("0x%08" PRIx64, 822 *toSectionOffset(Die.find(DW_AT_stmt_list))) 823 << "][" << RowIndex << "] has invalid file index " << Row.File 824 << " (valid values are [" << (isDWARF5 ? "0," : "1,") 825 << LineTable->Prologue.FileNames.size() 826 << (isDWARF5 ? ")" : "]") << "):\n"; 827 DWARFDebugLine::Row::dumpTableHeader(OS, 0); 828 Row.dump(OS); 829 OS << '\n'; 830 } 831 if (Row.EndSequence) 832 PrevAddress = 0; 833 else 834 PrevAddress = Row.Address.Address; 835 ++RowIndex; 836 } 837 } 838 } 839 840 DWARFVerifier::DWARFVerifier(raw_ostream &S, DWARFContext &D, 841 DIDumpOptions DumpOpts) 842 : OS(S), DCtx(D), DumpOpts(std::move(DumpOpts)), IsObjectFile(false), 843 IsMachOObject(false) { 844 if (const auto *F = DCtx.getDWARFObj().getFile()) { 845 IsObjectFile = F->isRelocatableObject(); 846 IsMachOObject = F->isMachO(); 847 } 848 } 849 850 bool DWARFVerifier::handleDebugLine() { 851 NumDebugLineErrors = 0; 852 OS << "Verifying .debug_line...\n"; 853 verifyDebugLineStmtOffsets(); 854 verifyDebugLineRows(); 855 return NumDebugLineErrors == 0; 856 } 857 858 unsigned DWARFVerifier::verifyAppleAccelTable(const DWARFSection *AccelSection, 859 DataExtractor *StrData, 860 const char *SectionName) { 861 unsigned NumErrors = 0; 862 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), *AccelSection, 863 DCtx.isLittleEndian(), 0); 864 AppleAcceleratorTable AccelTable(AccelSectionData, *StrData); 865 866 OS << "Verifying " << SectionName << "...\n"; 867 868 // Verify that the fixed part of the header is not too short. 869 if (!AccelSectionData.isValidOffset(AccelTable.getSizeHdr())) { 870 error() << "Section is too small to fit a section header.\n"; 871 return 1; 872 } 873 874 // Verify that the section is not too short. 875 if (Error E = AccelTable.extract()) { 876 error() << toString(std::move(E)) << '\n'; 877 return 1; 878 } 879 880 // Verify that all buckets have a valid hash index or are empty. 881 uint32_t NumBuckets = AccelTable.getNumBuckets(); 882 uint32_t NumHashes = AccelTable.getNumHashes(); 883 884 uint64_t BucketsOffset = 885 AccelTable.getSizeHdr() + AccelTable.getHeaderDataLength(); 886 uint64_t HashesBase = BucketsOffset + NumBuckets * 4; 887 uint64_t OffsetsBase = HashesBase + NumHashes * 4; 888 for (uint32_t BucketIdx = 0; BucketIdx < NumBuckets; ++BucketIdx) { 889 uint32_t HashIdx = AccelSectionData.getU32(&BucketsOffset); 890 if (HashIdx >= NumHashes && HashIdx != UINT32_MAX) { 891 error() << format("Bucket[%d] has invalid hash index: %u.\n", BucketIdx, 892 HashIdx); 893 ++NumErrors; 894 } 895 } 896 uint32_t NumAtoms = AccelTable.getAtomsDesc().size(); 897 if (NumAtoms == 0) { 898 error() << "No atoms: failed to read HashData.\n"; 899 return 1; 900 } 901 if (!AccelTable.validateForms()) { 902 error() << "Unsupported form: failed to read HashData.\n"; 903 return 1; 904 } 905 906 for (uint32_t HashIdx = 0; HashIdx < NumHashes; ++HashIdx) { 907 uint64_t HashOffset = HashesBase + 4 * HashIdx; 908 uint64_t DataOffset = OffsetsBase + 4 * HashIdx; 909 uint32_t Hash = AccelSectionData.getU32(&HashOffset); 910 uint64_t HashDataOffset = AccelSectionData.getU32(&DataOffset); 911 if (!AccelSectionData.isValidOffsetForDataOfSize(HashDataOffset, 912 sizeof(uint64_t))) { 913 error() << format("Hash[%d] has invalid HashData offset: " 914 "0x%08" PRIx64 ".\n", 915 HashIdx, HashDataOffset); 916 ++NumErrors; 917 } 918 919 uint64_t StrpOffset; 920 uint64_t StringOffset; 921 uint32_t StringCount = 0; 922 uint64_t Offset; 923 unsigned Tag; 924 while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) { 925 const uint32_t NumHashDataObjects = 926 AccelSectionData.getU32(&HashDataOffset); 927 for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects; 928 ++HashDataIdx) { 929 std::tie(Offset, Tag) = AccelTable.readAtoms(&HashDataOffset); 930 auto Die = DCtx.getDIEForOffset(Offset); 931 if (!Die) { 932 const uint32_t BucketIdx = 933 NumBuckets ? (Hash % NumBuckets) : UINT32_MAX; 934 StringOffset = StrpOffset; 935 const char *Name = StrData->getCStr(&StringOffset); 936 if (!Name) 937 Name = "<NULL>"; 938 939 error() << format( 940 "%s Bucket[%d] Hash[%d] = 0x%08x " 941 "Str[%u] = 0x%08" PRIx64 " DIE[%d] = 0x%08" PRIx64 " " 942 "is not a valid DIE offset for \"%s\".\n", 943 SectionName, BucketIdx, HashIdx, Hash, StringCount, StrpOffset, 944 HashDataIdx, Offset, Name); 945 946 ++NumErrors; 947 continue; 948 } 949 if ((Tag != dwarf::DW_TAG_null) && (Die.getTag() != Tag)) { 950 error() << "Tag " << dwarf::TagString(Tag) 951 << " in accelerator table does not match Tag " 952 << dwarf::TagString(Die.getTag()) << " of DIE[" << HashDataIdx 953 << "].\n"; 954 ++NumErrors; 955 } 956 } 957 ++StringCount; 958 } 959 } 960 return NumErrors; 961 } 962 963 unsigned 964 DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) { 965 // A map from CU offset to the (first) Name Index offset which claims to index 966 // this CU. 967 DenseMap<uint64_t, uint64_t> CUMap; 968 const uint64_t NotIndexed = std::numeric_limits<uint64_t>::max(); 969 970 CUMap.reserve(DCtx.getNumCompileUnits()); 971 for (const auto &CU : DCtx.compile_units()) 972 CUMap[CU->getOffset()] = NotIndexed; 973 974 unsigned NumErrors = 0; 975 for (const DWARFDebugNames::NameIndex &NI : AccelTable) { 976 if (NI.getCUCount() == 0) { 977 error() << formatv("Name Index @ {0:x} does not index any CU\n", 978 NI.getUnitOffset()); 979 ++NumErrors; 980 continue; 981 } 982 for (uint32_t CU = 0, End = NI.getCUCount(); CU < End; ++CU) { 983 uint64_t Offset = NI.getCUOffset(CU); 984 auto Iter = CUMap.find(Offset); 985 986 if (Iter == CUMap.end()) { 987 error() << formatv( 988 "Name Index @ {0:x} references a non-existing CU @ {1:x}\n", 989 NI.getUnitOffset(), Offset); 990 ++NumErrors; 991 continue; 992 } 993 994 if (Iter->second != NotIndexed) { 995 error() << formatv("Name Index @ {0:x} references a CU @ {1:x}, but " 996 "this CU is already indexed by Name Index @ {2:x}\n", 997 NI.getUnitOffset(), Offset, Iter->second); 998 continue; 999 } 1000 Iter->second = NI.getUnitOffset(); 1001 } 1002 } 1003 1004 for (const auto &KV : CUMap) { 1005 if (KV.second == NotIndexed) 1006 warn() << formatv("CU @ {0:x} not covered by any Name Index\n", KV.first); 1007 } 1008 1009 return NumErrors; 1010 } 1011 1012 unsigned 1013 DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI, 1014 const DataExtractor &StrData) { 1015 struct BucketInfo { 1016 uint32_t Bucket; 1017 uint32_t Index; 1018 1019 constexpr BucketInfo(uint32_t Bucket, uint32_t Index) 1020 : Bucket(Bucket), Index(Index) {} 1021 bool operator<(const BucketInfo &RHS) const { return Index < RHS.Index; } 1022 }; 1023 1024 uint32_t NumErrors = 0; 1025 if (NI.getBucketCount() == 0) { 1026 warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n", 1027 NI.getUnitOffset()); 1028 return NumErrors; 1029 } 1030 1031 // Build up a list of (Bucket, Index) pairs. We use this later to verify that 1032 // each Name is reachable from the appropriate bucket. 1033 std::vector<BucketInfo> BucketStarts; 1034 BucketStarts.reserve(NI.getBucketCount() + 1); 1035 for (uint32_t Bucket = 0, End = NI.getBucketCount(); Bucket < End; ++Bucket) { 1036 uint32_t Index = NI.getBucketArrayEntry(Bucket); 1037 if (Index > NI.getNameCount()) { 1038 error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid " 1039 "value {2}. Valid range is [0, {3}].\n", 1040 Bucket, NI.getUnitOffset(), Index, NI.getNameCount()); 1041 ++NumErrors; 1042 continue; 1043 } 1044 if (Index > 0) 1045 BucketStarts.emplace_back(Bucket, Index); 1046 } 1047 1048 // If there were any buckets with invalid values, skip further checks as they 1049 // will likely produce many errors which will only confuse the actual root 1050 // problem. 1051 if (NumErrors > 0) 1052 return NumErrors; 1053 1054 // Sort the list in the order of increasing "Index" entries. 1055 array_pod_sort(BucketStarts.begin(), BucketStarts.end()); 1056 1057 // Insert a sentinel entry at the end, so we can check that the end of the 1058 // table is covered in the loop below. 1059 BucketStarts.emplace_back(NI.getBucketCount(), NI.getNameCount() + 1); 1060 1061 // Loop invariant: NextUncovered is the (1-based) index of the first Name 1062 // which is not reachable by any of the buckets we processed so far (and 1063 // hasn't been reported as uncovered). 1064 uint32_t NextUncovered = 1; 1065 for (const BucketInfo &B : BucketStarts) { 1066 // Under normal circumstances B.Index be equal to NextUncovered, but it can 1067 // be less if a bucket points to names which are already known to be in some 1068 // bucket we processed earlier. In that case, we won't trigger this error, 1069 // but report the mismatched hash value error instead. (We know the hash 1070 // will not match because we have already verified that the name's hash 1071 // puts it into the previous bucket.) 1072 if (B.Index > NextUncovered) { 1073 error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] " 1074 "are not covered by the hash table.\n", 1075 NI.getUnitOffset(), NextUncovered, B.Index - 1); 1076 ++NumErrors; 1077 } 1078 uint32_t Idx = B.Index; 1079 1080 // The rest of the checks apply only to non-sentinel entries. 1081 if (B.Bucket == NI.getBucketCount()) 1082 break; 1083 1084 // This triggers if a non-empty bucket points to a name with a mismatched 1085 // hash. Clients are likely to interpret this as an empty bucket, because a 1086 // mismatched hash signals the end of a bucket, but if this is indeed an 1087 // empty bucket, the producer should have signalled this by marking the 1088 // bucket as empty. 1089 uint32_t FirstHash = NI.getHashArrayEntry(Idx); 1090 if (FirstHash % NI.getBucketCount() != B.Bucket) { 1091 error() << formatv( 1092 "Name Index @ {0:x}: Bucket {1} is not empty but points to a " 1093 "mismatched hash value {2:x} (belonging to bucket {3}).\n", 1094 NI.getUnitOffset(), B.Bucket, FirstHash, 1095 FirstHash % NI.getBucketCount()); 1096 ++NumErrors; 1097 } 1098 1099 // This find the end of this bucket and also verifies that all the hashes in 1100 // this bucket are correct by comparing the stored hashes to the ones we 1101 // compute ourselves. 1102 while (Idx <= NI.getNameCount()) { 1103 uint32_t Hash = NI.getHashArrayEntry(Idx); 1104 if (Hash % NI.getBucketCount() != B.Bucket) 1105 break; 1106 1107 const char *Str = NI.getNameTableEntry(Idx).getString(); 1108 if (caseFoldingDjbHash(Str) != Hash) { 1109 error() << formatv("Name Index @ {0:x}: String ({1}) at index {2} " 1110 "hashes to {3:x}, but " 1111 "the Name Index hash is {4:x}\n", 1112 NI.getUnitOffset(), Str, Idx, 1113 caseFoldingDjbHash(Str), Hash); 1114 ++NumErrors; 1115 } 1116 1117 ++Idx; 1118 } 1119 NextUncovered = std::max(NextUncovered, Idx); 1120 } 1121 return NumErrors; 1122 } 1123 1124 unsigned DWARFVerifier::verifyNameIndexAttribute( 1125 const DWARFDebugNames::NameIndex &NI, const DWARFDebugNames::Abbrev &Abbr, 1126 DWARFDebugNames::AttributeEncoding AttrEnc) { 1127 StringRef FormName = dwarf::FormEncodingString(AttrEnc.Form); 1128 if (FormName.empty()) { 1129 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an " 1130 "unknown form: {3}.\n", 1131 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index, 1132 AttrEnc.Form); 1133 return 1; 1134 } 1135 1136 if (AttrEnc.Index == DW_IDX_type_hash) { 1137 if (AttrEnc.Form != dwarf::DW_FORM_data8) { 1138 error() << formatv( 1139 "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash " 1140 "uses an unexpected form {2} (should be {3}).\n", 1141 NI.getUnitOffset(), Abbr.Code, AttrEnc.Form, dwarf::DW_FORM_data8); 1142 return 1; 1143 } 1144 } 1145 1146 // A list of known index attributes and their expected form classes. 1147 // DW_IDX_type_hash is handled specially in the check above, as it has a 1148 // specific form (not just a form class) we should expect. 1149 struct FormClassTable { 1150 dwarf::Index Index; 1151 DWARFFormValue::FormClass Class; 1152 StringLiteral ClassName; 1153 }; 1154 static constexpr FormClassTable Table[] = { 1155 {dwarf::DW_IDX_compile_unit, DWARFFormValue::FC_Constant, {"constant"}}, 1156 {dwarf::DW_IDX_type_unit, DWARFFormValue::FC_Constant, {"constant"}}, 1157 {dwarf::DW_IDX_die_offset, DWARFFormValue::FC_Reference, {"reference"}}, 1158 {dwarf::DW_IDX_parent, DWARFFormValue::FC_Constant, {"constant"}}, 1159 }; 1160 1161 ArrayRef<FormClassTable> TableRef(Table); 1162 auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) { 1163 return T.Index == AttrEnc.Index; 1164 }); 1165 if (Iter == TableRef.end()) { 1166 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an " 1167 "unknown index attribute: {2}.\n", 1168 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index); 1169 return 0; 1170 } 1171 1172 if (!DWARFFormValue(AttrEnc.Form).isFormClass(Iter->Class)) { 1173 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an " 1174 "unexpected form {3} (expected form class {4}).\n", 1175 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index, 1176 AttrEnc.Form, Iter->ClassName); 1177 return 1; 1178 } 1179 return 0; 1180 } 1181 1182 unsigned 1183 DWARFVerifier::verifyNameIndexAbbrevs(const DWARFDebugNames::NameIndex &NI) { 1184 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) { 1185 warn() << formatv("Name Index @ {0:x}: Verifying indexes of type units is " 1186 "not currently supported.\n", 1187 NI.getUnitOffset()); 1188 return 0; 1189 } 1190 1191 unsigned NumErrors = 0; 1192 for (const auto &Abbrev : NI.getAbbrevs()) { 1193 StringRef TagName = dwarf::TagString(Abbrev.Tag); 1194 if (TagName.empty()) { 1195 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an " 1196 "unknown tag: {2}.\n", 1197 NI.getUnitOffset(), Abbrev.Code, Abbrev.Tag); 1198 } 1199 SmallSet<unsigned, 5> Attributes; 1200 for (const auto &AttrEnc : Abbrev.Attributes) { 1201 if (!Attributes.insert(AttrEnc.Index).second) { 1202 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains " 1203 "multiple {2} attributes.\n", 1204 NI.getUnitOffset(), Abbrev.Code, AttrEnc.Index); 1205 ++NumErrors; 1206 continue; 1207 } 1208 NumErrors += verifyNameIndexAttribute(NI, Abbrev, AttrEnc); 1209 } 1210 1211 if (NI.getCUCount() > 1 && !Attributes.count(dwarf::DW_IDX_compile_unit)) { 1212 error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units " 1213 "and abbreviation {1:x} has no {2} attribute.\n", 1214 NI.getUnitOffset(), Abbrev.Code, 1215 dwarf::DW_IDX_compile_unit); 1216 ++NumErrors; 1217 } 1218 if (!Attributes.count(dwarf::DW_IDX_die_offset)) { 1219 error() << formatv( 1220 "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n", 1221 NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset); 1222 ++NumErrors; 1223 } 1224 } 1225 return NumErrors; 1226 } 1227 1228 static SmallVector<StringRef, 2> getNames(const DWARFDie &DIE, 1229 bool IncludeLinkageName = true) { 1230 SmallVector<StringRef, 2> Result; 1231 if (const char *Str = DIE.getName(DINameKind::ShortName)) 1232 Result.emplace_back(Str); 1233 else if (DIE.getTag() == dwarf::DW_TAG_namespace) 1234 Result.emplace_back("(anonymous namespace)"); 1235 1236 if (IncludeLinkageName) { 1237 if (const char *Str = DIE.getName(DINameKind::LinkageName)) { 1238 if (Result.empty() || Result[0] != Str) 1239 Result.emplace_back(Str); 1240 } 1241 } 1242 1243 return Result; 1244 } 1245 1246 unsigned DWARFVerifier::verifyNameIndexEntries( 1247 const DWARFDebugNames::NameIndex &NI, 1248 const DWARFDebugNames::NameTableEntry &NTE) { 1249 // Verifying type unit indexes not supported. 1250 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) 1251 return 0; 1252 1253 const char *CStr = NTE.getString(); 1254 if (!CStr) { 1255 error() << formatv( 1256 "Name Index @ {0:x}: Unable to get string associated with name {1}.\n", 1257 NI.getUnitOffset(), NTE.getIndex()); 1258 return 1; 1259 } 1260 StringRef Str(CStr); 1261 1262 unsigned NumErrors = 0; 1263 unsigned NumEntries = 0; 1264 uint64_t EntryID = NTE.getEntryOffset(); 1265 uint64_t NextEntryID = EntryID; 1266 Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&NextEntryID); 1267 for (; EntryOr; ++NumEntries, EntryID = NextEntryID, 1268 EntryOr = NI.getEntry(&NextEntryID)) { 1269 uint32_t CUIndex = *EntryOr->getCUIndex(); 1270 if (CUIndex > NI.getCUCount()) { 1271 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an " 1272 "invalid CU index ({2}).\n", 1273 NI.getUnitOffset(), EntryID, CUIndex); 1274 ++NumErrors; 1275 continue; 1276 } 1277 uint64_t CUOffset = NI.getCUOffset(CUIndex); 1278 uint64_t DIEOffset = CUOffset + *EntryOr->getDIEUnitOffset(); 1279 DWARFDie DIE = DCtx.getDIEForOffset(DIEOffset); 1280 if (!DIE) { 1281 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a " 1282 "non-existing DIE @ {2:x}.\n", 1283 NI.getUnitOffset(), EntryID, DIEOffset); 1284 ++NumErrors; 1285 continue; 1286 } 1287 if (DIE.getDwarfUnit()->getOffset() != CUOffset) { 1288 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of " 1289 "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n", 1290 NI.getUnitOffset(), EntryID, DIEOffset, CUOffset, 1291 DIE.getDwarfUnit()->getOffset()); 1292 ++NumErrors; 1293 } 1294 if (DIE.getTag() != EntryOr->tag()) { 1295 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of " 1296 "DIE @ {2:x}: index - {3}; debug_info - {4}.\n", 1297 NI.getUnitOffset(), EntryID, DIEOffset, EntryOr->tag(), 1298 DIE.getTag()); 1299 ++NumErrors; 1300 } 1301 1302 auto EntryNames = getNames(DIE); 1303 if (!is_contained(EntryNames, Str)) { 1304 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name " 1305 "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n", 1306 NI.getUnitOffset(), EntryID, DIEOffset, Str, 1307 make_range(EntryNames.begin(), EntryNames.end())); 1308 ++NumErrors; 1309 } 1310 } 1311 handleAllErrors(EntryOr.takeError(), 1312 [&](const DWARFDebugNames::SentinelError &) { 1313 if (NumEntries > 0) 1314 return; 1315 error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is " 1316 "not associated with any entries.\n", 1317 NI.getUnitOffset(), NTE.getIndex(), Str); 1318 ++NumErrors; 1319 }, 1320 [&](const ErrorInfoBase &Info) { 1321 error() 1322 << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n", 1323 NI.getUnitOffset(), NTE.getIndex(), Str, 1324 Info.message()); 1325 ++NumErrors; 1326 }); 1327 return NumErrors; 1328 } 1329 1330 static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) { 1331 Expected<std::vector<DWARFLocationExpression>> Loc = 1332 Die.getLocations(DW_AT_location); 1333 if (!Loc) { 1334 consumeError(Loc.takeError()); 1335 return false; 1336 } 1337 DWARFUnit *U = Die.getDwarfUnit(); 1338 for (const auto &Entry : *Loc) { 1339 DataExtractor Data(toStringRef(Entry.Expr), DCtx.isLittleEndian(), 1340 U->getAddressByteSize()); 1341 DWARFExpression Expression(Data, U->getAddressByteSize(), 1342 U->getFormParams().Format); 1343 bool IsInteresting = any_of(Expression, [](DWARFExpression::Operation &Op) { 1344 return !Op.isError() && (Op.getCode() == DW_OP_addr || 1345 Op.getCode() == DW_OP_form_tls_address || 1346 Op.getCode() == DW_OP_GNU_push_tls_address); 1347 }); 1348 if (IsInteresting) 1349 return true; 1350 } 1351 return false; 1352 } 1353 1354 unsigned DWARFVerifier::verifyNameIndexCompleteness( 1355 const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI) { 1356 1357 // First check, if the Die should be indexed. The code follows the DWARF v5 1358 // wording as closely as possible. 1359 1360 // "All non-defining declarations (that is, debugging information entries 1361 // with a DW_AT_declaration attribute) are excluded." 1362 if (Die.find(DW_AT_declaration)) 1363 return 0; 1364 1365 // "DW_TAG_namespace debugging information entries without a DW_AT_name 1366 // attribute are included with the name “(anonymous namespace)”. 1367 // All other debugging information entries without a DW_AT_name attribute 1368 // are excluded." 1369 // "If a subprogram or inlined subroutine is included, and has a 1370 // DW_AT_linkage_name attribute, there will be an additional index entry for 1371 // the linkage name." 1372 auto IncludeLinkageName = Die.getTag() == DW_TAG_subprogram || 1373 Die.getTag() == DW_TAG_inlined_subroutine; 1374 auto EntryNames = getNames(Die, IncludeLinkageName); 1375 if (EntryNames.empty()) 1376 return 0; 1377 1378 // We deviate from the specification here, which says: 1379 // "The name index must contain an entry for each debugging information entry 1380 // that defines a named subprogram, label, variable, type, or namespace, 1381 // subject to ..." 1382 // Explicitly exclude all TAGs that we know shouldn't be indexed. 1383 switch (Die.getTag()) { 1384 // Compile units and modules have names but shouldn't be indexed. 1385 case DW_TAG_compile_unit: 1386 case DW_TAG_module: 1387 return 0; 1388 1389 // Function and template parameters are not globally visible, so we shouldn't 1390 // index them. 1391 case DW_TAG_formal_parameter: 1392 case DW_TAG_template_value_parameter: 1393 case DW_TAG_template_type_parameter: 1394 case DW_TAG_GNU_template_parameter_pack: 1395 case DW_TAG_GNU_template_template_param: 1396 return 0; 1397 1398 // Object members aren't globally visible. 1399 case DW_TAG_member: 1400 return 0; 1401 1402 // According to a strict reading of the specification, enumerators should not 1403 // be indexed (and LLVM currently does not do that). However, this causes 1404 // problems for the debuggers, so we may need to reconsider this. 1405 case DW_TAG_enumerator: 1406 return 0; 1407 1408 // Imported declarations should not be indexed according to the specification 1409 // and LLVM currently does not do that. 1410 case DW_TAG_imported_declaration: 1411 return 0; 1412 1413 // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging 1414 // information entries without an address attribute (DW_AT_low_pc, 1415 // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded." 1416 case DW_TAG_subprogram: 1417 case DW_TAG_inlined_subroutine: 1418 case DW_TAG_label: 1419 if (Die.findRecursively( 1420 {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc})) 1421 break; 1422 return 0; 1423 1424 // "DW_TAG_variable debugging information entries with a DW_AT_location 1425 // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are 1426 // included; otherwise, they are excluded." 1427 // 1428 // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list. 1429 case DW_TAG_variable: 1430 if (isVariableIndexable(Die, DCtx)) 1431 break; 1432 return 0; 1433 1434 default: 1435 break; 1436 } 1437 1438 // Now we know that our Die should be present in the Index. Let's check if 1439 // that's the case. 1440 unsigned NumErrors = 0; 1441 uint64_t DieUnitOffset = Die.getOffset() - Die.getDwarfUnit()->getOffset(); 1442 for (StringRef Name : EntryNames) { 1443 if (none_of(NI.equal_range(Name), [&](const DWARFDebugNames::Entry &E) { 1444 return E.getDIEUnitOffset() == DieUnitOffset; 1445 })) { 1446 error() << formatv("Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with " 1447 "name {3} missing.\n", 1448 NI.getUnitOffset(), Die.getOffset(), Die.getTag(), 1449 Name); 1450 ++NumErrors; 1451 } 1452 } 1453 return NumErrors; 1454 } 1455 1456 unsigned DWARFVerifier::verifyDebugNames(const DWARFSection &AccelSection, 1457 const DataExtractor &StrData) { 1458 unsigned NumErrors = 0; 1459 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), AccelSection, 1460 DCtx.isLittleEndian(), 0); 1461 DWARFDebugNames AccelTable(AccelSectionData, StrData); 1462 1463 OS << "Verifying .debug_names...\n"; 1464 1465 // This verifies that we can read individual name indices and their 1466 // abbreviation tables. 1467 if (Error E = AccelTable.extract()) { 1468 error() << toString(std::move(E)) << '\n'; 1469 return 1; 1470 } 1471 1472 NumErrors += verifyDebugNamesCULists(AccelTable); 1473 for (const auto &NI : AccelTable) 1474 NumErrors += verifyNameIndexBuckets(NI, StrData); 1475 for (const auto &NI : AccelTable) 1476 NumErrors += verifyNameIndexAbbrevs(NI); 1477 1478 // Don't attempt Entry validation if any of the previous checks found errors 1479 if (NumErrors > 0) 1480 return NumErrors; 1481 for (const auto &NI : AccelTable) 1482 for (DWARFDebugNames::NameTableEntry NTE : NI) 1483 NumErrors += verifyNameIndexEntries(NI, NTE); 1484 1485 if (NumErrors > 0) 1486 return NumErrors; 1487 1488 for (const std::unique_ptr<DWARFUnit> &U : DCtx.compile_units()) { 1489 if (const DWARFDebugNames::NameIndex *NI = 1490 AccelTable.getCUNameIndex(U->getOffset())) { 1491 auto *CU = cast<DWARFCompileUnit>(U.get()); 1492 for (const DWARFDebugInfoEntry &Die : CU->dies()) 1493 NumErrors += verifyNameIndexCompleteness(DWARFDie(CU, &Die), *NI); 1494 } 1495 } 1496 return NumErrors; 1497 } 1498 1499 bool DWARFVerifier::handleAccelTables() { 1500 const DWARFObject &D = DCtx.getDWARFObj(); 1501 DataExtractor StrData(D.getStrSection(), DCtx.isLittleEndian(), 0); 1502 unsigned NumErrors = 0; 1503 if (!D.getAppleNamesSection().Data.empty()) 1504 NumErrors += verifyAppleAccelTable(&D.getAppleNamesSection(), &StrData, 1505 ".apple_names"); 1506 if (!D.getAppleTypesSection().Data.empty()) 1507 NumErrors += verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData, 1508 ".apple_types"); 1509 if (!D.getAppleNamespacesSection().Data.empty()) 1510 NumErrors += verifyAppleAccelTable(&D.getAppleNamespacesSection(), &StrData, 1511 ".apple_namespaces"); 1512 if (!D.getAppleObjCSection().Data.empty()) 1513 NumErrors += verifyAppleAccelTable(&D.getAppleObjCSection(), &StrData, 1514 ".apple_objc"); 1515 1516 if (!D.getNamesSection().Data.empty()) 1517 NumErrors += verifyDebugNames(D.getNamesSection(), StrData); 1518 return NumErrors == 0; 1519 } 1520 1521 raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); } 1522 1523 raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); } 1524 1525 raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); } 1526 1527 raw_ostream &DWARFVerifier::dump(const DWARFDie &Die, unsigned indent) const { 1528 Die.dump(OS, indent, DumpOpts); 1529 return OS; 1530 } 1531