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