1 //===- bolt/Rewrite/RewriteInstance.cpp - ELF rewriter --------------------===// 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 9 #include "bolt/Rewrite/RewriteInstance.h" 10 #include "bolt/Core/BinaryContext.h" 11 #include "bolt/Core/BinaryEmitter.h" 12 #include "bolt/Core/BinaryFunction.h" 13 #include "bolt/Core/DebugData.h" 14 #include "bolt/Core/Exceptions.h" 15 #include "bolt/Core/MCPlusBuilder.h" 16 #include "bolt/Core/ParallelUtilities.h" 17 #include "bolt/Core/Relocation.h" 18 #include "bolt/Passes/CacheMetrics.h" 19 #include "bolt/Passes/ReorderFunctions.h" 20 #include "bolt/Profile/BoltAddressTranslation.h" 21 #include "bolt/Profile/DataAggregator.h" 22 #include "bolt/Profile/DataReader.h" 23 #include "bolt/Profile/YAMLProfileReader.h" 24 #include "bolt/Profile/YAMLProfileWriter.h" 25 #include "bolt/Rewrite/BinaryPassManager.h" 26 #include "bolt/Rewrite/DWARFRewriter.h" 27 #include "bolt/Rewrite/ExecutableFileMemoryManager.h" 28 #include "bolt/RuntimeLibs/HugifyRuntimeLibrary.h" 29 #include "bolt/RuntimeLibs/InstrumentationRuntimeLibrary.h" 30 #include "bolt/Utils/CommandLineOpts.h" 31 #include "bolt/Utils/Utils.h" 32 #include "llvm/ADT/Optional.h" 33 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 34 #include "llvm/ExecutionEngine/RuntimeDyld.h" 35 #include "llvm/MC/MCAsmBackend.h" 36 #include "llvm/MC/MCAsmInfo.h" 37 #include "llvm/MC/MCAsmLayout.h" 38 #include "llvm/MC/MCContext.h" 39 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 40 #include "llvm/MC/MCObjectStreamer.h" 41 #include "llvm/MC/MCObjectWriter.h" 42 #include "llvm/MC/MCStreamer.h" 43 #include "llvm/MC/MCSymbol.h" 44 #include "llvm/MC/TargetRegistry.h" 45 #include "llvm/Object/ObjectFile.h" 46 #include "llvm/Support/Alignment.h" 47 #include "llvm/Support/Casting.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/DataExtractor.h" 50 #include "llvm/Support/Errc.h" 51 #include "llvm/Support/FileSystem.h" 52 #include "llvm/Support/LEB128.h" 53 #include "llvm/Support/ManagedStatic.h" 54 #include "llvm/Support/Timer.h" 55 #include "llvm/Support/ToolOutputFile.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include <algorithm> 58 #include <fstream> 59 #include <system_error> 60 61 #undef DEBUG_TYPE 62 #define DEBUG_TYPE "bolt" 63 64 using namespace llvm; 65 using namespace object; 66 using namespace bolt; 67 68 extern cl::opt<uint32_t> X86AlignBranchBoundary; 69 extern cl::opt<bool> X86AlignBranchWithin32BBoundaries; 70 71 namespace opts { 72 73 extern cl::opt<MacroFusionType> AlignMacroOpFusion; 74 extern cl::list<std::string> HotTextMoveSections; 75 extern cl::opt<bool> Hugify; 76 extern cl::opt<bool> Instrument; 77 extern cl::opt<JumpTableSupportLevel> JumpTables; 78 extern cl::list<std::string> ReorderData; 79 extern cl::opt<bolt::ReorderFunctions::ReorderType> ReorderFunctions; 80 extern cl::opt<bool> TimeBuild; 81 82 static cl::opt<bool> 83 ForceToDataRelocations("force-data-relocations", 84 cl::desc("force relocations to data sections to always be processed"), 85 cl::init(false), 86 cl::Hidden, 87 cl::ZeroOrMore, 88 cl::cat(BoltCategory)); 89 90 cl::opt<std::string> 91 BoltID("bolt-id", 92 cl::desc("add any string to tag this execution in the " 93 "output binary via bolt info section"), 94 cl::ZeroOrMore, 95 cl::cat(BoltCategory)); 96 97 cl::opt<bool> 98 AllowStripped("allow-stripped", 99 cl::desc("allow processing of stripped binaries"), 100 cl::Hidden, 101 cl::cat(BoltCategory)); 102 103 cl::opt<bool> 104 DumpDotAll("dump-dot-all", 105 cl::desc("dump function CFGs to graphviz format after each stage"), 106 cl::ZeroOrMore, 107 cl::Hidden, 108 cl::cat(BoltCategory)); 109 110 static cl::list<std::string> 111 ForceFunctionNames("funcs", 112 cl::CommaSeparated, 113 cl::desc("limit optimizations to functions from the list"), 114 cl::value_desc("func1,func2,func3,..."), 115 cl::Hidden, 116 cl::cat(BoltCategory)); 117 118 static cl::opt<std::string> 119 FunctionNamesFile("funcs-file", 120 cl::desc("file with list of functions to optimize"), 121 cl::Hidden, 122 cl::cat(BoltCategory)); 123 124 static cl::list<std::string> ForceFunctionNamesNR( 125 "funcs-no-regex", cl::CommaSeparated, 126 cl::desc("limit optimizations to functions from the list (non-regex)"), 127 cl::value_desc("func1,func2,func3,..."), cl::Hidden, cl::cat(BoltCategory)); 128 129 static cl::opt<std::string> FunctionNamesFileNR( 130 "funcs-file-no-regex", 131 cl::desc("file with list of functions to optimize (non-regex)"), cl::Hidden, 132 cl::cat(BoltCategory)); 133 134 cl::opt<bool> 135 KeepTmp("keep-tmp", 136 cl::desc("preserve intermediate .o file"), 137 cl::Hidden, 138 cl::cat(BoltCategory)); 139 140 static cl::opt<bool> 141 Lite("lite", 142 cl::desc("skip processing of cold functions"), 143 cl::init(false), 144 cl::ZeroOrMore, 145 cl::cat(BoltCategory)); 146 147 static cl::opt<unsigned> 148 LiteThresholdPct("lite-threshold-pct", 149 cl::desc("threshold (in percent) for selecting functions to process in lite " 150 "mode. Higher threshold means fewer functions to process. E.g " 151 "threshold of 90 means only top 10 percent of functions with " 152 "profile will be processed."), 153 cl::init(0), 154 cl::ZeroOrMore, 155 cl::Hidden, 156 cl::cat(BoltOptCategory)); 157 158 static cl::opt<unsigned> 159 LiteThresholdCount("lite-threshold-count", 160 cl::desc("similar to '-lite-threshold-pct' but specify threshold using " 161 "absolute function call count. I.e. limit processing to functions " 162 "executed at least the specified number of times."), 163 cl::init(0), 164 cl::ZeroOrMore, 165 cl::Hidden, 166 cl::cat(BoltOptCategory)); 167 168 static cl::opt<unsigned> 169 MaxFunctions("max-funcs", 170 cl::desc("maximum number of functions to process"), 171 cl::ZeroOrMore, 172 cl::Hidden, 173 cl::cat(BoltCategory)); 174 175 static cl::opt<unsigned> 176 MaxDataRelocations("max-data-relocations", 177 cl::desc("maximum number of data relocations to process"), 178 cl::ZeroOrMore, 179 cl::Hidden, 180 cl::cat(BoltCategory)); 181 182 cl::opt<bool> 183 PrintAll("print-all", 184 cl::desc("print functions after each stage"), 185 cl::ZeroOrMore, 186 cl::Hidden, 187 cl::cat(BoltCategory)); 188 189 cl::opt<bool> 190 PrintCFG("print-cfg", 191 cl::desc("print functions after CFG construction"), 192 cl::ZeroOrMore, 193 cl::Hidden, 194 cl::cat(BoltCategory)); 195 196 cl::opt<bool> PrintDisasm("print-disasm", 197 cl::desc("print function after disassembly"), 198 cl::ZeroOrMore, 199 cl::Hidden, 200 cl::cat(BoltCategory)); 201 202 static cl::opt<bool> 203 PrintGlobals("print-globals", 204 cl::desc("print global symbols after disassembly"), 205 cl::ZeroOrMore, 206 cl::Hidden, 207 cl::cat(BoltCategory)); 208 209 extern cl::opt<bool> PrintSections; 210 211 static cl::opt<bool> 212 PrintLoopInfo("print-loops", 213 cl::desc("print loop related information"), 214 cl::ZeroOrMore, 215 cl::Hidden, 216 cl::cat(BoltCategory)); 217 218 static cl::opt<bool> 219 PrintSDTMarkers("print-sdt", 220 cl::desc("print all SDT markers"), 221 cl::ZeroOrMore, 222 cl::Hidden, 223 cl::cat(BoltCategory)); 224 225 enum PrintPseudoProbesOptions { 226 PPP_None = 0, 227 PPP_Probes_Section_Decode = 0x1, 228 PPP_Probes_Address_Conversion = 0x2, 229 PPP_Encoded_Probes = 0x3, 230 PPP_All = 0xf 231 }; 232 233 cl::opt<PrintPseudoProbesOptions> PrintPseudoProbes( 234 "print-pseudo-probes", cl::desc("print pseudo probe info"), 235 cl::init(PPP_None), 236 cl::values(clEnumValN(PPP_Probes_Section_Decode, "decode", 237 "decode probes section from binary"), 238 clEnumValN(PPP_Probes_Address_Conversion, "address_conversion", 239 "update address2ProbesMap with output block address"), 240 clEnumValN(PPP_Encoded_Probes, "encoded_probes", 241 "display the encoded probes in binary section"), 242 clEnumValN(PPP_All, "all", "enable all debugging printout")), 243 cl::ZeroOrMore, cl::Hidden, cl::cat(BoltCategory)); 244 245 static cl::opt<cl::boolOrDefault> 246 RelocationMode("relocs", 247 cl::desc("use relocations in the binary (default=autodetect)"), 248 cl::ZeroOrMore, 249 cl::cat(BoltCategory)); 250 251 static cl::opt<std::string> 252 SaveProfile("w", 253 cl::desc("save recorded profile to a file"), 254 cl::cat(BoltOutputCategory)); 255 256 static cl::list<std::string> 257 SkipFunctionNames("skip-funcs", 258 cl::CommaSeparated, 259 cl::desc("list of functions to skip"), 260 cl::value_desc("func1,func2,func3,..."), 261 cl::Hidden, 262 cl::cat(BoltCategory)); 263 264 static cl::opt<std::string> 265 SkipFunctionNamesFile("skip-funcs-file", 266 cl::desc("file with list of functions to skip"), 267 cl::Hidden, 268 cl::cat(BoltCategory)); 269 270 cl::opt<bool> 271 TrapOldCode("trap-old-code", 272 cl::desc("insert traps in old function bodies (relocation mode)"), 273 cl::Hidden, 274 cl::cat(BoltCategory)); 275 276 static cl::opt<std::string> DWPPathName("dwp", 277 cl::desc("Path and name to DWP file."), 278 cl::Hidden, cl::ZeroOrMore, 279 cl::init(""), cl::cat(BoltCategory)); 280 281 static cl::opt<bool> 282 UseGnuStack("use-gnu-stack", 283 cl::desc("use GNU_STACK program header for new segment (workaround for " 284 "issues with strip/objcopy)"), 285 cl::ZeroOrMore, 286 cl::cat(BoltCategory)); 287 288 static cl::opt<bool> 289 TimeRewrite("time-rewrite", 290 cl::desc("print time spent in rewriting passes"), 291 cl::ZeroOrMore, 292 cl::Hidden, 293 cl::cat(BoltCategory)); 294 295 static cl::opt<bool> 296 SequentialDisassembly("sequential-disassembly", 297 cl::desc("performs disassembly sequentially"), 298 cl::init(false), 299 cl::cat(BoltOptCategory)); 300 301 static cl::opt<bool> 302 WriteBoltInfoSection("bolt-info", 303 cl::desc("write bolt info section in the output binary"), 304 cl::init(true), 305 cl::ZeroOrMore, 306 cl::Hidden, 307 cl::cat(BoltOutputCategory)); 308 309 } // namespace opts 310 311 constexpr const char *RewriteInstance::SectionsToOverwrite[]; 312 std::vector<std::string> RewriteInstance::DebugSectionsToOverwrite = { 313 ".debug_abbrev", ".debug_aranges", ".debug_line", ".debug_loc", 314 ".debug_ranges", ".gdb_index", ".debug_addr"}; 315 316 const char RewriteInstance::TimerGroupName[] = "rewrite"; 317 const char RewriteInstance::TimerGroupDesc[] = "Rewrite passes"; 318 319 namespace llvm { 320 namespace bolt { 321 322 extern const char *BoltRevision; 323 324 extern MCPlusBuilder *createX86MCPlusBuilder(const MCInstrAnalysis *, 325 const MCInstrInfo *, 326 const MCRegisterInfo *); 327 extern MCPlusBuilder *createAArch64MCPlusBuilder(const MCInstrAnalysis *, 328 const MCInstrInfo *, 329 const MCRegisterInfo *); 330 331 } // namespace bolt 332 } // namespace llvm 333 334 namespace { 335 336 bool refersToReorderedSection(ErrorOr<BinarySection &> Section) { 337 auto Itr = 338 std::find_if(opts::ReorderData.begin(), opts::ReorderData.end(), 339 [&](const std::string &SectionName) { 340 return (Section && Section->getName() == SectionName); 341 }); 342 return Itr != opts::ReorderData.end(); 343 } 344 345 MCPlusBuilder *createMCPlusBuilder(const Triple::ArchType Arch, 346 const MCInstrAnalysis *Analysis, 347 const MCInstrInfo *Info, 348 const MCRegisterInfo *RegInfo) { 349 #ifdef X86_AVAILABLE 350 if (Arch == Triple::x86_64) 351 return createX86MCPlusBuilder(Analysis, Info, RegInfo); 352 #endif 353 354 #ifdef AARCH64_AVAILABLE 355 if (Arch == Triple::aarch64) 356 return createAArch64MCPlusBuilder(Analysis, Info, RegInfo); 357 #endif 358 359 llvm_unreachable("architecture unsupported by MCPlusBuilder"); 360 } 361 362 } // anonymous namespace 363 364 RewriteInstance::RewriteInstance(ELFObjectFileBase *File, const int Argc, 365 const char *const *Argv, StringRef ToolPath) 366 : InputFile(File), Argc(Argc), Argv(Argv), ToolPath(ToolPath), 367 SHStrTab(StringTableBuilder::ELF) { 368 auto ELF64LEFile = dyn_cast<ELF64LEObjectFile>(InputFile); 369 if (!ELF64LEFile) { 370 errs() << "BOLT-ERROR: only 64-bit LE ELF binaries are supported\n"; 371 exit(1); 372 } 373 374 bool IsPIC = false; 375 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile(); 376 if (Obj.getHeader().e_type != ELF::ET_EXEC) { 377 outs() << "BOLT-INFO: shared object or position-independent executable " 378 "detected\n"; 379 IsPIC = true; 380 } 381 382 BC = BinaryContext::createBinaryContext( 383 File, IsPIC, 384 DWARFContext::create(*File, DWARFContext::ProcessDebugRelocations::Ignore, 385 nullptr, opts::DWPPathName, 386 WithColor::defaultErrorHandler, 387 WithColor::defaultWarningHandler)); 388 389 BC->initializeTarget(std::unique_ptr<MCPlusBuilder>(createMCPlusBuilder( 390 BC->TheTriple->getArch(), BC->MIA.get(), BC->MII.get(), BC->MRI.get()))); 391 392 BAT = std::make_unique<BoltAddressTranslation>(*BC); 393 394 if (opts::UpdateDebugSections) 395 DebugInfoRewriter = std::make_unique<DWARFRewriter>(*BC); 396 397 if (opts::Instrument) 398 BC->setRuntimeLibrary(std::make_unique<InstrumentationRuntimeLibrary>()); 399 else if (opts::Hugify) 400 BC->setRuntimeLibrary(std::make_unique<HugifyRuntimeLibrary>()); 401 } 402 403 RewriteInstance::~RewriteInstance() {} 404 405 Error RewriteInstance::setProfile(StringRef Filename) { 406 if (!sys::fs::exists(Filename)) 407 return errorCodeToError(make_error_code(errc::no_such_file_or_directory)); 408 409 if (ProfileReader) { 410 // Already exists 411 return make_error<StringError>(Twine("multiple profiles specified: ") + 412 ProfileReader->getFilename() + " and " + 413 Filename, 414 inconvertibleErrorCode()); 415 } 416 417 // Spawn a profile reader based on file contents. 418 if (DataAggregator::checkPerfDataMagic(Filename)) 419 ProfileReader = std::make_unique<DataAggregator>(Filename); 420 else if (YAMLProfileReader::isYAML(Filename)) 421 ProfileReader = std::make_unique<YAMLProfileReader>(Filename); 422 else 423 ProfileReader = std::make_unique<DataReader>(Filename); 424 425 return Error::success(); 426 } 427 428 /// Return true if the function \p BF should be disassembled. 429 static bool shouldDisassemble(const BinaryFunction &BF) { 430 if (BF.isPseudo()) 431 return false; 432 433 if (opts::processAllFunctions()) 434 return true; 435 436 return !BF.isIgnored(); 437 } 438 439 void RewriteInstance::discoverStorage() { 440 NamedRegionTimer T("discoverStorage", "discover storage", TimerGroupName, 441 TimerGroupDesc, opts::TimeRewrite); 442 443 // Stubs are harmful because RuntimeDyld may try to increase the size of 444 // sections accounting for stubs when we need those sections to match the 445 // same size seen in the input binary, in case this section is a copy 446 // of the original one seen in the binary. 447 BC->EFMM.reset(new ExecutableFileMemoryManager(*BC, /*AllowStubs*/ false)); 448 449 auto ELF64LEFile = dyn_cast<ELF64LEObjectFile>(InputFile); 450 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile(); 451 452 BC->StartFunctionAddress = Obj.getHeader().e_entry; 453 454 NextAvailableAddress = 0; 455 uint64_t NextAvailableOffset = 0; 456 ELF64LE::PhdrRange PHs = 457 cantFail(Obj.program_headers(), "program_headers() failed"); 458 for (const ELF64LE::Phdr &Phdr : PHs) { 459 switch (Phdr.p_type) { 460 case ELF::PT_LOAD: 461 BC->FirstAllocAddress = std::min(BC->FirstAllocAddress, 462 static_cast<uint64_t>(Phdr.p_vaddr)); 463 NextAvailableAddress = std::max(NextAvailableAddress, 464 Phdr.p_vaddr + Phdr.p_memsz); 465 NextAvailableOffset = std::max(NextAvailableOffset, 466 Phdr.p_offset + Phdr.p_filesz); 467 468 BC->SegmentMapInfo[Phdr.p_vaddr] = SegmentInfo{Phdr.p_vaddr, 469 Phdr.p_memsz, 470 Phdr.p_offset, 471 Phdr.p_filesz, 472 Phdr.p_align}; 473 break; 474 case ELF::PT_INTERP: 475 BC->HasInterpHeader = true; 476 break; 477 } 478 } 479 480 for (const SectionRef &Section : InputFile->sections()) { 481 StringRef SectionName = cantFail(Section.getName()); 482 if (SectionName == ".text") { 483 BC->OldTextSectionAddress = Section.getAddress(); 484 BC->OldTextSectionSize = Section.getSize(); 485 486 StringRef SectionContents = cantFail(Section.getContents()); 487 BC->OldTextSectionOffset = 488 SectionContents.data() - InputFile->getData().data(); 489 } 490 491 if (!opts::HeatmapMode && 492 !(opts::AggregateOnly && BAT->enabledFor(InputFile)) && 493 (SectionName.startswith(getOrgSecPrefix()) || 494 SectionName == getBOLTTextSectionName())) { 495 errs() << "BOLT-ERROR: input file was processed by BOLT. " 496 "Cannot re-optimize.\n"; 497 exit(1); 498 } 499 } 500 501 assert(NextAvailableAddress && NextAvailableOffset && 502 "no PT_LOAD pheader seen"); 503 504 outs() << "BOLT-INFO: first alloc address is 0x" 505 << Twine::utohexstr(BC->FirstAllocAddress) << '\n'; 506 507 FirstNonAllocatableOffset = NextAvailableOffset; 508 509 NextAvailableAddress = alignTo(NextAvailableAddress, BC->PageAlign); 510 NextAvailableOffset = alignTo(NextAvailableOffset, BC->PageAlign); 511 512 if (!opts::UseGnuStack) { 513 // This is where the black magic happens. Creating PHDR table in a segment 514 // other than that containing ELF header is tricky. Some loaders and/or 515 // parts of loaders will apply e_phoff from ELF header assuming both are in 516 // the same segment, while others will do the proper calculation. 517 // We create the new PHDR table in such a way that both of the methods 518 // of loading and locating the table work. There's a slight file size 519 // overhead because of that. 520 // 521 // NB: bfd's strip command cannot do the above and will corrupt the 522 // binary during the process of stripping non-allocatable sections. 523 if (NextAvailableOffset <= NextAvailableAddress - BC->FirstAllocAddress) 524 NextAvailableOffset = NextAvailableAddress - BC->FirstAllocAddress; 525 else 526 NextAvailableAddress = NextAvailableOffset + BC->FirstAllocAddress; 527 528 assert(NextAvailableOffset == 529 NextAvailableAddress - BC->FirstAllocAddress && 530 "PHDR table address calculation error"); 531 532 outs() << "BOLT-INFO: creating new program header table at address 0x" 533 << Twine::utohexstr(NextAvailableAddress) << ", offset 0x" 534 << Twine::utohexstr(NextAvailableOffset) << '\n'; 535 536 PHDRTableAddress = NextAvailableAddress; 537 PHDRTableOffset = NextAvailableOffset; 538 539 // Reserve space for 3 extra pheaders. 540 unsigned Phnum = Obj.getHeader().e_phnum; 541 Phnum += 3; 542 543 NextAvailableAddress += Phnum * sizeof(ELF64LEPhdrTy); 544 NextAvailableOffset += Phnum * sizeof(ELF64LEPhdrTy); 545 } 546 547 // Align at cache line. 548 NextAvailableAddress = alignTo(NextAvailableAddress, 64); 549 NextAvailableOffset = alignTo(NextAvailableOffset, 64); 550 551 NewTextSegmentAddress = NextAvailableAddress; 552 NewTextSegmentOffset = NextAvailableOffset; 553 BC->LayoutStartAddress = NextAvailableAddress; 554 555 // Tools such as objcopy can strip section contents but leave header 556 // entries. Check that at least .text is mapped in the file. 557 if (!getFileOffsetForAddress(BC->OldTextSectionAddress)) { 558 errs() << "BOLT-ERROR: input binary is not a valid ELF executable as its " 559 "text section is not mapped to a valid segment\n"; 560 exit(1); 561 } 562 } 563 564 void RewriteInstance::parseSDTNotes() { 565 if (!SDTSection) 566 return; 567 568 StringRef Buf = SDTSection->getContents(); 569 DataExtractor DE = DataExtractor(Buf, BC->AsmInfo->isLittleEndian(), 570 BC->AsmInfo->getCodePointerSize()); 571 uint64_t Offset = 0; 572 573 while (DE.isValidOffset(Offset)) { 574 uint32_t NameSz = DE.getU32(&Offset); 575 DE.getU32(&Offset); // skip over DescSz 576 uint32_t Type = DE.getU32(&Offset); 577 Offset = alignTo(Offset, 4); 578 579 if (Type != 3) 580 errs() << "BOLT-WARNING: SDT note type \"" << Type 581 << "\" is not expected\n"; 582 583 if (NameSz == 0) 584 errs() << "BOLT-WARNING: SDT note has empty name\n"; 585 586 StringRef Name = DE.getCStr(&Offset); 587 588 if (!Name.equals("stapsdt")) 589 errs() << "BOLT-WARNING: SDT note name \"" << Name 590 << "\" is not expected\n"; 591 592 // Parse description 593 SDTMarkerInfo Marker; 594 Marker.PCOffset = Offset; 595 Marker.PC = DE.getU64(&Offset); 596 Marker.Base = DE.getU64(&Offset); 597 Marker.Semaphore = DE.getU64(&Offset); 598 Marker.Provider = DE.getCStr(&Offset); 599 Marker.Name = DE.getCStr(&Offset); 600 Marker.Args = DE.getCStr(&Offset); 601 Offset = alignTo(Offset, 4); 602 BC->SDTMarkers[Marker.PC] = Marker; 603 } 604 605 if (opts::PrintSDTMarkers) 606 printSDTMarkers(); 607 } 608 609 void RewriteInstance::parsePseudoProbe() { 610 if (!PseudoProbeDescSection && !PseudoProbeSection) { 611 // pesudo probe is not added to binary. It is normal and no warning needed. 612 return; 613 } 614 615 // If only one section is found, it might mean the ELF is corrupted. 616 if (!PseudoProbeDescSection) { 617 errs() << "BOLT-WARNING: fail in reading .pseudo_probe_desc binary\n"; 618 return; 619 } else if (!PseudoProbeSection) { 620 errs() << "BOLT-WARNING: fail in reading .pseudo_probe binary\n"; 621 return; 622 } 623 624 StringRef Contents = PseudoProbeDescSection->getContents(); 625 if (!BC->ProbeDecoder.buildGUID2FuncDescMap( 626 reinterpret_cast<const uint8_t *>(Contents.data()), 627 Contents.size())) { 628 errs() << "BOLT-WARNING: fail in building GUID2FuncDescMap\n"; 629 return; 630 } 631 Contents = PseudoProbeSection->getContents(); 632 if (!BC->ProbeDecoder.buildAddress2ProbeMap( 633 reinterpret_cast<const uint8_t *>(Contents.data()), 634 Contents.size())) { 635 BC->ProbeDecoder.getAddress2ProbesMap().clear(); 636 errs() << "BOLT-WARNING: fail in building Address2ProbeMap\n"; 637 return; 638 } 639 640 if (opts::PrintPseudoProbes == opts::PrintPseudoProbesOptions::PPP_All || 641 opts::PrintPseudoProbes == 642 opts::PrintPseudoProbesOptions::PPP_Probes_Section_Decode) { 643 outs() << "Report of decoding input pseudo probe binaries \n"; 644 BC->ProbeDecoder.printGUID2FuncDescMap(outs()); 645 BC->ProbeDecoder.printProbesForAllAddresses(outs()); 646 } 647 } 648 649 void RewriteInstance::printSDTMarkers() { 650 outs() << "BOLT-INFO: Number of SDT markers is " << BC->SDTMarkers.size() 651 << "\n"; 652 for (auto It : BC->SDTMarkers) { 653 SDTMarkerInfo &Marker = It.second; 654 outs() << "BOLT-INFO: PC: " << utohexstr(Marker.PC) 655 << ", Base: " << utohexstr(Marker.Base) 656 << ", Semaphore: " << utohexstr(Marker.Semaphore) 657 << ", Provider: " << Marker.Provider << ", Name: " << Marker.Name 658 << ", Args: " << Marker.Args << "\n"; 659 } 660 } 661 662 void RewriteInstance::parseBuildID() { 663 if (!BuildIDSection) 664 return; 665 666 StringRef Buf = BuildIDSection->getContents(); 667 668 // Reading notes section (see Portable Formats Specification, Version 1.1, 669 // pg 2-5, section "Note Section"). 670 DataExtractor DE = DataExtractor(Buf, true, 8); 671 uint64_t Offset = 0; 672 if (!DE.isValidOffset(Offset)) 673 return; 674 uint32_t NameSz = DE.getU32(&Offset); 675 if (!DE.isValidOffset(Offset)) 676 return; 677 uint32_t DescSz = DE.getU32(&Offset); 678 if (!DE.isValidOffset(Offset)) 679 return; 680 uint32_t Type = DE.getU32(&Offset); 681 682 LLVM_DEBUG(dbgs() << "NameSz = " << NameSz << "; DescSz = " << DescSz 683 << "; Type = " << Type << "\n"); 684 685 // Type 3 is a GNU build-id note section 686 if (Type != 3) 687 return; 688 689 StringRef Name = Buf.slice(Offset, Offset + NameSz); 690 Offset = alignTo(Offset + NameSz, 4); 691 if (Name.substr(0, 3) != "GNU") 692 return; 693 694 BuildID = Buf.slice(Offset, Offset + DescSz); 695 } 696 697 Optional<std::string> RewriteInstance::getPrintableBuildID() const { 698 if (BuildID.empty()) 699 return NoneType(); 700 701 std::string Str; 702 raw_string_ostream OS(Str); 703 const unsigned char *CharIter = BuildID.bytes_begin(); 704 while (CharIter != BuildID.bytes_end()) { 705 if (*CharIter < 0x10) 706 OS << "0"; 707 OS << Twine::utohexstr(*CharIter); 708 ++CharIter; 709 } 710 return OS.str(); 711 } 712 713 void RewriteInstance::patchBuildID() { 714 raw_fd_ostream &OS = Out->os(); 715 716 if (BuildID.empty()) 717 return; 718 719 size_t IDOffset = BuildIDSection->getContents().rfind(BuildID); 720 assert(IDOffset != StringRef::npos && "failed to patch build-id"); 721 722 uint64_t FileOffset = getFileOffsetForAddress(BuildIDSection->getAddress()); 723 if (!FileOffset) { 724 errs() << "BOLT-WARNING: Non-allocatable build-id will not be updated.\n"; 725 return; 726 } 727 728 char LastIDByte = BuildID[BuildID.size() - 1]; 729 LastIDByte ^= 1; 730 OS.pwrite(&LastIDByte, 1, FileOffset + IDOffset + BuildID.size() - 1); 731 732 outs() << "BOLT-INFO: patched build-id (flipped last bit)\n"; 733 } 734 735 void RewriteInstance::run() { 736 if (!BC) { 737 errs() << "BOLT-ERROR: failed to create a binary context\n"; 738 return; 739 } 740 741 outs() << "BOLT-INFO: Target architecture: " 742 << Triple::getArchTypeName( 743 (llvm::Triple::ArchType)InputFile->getArch()) 744 << "\n"; 745 outs() << "BOLT-INFO: BOLT version: " << BoltRevision << "\n"; 746 747 discoverStorage(); 748 readSpecialSections(); 749 adjustCommandLineOptions(); 750 discoverFileObjects(); 751 752 preprocessProfileData(); 753 754 // Skip disassembling if we have a translation table and we are running an 755 // aggregation job. 756 if (opts::AggregateOnly && BAT->enabledFor(InputFile)) { 757 processProfileData(); 758 return; 759 } 760 761 selectFunctionsToProcess(); 762 763 readDebugInfo(); 764 765 disassembleFunctions(); 766 767 processProfileDataPreCFG(); 768 769 buildFunctionsCFG(); 770 771 processProfileData(); 772 773 postProcessFunctions(); 774 775 if (opts::DiffOnly) 776 return; 777 778 runOptimizationPasses(); 779 780 emitAndLink(); 781 782 updateMetadata(); 783 784 if (opts::LinuxKernelMode) { 785 errs() << "BOLT-WARNING: not writing the output file for Linux Kernel\n"; 786 return; 787 } else if (opts::OutputFilename == "/dev/null") { 788 outs() << "BOLT-INFO: skipping writing final binary to disk\n"; 789 return; 790 } 791 792 // Rewrite allocatable contents and copy non-allocatable parts with mods. 793 rewriteFile(); 794 } 795 796 void RewriteInstance::discoverFileObjects() { 797 NamedRegionTimer T("discoverFileObjects", "discover file objects", 798 TimerGroupName, TimerGroupDesc, opts::TimeRewrite); 799 FileSymRefs.clear(); 800 BC->getBinaryFunctions().clear(); 801 BC->clearBinaryData(); 802 803 // For local symbols we want to keep track of associated FILE symbol name for 804 // disambiguation by combined name. 805 StringRef FileSymbolName; 806 bool SeenFileName = false; 807 struct SymbolRefHash { 808 size_t operator()(SymbolRef const &S) const { 809 return std::hash<decltype(DataRefImpl::p)>{}(S.getRawDataRefImpl().p); 810 } 811 }; 812 std::unordered_map<SymbolRef, StringRef, SymbolRefHash> SymbolToFileName; 813 for (const ELFSymbolRef &Symbol : InputFile->symbols()) { 814 Expected<StringRef> NameOrError = Symbol.getName(); 815 if (NameOrError && NameOrError->startswith("__asan_init")) { 816 errs() << "BOLT-ERROR: input file was compiled or linked with sanitizer " 817 "support. Cannot optimize.\n"; 818 exit(1); 819 } 820 if (NameOrError && NameOrError->startswith("__llvm_coverage_mapping")) { 821 errs() << "BOLT-ERROR: input file was compiled or linked with coverage " 822 "support. Cannot optimize.\n"; 823 exit(1); 824 } 825 826 if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Undefined) 827 continue; 828 829 if (cantFail(Symbol.getType()) == SymbolRef::ST_File) { 830 StringRef Name = 831 cantFail(std::move(NameOrError), "cannot get symbol name for file"); 832 // Ignore Clang LTO artificial FILE symbol as it is not always generated, 833 // and this uncertainty is causing havoc in function name matching. 834 if (Name == "ld-temp.o") 835 continue; 836 FileSymbolName = Name; 837 SeenFileName = true; 838 continue; 839 } 840 if (!FileSymbolName.empty() && 841 !(cantFail(Symbol.getFlags()) & SymbolRef::SF_Global)) 842 SymbolToFileName[Symbol] = FileSymbolName; 843 } 844 845 // Sort symbols in the file by value. Ignore symbols from non-allocatable 846 // sections. 847 auto isSymbolInMemory = [this](const SymbolRef &Sym) { 848 if (cantFail(Sym.getType()) == SymbolRef::ST_File) 849 return false; 850 if (cantFail(Sym.getFlags()) & SymbolRef::SF_Absolute) 851 return true; 852 if (cantFail(Sym.getFlags()) & SymbolRef::SF_Undefined) 853 return false; 854 BinarySection Section(*BC, *cantFail(Sym.getSection())); 855 return Section.isAllocatable(); 856 }; 857 std::vector<SymbolRef> SortedFileSymbols; 858 std::copy_if(InputFile->symbol_begin(), InputFile->symbol_end(), 859 std::back_inserter(SortedFileSymbols), isSymbolInMemory); 860 861 std::stable_sort( 862 SortedFileSymbols.begin(), SortedFileSymbols.end(), 863 [](const SymbolRef &A, const SymbolRef &B) { 864 // FUNC symbols have the highest precedence, while SECTIONs 865 // have the lowest. 866 uint64_t AddressA = cantFail(A.getAddress()); 867 uint64_t AddressB = cantFail(B.getAddress()); 868 if (AddressA != AddressB) 869 return AddressA < AddressB; 870 871 SymbolRef::Type AType = cantFail(A.getType()); 872 SymbolRef::Type BType = cantFail(B.getType()); 873 if (AType == SymbolRef::ST_Function && BType != SymbolRef::ST_Function) 874 return true; 875 if (BType == SymbolRef::ST_Debug && AType != SymbolRef::ST_Debug) 876 return true; 877 878 return false; 879 }); 880 881 // For aarch64, the ABI defines mapping symbols so we identify data in the 882 // code section (see IHI0056B). $d identifies data contents. 883 auto LastSymbol = SortedFileSymbols.end() - 1; 884 if (BC->isAArch64()) { 885 LastSymbol = std::stable_partition( 886 SortedFileSymbols.begin(), SortedFileSymbols.end(), 887 [](const SymbolRef &Symbol) { 888 StringRef Name = cantFail(Symbol.getName()); 889 return !(cantFail(Symbol.getType()) == SymbolRef::ST_Unknown && 890 (Name == "$d" || Name.startswith("$d.") || Name == "$x" || 891 Name.startswith("$x."))); 892 }); 893 --LastSymbol; 894 } 895 896 BinaryFunction *PreviousFunction = nullptr; 897 unsigned AnonymousId = 0; 898 899 const auto MarkersBegin = std::next(LastSymbol); 900 for (auto ISym = SortedFileSymbols.begin(); ISym != MarkersBegin; ++ISym) { 901 const SymbolRef &Symbol = *ISym; 902 // Keep undefined symbols for pretty printing? 903 if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Undefined) 904 continue; 905 906 const SymbolRef::Type SymbolType = cantFail(Symbol.getType()); 907 908 if (SymbolType == SymbolRef::ST_File) 909 continue; 910 911 StringRef SymName = cantFail(Symbol.getName(), "cannot get symbol name"); 912 uint64_t Address = 913 cantFail(Symbol.getAddress(), "cannot get symbol address"); 914 if (Address == 0) { 915 if (opts::Verbosity >= 1 && SymbolType == SymbolRef::ST_Function) 916 errs() << "BOLT-WARNING: function with 0 address seen\n"; 917 continue; 918 } 919 920 // Ignore input hot markers 921 if (SymName == "__hot_start" || SymName == "__hot_end") 922 continue; 923 924 FileSymRefs[Address] = Symbol; 925 926 // Skip section symbols that will be registered by disassemblePLT(). 927 if ((cantFail(Symbol.getType()) == SymbolRef::ST_Debug)) { 928 ErrorOr<BinarySection &> BSection = BC->getSectionForAddress(Address); 929 if (BSection && getPLTSectionInfo(BSection->getName())) 930 continue; 931 } 932 933 /// It is possible we are seeing a globalized local. LLVM might treat it as 934 /// a local if it has a "private global" prefix, e.g. ".L". Thus we have to 935 /// change the prefix to enforce global scope of the symbol. 936 std::string Name = SymName.startswith(BC->AsmInfo->getPrivateGlobalPrefix()) 937 ? "PG" + std::string(SymName) 938 : std::string(SymName); 939 940 // Disambiguate all local symbols before adding to symbol table. 941 // Since we don't know if we will see a global with the same name, 942 // always modify the local name. 943 // 944 // NOTE: the naming convention for local symbols should match 945 // the one we use for profile data. 946 std::string UniqueName; 947 std::string AlternativeName; 948 if (Name.empty()) { 949 UniqueName = "ANONYMOUS." + std::to_string(AnonymousId++); 950 } else if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Global) { 951 assert(!BC->getBinaryDataByName(Name) && "global name not unique"); 952 UniqueName = Name; 953 } else { 954 // If we have a local file name, we should create 2 variants for the 955 // function name. The reason is that perf profile might have been 956 // collected on a binary that did not have the local file name (e.g. as 957 // a side effect of stripping debug info from the binary): 958 // 959 // primary: <function>/<id> 960 // alternative: <function>/<file>/<id2> 961 // 962 // The <id> field is used for disambiguation of local symbols since there 963 // could be identical function names coming from identical file names 964 // (e.g. from different directories). 965 std::string AltPrefix; 966 auto SFI = SymbolToFileName.find(Symbol); 967 if (SymbolType == SymbolRef::ST_Function && SFI != SymbolToFileName.end()) 968 AltPrefix = Name + "/" + std::string(SFI->second); 969 970 UniqueName = NR.uniquify(Name); 971 if (!AltPrefix.empty()) 972 AlternativeName = NR.uniquify(AltPrefix); 973 } 974 975 uint64_t SymbolSize = ELFSymbolRef(Symbol).getSize(); 976 uint64_t SymbolAlignment = Symbol.getAlignment(); 977 unsigned SymbolFlags = cantFail(Symbol.getFlags()); 978 979 auto registerName = [&](uint64_t FinalSize) { 980 // Register names even if it's not a function, e.g. for an entry point. 981 BC->registerNameAtAddress(UniqueName, Address, FinalSize, SymbolAlignment, 982 SymbolFlags); 983 if (!AlternativeName.empty()) 984 BC->registerNameAtAddress(AlternativeName, Address, FinalSize, 985 SymbolAlignment, SymbolFlags); 986 }; 987 988 section_iterator Section = 989 cantFail(Symbol.getSection(), "cannot get symbol section"); 990 if (Section == InputFile->section_end()) { 991 // Could be an absolute symbol. Could record for pretty printing. 992 LLVM_DEBUG(if (opts::Verbosity > 1) { 993 dbgs() << "BOLT-INFO: absolute sym " << UniqueName << "\n"; 994 }); 995 registerName(SymbolSize); 996 continue; 997 } 998 999 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: considering symbol " << UniqueName 1000 << " for function\n"); 1001 1002 if (!Section->isText()) { 1003 assert(SymbolType != SymbolRef::ST_Function && 1004 "unexpected function inside non-code section"); 1005 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: rejecting as symbol is not in code\n"); 1006 registerName(SymbolSize); 1007 continue; 1008 } 1009 1010 // Assembly functions could be ST_NONE with 0 size. Check that the 1011 // corresponding section is a code section and they are not inside any 1012 // other known function to consider them. 1013 // 1014 // Sometimes assembly functions are not marked as functions and neither are 1015 // their local labels. The only way to tell them apart is to look at 1016 // symbol scope - global vs local. 1017 if (PreviousFunction && SymbolType != SymbolRef::ST_Function) { 1018 if (PreviousFunction->containsAddress(Address)) { 1019 if (PreviousFunction->isSymbolValidInScope(Symbol, SymbolSize)) { 1020 LLVM_DEBUG(dbgs() 1021 << "BOLT-DEBUG: symbol is a function local symbol\n"); 1022 } else if (Address == PreviousFunction->getAddress() && !SymbolSize) { 1023 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring symbol as a marker\n"); 1024 } else if (opts::Verbosity > 1) { 1025 errs() << "BOLT-WARNING: symbol " << UniqueName 1026 << " seen in the middle of function " << *PreviousFunction 1027 << ". Could be a new entry.\n"; 1028 } 1029 registerName(SymbolSize); 1030 continue; 1031 } else if (PreviousFunction->getSize() == 0 && 1032 PreviousFunction->isSymbolValidInScope(Symbol, SymbolSize)) { 1033 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: symbol is a function local symbol\n"); 1034 registerName(SymbolSize); 1035 continue; 1036 } 1037 } 1038 1039 if (PreviousFunction && PreviousFunction->containsAddress(Address) && 1040 PreviousFunction->getAddress() != Address) { 1041 if (PreviousFunction->isSymbolValidInScope(Symbol, SymbolSize)) { 1042 if (opts::Verbosity >= 1) 1043 outs() << "BOLT-INFO: skipping possibly another entry for function " 1044 << *PreviousFunction << " : " << UniqueName << '\n'; 1045 } else { 1046 outs() << "BOLT-INFO: using " << UniqueName << " as another entry to " 1047 << "function " << *PreviousFunction << '\n'; 1048 1049 registerName(0); 1050 1051 PreviousFunction->addEntryPointAtOffset(Address - 1052 PreviousFunction->getAddress()); 1053 1054 // Remove the symbol from FileSymRefs so that we can skip it from 1055 // in the future. 1056 auto SI = FileSymRefs.find(Address); 1057 assert(SI != FileSymRefs.end() && "symbol expected to be present"); 1058 assert(SI->second == Symbol && "wrong symbol found"); 1059 FileSymRefs.erase(SI); 1060 } 1061 registerName(SymbolSize); 1062 continue; 1063 } 1064 1065 // Checkout for conflicts with function data from FDEs. 1066 bool IsSimple = true; 1067 auto FDEI = CFIRdWrt->getFDEs().lower_bound(Address); 1068 if (FDEI != CFIRdWrt->getFDEs().end()) { 1069 const dwarf::FDE &FDE = *FDEI->second; 1070 if (FDEI->first != Address) { 1071 // There's no matching starting address in FDE. Make sure the previous 1072 // FDE does not contain this address. 1073 if (FDEI != CFIRdWrt->getFDEs().begin()) { 1074 --FDEI; 1075 const dwarf::FDE &PrevFDE = *FDEI->second; 1076 uint64_t PrevStart = PrevFDE.getInitialLocation(); 1077 uint64_t PrevLength = PrevFDE.getAddressRange(); 1078 if (Address > PrevStart && Address < PrevStart + PrevLength) { 1079 errs() << "BOLT-ERROR: function " << UniqueName 1080 << " is in conflict with FDE [" 1081 << Twine::utohexstr(PrevStart) << ", " 1082 << Twine::utohexstr(PrevStart + PrevLength) 1083 << "). Skipping.\n"; 1084 IsSimple = false; 1085 } 1086 } 1087 } else if (FDE.getAddressRange() != SymbolSize) { 1088 if (SymbolSize) { 1089 // Function addresses match but sizes differ. 1090 errs() << "BOLT-WARNING: sizes differ for function " << UniqueName 1091 << ". FDE : " << FDE.getAddressRange() 1092 << "; symbol table : " << SymbolSize << ". Using max size.\n"; 1093 } 1094 SymbolSize = std::max(SymbolSize, FDE.getAddressRange()); 1095 if (BC->getBinaryDataAtAddress(Address)) { 1096 BC->setBinaryDataSize(Address, SymbolSize); 1097 } else { 1098 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: No BD @ 0x" 1099 << Twine::utohexstr(Address) << "\n"); 1100 } 1101 } 1102 } 1103 1104 BinaryFunction *BF = nullptr; 1105 // Since function may not have yet obtained its real size, do a search 1106 // using the list of registered functions instead of calling 1107 // getBinaryFunctionAtAddress(). 1108 auto BFI = BC->getBinaryFunctions().find(Address); 1109 if (BFI != BC->getBinaryFunctions().end()) { 1110 BF = &BFI->second; 1111 // Duplicate the function name. Make sure everything matches before we add 1112 // an alternative name. 1113 if (SymbolSize != BF->getSize()) { 1114 if (opts::Verbosity >= 1) { 1115 if (SymbolSize && BF->getSize()) 1116 errs() << "BOLT-WARNING: size mismatch for duplicate entries " 1117 << *BF << " and " << UniqueName << '\n'; 1118 outs() << "BOLT-INFO: adjusting size of function " << *BF << " old " 1119 << BF->getSize() << " new " << SymbolSize << "\n"; 1120 } 1121 BF->setSize(std::max(SymbolSize, BF->getSize())); 1122 BC->setBinaryDataSize(Address, BF->getSize()); 1123 } 1124 BF->addAlternativeName(UniqueName); 1125 } else { 1126 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(Address); 1127 // Skip symbols from invalid sections 1128 if (!Section) { 1129 errs() << "BOLT-WARNING: " << UniqueName << " (0x" 1130 << Twine::utohexstr(Address) << ") does not have any section\n"; 1131 continue; 1132 } 1133 assert(Section && "section for functions must be registered"); 1134 1135 // Skip symbols from zero-sized sections. 1136 if (!Section->getSize()) 1137 continue; 1138 1139 BF = BC->createBinaryFunction(UniqueName, *Section, Address, SymbolSize); 1140 if (!IsSimple) 1141 BF->setSimple(false); 1142 } 1143 if (!AlternativeName.empty()) 1144 BF->addAlternativeName(AlternativeName); 1145 1146 registerName(SymbolSize); 1147 PreviousFunction = BF; 1148 } 1149 1150 // Read dynamic relocation first as their presence affects the way we process 1151 // static relocations. E.g. we will ignore a static relocation at an address 1152 // that is a subject to dynamic relocation processing. 1153 processDynamicRelocations(); 1154 1155 // Process PLT section. 1156 if (BC->TheTriple->getArch() == Triple::x86_64) 1157 disassemblePLT(); 1158 1159 // See if we missed any functions marked by FDE. 1160 for (const auto &FDEI : CFIRdWrt->getFDEs()) { 1161 const uint64_t Address = FDEI.first; 1162 const dwarf::FDE *FDE = FDEI.second; 1163 const BinaryFunction *BF = BC->getBinaryFunctionAtAddress(Address); 1164 if (BF) 1165 continue; 1166 1167 BF = BC->getBinaryFunctionContainingAddress(Address); 1168 if (BF) { 1169 errs() << "BOLT-WARNING: FDE [0x" << Twine::utohexstr(Address) << ", 0x" 1170 << Twine::utohexstr(Address + FDE->getAddressRange()) 1171 << ") conflicts with function " << *BF << '\n'; 1172 continue; 1173 } 1174 1175 if (opts::Verbosity >= 1) 1176 errs() << "BOLT-WARNING: FDE [0x" << Twine::utohexstr(Address) << ", 0x" 1177 << Twine::utohexstr(Address + FDE->getAddressRange()) 1178 << ") has no corresponding symbol table entry\n"; 1179 1180 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(Address); 1181 assert(Section && "cannot get section for address from FDE"); 1182 std::string FunctionName = 1183 "__BOLT_FDE_FUNCat" + Twine::utohexstr(Address).str(); 1184 BC->createBinaryFunction(FunctionName, *Section, Address, 1185 FDE->getAddressRange()); 1186 } 1187 1188 BC->setHasSymbolsWithFileName(SeenFileName); 1189 1190 // Now that all the functions were created - adjust their boundaries. 1191 adjustFunctionBoundaries(); 1192 1193 // Annotate functions with code/data markers in AArch64 1194 for (auto ISym = MarkersBegin; ISym != SortedFileSymbols.end(); ++ISym) { 1195 const SymbolRef &Symbol = *ISym; 1196 uint64_t Address = 1197 cantFail(Symbol.getAddress(), "cannot get symbol address"); 1198 uint64_t SymbolSize = ELFSymbolRef(Symbol).getSize(); 1199 BinaryFunction *BF = 1200 BC->getBinaryFunctionContainingAddress(Address, true, true); 1201 if (!BF) { 1202 // Stray marker 1203 continue; 1204 } 1205 const uint64_t EntryOffset = Address - BF->getAddress(); 1206 if (BF->isCodeMarker(Symbol, SymbolSize)) { 1207 BF->markCodeAtOffset(EntryOffset); 1208 continue; 1209 } 1210 if (BF->isDataMarker(Symbol, SymbolSize)) { 1211 BF->markDataAtOffset(EntryOffset); 1212 BC->AddressToConstantIslandMap[Address] = BF; 1213 continue; 1214 } 1215 llvm_unreachable("Unknown marker"); 1216 } 1217 1218 if (opts::LinuxKernelMode) { 1219 // Read all special linux kernel sections and their relocations 1220 processLKSections(); 1221 } else { 1222 // Read all relocations now that we have binary functions mapped. 1223 processRelocations(); 1224 } 1225 } 1226 1227 void RewriteInstance::disassemblePLT() { 1228 auto analyzeOnePLTSection = [&](BinarySection &Section, uint64_t EntrySize) { 1229 const uint64_t PLTAddress = Section.getAddress(); 1230 StringRef PLTContents = Section.getContents(); 1231 ArrayRef<uint8_t> PLTData( 1232 reinterpret_cast<const uint8_t *>(PLTContents.data()), 1233 Section.getSize()); 1234 const unsigned PtrSize = BC->AsmInfo->getCodePointerSize(); 1235 1236 for (uint64_t EntryOffset = 0; EntryOffset + EntrySize <= Section.getSize(); 1237 EntryOffset += EntrySize) { 1238 uint64_t InstrOffset = EntryOffset; 1239 uint64_t InstrSize; 1240 MCInst Instruction; 1241 while (InstrOffset < EntryOffset + EntrySize) { 1242 uint64_t InstrAddr = PLTAddress + InstrOffset; 1243 if (!BC->DisAsm->getInstruction(Instruction, InstrSize, 1244 PLTData.slice(InstrOffset), InstrAddr, 1245 nulls())) { 1246 errs() << "BOLT-ERROR: unable to disassemble instruction in PLT " 1247 "section " 1248 << Section.getName() << " at offset 0x" 1249 << Twine::utohexstr(InstrOffset) << '\n'; 1250 exit(1); 1251 } 1252 1253 // Check if the entry size needs adjustment. 1254 if (EntryOffset == 0 && BC->MIB->isTerminateBranch(Instruction) && 1255 EntrySize == 8) 1256 EntrySize = 16; 1257 1258 if (BC->MIB->isIndirectBranch(Instruction)) 1259 break; 1260 1261 InstrOffset += InstrSize; 1262 } 1263 1264 if (InstrOffset + InstrSize > EntryOffset + EntrySize) 1265 continue; 1266 1267 uint64_t TargetAddress; 1268 if (!BC->MIB->evaluateMemOperandTarget(Instruction, TargetAddress, 1269 PLTAddress + InstrOffset, 1270 InstrSize)) { 1271 errs() << "BOLT-ERROR: error evaluating PLT instruction at offset 0x" 1272 << Twine::utohexstr(PLTAddress + InstrOffset) << '\n'; 1273 exit(1); 1274 } 1275 1276 const Relocation *Rel = BC->getDynamicRelocationAt(TargetAddress); 1277 if (!Rel || !Rel->Symbol) 1278 continue; 1279 1280 BinaryFunction *BF = BC->createBinaryFunction( 1281 Rel->Symbol->getName().str() + "@PLT", Section, 1282 PLTAddress + EntryOffset, 0, EntrySize, Section.getAlignment()); 1283 MCSymbol *TargetSymbol = 1284 BC->registerNameAtAddress(Rel->Symbol->getName().str() + "@GOT", 1285 TargetAddress, PtrSize, PtrSize); 1286 BF->setPLTSymbol(TargetSymbol); 1287 } 1288 }; 1289 1290 for (BinarySection &Section : BC->allocatableSections()) { 1291 const PLTSectionInfo *PLTSI = getPLTSectionInfo(Section.getName()); 1292 if (!PLTSI) 1293 continue; 1294 1295 analyzeOnePLTSection(Section, PLTSI->EntrySize); 1296 // If we did not register any function at the start of the section, 1297 // then it must be a general PLT entry. Add a function at the location. 1298 if (BC->getBinaryFunctions().find(Section.getAddress()) == 1299 BC->getBinaryFunctions().end()) { 1300 BinaryFunction *BF = BC->createBinaryFunction( 1301 "__BOLT_PSEUDO_" + Section.getName().str(), Section, 1302 Section.getAddress(), 0, PLTSI->EntrySize, Section.getAlignment()); 1303 BF->setPseudo(true); 1304 } 1305 } 1306 } 1307 1308 void RewriteInstance::adjustFunctionBoundaries() { 1309 for (auto BFI = BC->getBinaryFunctions().begin(), 1310 BFE = BC->getBinaryFunctions().end(); 1311 BFI != BFE; ++BFI) { 1312 BinaryFunction &Function = BFI->second; 1313 const BinaryFunction *NextFunction = nullptr; 1314 if (std::next(BFI) != BFE) 1315 NextFunction = &std::next(BFI)->second; 1316 1317 // Check if it's a fragment of a function. 1318 Optional<StringRef> FragName = 1319 Function.hasRestoredNameRegex(".*\\.cold(\\.[0-9]+)?"); 1320 if (FragName) { 1321 static bool PrintedWarning = false; 1322 if (BC->HasRelocations && !PrintedWarning) { 1323 errs() << "BOLT-WARNING: split function detected on input : " 1324 << *FragName << ". The support is limited in relocation mode.\n"; 1325 PrintedWarning = true; 1326 } 1327 Function.IsFragment = true; 1328 } 1329 1330 // Check if there's a symbol or a function with a larger address in the 1331 // same section. If there is - it determines the maximum size for the 1332 // current function. Otherwise, it is the size of a containing section 1333 // the defines it. 1334 // 1335 // NOTE: ignore some symbols that could be tolerated inside the body 1336 // of a function. 1337 auto NextSymRefI = FileSymRefs.upper_bound(Function.getAddress()); 1338 while (NextSymRefI != FileSymRefs.end()) { 1339 SymbolRef &Symbol = NextSymRefI->second; 1340 const uint64_t SymbolAddress = NextSymRefI->first; 1341 const uint64_t SymbolSize = ELFSymbolRef(Symbol).getSize(); 1342 1343 if (NextFunction && SymbolAddress >= NextFunction->getAddress()) 1344 break; 1345 1346 if (!Function.isSymbolValidInScope(Symbol, SymbolSize)) 1347 break; 1348 1349 // This is potentially another entry point into the function. 1350 uint64_t EntryOffset = NextSymRefI->first - Function.getAddress(); 1351 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding entry point to function " 1352 << Function << " at offset 0x" 1353 << Twine::utohexstr(EntryOffset) << '\n'); 1354 Function.addEntryPointAtOffset(EntryOffset); 1355 1356 ++NextSymRefI; 1357 } 1358 1359 // Function runs at most till the end of the containing section. 1360 uint64_t NextObjectAddress = Function.getOriginSection()->getEndAddress(); 1361 // Or till the next object marked by a symbol. 1362 if (NextSymRefI != FileSymRefs.end()) 1363 NextObjectAddress = std::min(NextSymRefI->first, NextObjectAddress); 1364 1365 // Or till the next function not marked by a symbol. 1366 if (NextFunction) 1367 NextObjectAddress = 1368 std::min(NextFunction->getAddress(), NextObjectAddress); 1369 1370 const uint64_t MaxSize = NextObjectAddress - Function.getAddress(); 1371 if (MaxSize < Function.getSize()) { 1372 errs() << "BOLT-ERROR: symbol seen in the middle of the function " 1373 << Function << ". Skipping.\n"; 1374 Function.setSimple(false); 1375 Function.setMaxSize(Function.getSize()); 1376 continue; 1377 } 1378 Function.setMaxSize(MaxSize); 1379 if (!Function.getSize() && Function.isSimple()) { 1380 // Some assembly functions have their size set to 0, use the max 1381 // size as their real size. 1382 if (opts::Verbosity >= 1) 1383 outs() << "BOLT-INFO: setting size of function " << Function << " to " 1384 << Function.getMaxSize() << " (was 0)\n"; 1385 Function.setSize(Function.getMaxSize()); 1386 } 1387 } 1388 } 1389 1390 void RewriteInstance::relocateEHFrameSection() { 1391 assert(EHFrameSection && "non-empty .eh_frame section expected"); 1392 1393 DWARFDataExtractor DE(EHFrameSection->getContents(), 1394 BC->AsmInfo->isLittleEndian(), 1395 BC->AsmInfo->getCodePointerSize()); 1396 auto createReloc = [&](uint64_t Value, uint64_t Offset, uint64_t DwarfType) { 1397 if (DwarfType == dwarf::DW_EH_PE_omit) 1398 return; 1399 1400 // Only fix references that are relative to other locations. 1401 if (!(DwarfType & dwarf::DW_EH_PE_pcrel) && 1402 !(DwarfType & dwarf::DW_EH_PE_textrel) && 1403 !(DwarfType & dwarf::DW_EH_PE_funcrel) && 1404 !(DwarfType & dwarf::DW_EH_PE_datarel)) 1405 return; 1406 1407 if (!(DwarfType & dwarf::DW_EH_PE_sdata4)) 1408 return; 1409 1410 uint64_t RelType; 1411 switch (DwarfType & 0x0f) { 1412 default: 1413 llvm_unreachable("unsupported DWARF encoding type"); 1414 case dwarf::DW_EH_PE_sdata4: 1415 case dwarf::DW_EH_PE_udata4: 1416 RelType = Relocation::getPC32(); 1417 Offset -= 4; 1418 break; 1419 case dwarf::DW_EH_PE_sdata8: 1420 case dwarf::DW_EH_PE_udata8: 1421 RelType = Relocation::getPC64(); 1422 Offset -= 8; 1423 break; 1424 } 1425 1426 // Create a relocation against an absolute value since the goal is to 1427 // preserve the contents of the section independent of the new values 1428 // of referenced symbols. 1429 EHFrameSection->addRelocation(Offset, nullptr, RelType, Value); 1430 }; 1431 1432 Error E = EHFrameParser::parse(DE, EHFrameSection->getAddress(), createReloc); 1433 check_error(std::move(E), "failed to patch EH frame"); 1434 } 1435 1436 ArrayRef<uint8_t> RewriteInstance::getLSDAData() { 1437 return ArrayRef<uint8_t>(LSDASection->getData(), 1438 LSDASection->getContents().size()); 1439 } 1440 1441 uint64_t RewriteInstance::getLSDAAddress() { return LSDASection->getAddress(); } 1442 1443 void RewriteInstance::readSpecialSections() { 1444 NamedRegionTimer T("readSpecialSections", "read special sections", 1445 TimerGroupName, TimerGroupDesc, opts::TimeRewrite); 1446 1447 bool HasTextRelocations = false; 1448 bool HasDebugInfo = false; 1449 1450 // Process special sections. 1451 for (const SectionRef &Section : InputFile->sections()) { 1452 Expected<StringRef> SectionNameOrErr = Section.getName(); 1453 check_error(SectionNameOrErr.takeError(), "cannot get section name"); 1454 StringRef SectionName = *SectionNameOrErr; 1455 1456 // Only register sections with names. 1457 if (!SectionName.empty()) { 1458 BC->registerSection(Section); 1459 LLVM_DEBUG( 1460 dbgs() << "BOLT-DEBUG: registering section " << SectionName << " @ 0x" 1461 << Twine::utohexstr(Section.getAddress()) << ":0x" 1462 << Twine::utohexstr(Section.getAddress() + Section.getSize()) 1463 << "\n"); 1464 if (isDebugSection(SectionName)) 1465 HasDebugInfo = true; 1466 if (isKSymtabSection(SectionName)) 1467 opts::LinuxKernelMode = true; 1468 } 1469 } 1470 1471 if (HasDebugInfo && !opts::UpdateDebugSections && !opts::AggregateOnly) { 1472 errs() << "BOLT-WARNING: debug info will be stripped from the binary. " 1473 "Use -update-debug-sections to keep it.\n"; 1474 } 1475 1476 HasTextRelocations = (bool)BC->getUniqueSectionByName(".rela.text"); 1477 LSDASection = BC->getUniqueSectionByName(".gcc_except_table"); 1478 EHFrameSection = BC->getUniqueSectionByName(".eh_frame"); 1479 GOTPLTSection = BC->getUniqueSectionByName(".got.plt"); 1480 RelaPLTSection = BC->getUniqueSectionByName(".rela.plt"); 1481 RelaDynSection = BC->getUniqueSectionByName(".rela.dyn"); 1482 BuildIDSection = BC->getUniqueSectionByName(".note.gnu.build-id"); 1483 SDTSection = BC->getUniqueSectionByName(".note.stapsdt"); 1484 PseudoProbeDescSection = BC->getUniqueSectionByName(".pseudo_probe_desc"); 1485 PseudoProbeSection = BC->getUniqueSectionByName(".pseudo_probe"); 1486 1487 if (ErrorOr<BinarySection &> BATSec = 1488 BC->getUniqueSectionByName(BoltAddressTranslation::SECTION_NAME)) { 1489 // Do not read BAT when plotting a heatmap 1490 if (!opts::HeatmapMode) { 1491 if (std::error_code EC = BAT->parse(BATSec->getContents())) { 1492 errs() << "BOLT-ERROR: failed to parse BOLT address translation " 1493 "table.\n"; 1494 exit(1); 1495 } 1496 } 1497 } 1498 1499 if (opts::PrintSections) { 1500 outs() << "BOLT-INFO: Sections from original binary:\n"; 1501 BC->printSections(outs()); 1502 } 1503 1504 if (opts::RelocationMode == cl::BOU_TRUE && !HasTextRelocations) { 1505 errs() << "BOLT-ERROR: relocations against code are missing from the input " 1506 "file. Cannot proceed in relocations mode (-relocs).\n"; 1507 exit(1); 1508 } 1509 1510 BC->HasRelocations = 1511 HasTextRelocations && (opts::RelocationMode != cl::BOU_FALSE); 1512 1513 // Force non-relocation mode for heatmap generation 1514 if (opts::HeatmapMode) 1515 BC->HasRelocations = false; 1516 1517 if (BC->HasRelocations) 1518 outs() << "BOLT-INFO: enabling " << (opts::StrictMode ? "strict " : "") 1519 << "relocation mode\n"; 1520 1521 // Read EH frame for function boundaries info. 1522 Expected<const DWARFDebugFrame *> EHFrameOrError = BC->DwCtx->getEHFrame(); 1523 if (!EHFrameOrError) 1524 report_error("expected valid eh_frame section", EHFrameOrError.takeError()); 1525 CFIRdWrt.reset(new CFIReaderWriter(*EHFrameOrError.get())); 1526 1527 // Parse build-id 1528 parseBuildID(); 1529 if (Optional<std::string> FileBuildID = getPrintableBuildID()) 1530 BC->setFileBuildID(*FileBuildID); 1531 1532 parseSDTNotes(); 1533 1534 // Read .dynamic/PT_DYNAMIC. 1535 readELFDynamic(); 1536 } 1537 1538 void RewriteInstance::adjustCommandLineOptions() { 1539 if (BC->isAArch64() && !BC->HasRelocations) 1540 errs() << "BOLT-WARNING: non-relocation mode for AArch64 is not fully " 1541 "supported\n"; 1542 1543 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary()) 1544 RtLibrary->adjustCommandLineOptions(*BC); 1545 1546 if (opts::AlignMacroOpFusion != MFT_NONE && !BC->isX86()) { 1547 outs() << "BOLT-INFO: disabling -align-macro-fusion on non-x86 platform\n"; 1548 opts::AlignMacroOpFusion = MFT_NONE; 1549 } 1550 1551 if (BC->isX86() && BC->MAB->allowAutoPadding()) { 1552 if (!BC->HasRelocations) { 1553 errs() << "BOLT-ERROR: cannot apply mitigations for Intel JCC erratum in " 1554 "non-relocation mode\n"; 1555 exit(1); 1556 } 1557 outs() << "BOLT-WARNING: using mitigation for Intel JCC erratum, layout " 1558 "may take several minutes\n"; 1559 opts::AlignMacroOpFusion = MFT_NONE; 1560 } 1561 1562 if (opts::AlignMacroOpFusion != MFT_NONE && !BC->HasRelocations) { 1563 outs() << "BOLT-INFO: disabling -align-macro-fusion in non-relocation " 1564 "mode\n"; 1565 opts::AlignMacroOpFusion = MFT_NONE; 1566 } 1567 1568 if (opts::SplitEH && !BC->HasRelocations) { 1569 errs() << "BOLT-WARNING: disabling -split-eh in non-relocation mode\n"; 1570 opts::SplitEH = false; 1571 } 1572 1573 if (opts::SplitEH && !BC->HasFixedLoadAddress) { 1574 errs() << "BOLT-WARNING: disabling -split-eh for shared object\n"; 1575 opts::SplitEH = false; 1576 } 1577 1578 if (opts::StrictMode && !BC->HasRelocations) { 1579 errs() << "BOLT-WARNING: disabling strict mode (-strict) in non-relocation " 1580 "mode\n"; 1581 opts::StrictMode = false; 1582 } 1583 1584 if (BC->HasRelocations && opts::AggregateOnly && 1585 !opts::StrictMode.getNumOccurrences()) { 1586 outs() << "BOLT-INFO: enabling strict relocation mode for aggregation " 1587 "purposes\n"; 1588 opts::StrictMode = true; 1589 } 1590 1591 if (BC->isX86() && BC->HasRelocations && 1592 opts::AlignMacroOpFusion == MFT_HOT && !ProfileReader) { 1593 outs() << "BOLT-INFO: enabling -align-macro-fusion=all since no profile " 1594 "was specified\n"; 1595 opts::AlignMacroOpFusion = MFT_ALL; 1596 } 1597 1598 if (!BC->HasRelocations && 1599 opts::ReorderFunctions != ReorderFunctions::RT_NONE) { 1600 errs() << "BOLT-ERROR: function reordering only works when " 1601 << "relocations are enabled\n"; 1602 exit(1); 1603 } 1604 1605 if (opts::ReorderFunctions != ReorderFunctions::RT_NONE && 1606 !opts::HotText.getNumOccurrences()) { 1607 opts::HotText = true; 1608 } else if (opts::HotText && !BC->HasRelocations) { 1609 errs() << "BOLT-WARNING: hot text is disabled in non-relocation mode\n"; 1610 opts::HotText = false; 1611 } 1612 1613 if (opts::HotText && opts::HotTextMoveSections.getNumOccurrences() == 0) { 1614 opts::HotTextMoveSections.addValue(".stub"); 1615 opts::HotTextMoveSections.addValue(".mover"); 1616 opts::HotTextMoveSections.addValue(".never_hugify"); 1617 } 1618 1619 if (opts::UseOldText && !BC->OldTextSectionAddress) { 1620 errs() << "BOLT-WARNING: cannot use old .text as the section was not found" 1621 "\n"; 1622 opts::UseOldText = false; 1623 } 1624 if (opts::UseOldText && !BC->HasRelocations) { 1625 errs() << "BOLT-WARNING: cannot use old .text in non-relocation mode\n"; 1626 opts::UseOldText = false; 1627 } 1628 1629 if (!opts::AlignText.getNumOccurrences()) 1630 opts::AlignText = BC->PageAlign; 1631 1632 if (BC->isX86() && opts::Lite.getNumOccurrences() == 0 && !opts::StrictMode && 1633 !opts::UseOldText) 1634 opts::Lite = true; 1635 1636 if (opts::Lite && opts::UseOldText) { 1637 errs() << "BOLT-WARNING: cannot combine -lite with -use-old-text. " 1638 "Disabling -use-old-text.\n"; 1639 opts::UseOldText = false; 1640 } 1641 1642 if (opts::Lite && opts::StrictMode) { 1643 errs() << "BOLT-ERROR: -strict and -lite cannot be used at the same time\n"; 1644 exit(1); 1645 } 1646 1647 if (opts::Lite) 1648 outs() << "BOLT-INFO: enabling lite mode\n"; 1649 1650 if (!opts::SaveProfile.empty() && BAT->enabledFor(InputFile)) { 1651 errs() << "BOLT-ERROR: unable to save profile in YAML format for input " 1652 "file processed by BOLT. Please remove -w option and use branch " 1653 "profile.\n"; 1654 exit(1); 1655 } 1656 } 1657 1658 namespace { 1659 template <typename ELFT> 1660 int64_t getRelocationAddend(const ELFObjectFile<ELFT> *Obj, 1661 const RelocationRef &RelRef) { 1662 using ELFShdrTy = typename ELFT::Shdr; 1663 using Elf_Rela = typename ELFT::Rela; 1664 int64_t Addend = 0; 1665 const ELFFile<ELFT> &EF = Obj->getELFFile(); 1666 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 1667 const ELFShdrTy *RelocationSection = cantFail(EF.getSection(Rel.d.a)); 1668 switch (RelocationSection->sh_type) { 1669 default: 1670 llvm_unreachable("unexpected relocation section type"); 1671 case ELF::SHT_REL: 1672 break; 1673 case ELF::SHT_RELA: { 1674 const Elf_Rela *RelA = Obj->getRela(Rel); 1675 Addend = RelA->r_addend; 1676 break; 1677 } 1678 } 1679 1680 return Addend; 1681 } 1682 1683 int64_t getRelocationAddend(const ELFObjectFileBase *Obj, 1684 const RelocationRef &Rel) { 1685 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj)) 1686 return getRelocationAddend(ELF32LE, Rel); 1687 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj)) 1688 return getRelocationAddend(ELF64LE, Rel); 1689 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj)) 1690 return getRelocationAddend(ELF32BE, Rel); 1691 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj); 1692 return getRelocationAddend(ELF64BE, Rel); 1693 } 1694 } // anonymous namespace 1695 1696 bool RewriteInstance::analyzeRelocation( 1697 const RelocationRef &Rel, uint64_t RType, std::string &SymbolName, 1698 bool &IsSectionRelocation, uint64_t &SymbolAddress, int64_t &Addend, 1699 uint64_t &ExtractedValue, bool &Skip) const { 1700 Skip = false; 1701 if (!Relocation::isSupported(RType)) 1702 return false; 1703 1704 const bool IsAArch64 = BC->isAArch64(); 1705 1706 const size_t RelSize = Relocation::getSizeForType(RType); 1707 1708 ErrorOr<uint64_t> Value = 1709 BC->getUnsignedValueAtAddress(Rel.getOffset(), RelSize); 1710 assert(Value && "failed to extract relocated value"); 1711 if ((Skip = Relocation::skipRelocationProcess(RType, *Value))) 1712 return true; 1713 1714 ExtractedValue = Relocation::extractValue(RType, *Value, Rel.getOffset()); 1715 Addend = getRelocationAddend(InputFile, Rel); 1716 1717 const bool IsPCRelative = Relocation::isPCRelative(RType); 1718 const uint64_t PCRelOffset = IsPCRelative && !IsAArch64 ? Rel.getOffset() : 0; 1719 bool SkipVerification = false; 1720 auto SymbolIter = Rel.getSymbol(); 1721 if (SymbolIter == InputFile->symbol_end()) { 1722 SymbolAddress = ExtractedValue - Addend + PCRelOffset; 1723 MCSymbol *RelSymbol = 1724 BC->getOrCreateGlobalSymbol(SymbolAddress, "RELSYMat"); 1725 SymbolName = std::string(RelSymbol->getName()); 1726 IsSectionRelocation = false; 1727 } else { 1728 const SymbolRef &Symbol = *SymbolIter; 1729 SymbolName = std::string(cantFail(Symbol.getName())); 1730 SymbolAddress = cantFail(Symbol.getAddress()); 1731 SkipVerification = (cantFail(Symbol.getType()) == SymbolRef::ST_Other); 1732 // Section symbols are marked as ST_Debug. 1733 IsSectionRelocation = (cantFail(Symbol.getType()) == SymbolRef::ST_Debug); 1734 } 1735 // For PIE or dynamic libs, the linker may choose not to put the relocation 1736 // result at the address if it is a X86_64_64 one because it will emit a 1737 // dynamic relocation (X86_RELATIVE) for the dynamic linker and loader to 1738 // resolve it at run time. The static relocation result goes as the addend 1739 // of the dynamic relocation in this case. We can't verify these cases. 1740 // FIXME: perhaps we can try to find if it really emitted a corresponding 1741 // RELATIVE relocation at this offset with the correct value as the addend. 1742 if (!BC->HasFixedLoadAddress && RelSize == 8) 1743 SkipVerification = true; 1744 1745 if (IsSectionRelocation && !IsAArch64) { 1746 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(SymbolAddress); 1747 assert(Section && "section expected for section relocation"); 1748 SymbolName = "section " + std::string(Section->getName()); 1749 // Convert section symbol relocations to regular relocations inside 1750 // non-section symbols. 1751 if (Section->containsAddress(ExtractedValue) && !IsPCRelative) { 1752 SymbolAddress = ExtractedValue; 1753 Addend = 0; 1754 } else { 1755 Addend = ExtractedValue - (SymbolAddress - PCRelOffset); 1756 } 1757 } 1758 1759 // If no symbol has been found or if it is a relocation requiring the 1760 // creation of a GOT entry, do not link against the symbol but against 1761 // whatever address was extracted from the instruction itself. We are 1762 // not creating a GOT entry as this was already processed by the linker. 1763 // For GOT relocs, do not subtract addend as the addend does not refer 1764 // to this instruction's target, but it refers to the target in the GOT 1765 // entry. 1766 if (Relocation::isGOT(RType)) { 1767 Addend = 0; 1768 SymbolAddress = ExtractedValue + PCRelOffset; 1769 } else if (Relocation::isTLS(RType)) { 1770 SkipVerification = true; 1771 } else if (!SymbolAddress) { 1772 assert(!IsSectionRelocation); 1773 if (ExtractedValue || Addend == 0 || IsPCRelative) { 1774 SymbolAddress = 1775 truncateToSize(ExtractedValue - Addend + PCRelOffset, RelSize); 1776 } else { 1777 // This is weird case. The extracted value is zero but the addend is 1778 // non-zero and the relocation is not pc-rel. Using the previous logic, 1779 // the SymbolAddress would end up as a huge number. Seen in 1780 // exceptions_pic.test. 1781 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: relocation @ 0x" 1782 << Twine::utohexstr(Rel.getOffset()) 1783 << " value does not match addend for " 1784 << "relocation to undefined symbol.\n"); 1785 return true; 1786 } 1787 } 1788 1789 auto verifyExtractedValue = [&]() { 1790 if (SkipVerification) 1791 return true; 1792 1793 if (IsAArch64) 1794 return true; 1795 1796 if (SymbolName == "__hot_start" || SymbolName == "__hot_end") 1797 return true; 1798 1799 if (RType == ELF::R_X86_64_PLT32) 1800 return true; 1801 1802 return truncateToSize(ExtractedValue, RelSize) == 1803 truncateToSize(SymbolAddress + Addend - PCRelOffset, RelSize); 1804 }; 1805 1806 (void)verifyExtractedValue; 1807 assert(verifyExtractedValue() && "mismatched extracted relocation value"); 1808 1809 return true; 1810 } 1811 1812 void RewriteInstance::processDynamicRelocations() { 1813 // Read relocations for PLT - DT_JMPREL. 1814 if (PLTRelocationsSize > 0) { 1815 ErrorOr<BinarySection &> PLTRelSectionOrErr = 1816 BC->getSectionForAddress(*PLTRelocationsAddress); 1817 if (!PLTRelSectionOrErr) 1818 report_error("unable to find section corresponding to DT_JMPREL", 1819 PLTRelSectionOrErr.getError()); 1820 if (PLTRelSectionOrErr->getSize() != PLTRelocationsSize) 1821 report_error("section size mismatch for DT_PLTRELSZ", 1822 errc::executable_format_error); 1823 readDynamicRelocations(PLTRelSectionOrErr->getSectionRef()); 1824 } 1825 1826 // The rest of dynamic relocations - DT_RELA. 1827 if (DynamicRelocationsSize > 0) { 1828 ErrorOr<BinarySection &> DynamicRelSectionOrErr = 1829 BC->getSectionForAddress(*DynamicRelocationsAddress); 1830 if (!DynamicRelSectionOrErr) 1831 report_error("unable to find section corresponding to DT_RELA", 1832 DynamicRelSectionOrErr.getError()); 1833 if (DynamicRelSectionOrErr->getSize() != DynamicRelocationsSize) 1834 report_error("section size mismatch for DT_RELASZ", 1835 errc::executable_format_error); 1836 readDynamicRelocations(DynamicRelSectionOrErr->getSectionRef()); 1837 } 1838 } 1839 1840 void RewriteInstance::processRelocations() { 1841 if (!BC->HasRelocations) 1842 return; 1843 1844 for (const SectionRef &Section : InputFile->sections()) { 1845 if (cantFail(Section.getRelocatedSection()) != InputFile->section_end() && 1846 !BinarySection(*BC, Section).isAllocatable()) 1847 readRelocations(Section); 1848 } 1849 1850 if (NumFailedRelocations) 1851 errs() << "BOLT-WARNING: Failed to analyze " << NumFailedRelocations 1852 << " relocations\n"; 1853 } 1854 1855 void RewriteInstance::insertLKMarker(uint64_t PC, uint64_t SectionOffset, 1856 int32_t PCRelativeOffset, 1857 bool IsPCRelative, StringRef SectionName) { 1858 BC->LKMarkers[PC].emplace_back(LKInstructionMarkerInfo{ 1859 SectionOffset, PCRelativeOffset, IsPCRelative, SectionName}); 1860 } 1861 1862 void RewriteInstance::processLKSections() { 1863 assert(opts::LinuxKernelMode && 1864 "process Linux Kernel special sections and their relocations only in " 1865 "linux kernel mode.\n"); 1866 1867 processLKExTable(); 1868 processLKPCIFixup(); 1869 processLKKSymtab(); 1870 processLKKSymtab(true); 1871 processLKBugTable(); 1872 processLKSMPLocks(); 1873 } 1874 1875 /// Process __ex_table section of Linux Kernel. 1876 /// This section contains information regarding kernel level exception 1877 /// handling (https://www.kernel.org/doc/html/latest/x86/exception-tables.html). 1878 /// More documentation is in arch/x86/include/asm/extable.h. 1879 /// 1880 /// The section is the list of the following structures: 1881 /// 1882 /// struct exception_table_entry { 1883 /// int insn; 1884 /// int fixup; 1885 /// int handler; 1886 /// }; 1887 /// 1888 void RewriteInstance::processLKExTable() { 1889 ErrorOr<BinarySection &> SectionOrError = 1890 BC->getUniqueSectionByName("__ex_table"); 1891 if (!SectionOrError) 1892 return; 1893 1894 const uint64_t SectionSize = SectionOrError->getSize(); 1895 const uint64_t SectionAddress = SectionOrError->getAddress(); 1896 assert((SectionSize % 12) == 0 && 1897 "The size of the __ex_table section should be a multiple of 12"); 1898 for (uint64_t I = 0; I < SectionSize; I += 4) { 1899 const uint64_t EntryAddress = SectionAddress + I; 1900 ErrorOr<uint64_t> Offset = BC->getSignedValueAtAddress(EntryAddress, 4); 1901 assert(Offset && "failed reading PC-relative offset for __ex_table"); 1902 int32_t SignedOffset = *Offset; 1903 const uint64_t RefAddress = EntryAddress + SignedOffset; 1904 1905 BinaryFunction *ContainingBF = 1906 BC->getBinaryFunctionContainingAddress(RefAddress); 1907 if (!ContainingBF) 1908 continue; 1909 1910 MCSymbol *ReferencedSymbol = ContainingBF->getSymbol(); 1911 const uint64_t FunctionOffset = RefAddress - ContainingBF->getAddress(); 1912 switch (I % 12) { 1913 default: 1914 llvm_unreachable("bad alignment of __ex_table"); 1915 break; 1916 case 0: 1917 // insn 1918 insertLKMarker(RefAddress, I, SignedOffset, true, "__ex_table"); 1919 break; 1920 case 4: 1921 // fixup 1922 if (FunctionOffset) 1923 ReferencedSymbol = ContainingBF->addEntryPointAtOffset(FunctionOffset); 1924 BC->addRelocation(EntryAddress, ReferencedSymbol, Relocation::getPC32(), 1925 0, *Offset); 1926 break; 1927 case 8: 1928 // handler 1929 assert(!FunctionOffset && 1930 "__ex_table handler entry should point to function start"); 1931 BC->addRelocation(EntryAddress, ReferencedSymbol, Relocation::getPC32(), 1932 0, *Offset); 1933 break; 1934 } 1935 } 1936 } 1937 1938 /// Process .pci_fixup section of Linux Kernel. 1939 /// This section contains a list of entries for different PCI devices and their 1940 /// corresponding hook handler (code pointer where the fixup 1941 /// code resides, usually on x86_64 it is an entry PC relative 32 bit offset). 1942 /// Documentation is in include/linux/pci.h. 1943 void RewriteInstance::processLKPCIFixup() { 1944 ErrorOr<BinarySection &> SectionOrError = 1945 BC->getUniqueSectionByName(".pci_fixup"); 1946 assert(SectionOrError && 1947 ".pci_fixup section not found in Linux Kernel binary"); 1948 const uint64_t SectionSize = SectionOrError->getSize(); 1949 const uint64_t SectionAddress = SectionOrError->getAddress(); 1950 assert((SectionSize % 16) == 0 && ".pci_fixup size is not a multiple of 16"); 1951 1952 for (uint64_t I = 12; I + 4 <= SectionSize; I += 16) { 1953 const uint64_t PC = SectionAddress + I; 1954 ErrorOr<uint64_t> Offset = BC->getSignedValueAtAddress(PC, 4); 1955 assert(Offset && "cannot read value from .pci_fixup"); 1956 const int32_t SignedOffset = *Offset; 1957 const uint64_t HookupAddress = PC + SignedOffset; 1958 BinaryFunction *HookupFunction = 1959 BC->getBinaryFunctionAtAddress(HookupAddress); 1960 assert(HookupFunction && "expected function for entry in .pci_fixup"); 1961 BC->addRelocation(PC, HookupFunction->getSymbol(), Relocation::getPC32(), 0, 1962 *Offset); 1963 } 1964 } 1965 1966 /// Process __ksymtab[_gpl] sections of Linux Kernel. 1967 /// This section lists all the vmlinux symbols that kernel modules can access. 1968 /// 1969 /// All the entries are 4 bytes each and hence we can read them by one by one 1970 /// and ignore the ones that are not pointing to the .text section. All pointers 1971 /// are PC relative offsets. Always, points to the beginning of the function. 1972 void RewriteInstance::processLKKSymtab(bool IsGPL) { 1973 StringRef SectionName = "__ksymtab"; 1974 if (IsGPL) 1975 SectionName = "__ksymtab_gpl"; 1976 ErrorOr<BinarySection &> SectionOrError = 1977 BC->getUniqueSectionByName(SectionName); 1978 assert(SectionOrError && 1979 "__ksymtab[_gpl] section not found in Linux Kernel binary"); 1980 const uint64_t SectionSize = SectionOrError->getSize(); 1981 const uint64_t SectionAddress = SectionOrError->getAddress(); 1982 assert((SectionSize % 4) == 0 && 1983 "The size of the __ksymtab[_gpl] section should be a multiple of 4"); 1984 1985 for (uint64_t I = 0; I < SectionSize; I += 4) { 1986 const uint64_t EntryAddress = SectionAddress + I; 1987 ErrorOr<uint64_t> Offset = BC->getSignedValueAtAddress(EntryAddress, 4); 1988 assert(Offset && "Reading valid PC-relative offset for a ksymtab entry"); 1989 const int32_t SignedOffset = *Offset; 1990 const uint64_t RefAddress = EntryAddress + SignedOffset; 1991 BinaryFunction *BF = BC->getBinaryFunctionAtAddress(RefAddress); 1992 if (!BF) 1993 continue; 1994 1995 BC->addRelocation(EntryAddress, BF->getSymbol(), Relocation::getPC32(), 0, 1996 *Offset); 1997 } 1998 } 1999 2000 /// Process __bug_table section. 2001 /// This section contains information useful for kernel debugging. 2002 /// Each entry in the section is a struct bug_entry that contains a pointer to 2003 /// the ud2 instruction corresponding to the bug, corresponding file name (both 2004 /// pointers use PC relative offset addressing), line number, and flags. 2005 /// The definition of the struct bug_entry can be found in 2006 /// `include/asm-generic/bug.h` 2007 void RewriteInstance::processLKBugTable() { 2008 ErrorOr<BinarySection &> SectionOrError = 2009 BC->getUniqueSectionByName("__bug_table"); 2010 if (!SectionOrError) 2011 return; 2012 2013 const uint64_t SectionSize = SectionOrError->getSize(); 2014 const uint64_t SectionAddress = SectionOrError->getAddress(); 2015 assert((SectionSize % 12) == 0 && 2016 "The size of the __bug_table section should be a multiple of 12"); 2017 for (uint64_t I = 0; I < SectionSize; I += 12) { 2018 const uint64_t EntryAddress = SectionAddress + I; 2019 ErrorOr<uint64_t> Offset = BC->getSignedValueAtAddress(EntryAddress, 4); 2020 assert(Offset && 2021 "Reading valid PC-relative offset for a __bug_table entry"); 2022 const int32_t SignedOffset = *Offset; 2023 const uint64_t RefAddress = EntryAddress + SignedOffset; 2024 assert(BC->getBinaryFunctionContainingAddress(RefAddress) && 2025 "__bug_table entries should point to a function"); 2026 2027 insertLKMarker(RefAddress, I, SignedOffset, true, "__bug_table"); 2028 } 2029 } 2030 2031 /// .smp_locks section contains PC-relative references to instructions with LOCK 2032 /// prefix. The prefix can be converted to NOP at boot time on non-SMP systems. 2033 void RewriteInstance::processLKSMPLocks() { 2034 ErrorOr<BinarySection &> SectionOrError = 2035 BC->getUniqueSectionByName(".smp_locks"); 2036 if (!SectionOrError) 2037 return; 2038 2039 uint64_t SectionSize = SectionOrError->getSize(); 2040 const uint64_t SectionAddress = SectionOrError->getAddress(); 2041 assert((SectionSize % 4) == 0 && 2042 "The size of the .smp_locks section should be a multiple of 4"); 2043 2044 for (uint64_t I = 0; I < SectionSize; I += 4) { 2045 const uint64_t EntryAddress = SectionAddress + I; 2046 ErrorOr<uint64_t> Offset = BC->getSignedValueAtAddress(EntryAddress, 4); 2047 assert(Offset && "Reading valid PC-relative offset for a .smp_locks entry"); 2048 int32_t SignedOffset = *Offset; 2049 uint64_t RefAddress = EntryAddress + SignedOffset; 2050 2051 BinaryFunction *ContainingBF = 2052 BC->getBinaryFunctionContainingAddress(RefAddress); 2053 if (!ContainingBF) 2054 continue; 2055 2056 insertLKMarker(RefAddress, I, SignedOffset, true, ".smp_locks"); 2057 } 2058 } 2059 2060 void RewriteInstance::readDynamicRelocations(const SectionRef &Section) { 2061 assert(BinarySection(*BC, Section).isAllocatable() && "allocatable expected"); 2062 2063 LLVM_DEBUG({ 2064 StringRef SectionName = cantFail(Section.getName()); 2065 dbgs() << "BOLT-DEBUG: reading relocations for section " << SectionName 2066 << ":\n"; 2067 }); 2068 2069 for (const RelocationRef &Rel : Section.relocations()) { 2070 uint64_t RType = Rel.getType(); 2071 if (Relocation::isNone(RType)) 2072 continue; 2073 2074 StringRef SymbolName = "<none>"; 2075 MCSymbol *Symbol = nullptr; 2076 uint64_t SymbolAddress = 0; 2077 const uint64_t Addend = getRelocationAddend(InputFile, Rel); 2078 2079 symbol_iterator SymbolIter = Rel.getSymbol(); 2080 if (SymbolIter != InputFile->symbol_end()) { 2081 SymbolName = cantFail(SymbolIter->getName()); 2082 BinaryData *BD = BC->getBinaryDataByName(SymbolName); 2083 Symbol = BD ? BD->getSymbol() 2084 : BC->getOrCreateUndefinedGlobalSymbol(SymbolName); 2085 SymbolAddress = cantFail(SymbolIter->getAddress()); 2086 (void)SymbolAddress; 2087 } 2088 2089 LLVM_DEBUG( 2090 SmallString<16> TypeName; 2091 Rel.getTypeName(TypeName); 2092 dbgs() << "BOLT-DEBUG: dynamic relocation at 0x" 2093 << Twine::utohexstr(Rel.getOffset()) << " : " << TypeName 2094 << " : " << SymbolName << " : " << Twine::utohexstr(SymbolAddress) 2095 << " : + 0x" << Twine::utohexstr(Addend) << '\n' 2096 ); 2097 2098 BC->addDynamicRelocation(Rel.getOffset(), Symbol, Rel.getType(), Addend); 2099 } 2100 } 2101 2102 void RewriteInstance::readRelocations(const SectionRef &Section) { 2103 LLVM_DEBUG({ 2104 StringRef SectionName = cantFail(Section.getName()); 2105 dbgs() << "BOLT-DEBUG: reading relocations for section " << SectionName 2106 << ":\n"; 2107 }); 2108 if (BinarySection(*BC, Section).isAllocatable()) { 2109 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring runtime relocations\n"); 2110 return; 2111 } 2112 section_iterator SecIter = cantFail(Section.getRelocatedSection()); 2113 assert(SecIter != InputFile->section_end() && "relocated section expected"); 2114 SectionRef RelocatedSection = *SecIter; 2115 2116 StringRef RelocatedSectionName = cantFail(RelocatedSection.getName()); 2117 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: relocated section is " 2118 << RelocatedSectionName << '\n'); 2119 2120 if (!BinarySection(*BC, RelocatedSection).isAllocatable()) { 2121 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring relocations against " 2122 << "non-allocatable section\n"); 2123 return; 2124 } 2125 const bool SkipRelocs = StringSwitch<bool>(RelocatedSectionName) 2126 .Cases(".plt", ".rela.plt", ".got.plt", 2127 ".eh_frame", ".gcc_except_table", true) 2128 .Default(false); 2129 if (SkipRelocs) { 2130 LLVM_DEBUG( 2131 dbgs() << "BOLT-DEBUG: ignoring relocations against known section\n"); 2132 return; 2133 } 2134 2135 const bool IsAArch64 = BC->isAArch64(); 2136 const bool IsFromCode = RelocatedSection.isText(); 2137 2138 auto printRelocationInfo = [&](const RelocationRef &Rel, 2139 StringRef SymbolName, 2140 uint64_t SymbolAddress, 2141 uint64_t Addend, 2142 uint64_t ExtractedValue) { 2143 SmallString<16> TypeName; 2144 Rel.getTypeName(TypeName); 2145 const uint64_t Address = SymbolAddress + Addend; 2146 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(SymbolAddress); 2147 dbgs() << "Relocation: offset = 0x" 2148 << Twine::utohexstr(Rel.getOffset()) 2149 << "; type = " << TypeName 2150 << "; value = 0x" << Twine::utohexstr(ExtractedValue) 2151 << "; symbol = " << SymbolName 2152 << " (" << (Section ? Section->getName() : "") << ")" 2153 << "; symbol address = 0x" << Twine::utohexstr(SymbolAddress) 2154 << "; addend = 0x" << Twine::utohexstr(Addend) 2155 << "; address = 0x" << Twine::utohexstr(Address) 2156 << "; in = "; 2157 if (BinaryFunction *Func = BC->getBinaryFunctionContainingAddress( 2158 Rel.getOffset(), false, IsAArch64)) 2159 dbgs() << Func->getPrintName() << "\n"; 2160 else 2161 dbgs() << BC->getSectionForAddress(Rel.getOffset())->getName() << "\n"; 2162 }; 2163 2164 for (const RelocationRef &Rel : Section.relocations()) { 2165 SmallString<16> TypeName; 2166 Rel.getTypeName(TypeName); 2167 uint64_t RType = Rel.getType(); 2168 if (Relocation::isNone(RType)) 2169 continue; 2170 2171 // Adjust the relocation type as the linker might have skewed it. 2172 if (BC->isX86() && (RType & ELF::R_X86_64_converted_reloc_bit)) { 2173 if (opts::Verbosity >= 1) 2174 dbgs() << "BOLT-WARNING: ignoring R_X86_64_converted_reloc_bit\n"; 2175 RType &= ~ELF::R_X86_64_converted_reloc_bit; 2176 } 2177 2178 if (Relocation::isTLS(RType)) { 2179 // No special handling required for TLS relocations on X86. 2180 if (BC->isX86()) 2181 continue; 2182 2183 // The non-got related TLS relocations on AArch64 also could be skipped. 2184 if (!Relocation::isGOT(RType)) 2185 continue; 2186 } 2187 2188 if (BC->getDynamicRelocationAt(Rel.getOffset())) { 2189 LLVM_DEBUG( 2190 dbgs() << "BOLT-DEBUG: address 0x" 2191 << Twine::utohexstr(Rel.getOffset()) 2192 << " has a dynamic relocation against it. Ignoring static " 2193 "relocation.\n"); 2194 continue; 2195 } 2196 2197 std::string SymbolName; 2198 uint64_t SymbolAddress; 2199 int64_t Addend; 2200 uint64_t ExtractedValue; 2201 bool IsSectionRelocation; 2202 bool Skip; 2203 if (!analyzeRelocation(Rel, RType, SymbolName, IsSectionRelocation, 2204 SymbolAddress, Addend, ExtractedValue, Skip)) { 2205 LLVM_DEBUG(dbgs() << "BOLT-WARNING: failed to analyze relocation @ " 2206 << "offset = 0x" << Twine::utohexstr(Rel.getOffset()) 2207 << "; type name = " << TypeName << '\n'); 2208 ++NumFailedRelocations; 2209 continue; 2210 } 2211 2212 if (Skip) { 2213 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: skipping relocation @ offset = 0x" 2214 << Twine::utohexstr(Rel.getOffset()) 2215 << "; type name = " << TypeName << '\n'); 2216 continue; 2217 } 2218 2219 const uint64_t Address = SymbolAddress + Addend; 2220 2221 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: "; printRelocationInfo( 2222 Rel, SymbolName, SymbolAddress, Addend, ExtractedValue)); 2223 2224 BinaryFunction *ContainingBF = nullptr; 2225 if (IsFromCode) { 2226 ContainingBF = 2227 BC->getBinaryFunctionContainingAddress(Rel.getOffset(), 2228 /*CheckPastEnd*/ false, 2229 /*UseMaxSize*/ true); 2230 assert(ContainingBF && "cannot find function for address in code"); 2231 if (!IsAArch64 && !ContainingBF->containsAddress(Rel.getOffset())) { 2232 if (opts::Verbosity >= 1) 2233 outs() << "BOLT-INFO: " << *ContainingBF 2234 << " has relocations in padding area\n"; 2235 ContainingBF->setSize(ContainingBF->getMaxSize()); 2236 ContainingBF->setSimple(false); 2237 continue; 2238 } 2239 } 2240 2241 // PC-relative relocations from data to code are tricky since the original 2242 // information is typically lost after linking even with '--emit-relocs'. 2243 // They are normally used by PIC-style jump tables and reference both 2244 // the jump table and jump destination by computing the difference 2245 // between the two. If we blindly apply the relocation it will appear 2246 // that it references an arbitrary location in the code, possibly even 2247 // in a different function from that containing the jump table. 2248 if (!IsAArch64 && Relocation::isPCRelative(RType)) { 2249 // Just register the fact that we have PC-relative relocation at a given 2250 // address. The actual referenced label/address cannot be determined 2251 // from linker data alone. 2252 if (!IsFromCode) 2253 BC->addPCRelativeDataRelocation(Rel.getOffset()); 2254 2255 LLVM_DEBUG( 2256 dbgs() << "BOLT-DEBUG: not creating PC-relative relocation at 0x" 2257 << Twine::utohexstr(Rel.getOffset()) << " for " << SymbolName 2258 << "\n"); 2259 continue; 2260 } 2261 2262 bool ForceRelocation = BC->forceSymbolRelocations(SymbolName); 2263 ErrorOr<BinarySection &> RefSection = 2264 std::make_error_code(std::errc::bad_address); 2265 if (BC->isAArch64() && Relocation::isGOT(RType)) { 2266 ForceRelocation = true; 2267 } else { 2268 RefSection = BC->getSectionForAddress(SymbolAddress); 2269 if (!RefSection && !ForceRelocation) { 2270 LLVM_DEBUG( 2271 dbgs() << "BOLT-DEBUG: cannot determine referenced section.\n"); 2272 continue; 2273 } 2274 } 2275 2276 const bool IsToCode = RefSection && RefSection->isText(); 2277 2278 // Occasionally we may see a reference past the last byte of the function 2279 // typically as a result of __builtin_unreachable(). Check it here. 2280 BinaryFunction *ReferencedBF = BC->getBinaryFunctionContainingAddress( 2281 Address, /*CheckPastEnd*/ true, /*UseMaxSize*/ IsAArch64); 2282 2283 if (!IsSectionRelocation) { 2284 if (BinaryFunction *BF = 2285 BC->getBinaryFunctionContainingAddress(SymbolAddress)) { 2286 if (BF != ReferencedBF) { 2287 // It's possible we are referencing a function without referencing any 2288 // code, e.g. when taking a bitmask action on a function address. 2289 errs() << "BOLT-WARNING: non-standard function reference (e.g. " 2290 "bitmask) detected against function " 2291 << *BF; 2292 if (IsFromCode) 2293 errs() << " from function " << *ContainingBF << '\n'; 2294 else 2295 errs() << " from data section at 0x" 2296 << Twine::utohexstr(Rel.getOffset()) << '\n'; 2297 LLVM_DEBUG(printRelocationInfo(Rel, SymbolName, SymbolAddress, Addend, 2298 ExtractedValue)); 2299 ReferencedBF = BF; 2300 } 2301 } 2302 } else if (ReferencedBF) { 2303 assert(RefSection && "section expected for section relocation"); 2304 if (*ReferencedBF->getOriginSection() != *RefSection) { 2305 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring false function reference\n"); 2306 ReferencedBF = nullptr; 2307 } 2308 } 2309 2310 // Workaround for a member function pointer de-virtualization bug. We check 2311 // if a non-pc-relative relocation in the code is pointing to (fptr - 1). 2312 if (IsToCode && ContainingBF && !Relocation::isPCRelative(RType) && 2313 (!ReferencedBF || (ReferencedBF->getAddress() != Address))) { 2314 if (const BinaryFunction *RogueBF = 2315 BC->getBinaryFunctionAtAddress(Address + 1)) { 2316 // Do an extra check that the function was referenced previously. 2317 // It's a linear search, but it should rarely happen. 2318 bool Found = false; 2319 for (const auto &RelKV : ContainingBF->Relocations) { 2320 const Relocation &Rel = RelKV.second; 2321 if (Rel.Symbol == RogueBF->getSymbol() && 2322 !Relocation::isPCRelative(Rel.Type)) { 2323 Found = true; 2324 break; 2325 } 2326 } 2327 2328 if (Found) { 2329 errs() << "BOLT-WARNING: detected possible compiler " 2330 "de-virtualization bug: -1 addend used with " 2331 "non-pc-relative relocation against function " 2332 << *RogueBF << " in function " << *ContainingBF << '\n'; 2333 continue; 2334 } 2335 } 2336 } 2337 2338 MCSymbol *ReferencedSymbol = nullptr; 2339 if (ForceRelocation) { 2340 std::string Name = Relocation::isGOT(RType) ? "Zero" : SymbolName; 2341 ReferencedSymbol = BC->registerNameAtAddress(Name, 0, 0, 0); 2342 SymbolAddress = 0; 2343 if (Relocation::isGOT(RType)) 2344 Addend = Address; 2345 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: forcing relocation against symbol " 2346 << SymbolName << " with addend " << Addend << '\n'); 2347 } else if (ReferencedBF) { 2348 ReferencedSymbol = ReferencedBF->getSymbol(); 2349 uint64_t RefFunctionOffset = 0; 2350 2351 // Adjust the point of reference to a code location inside a function. 2352 if (ReferencedBF->containsAddress(Address, /*UseMaxSize = */true)) { 2353 RefFunctionOffset = Address - ReferencedBF->getAddress(); 2354 if (RefFunctionOffset) { 2355 if (ContainingBF && ContainingBF != ReferencedBF) { 2356 ReferencedSymbol = 2357 ReferencedBF->addEntryPointAtOffset(RefFunctionOffset); 2358 } else { 2359 ReferencedSymbol = 2360 ReferencedBF->getOrCreateLocalLabel(Address, 2361 /*CreatePastEnd =*/true); 2362 ReferencedBF->registerReferencedOffset(RefFunctionOffset); 2363 } 2364 if (opts::Verbosity > 1 && 2365 !BinarySection(*BC, RelocatedSection).isReadOnly()) 2366 errs() << "BOLT-WARNING: writable reference into the middle of " 2367 << "the function " << *ReferencedBF 2368 << " detected at address 0x" 2369 << Twine::utohexstr(Rel.getOffset()) << '\n'; 2370 } 2371 SymbolAddress = Address; 2372 Addend = 0; 2373 } 2374 LLVM_DEBUG( 2375 dbgs() << " referenced function " << *ReferencedBF; 2376 if (Address != ReferencedBF->getAddress()) 2377 dbgs() << " at offset 0x" << Twine::utohexstr(RefFunctionOffset); 2378 dbgs() << '\n' 2379 ); 2380 } else { 2381 if (IsToCode && SymbolAddress) { 2382 // This can happen e.g. with PIC-style jump tables. 2383 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: no corresponding function for " 2384 "relocation against code\n"); 2385 } 2386 2387 // In AArch64 there are zero reasons to keep a reference to the 2388 // "original" symbol plus addend. The original symbol is probably just a 2389 // section symbol. If we are here, this means we are probably accessing 2390 // data, so it is imperative to keep the original address. 2391 if (IsAArch64) { 2392 SymbolName = ("SYMBOLat0x" + Twine::utohexstr(Address)).str(); 2393 SymbolAddress = Address; 2394 Addend = 0; 2395 } 2396 2397 if (BinaryData *BD = BC->getBinaryDataContainingAddress(SymbolAddress)) { 2398 // Note: this assertion is trying to check sanity of BinaryData objects 2399 // but AArch64 has inferred and incomplete object locations coming from 2400 // GOT/TLS or any other non-trivial relocation (that requires creation 2401 // of sections and whose symbol address is not really what should be 2402 // encoded in the instruction). So we essentially disabled this check 2403 // for AArch64 and live with bogus names for objects. 2404 assert((IsAArch64 || IsSectionRelocation || 2405 BD->nameStartsWith(SymbolName) || 2406 BD->nameStartsWith("PG" + SymbolName) || 2407 (BD->nameStartsWith("ANONYMOUS") && 2408 (BD->getSectionName().startswith(".plt") || 2409 BD->getSectionName().endswith(".plt")))) && 2410 "BOLT symbol names of all non-section relocations must match " 2411 "up with symbol names referenced in the relocation"); 2412 2413 if (IsSectionRelocation) 2414 BC->markAmbiguousRelocations(*BD, Address); 2415 2416 ReferencedSymbol = BD->getSymbol(); 2417 Addend += (SymbolAddress - BD->getAddress()); 2418 SymbolAddress = BD->getAddress(); 2419 assert(Address == SymbolAddress + Addend); 2420 } else { 2421 // These are mostly local data symbols but undefined symbols 2422 // in relocation sections can get through here too, from .plt. 2423 assert( 2424 (IsAArch64 || IsSectionRelocation || 2425 BC->getSectionNameForAddress(SymbolAddress)->startswith(".plt")) && 2426 "known symbols should not resolve to anonymous locals"); 2427 2428 if (IsSectionRelocation) { 2429 ReferencedSymbol = 2430 BC->getOrCreateGlobalSymbol(SymbolAddress, "SYMBOLat"); 2431 } else { 2432 SymbolRef Symbol = *Rel.getSymbol(); 2433 const uint64_t SymbolSize = 2434 IsAArch64 ? 0 : ELFSymbolRef(Symbol).getSize(); 2435 const uint64_t SymbolAlignment = 2436 IsAArch64 ? 1 : Symbol.getAlignment(); 2437 const uint32_t SymbolFlags = cantFail(Symbol.getFlags()); 2438 std::string Name; 2439 if (SymbolFlags & SymbolRef::SF_Global) { 2440 Name = SymbolName; 2441 } else { 2442 if (StringRef(SymbolName) 2443 .startswith(BC->AsmInfo->getPrivateGlobalPrefix())) 2444 Name = NR.uniquify("PG" + SymbolName); 2445 else 2446 Name = NR.uniquify(SymbolName); 2447 } 2448 ReferencedSymbol = BC->registerNameAtAddress( 2449 Name, SymbolAddress, SymbolSize, SymbolAlignment, SymbolFlags); 2450 } 2451 2452 if (IsSectionRelocation) { 2453 BinaryData *BD = BC->getBinaryDataByName(ReferencedSymbol->getName()); 2454 BC->markAmbiguousRelocations(*BD, Address); 2455 } 2456 } 2457 } 2458 2459 auto checkMaxDataRelocations = [&]() { 2460 ++NumDataRelocations; 2461 if (opts::MaxDataRelocations && 2462 NumDataRelocations + 1 == opts::MaxDataRelocations) { 2463 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: processing ending on data relocation " 2464 << NumDataRelocations << ": "); 2465 printRelocationInfo(Rel, ReferencedSymbol->getName(), SymbolAddress, 2466 Addend, ExtractedValue); 2467 } 2468 2469 return (!opts::MaxDataRelocations || 2470 NumDataRelocations < opts::MaxDataRelocations); 2471 }; 2472 2473 if ((RefSection && refersToReorderedSection(RefSection)) || 2474 (opts::ForceToDataRelocations && checkMaxDataRelocations())) 2475 ForceRelocation = true; 2476 2477 if (IsFromCode) { 2478 ContainingBF->addRelocation(Rel.getOffset(), ReferencedSymbol, RType, 2479 Addend, ExtractedValue); 2480 } else if (IsToCode || ForceRelocation) { 2481 BC->addRelocation(Rel.getOffset(), ReferencedSymbol, RType, Addend, 2482 ExtractedValue); 2483 } else { 2484 LLVM_DEBUG( 2485 dbgs() << "BOLT-DEBUG: ignoring relocation from data to data\n"); 2486 } 2487 } 2488 } 2489 2490 void RewriteInstance::selectFunctionsToProcess() { 2491 // Extend the list of functions to process or skip from a file. 2492 auto populateFunctionNames = [](cl::opt<std::string> &FunctionNamesFile, 2493 cl::list<std::string> &FunctionNames) { 2494 if (FunctionNamesFile.empty()) 2495 return; 2496 std::ifstream FuncsFile(FunctionNamesFile, std::ios::in); 2497 std::string FuncName; 2498 while (std::getline(FuncsFile, FuncName)) 2499 FunctionNames.push_back(FuncName); 2500 }; 2501 populateFunctionNames(opts::FunctionNamesFile, opts::ForceFunctionNames); 2502 populateFunctionNames(opts::SkipFunctionNamesFile, opts::SkipFunctionNames); 2503 populateFunctionNames(opts::FunctionNamesFileNR, opts::ForceFunctionNamesNR); 2504 2505 // Make a set of functions to process to speed up lookups. 2506 std::unordered_set<std::string> ForceFunctionsNR( 2507 opts::ForceFunctionNamesNR.begin(), opts::ForceFunctionNamesNR.end()); 2508 2509 if ((!opts::ForceFunctionNames.empty() || 2510 !opts::ForceFunctionNamesNR.empty()) && 2511 !opts::SkipFunctionNames.empty()) { 2512 errs() << "BOLT-ERROR: cannot select functions to process and skip at the " 2513 "same time. Please use only one type of selection.\n"; 2514 exit(1); 2515 } 2516 2517 uint64_t LiteThresholdExecCount = 0; 2518 if (opts::LiteThresholdPct) { 2519 if (opts::LiteThresholdPct > 100) 2520 opts::LiteThresholdPct = 100; 2521 2522 std::vector<const BinaryFunction *> TopFunctions; 2523 for (auto &BFI : BC->getBinaryFunctions()) { 2524 const BinaryFunction &Function = BFI.second; 2525 if (ProfileReader->mayHaveProfileData(Function)) 2526 TopFunctions.push_back(&Function); 2527 } 2528 std::sort(TopFunctions.begin(), TopFunctions.end(), 2529 [](const BinaryFunction *A, const BinaryFunction *B) { 2530 return 2531 A->getKnownExecutionCount() < B->getKnownExecutionCount(); 2532 }); 2533 2534 size_t Index = TopFunctions.size() * opts::LiteThresholdPct / 100; 2535 if (Index) 2536 --Index; 2537 LiteThresholdExecCount = TopFunctions[Index]->getKnownExecutionCount(); 2538 outs() << "BOLT-INFO: limiting processing to functions with at least " 2539 << LiteThresholdExecCount << " invocations\n"; 2540 } 2541 LiteThresholdExecCount = std::max( 2542 LiteThresholdExecCount, static_cast<uint64_t>(opts::LiteThresholdCount)); 2543 2544 uint64_t NumFunctionsToProcess = 0; 2545 auto shouldProcess = [&](const BinaryFunction &Function) { 2546 if (opts::MaxFunctions && NumFunctionsToProcess > opts::MaxFunctions) 2547 return false; 2548 2549 // If the list is not empty, only process functions from the list. 2550 if (!opts::ForceFunctionNames.empty() || !ForceFunctionsNR.empty()) { 2551 // Regex check (-funcs and -funcs-file options). 2552 for (std::string &Name : opts::ForceFunctionNames) 2553 if (Function.hasNameRegex(Name)) 2554 return true; 2555 2556 // Non-regex check (-funcs-no-regex and -funcs-file-no-regex). 2557 Optional<StringRef> Match = 2558 Function.forEachName([&ForceFunctionsNR](StringRef Name) { 2559 return ForceFunctionsNR.count(Name.str()); 2560 }); 2561 return Match.hasValue(); 2562 } 2563 2564 for (std::string &Name : opts::SkipFunctionNames) 2565 if (Function.hasNameRegex(Name)) 2566 return false; 2567 2568 if (opts::Lite) { 2569 if (ProfileReader && !ProfileReader->mayHaveProfileData(Function)) 2570 return false; 2571 2572 if (Function.getKnownExecutionCount() < LiteThresholdExecCount) 2573 return false; 2574 } 2575 2576 return true; 2577 }; 2578 2579 for (auto &BFI : BC->getBinaryFunctions()) { 2580 BinaryFunction &Function = BFI.second; 2581 2582 // Pseudo functions are explicitly marked by us not to be processed. 2583 if (Function.isPseudo()) { 2584 Function.IsIgnored = true; 2585 Function.HasExternalRefRelocations = true; 2586 continue; 2587 } 2588 2589 if (!shouldProcess(Function)) { 2590 LLVM_DEBUG(dbgs() << "BOLT-INFO: skipping processing of function " 2591 << Function << " per user request\n"); 2592 Function.setIgnored(); 2593 } else { 2594 ++NumFunctionsToProcess; 2595 if (opts::MaxFunctions && NumFunctionsToProcess == opts::MaxFunctions) 2596 outs() << "BOLT-INFO: processing ending on " << Function << '\n'; 2597 } 2598 } 2599 } 2600 2601 void RewriteInstance::readDebugInfo() { 2602 NamedRegionTimer T("readDebugInfo", "read debug info", TimerGroupName, 2603 TimerGroupDesc, opts::TimeRewrite); 2604 if (!opts::UpdateDebugSections) 2605 return; 2606 2607 BC->preprocessDebugInfo(); 2608 } 2609 2610 void RewriteInstance::preprocessProfileData() { 2611 if (!ProfileReader) 2612 return; 2613 2614 NamedRegionTimer T("preprocessprofile", "pre-process profile data", 2615 TimerGroupName, TimerGroupDesc, opts::TimeRewrite); 2616 2617 outs() << "BOLT-INFO: pre-processing profile using " 2618 << ProfileReader->getReaderName() << '\n'; 2619 2620 if (BAT->enabledFor(InputFile)) { 2621 outs() << "BOLT-INFO: profile collection done on a binary already " 2622 "processed by BOLT\n"; 2623 ProfileReader->setBAT(&*BAT); 2624 } 2625 2626 if (Error E = ProfileReader->preprocessProfile(*BC.get())) 2627 report_error("cannot pre-process profile", std::move(E)); 2628 2629 if (!BC->hasSymbolsWithFileName() && ProfileReader->hasLocalsWithFileName() && 2630 !opts::AllowStripped) { 2631 errs() << "BOLT-ERROR: input binary does not have local file symbols " 2632 "but profile data includes function names with embedded file " 2633 "names. It appears that the input binary was stripped while a " 2634 "profiled binary was not. If you know what you are doing and " 2635 "wish to proceed, use -allow-stripped option.\n"; 2636 exit(1); 2637 } 2638 } 2639 2640 void RewriteInstance::processProfileDataPreCFG() { 2641 if (!ProfileReader) 2642 return; 2643 2644 NamedRegionTimer T("processprofile-precfg", "process profile data pre-CFG", 2645 TimerGroupName, TimerGroupDesc, opts::TimeRewrite); 2646 2647 if (Error E = ProfileReader->readProfilePreCFG(*BC.get())) 2648 report_error("cannot read profile pre-CFG", std::move(E)); 2649 } 2650 2651 void RewriteInstance::processProfileData() { 2652 if (!ProfileReader) 2653 return; 2654 2655 NamedRegionTimer T("processprofile", "process profile data", TimerGroupName, 2656 TimerGroupDesc, opts::TimeRewrite); 2657 2658 if (Error E = ProfileReader->readProfile(*BC.get())) 2659 report_error("cannot read profile", std::move(E)); 2660 2661 if (!opts::SaveProfile.empty()) { 2662 YAMLProfileWriter PW(opts::SaveProfile); 2663 PW.writeProfile(*this); 2664 } 2665 2666 // Release memory used by profile reader. 2667 ProfileReader.reset(); 2668 2669 if (opts::AggregateOnly) 2670 exit(0); 2671 } 2672 2673 void RewriteInstance::disassembleFunctions() { 2674 NamedRegionTimer T("disassembleFunctions", "disassemble functions", 2675 TimerGroupName, TimerGroupDesc, opts::TimeRewrite); 2676 for (auto &BFI : BC->getBinaryFunctions()) { 2677 BinaryFunction &Function = BFI.second; 2678 2679 ErrorOr<ArrayRef<uint8_t>> FunctionData = Function.getData(); 2680 if (!FunctionData) { 2681 errs() << "BOLT-ERROR: corresponding section is non-executable or " 2682 << "empty for function " << Function << '\n'; 2683 exit(1); 2684 } 2685 2686 // Treat zero-sized functions as non-simple ones. 2687 if (Function.getSize() == 0) { 2688 Function.setSimple(false); 2689 continue; 2690 } 2691 2692 // Offset of the function in the file. 2693 const auto *FileBegin = 2694 reinterpret_cast<const uint8_t *>(InputFile->getData().data()); 2695 Function.setFileOffset(FunctionData->begin() - FileBegin); 2696 2697 if (!shouldDisassemble(Function)) { 2698 NamedRegionTimer T("scan", "scan functions", "buildfuncs", 2699 "Scan Binary Functions", opts::TimeBuild); 2700 Function.scanExternalRefs(); 2701 Function.setSimple(false); 2702 continue; 2703 } 2704 2705 if (!Function.disassemble()) { 2706 if (opts::processAllFunctions()) 2707 BC->exitWithBugReport("function cannot be properly disassembled. " 2708 "Unable to continue in relocation mode.", 2709 Function); 2710 if (opts::Verbosity >= 1) 2711 outs() << "BOLT-INFO: could not disassemble function " << Function 2712 << ". Will ignore.\n"; 2713 // Forcefully ignore the function. 2714 Function.setIgnored(); 2715 continue; 2716 } 2717 2718 if (opts::PrintAll || opts::PrintDisasm) 2719 Function.print(outs(), "after disassembly", true); 2720 2721 BC->processInterproceduralReferences(Function); 2722 } 2723 2724 BC->populateJumpTables(); 2725 BC->skipMarkedFragments(); 2726 2727 for (auto &BFI : BC->getBinaryFunctions()) { 2728 BinaryFunction &Function = BFI.second; 2729 2730 if (!shouldDisassemble(Function)) 2731 continue; 2732 2733 Function.postProcessEntryPoints(); 2734 Function.postProcessJumpTables(); 2735 } 2736 2737 BC->adjustCodePadding(); 2738 2739 for (auto &BFI : BC->getBinaryFunctions()) { 2740 BinaryFunction &Function = BFI.second; 2741 2742 if (!shouldDisassemble(Function)) 2743 continue; 2744 2745 if (!Function.isSimple()) { 2746 assert((!BC->HasRelocations || Function.getSize() == 0) && 2747 "unexpected non-simple function in relocation mode"); 2748 continue; 2749 } 2750 2751 // Fill in CFI information for this function 2752 if (!Function.trapsOnEntry() && !CFIRdWrt->fillCFIInfoFor(Function)) { 2753 if (BC->HasRelocations) { 2754 BC->exitWithBugReport("unable to fill CFI.", Function); 2755 } else { 2756 errs() << "BOLT-WARNING: unable to fill CFI for function " << Function 2757 << ". Skipping.\n"; 2758 Function.setSimple(false); 2759 continue; 2760 } 2761 } 2762 2763 // Parse LSDA. 2764 if (Function.getLSDAAddress() != 0) 2765 Function.parseLSDA(getLSDAData(), getLSDAAddress()); 2766 } 2767 } 2768 2769 void RewriteInstance::buildFunctionsCFG() { 2770 NamedRegionTimer T("buildCFG", "buildCFG", "buildfuncs", 2771 "Build Binary Functions", opts::TimeBuild); 2772 2773 // Create annotation indices to allow lock-free execution 2774 BC->MIB->getOrCreateAnnotationIndex("Offset"); 2775 BC->MIB->getOrCreateAnnotationIndex("JTIndexReg"); 2776 BC->MIB->getOrCreateAnnotationIndex("NOP"); 2777 BC->MIB->getOrCreateAnnotationIndex("Size"); 2778 2779 ParallelUtilities::WorkFuncWithAllocTy WorkFun = 2780 [&](BinaryFunction &BF, MCPlusBuilder::AllocatorIdTy AllocId) { 2781 if (!BF.buildCFG(AllocId)) 2782 return; 2783 2784 if (opts::PrintAll) 2785 BF.print(outs(), "while building cfg", true); 2786 }; 2787 2788 ParallelUtilities::PredicateTy SkipPredicate = [&](const BinaryFunction &BF) { 2789 return !shouldDisassemble(BF) || !BF.isSimple(); 2790 }; 2791 2792 ParallelUtilities::runOnEachFunctionWithUniqueAllocId( 2793 *BC, ParallelUtilities::SchedulingPolicy::SP_INST_LINEAR, WorkFun, 2794 SkipPredicate, "disassembleFunctions-buildCFG", 2795 /*ForceSequential*/ opts::SequentialDisassembly || opts::PrintAll); 2796 2797 BC->postProcessSymbolTable(); 2798 } 2799 2800 void RewriteInstance::postProcessFunctions() { 2801 BC->TotalScore = 0; 2802 BC->SumExecutionCount = 0; 2803 for (auto &BFI : BC->getBinaryFunctions()) { 2804 BinaryFunction &Function = BFI.second; 2805 2806 if (Function.empty()) 2807 continue; 2808 2809 Function.postProcessCFG(); 2810 2811 if (opts::PrintAll || opts::PrintCFG) 2812 Function.print(outs(), "after building cfg", true); 2813 2814 if (opts::DumpDotAll) 2815 Function.dumpGraphForPass("00_build-cfg"); 2816 2817 if (opts::PrintLoopInfo) { 2818 Function.calculateLoopInfo(); 2819 Function.printLoopInfo(outs()); 2820 } 2821 2822 BC->TotalScore += Function.getFunctionScore(); 2823 BC->SumExecutionCount += Function.getKnownExecutionCount(); 2824 } 2825 2826 if (opts::PrintGlobals) { 2827 outs() << "BOLT-INFO: Global symbols:\n"; 2828 BC->printGlobalSymbols(outs()); 2829 } 2830 } 2831 2832 void RewriteInstance::runOptimizationPasses() { 2833 NamedRegionTimer T("runOptimizationPasses", "run optimization passes", 2834 TimerGroupName, TimerGroupDesc, opts::TimeRewrite); 2835 BinaryFunctionPassManager::runAllPasses(*BC); 2836 } 2837 2838 namespace { 2839 2840 class BOLTSymbolResolver : public JITSymbolResolver { 2841 BinaryContext &BC; 2842 2843 public: 2844 BOLTSymbolResolver(BinaryContext &BC) : BC(BC) {} 2845 2846 // We are responsible for all symbols 2847 Expected<LookupSet> getResponsibilitySet(const LookupSet &Symbols) override { 2848 return Symbols; 2849 } 2850 2851 // Some of our symbols may resolve to zero and this should not be an error 2852 bool allowsZeroSymbols() override { return true; } 2853 2854 /// Resolves the address of each symbol requested 2855 void lookup(const LookupSet &Symbols, 2856 OnResolvedFunction OnResolved) override { 2857 JITSymbolResolver::LookupResult AllResults; 2858 2859 if (BC.EFMM->ObjectsLoaded) { 2860 for (const StringRef &Symbol : Symbols) { 2861 std::string SymName = Symbol.str(); 2862 LLVM_DEBUG(dbgs() << "BOLT: looking for " << SymName << "\n"); 2863 // Resolve to a PLT entry if possible 2864 if (BinaryData *I = BC.getBinaryDataByName(SymName + "@PLT")) { 2865 AllResults[Symbol] = 2866 JITEvaluatedSymbol(I->getAddress(), JITSymbolFlags()); 2867 continue; 2868 } 2869 OnResolved(make_error<StringError>( 2870 "Symbol not found required by runtime: " + Symbol, 2871 inconvertibleErrorCode())); 2872 return; 2873 } 2874 OnResolved(std::move(AllResults)); 2875 return; 2876 } 2877 2878 for (const StringRef &Symbol : Symbols) { 2879 std::string SymName = Symbol.str(); 2880 LLVM_DEBUG(dbgs() << "BOLT: looking for " << SymName << "\n"); 2881 2882 if (BinaryData *I = BC.getBinaryDataByName(SymName)) { 2883 uint64_t Address = I->isMoved() && !I->isJumpTable() 2884 ? I->getOutputAddress() 2885 : I->getAddress(); 2886 LLVM_DEBUG(dbgs() << "Resolved to address 0x" 2887 << Twine::utohexstr(Address) << "\n"); 2888 AllResults[Symbol] = JITEvaluatedSymbol(Address, JITSymbolFlags()); 2889 continue; 2890 } 2891 LLVM_DEBUG(dbgs() << "Resolved to address 0x0\n"); 2892 AllResults[Symbol] = JITEvaluatedSymbol(0, JITSymbolFlags()); 2893 } 2894 2895 OnResolved(std::move(AllResults)); 2896 } 2897 }; 2898 2899 } // anonymous namespace 2900 2901 void RewriteInstance::emitAndLink() { 2902 NamedRegionTimer T("emitAndLink", "emit and link", TimerGroupName, 2903 TimerGroupDesc, opts::TimeRewrite); 2904 std::error_code EC; 2905 2906 // This is an object file, which we keep for debugging purposes. 2907 // Once we decide it's useless, we should create it in memory. 2908 SmallString<128> OutObjectPath; 2909 sys::fs::getPotentiallyUniqueTempFileName("output", "o", OutObjectPath); 2910 std::unique_ptr<ToolOutputFile> TempOut = 2911 std::make_unique<ToolOutputFile>(OutObjectPath, EC, sys::fs::OF_None); 2912 check_error(EC, "cannot create output object file"); 2913 2914 std::unique_ptr<buffer_ostream> BOS = 2915 std::make_unique<buffer_ostream>(TempOut->os()); 2916 raw_pwrite_stream *OS = BOS.get(); 2917 2918 // Implicitly MCObjectStreamer takes ownership of MCAsmBackend (MAB) 2919 // and MCCodeEmitter (MCE). ~MCObjectStreamer() will delete these 2920 // two instances. 2921 std::unique_ptr<MCStreamer> Streamer = BC->createStreamer(*OS); 2922 2923 if (EHFrameSection) { 2924 if (opts::UseOldText || opts::StrictMode) { 2925 // The section is going to be regenerated from scratch. 2926 // Empty the contents, but keep the section reference. 2927 EHFrameSection->clearContents(); 2928 } else { 2929 // Make .eh_frame relocatable. 2930 relocateEHFrameSection(); 2931 } 2932 } 2933 2934 emitBinaryContext(*Streamer, *BC, getOrgSecPrefix()); 2935 2936 Streamer->Finish(); 2937 2938 ////////////////////////////////////////////////////////////////////////////// 2939 // Assign addresses to new sections. 2940 ////////////////////////////////////////////////////////////////////////////// 2941 2942 // Get output object as ObjectFile. 2943 std::unique_ptr<MemoryBuffer> ObjectMemBuffer = 2944 MemoryBuffer::getMemBuffer(BOS->str(), "in-memory object file", false); 2945 std::unique_ptr<object::ObjectFile> Obj = cantFail( 2946 object::ObjectFile::createObjectFile(ObjectMemBuffer->getMemBufferRef()), 2947 "error creating in-memory object"); 2948 2949 BOLTSymbolResolver Resolver = BOLTSymbolResolver(*BC); 2950 2951 MCAsmLayout FinalLayout( 2952 static_cast<MCObjectStreamer *>(Streamer.get())->getAssembler()); 2953 2954 RTDyld.reset(new decltype(RTDyld)::element_type(*BC->EFMM, Resolver)); 2955 RTDyld->setProcessAllSections(false); 2956 RTDyld->loadObject(*Obj); 2957 2958 // Assign addresses to all sections. If key corresponds to the object 2959 // created by ourselves, call our regular mapping function. If we are 2960 // loading additional objects as part of runtime libraries for 2961 // instrumentation, treat them as extra sections. 2962 mapFileSections(*RTDyld); 2963 2964 RTDyld->finalizeWithMemoryManagerLocking(); 2965 if (RTDyld->hasError()) { 2966 outs() << "BOLT-ERROR: RTDyld failed: " << RTDyld->getErrorString() << "\n"; 2967 exit(1); 2968 } 2969 2970 // Update output addresses based on the new section map and 2971 // layout. Only do this for the object created by ourselves. 2972 updateOutputValues(FinalLayout); 2973 2974 if (opts::UpdateDebugSections) 2975 DebugInfoRewriter->updateLineTableOffsets(FinalLayout); 2976 2977 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary()) 2978 RtLibrary->link(*BC, ToolPath, *RTDyld, [this](RuntimeDyld &R) { 2979 this->mapExtraSections(*RTDyld); 2980 }); 2981 2982 // Once the code is emitted, we can rename function sections to actual 2983 // output sections and de-register sections used for emission. 2984 for (BinaryFunction *Function : BC->getAllBinaryFunctions()) { 2985 ErrorOr<BinarySection &> Section = Function->getCodeSection(); 2986 if (Section && 2987 (Function->getImageAddress() == 0 || Function->getImageSize() == 0)) 2988 continue; 2989 2990 // Restore origin section for functions that were emitted or supposed to 2991 // be emitted to patch sections. 2992 if (Section) 2993 BC->deregisterSection(*Section); 2994 assert(Function->getOriginSectionName() && "expected origin section"); 2995 Function->CodeSectionName = std::string(*Function->getOriginSectionName()); 2996 if (Function->isSplit()) { 2997 if (ErrorOr<BinarySection &> ColdSection = Function->getColdCodeSection()) 2998 BC->deregisterSection(*ColdSection); 2999 Function->ColdCodeSectionName = std::string(getBOLTTextSectionName()); 3000 } 3001 } 3002 3003 if (opts::PrintCacheMetrics) { 3004 outs() << "BOLT-INFO: cache metrics after emitting functions:\n"; 3005 CacheMetrics::printAll(BC->getSortedFunctions()); 3006 } 3007 3008 if (opts::KeepTmp) { 3009 TempOut->keep(); 3010 outs() << "BOLT-INFO: intermediary output object file saved for debugging " 3011 "purposes: " 3012 << OutObjectPath << "\n"; 3013 } 3014 } 3015 3016 void RewriteInstance::updateMetadata() { 3017 updateSDTMarkers(); 3018 updateLKMarkers(); 3019 parsePseudoProbe(); 3020 updatePseudoProbes(); 3021 3022 if (opts::UpdateDebugSections) { 3023 NamedRegionTimer T("updateDebugInfo", "update debug info", TimerGroupName, 3024 TimerGroupDesc, opts::TimeRewrite); 3025 DebugInfoRewriter->updateDebugInfo(); 3026 } 3027 3028 if (opts::WriteBoltInfoSection) 3029 addBoltInfoSection(); 3030 } 3031 3032 void RewriteInstance::updatePseudoProbes() { 3033 // check if there is pseudo probe section decoded 3034 if (BC->ProbeDecoder.getAddress2ProbesMap().empty()) 3035 return; 3036 // input address converted to output 3037 AddressProbesMap &Address2ProbesMap = BC->ProbeDecoder.getAddress2ProbesMap(); 3038 const GUIDProbeFunctionMap &GUID2Func = 3039 BC->ProbeDecoder.getGUID2FuncDescMap(); 3040 3041 for (auto &AP : Address2ProbesMap) { 3042 BinaryFunction *F = BC->getBinaryFunctionContainingAddress(AP.first); 3043 // If F is removed, eliminate all probes inside it from inline tree 3044 // Setting probes' addresses as INT64_MAX means elimination 3045 if (!F) { 3046 for (MCDecodedPseudoProbe &Probe : AP.second) 3047 Probe.setAddress(INT64_MAX); 3048 continue; 3049 } 3050 // If F is not emitted, the function will remain in the same address as its 3051 // input 3052 if (!F->isEmitted()) 3053 continue; 3054 3055 uint64_t Offset = AP.first - F->getAddress(); 3056 const BinaryBasicBlock *BB = F->getBasicBlockContainingOffset(Offset); 3057 uint64_t BlkOutputAddress = BB->getOutputAddressRange().first; 3058 // Check if block output address is defined. 3059 // If not, such block is removed from binary. Then remove the probes from 3060 // inline tree 3061 if (BlkOutputAddress == 0) { 3062 for (MCDecodedPseudoProbe &Probe : AP.second) 3063 Probe.setAddress(INT64_MAX); 3064 continue; 3065 } 3066 3067 unsigned ProbeTrack = AP.second.size(); 3068 std::list<MCDecodedPseudoProbe>::iterator Probe = AP.second.begin(); 3069 while (ProbeTrack != 0) { 3070 if (Probe->isBlock()) { 3071 Probe->setAddress(BlkOutputAddress); 3072 } else if (Probe->isCall()) { 3073 // A call probe may be duplicated due to ICP 3074 // Go through output of InputOffsetToAddressMap to collect all related 3075 // probes 3076 const InputOffsetToAddressMapTy &Offset2Addr = 3077 F->getInputOffsetToAddressMap(); 3078 auto CallOutputAddresses = Offset2Addr.equal_range(Offset); 3079 auto CallOutputAddress = CallOutputAddresses.first; 3080 if (CallOutputAddress == CallOutputAddresses.second) { 3081 Probe->setAddress(INT64_MAX); 3082 } else { 3083 Probe->setAddress(CallOutputAddress->second); 3084 CallOutputAddress = std::next(CallOutputAddress); 3085 } 3086 3087 while (CallOutputAddress != CallOutputAddresses.second) { 3088 AP.second.push_back(*Probe); 3089 AP.second.back().setAddress(CallOutputAddress->second); 3090 Probe->getInlineTreeNode()->addProbes(&(AP.second.back())); 3091 CallOutputAddress = std::next(CallOutputAddress); 3092 } 3093 } 3094 Probe = std::next(Probe); 3095 ProbeTrack--; 3096 } 3097 } 3098 3099 if (opts::PrintPseudoProbes == opts::PrintPseudoProbesOptions::PPP_All || 3100 opts::PrintPseudoProbes == 3101 opts::PrintPseudoProbesOptions::PPP_Probes_Address_Conversion) { 3102 outs() << "Pseudo Probe Address Conversion results:\n"; 3103 // table that correlates address to block 3104 std::unordered_map<uint64_t, StringRef> Addr2BlockNames; 3105 for (auto &F : BC->getBinaryFunctions()) 3106 for (BinaryBasicBlock &BinaryBlock : F.second) 3107 Addr2BlockNames[BinaryBlock.getOutputAddressRange().first] = 3108 BinaryBlock.getName(); 3109 3110 // scan all addresses -> correlate probe to block when print out 3111 std::vector<uint64_t> Addresses; 3112 for (auto &Entry : Address2ProbesMap) 3113 Addresses.push_back(Entry.first); 3114 std::sort(Addresses.begin(), Addresses.end()); 3115 for (uint64_t Key : Addresses) { 3116 for (MCDecodedPseudoProbe &Probe : Address2ProbesMap[Key]) { 3117 if (Probe.getAddress() == INT64_MAX) 3118 outs() << "Deleted Probe: "; 3119 else 3120 outs() << "Address: " << format_hex(Probe.getAddress(), 8) << " "; 3121 Probe.print(outs(), GUID2Func, true); 3122 // print block name only if the probe is block type and undeleted. 3123 if (Probe.isBlock() && Probe.getAddress() != INT64_MAX) 3124 outs() << format_hex(Probe.getAddress(), 8) << " Probe is in " 3125 << Addr2BlockNames[Probe.getAddress()] << "\n"; 3126 } 3127 } 3128 outs() << "=======================================\n"; 3129 } 3130 3131 // encode pseudo probes with updated addresses 3132 encodePseudoProbes(); 3133 } 3134 3135 template <typename F> 3136 static void emitLEB128IntValue(F encode, uint64_t Value, 3137 SmallString<8> &Contents) { 3138 SmallString<128> Tmp; 3139 raw_svector_ostream OSE(Tmp); 3140 encode(Value, OSE); 3141 Contents.append(OSE.str().begin(), OSE.str().end()); 3142 } 3143 3144 void RewriteInstance::encodePseudoProbes() { 3145 // Buffer for new pseudo probes section 3146 SmallString<8> Contents; 3147 MCDecodedPseudoProbe *LastProbe = nullptr; 3148 3149 auto EmitInt = [&](uint64_t Value, uint32_t Size) { 3150 const bool IsLittleEndian = BC->AsmInfo->isLittleEndian(); 3151 uint64_t Swapped = support::endian::byte_swap( 3152 Value, IsLittleEndian ? support::little : support::big); 3153 unsigned Index = IsLittleEndian ? 0 : 8 - Size; 3154 auto Entry = StringRef(reinterpret_cast<char *>(&Swapped) + Index, Size); 3155 Contents.append(Entry.begin(), Entry.end()); 3156 }; 3157 3158 auto EmitULEB128IntValue = [&](uint64_t Value) { 3159 SmallString<128> Tmp; 3160 raw_svector_ostream OSE(Tmp); 3161 encodeULEB128(Value, OSE, 0); 3162 Contents.append(OSE.str().begin(), OSE.str().end()); 3163 }; 3164 3165 auto EmitSLEB128IntValue = [&](int64_t Value) { 3166 SmallString<128> Tmp; 3167 raw_svector_ostream OSE(Tmp); 3168 encodeSLEB128(Value, OSE); 3169 Contents.append(OSE.str().begin(), OSE.str().end()); 3170 }; 3171 3172 // Emit indiviual pseudo probes in a inline tree node 3173 // Probe index, type, attribute, address type and address are encoded 3174 // Address of the first probe is absolute. 3175 // Other probes' address are represented by delta 3176 auto EmitDecodedPseudoProbe = [&](MCDecodedPseudoProbe *&CurProbe) { 3177 EmitULEB128IntValue(CurProbe->getIndex()); 3178 uint8_t PackedType = CurProbe->getType() | (CurProbe->getAttributes() << 4); 3179 uint8_t Flag = 3180 LastProbe ? ((int8_t)MCPseudoProbeFlag::AddressDelta << 7) : 0; 3181 EmitInt(Flag | PackedType, 1); 3182 if (LastProbe) { 3183 // Emit the delta between the address label and LastProbe. 3184 int64_t Delta = CurProbe->getAddress() - LastProbe->getAddress(); 3185 EmitSLEB128IntValue(Delta); 3186 } else { 3187 // Emit absolute address for encoding the first pseudo probe. 3188 uint32_t AddrSize = BC->AsmInfo->getCodePointerSize(); 3189 EmitInt(CurProbe->getAddress(), AddrSize); 3190 } 3191 }; 3192 3193 std::map<InlineSite, MCDecodedPseudoProbeInlineTree *, 3194 std::greater<InlineSite>> 3195 Inlinees; 3196 3197 // DFS of inline tree to emit pseudo probes in all tree node 3198 // Inline site index of a probe is emitted first. 3199 // Then tree node Guid, size of pseudo probes and children nodes, and detail 3200 // of contained probes are emitted Deleted probes are skipped Root node is not 3201 // encoded to binaries. It's a "wrapper" of inline trees of each function. 3202 std::list<std::pair<uint64_t, MCDecodedPseudoProbeInlineTree *>> NextNodes; 3203 const MCDecodedPseudoProbeInlineTree &Root = 3204 BC->ProbeDecoder.getDummyInlineRoot(); 3205 for (auto Child = Root.getChildren().begin(); 3206 Child != Root.getChildren().end(); ++Child) 3207 Inlinees[Child->first] = Child->second.get(); 3208 3209 for (auto Inlinee : Inlinees) 3210 // INT64_MAX is "placeholder" of unused callsite index field in the pair 3211 NextNodes.push_back({INT64_MAX, Inlinee.second}); 3212 3213 Inlinees.clear(); 3214 3215 while (!NextNodes.empty()) { 3216 uint64_t ProbeIndex = NextNodes.back().first; 3217 MCDecodedPseudoProbeInlineTree *Cur = NextNodes.back().second; 3218 NextNodes.pop_back(); 3219 3220 if (Cur->Parent && !Cur->Parent->isRoot()) 3221 // Emit probe inline site 3222 EmitULEB128IntValue(ProbeIndex); 3223 3224 // Emit probes grouped by GUID. 3225 LLVM_DEBUG({ 3226 dbgs().indent(MCPseudoProbeTable::DdgPrintIndent); 3227 dbgs() << "GUID: " << Cur->Guid << "\n"; 3228 }); 3229 // Emit Guid 3230 EmitInt(Cur->Guid, 8); 3231 // Emit number of probes in this node 3232 uint64_t Deleted = 0; 3233 for (MCDecodedPseudoProbe *&Probe : Cur->getProbes()) 3234 if (Probe->getAddress() == INT64_MAX) 3235 Deleted++; 3236 LLVM_DEBUG(dbgs() << "Deleted Probes:" << Deleted << "\n"); 3237 uint64_t ProbesSize = Cur->getProbes().size() - Deleted; 3238 EmitULEB128IntValue(ProbesSize); 3239 // Emit number of direct inlinees 3240 EmitULEB128IntValue(Cur->getChildren().size()); 3241 // Emit probes in this group 3242 for (MCDecodedPseudoProbe *&Probe : Cur->getProbes()) { 3243 if (Probe->getAddress() == INT64_MAX) 3244 continue; 3245 EmitDecodedPseudoProbe(Probe); 3246 LastProbe = Probe; 3247 } 3248 3249 for (auto Child = Cur->getChildren().begin(); 3250 Child != Cur->getChildren().end(); ++Child) 3251 Inlinees[Child->first] = Child->second.get(); 3252 for (const auto &Inlinee : Inlinees) { 3253 assert(Cur->Guid != 0 && "non root tree node must have nonzero Guid"); 3254 NextNodes.push_back({std::get<1>(Inlinee.first), Inlinee.second}); 3255 LLVM_DEBUG({ 3256 dbgs().indent(MCPseudoProbeTable::DdgPrintIndent); 3257 dbgs() << "InlineSite: " << std::get<1>(Inlinee.first) << "\n"; 3258 }); 3259 } 3260 Inlinees.clear(); 3261 } 3262 3263 // Create buffer for new contents for the section 3264 // Freed when parent section is destroyed 3265 uint8_t *Output = new uint8_t[Contents.str().size()]; 3266 memcpy(Output, Contents.str().data(), Contents.str().size()); 3267 addToDebugSectionsToOverwrite(".pseudo_probe"); 3268 BC->registerOrUpdateSection(".pseudo_probe", PseudoProbeSection->getELFType(), 3269 PseudoProbeSection->getELFFlags(), Output, 3270 Contents.str().size(), 1); 3271 if (opts::PrintPseudoProbes == opts::PrintPseudoProbesOptions::PPP_All || 3272 opts::PrintPseudoProbes == 3273 opts::PrintPseudoProbesOptions::PPP_Encoded_Probes) { 3274 // create a dummy decoder; 3275 MCPseudoProbeDecoder DummyDecoder; 3276 StringRef DescContents = PseudoProbeDescSection->getContents(); 3277 DummyDecoder.buildGUID2FuncDescMap( 3278 reinterpret_cast<const uint8_t *>(DescContents.data()), 3279 DescContents.size()); 3280 StringRef ProbeContents = PseudoProbeSection->getOutputContents(); 3281 DummyDecoder.buildAddress2ProbeMap( 3282 reinterpret_cast<const uint8_t *>(ProbeContents.data()), 3283 ProbeContents.size()); 3284 DummyDecoder.printProbesForAllAddresses(outs()); 3285 } 3286 } 3287 3288 void RewriteInstance::updateSDTMarkers() { 3289 NamedRegionTimer T("updateSDTMarkers", "update SDT markers", TimerGroupName, 3290 TimerGroupDesc, opts::TimeRewrite); 3291 3292 if (!SDTSection) 3293 return; 3294 SDTSection->registerPatcher(std::make_unique<SimpleBinaryPatcher>()); 3295 3296 SimpleBinaryPatcher *SDTNotePatcher = 3297 static_cast<SimpleBinaryPatcher *>(SDTSection->getPatcher()); 3298 for (auto &SDTInfoKV : BC->SDTMarkers) { 3299 const uint64_t OriginalAddress = SDTInfoKV.first; 3300 SDTMarkerInfo &SDTInfo = SDTInfoKV.second; 3301 const BinaryFunction *F = 3302 BC->getBinaryFunctionContainingAddress(OriginalAddress); 3303 if (!F) 3304 continue; 3305 const uint64_t NewAddress = 3306 F->translateInputToOutputAddress(OriginalAddress); 3307 SDTNotePatcher->addLE64Patch(SDTInfo.PCOffset, NewAddress); 3308 } 3309 } 3310 3311 void RewriteInstance::updateLKMarkers() { 3312 if (BC->LKMarkers.size() == 0) 3313 return; 3314 3315 NamedRegionTimer T("updateLKMarkers", "update LK markers", TimerGroupName, 3316 TimerGroupDesc, opts::TimeRewrite); 3317 3318 std::unordered_map<std::string, uint64_t> PatchCounts; 3319 for (std::pair<const uint64_t, std::vector<LKInstructionMarkerInfo>> 3320 &LKMarkerInfoKV : BC->LKMarkers) { 3321 const uint64_t OriginalAddress = LKMarkerInfoKV.first; 3322 const BinaryFunction *BF = 3323 BC->getBinaryFunctionContainingAddress(OriginalAddress, false, true); 3324 if (!BF) 3325 continue; 3326 3327 uint64_t NewAddress = BF->translateInputToOutputAddress(OriginalAddress); 3328 if (NewAddress == 0) 3329 continue; 3330 3331 // Apply base address. 3332 if (OriginalAddress >= 0xffffffff00000000 && NewAddress < 0xffffffff) 3333 NewAddress = NewAddress + 0xffffffff00000000; 3334 3335 if (OriginalAddress == NewAddress) 3336 continue; 3337 3338 for (LKInstructionMarkerInfo &LKMarkerInfo : LKMarkerInfoKV.second) { 3339 StringRef SectionName = LKMarkerInfo.SectionName; 3340 SimpleBinaryPatcher *LKPatcher; 3341 ErrorOr<BinarySection &> BSec = BC->getUniqueSectionByName(SectionName); 3342 assert(BSec && "missing section info for kernel section"); 3343 if (!BSec->getPatcher()) 3344 BSec->registerPatcher(std::make_unique<SimpleBinaryPatcher>()); 3345 LKPatcher = static_cast<SimpleBinaryPatcher *>(BSec->getPatcher()); 3346 PatchCounts[std::string(SectionName)]++; 3347 if (LKMarkerInfo.IsPCRelative) 3348 LKPatcher->addLE32Patch(LKMarkerInfo.SectionOffset, 3349 NewAddress - OriginalAddress + 3350 LKMarkerInfo.PCRelativeOffset); 3351 else 3352 LKPatcher->addLE64Patch(LKMarkerInfo.SectionOffset, NewAddress); 3353 } 3354 } 3355 outs() << "BOLT-INFO: patching linux kernel sections. Total patches per " 3356 "section are as follows:\n"; 3357 for (const std::pair<const std::string, uint64_t> &KV : PatchCounts) 3358 outs() << " Section: " << KV.first << ", patch-counts: " << KV.second 3359 << '\n'; 3360 } 3361 3362 void RewriteInstance::mapFileSections(RuntimeDyld &RTDyld) { 3363 mapCodeSections(RTDyld); 3364 mapDataSections(RTDyld); 3365 } 3366 3367 std::vector<BinarySection *> RewriteInstance::getCodeSections() { 3368 std::vector<BinarySection *> CodeSections; 3369 for (BinarySection &Section : BC->textSections()) 3370 if (Section.hasValidSectionID()) 3371 CodeSections.emplace_back(&Section); 3372 3373 auto compareSections = [&](const BinarySection *A, const BinarySection *B) { 3374 // Place movers before anything else. 3375 if (A->getName() == BC->getHotTextMoverSectionName()) 3376 return true; 3377 if (B->getName() == BC->getHotTextMoverSectionName()) 3378 return false; 3379 3380 // Depending on the option, put main text at the beginning or at the end. 3381 if (opts::HotFunctionsAtEnd) 3382 return B->getName() == BC->getMainCodeSectionName(); 3383 else 3384 return A->getName() == BC->getMainCodeSectionName(); 3385 }; 3386 3387 // Determine the order of sections. 3388 std::stable_sort(CodeSections.begin(), CodeSections.end(), compareSections); 3389 3390 return CodeSections; 3391 } 3392 3393 void RewriteInstance::mapCodeSections(RuntimeDyld &RTDyld) { 3394 if (BC->HasRelocations) { 3395 ErrorOr<BinarySection &> TextSection = 3396 BC->getUniqueSectionByName(BC->getMainCodeSectionName()); 3397 assert(TextSection && ".text section not found in output"); 3398 assert(TextSection->hasValidSectionID() && ".text section should be valid"); 3399 3400 // Map sections for functions with pre-assigned addresses. 3401 for (BinaryFunction *InjectedFunction : BC->getInjectedBinaryFunctions()) { 3402 const uint64_t OutputAddress = InjectedFunction->getOutputAddress(); 3403 if (!OutputAddress) 3404 continue; 3405 3406 ErrorOr<BinarySection &> FunctionSection = 3407 InjectedFunction->getCodeSection(); 3408 assert(FunctionSection && "function should have section"); 3409 FunctionSection->setOutputAddress(OutputAddress); 3410 RTDyld.reassignSectionAddress(FunctionSection->getSectionID(), 3411 OutputAddress); 3412 InjectedFunction->setImageAddress(FunctionSection->getAllocAddress()); 3413 InjectedFunction->setImageSize(FunctionSection->getOutputSize()); 3414 } 3415 3416 // Populate the list of sections to be allocated. 3417 std::vector<BinarySection *> CodeSections = getCodeSections(); 3418 3419 // Remove sections that were pre-allocated (patch sections). 3420 CodeSections.erase( 3421 std::remove_if(CodeSections.begin(), CodeSections.end(), 3422 [](BinarySection *Section) { 3423 return Section->getOutputAddress(); 3424 }), 3425 CodeSections.end()); 3426 LLVM_DEBUG(dbgs() << "Code sections in the order of output:\n"; 3427 for (const BinarySection *Section : CodeSections) 3428 dbgs() << Section->getName() << '\n'; 3429 ); 3430 3431 uint64_t PaddingSize = 0; // size of padding required at the end 3432 3433 // Allocate sections starting at a given Address. 3434 auto allocateAt = [&](uint64_t Address) { 3435 for (BinarySection *Section : CodeSections) { 3436 Address = alignTo(Address, Section->getAlignment()); 3437 Section->setOutputAddress(Address); 3438 Address += Section->getOutputSize(); 3439 } 3440 3441 // Make sure we allocate enough space for huge pages. 3442 if (opts::HotText) { 3443 uint64_t HotTextEnd = 3444 TextSection->getOutputAddress() + TextSection->getOutputSize(); 3445 HotTextEnd = alignTo(HotTextEnd, BC->PageAlign); 3446 if (HotTextEnd > Address) { 3447 PaddingSize = HotTextEnd - Address; 3448 Address = HotTextEnd; 3449 } 3450 } 3451 return Address; 3452 }; 3453 3454 // Check if we can fit code in the original .text 3455 bool AllocationDone = false; 3456 if (opts::UseOldText) { 3457 const uint64_t CodeSize = 3458 allocateAt(BC->OldTextSectionAddress) - BC->OldTextSectionAddress; 3459 3460 if (CodeSize <= BC->OldTextSectionSize) { 3461 outs() << "BOLT-INFO: using original .text for new code with 0x" 3462 << Twine::utohexstr(opts::AlignText) << " alignment\n"; 3463 AllocationDone = true; 3464 } else { 3465 errs() << "BOLT-WARNING: original .text too small to fit the new code" 3466 << " using 0x" << Twine::utohexstr(opts::AlignText) 3467 << " alignment. " << CodeSize << " bytes needed, have " 3468 << BC->OldTextSectionSize << " bytes available.\n"; 3469 opts::UseOldText = false; 3470 } 3471 } 3472 3473 if (!AllocationDone) 3474 NextAvailableAddress = allocateAt(NextAvailableAddress); 3475 3476 // Do the mapping for ORC layer based on the allocation. 3477 for (BinarySection *Section : CodeSections) { 3478 LLVM_DEBUG( 3479 dbgs() << "BOLT: mapping " << Section->getName() << " at 0x" 3480 << Twine::utohexstr(Section->getAllocAddress()) << " to 0x" 3481 << Twine::utohexstr(Section->getOutputAddress()) << '\n'); 3482 RTDyld.reassignSectionAddress(Section->getSectionID(), 3483 Section->getOutputAddress()); 3484 Section->setOutputFileOffset( 3485 getFileOffsetForAddress(Section->getOutputAddress())); 3486 } 3487 3488 // Check if we need to insert a padding section for hot text. 3489 if (PaddingSize && !opts::UseOldText) 3490 outs() << "BOLT-INFO: padding code to 0x" 3491 << Twine::utohexstr(NextAvailableAddress) 3492 << " to accommodate hot text\n"; 3493 3494 return; 3495 } 3496 3497 // Processing in non-relocation mode. 3498 uint64_t NewTextSectionStartAddress = NextAvailableAddress; 3499 3500 for (auto &BFI : BC->getBinaryFunctions()) { 3501 BinaryFunction &Function = BFI.second; 3502 if (!Function.isEmitted()) 3503 continue; 3504 3505 bool TooLarge = false; 3506 ErrorOr<BinarySection &> FuncSection = Function.getCodeSection(); 3507 assert(FuncSection && "cannot find section for function"); 3508 FuncSection->setOutputAddress(Function.getAddress()); 3509 LLVM_DEBUG(dbgs() << "BOLT: mapping 0x" 3510 << Twine::utohexstr(FuncSection->getAllocAddress()) 3511 << " to 0x" << Twine::utohexstr(Function.getAddress()) 3512 << '\n'); 3513 RTDyld.reassignSectionAddress(FuncSection->getSectionID(), 3514 Function.getAddress()); 3515 Function.setImageAddress(FuncSection->getAllocAddress()); 3516 Function.setImageSize(FuncSection->getOutputSize()); 3517 if (Function.getImageSize() > Function.getMaxSize()) { 3518 TooLarge = true; 3519 FailedAddresses.emplace_back(Function.getAddress()); 3520 } 3521 3522 // Map jump tables if updating in-place. 3523 if (opts::JumpTables == JTS_BASIC) { 3524 for (auto &JTI : Function.JumpTables) { 3525 JumpTable *JT = JTI.second; 3526 BinarySection &Section = JT->getOutputSection(); 3527 Section.setOutputAddress(JT->getAddress()); 3528 Section.setOutputFileOffset(getFileOffsetForAddress(JT->getAddress())); 3529 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: mapping " << Section.getName() 3530 << " to 0x" << Twine::utohexstr(JT->getAddress()) 3531 << '\n'); 3532 RTDyld.reassignSectionAddress(Section.getSectionID(), JT->getAddress()); 3533 } 3534 } 3535 3536 if (!Function.isSplit()) 3537 continue; 3538 3539 ErrorOr<BinarySection &> ColdSection = Function.getColdCodeSection(); 3540 assert(ColdSection && "cannot find section for cold part"); 3541 // Cold fragments are aligned at 16 bytes. 3542 NextAvailableAddress = alignTo(NextAvailableAddress, 16); 3543 BinaryFunction::FragmentInfo &ColdPart = Function.cold(); 3544 if (TooLarge) { 3545 // The corresponding FDE will refer to address 0. 3546 ColdPart.setAddress(0); 3547 ColdPart.setImageAddress(0); 3548 ColdPart.setImageSize(0); 3549 ColdPart.setFileOffset(0); 3550 } else { 3551 ColdPart.setAddress(NextAvailableAddress); 3552 ColdPart.setImageAddress(ColdSection->getAllocAddress()); 3553 ColdPart.setImageSize(ColdSection->getOutputSize()); 3554 ColdPart.setFileOffset(getFileOffsetForAddress(NextAvailableAddress)); 3555 ColdSection->setOutputAddress(ColdPart.getAddress()); 3556 } 3557 3558 LLVM_DEBUG(dbgs() << "BOLT: mapping cold fragment 0x" 3559 << Twine::utohexstr(ColdPart.getImageAddress()) 3560 << " to 0x" << Twine::utohexstr(ColdPart.getAddress()) 3561 << " with size " 3562 << Twine::utohexstr(ColdPart.getImageSize()) << '\n'); 3563 RTDyld.reassignSectionAddress(ColdSection->getSectionID(), 3564 ColdPart.getAddress()); 3565 3566 NextAvailableAddress += ColdPart.getImageSize(); 3567 } 3568 3569 // Add the new text section aggregating all existing code sections. 3570 // This is pseudo-section that serves a purpose of creating a corresponding 3571 // entry in section header table. 3572 int64_t NewTextSectionSize = 3573 NextAvailableAddress - NewTextSectionStartAddress; 3574 if (NewTextSectionSize) { 3575 const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/true, 3576 /*IsText=*/true, 3577 /*IsAllocatable=*/true); 3578 BinarySection &Section = 3579 BC->registerOrUpdateSection(getBOLTTextSectionName(), 3580 ELF::SHT_PROGBITS, 3581 Flags, 3582 /*Data=*/nullptr, 3583 NewTextSectionSize, 3584 16); 3585 Section.setOutputAddress(NewTextSectionStartAddress); 3586 Section.setOutputFileOffset( 3587 getFileOffsetForAddress(NewTextSectionStartAddress)); 3588 } 3589 } 3590 3591 void RewriteInstance::mapDataSections(RuntimeDyld &RTDyld) { 3592 // Map special sections to their addresses in the output image. 3593 // These are the sections that we generate via MCStreamer. 3594 // The order is important. 3595 std::vector<std::string> Sections = { 3596 ".eh_frame", Twine(getOrgSecPrefix(), ".eh_frame").str(), 3597 ".gcc_except_table", ".rodata", ".rodata.cold"}; 3598 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary()) 3599 RtLibrary->addRuntimeLibSections(Sections); 3600 3601 for (std::string &SectionName : Sections) { 3602 ErrorOr<BinarySection &> Section = BC->getUniqueSectionByName(SectionName); 3603 if (!Section || !Section->isAllocatable() || !Section->isFinalized()) 3604 continue; 3605 NextAvailableAddress = 3606 alignTo(NextAvailableAddress, Section->getAlignment()); 3607 LLVM_DEBUG(dbgs() << "BOLT: mapping section " << SectionName << " (0x" 3608 << Twine::utohexstr(Section->getAllocAddress()) 3609 << ") to 0x" << Twine::utohexstr(NextAvailableAddress) 3610 << ":0x" 3611 << Twine::utohexstr(NextAvailableAddress + 3612 Section->getOutputSize()) 3613 << '\n'); 3614 3615 RTDyld.reassignSectionAddress(Section->getSectionID(), 3616 NextAvailableAddress); 3617 Section->setOutputAddress(NextAvailableAddress); 3618 Section->setOutputFileOffset(getFileOffsetForAddress(NextAvailableAddress)); 3619 3620 NextAvailableAddress += Section->getOutputSize(); 3621 } 3622 3623 // Handling for sections with relocations. 3624 for (BinarySection &Section : BC->sections()) { 3625 if (!Section.hasSectionRef()) 3626 continue; 3627 3628 StringRef SectionName = Section.getName(); 3629 ErrorOr<BinarySection &> OrgSection = 3630 BC->getUniqueSectionByName((getOrgSecPrefix() + SectionName).str()); 3631 if (!OrgSection || 3632 !OrgSection->isAllocatable() || 3633 !OrgSection->isFinalized() || 3634 !OrgSection->hasValidSectionID()) 3635 continue; 3636 3637 if (OrgSection->getOutputAddress()) { 3638 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: section " << SectionName 3639 << " is already mapped at 0x" 3640 << Twine::utohexstr(OrgSection->getOutputAddress()) 3641 << '\n'); 3642 continue; 3643 } 3644 LLVM_DEBUG( 3645 dbgs() << "BOLT: mapping original section " << SectionName << " (0x" 3646 << Twine::utohexstr(OrgSection->getAllocAddress()) << ") to 0x" 3647 << Twine::utohexstr(Section.getAddress()) << '\n'); 3648 3649 RTDyld.reassignSectionAddress(OrgSection->getSectionID(), 3650 Section.getAddress()); 3651 3652 OrgSection->setOutputAddress(Section.getAddress()); 3653 OrgSection->setOutputFileOffset(Section.getContents().data() - 3654 InputFile->getData().data()); 3655 } 3656 } 3657 3658 void RewriteInstance::mapExtraSections(RuntimeDyld &RTDyld) { 3659 for (BinarySection &Section : BC->allocatableSections()) { 3660 if (Section.getOutputAddress() || !Section.hasValidSectionID()) 3661 continue; 3662 NextAvailableAddress = 3663 alignTo(NextAvailableAddress, Section.getAlignment()); 3664 Section.setOutputAddress(NextAvailableAddress); 3665 NextAvailableAddress += Section.getOutputSize(); 3666 3667 LLVM_DEBUG(dbgs() << "BOLT: (extra) mapping " << Section.getName() 3668 << " at 0x" << Twine::utohexstr(Section.getAllocAddress()) 3669 << " to 0x" 3670 << Twine::utohexstr(Section.getOutputAddress()) << '\n'); 3671 3672 RTDyld.reassignSectionAddress(Section.getSectionID(), 3673 Section.getOutputAddress()); 3674 Section.setOutputFileOffset( 3675 getFileOffsetForAddress(Section.getOutputAddress())); 3676 } 3677 } 3678 3679 void RewriteInstance::updateOutputValues(const MCAsmLayout &Layout) { 3680 for (BinaryFunction *Function : BC->getAllBinaryFunctions()) 3681 Function->updateOutputValues(Layout); 3682 } 3683 3684 void RewriteInstance::patchELFPHDRTable() { 3685 auto ELF64LEFile = dyn_cast<ELF64LEObjectFile>(InputFile); 3686 if (!ELF64LEFile) { 3687 errs() << "BOLT-ERROR: only 64-bit LE ELF binaries are supported\n"; 3688 exit(1); 3689 } 3690 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile(); 3691 raw_fd_ostream &OS = Out->os(); 3692 3693 // Write/re-write program headers. 3694 Phnum = Obj.getHeader().e_phnum; 3695 if (PHDRTableOffset) { 3696 // Writing new pheader table. 3697 Phnum += 1; // only adding one new segment 3698 // Segment size includes the size of the PHDR area. 3699 NewTextSegmentSize = NextAvailableAddress - PHDRTableAddress; 3700 } else { 3701 assert(!PHDRTableAddress && "unexpected address for program header table"); 3702 // Update existing table. 3703 PHDRTableOffset = Obj.getHeader().e_phoff; 3704 NewTextSegmentSize = NextAvailableAddress - NewTextSegmentAddress; 3705 } 3706 OS.seek(PHDRTableOffset); 3707 3708 bool ModdedGnuStack = false; 3709 (void)ModdedGnuStack; 3710 bool AddedSegment = false; 3711 (void)AddedSegment; 3712 3713 auto createNewTextPhdr = [&]() { 3714 ELF64LEPhdrTy NewPhdr; 3715 NewPhdr.p_type = ELF::PT_LOAD; 3716 if (PHDRTableAddress) { 3717 NewPhdr.p_offset = PHDRTableOffset; 3718 NewPhdr.p_vaddr = PHDRTableAddress; 3719 NewPhdr.p_paddr = PHDRTableAddress; 3720 } else { 3721 NewPhdr.p_offset = NewTextSegmentOffset; 3722 NewPhdr.p_vaddr = NewTextSegmentAddress; 3723 NewPhdr.p_paddr = NewTextSegmentAddress; 3724 } 3725 NewPhdr.p_filesz = NewTextSegmentSize; 3726 NewPhdr.p_memsz = NewTextSegmentSize; 3727 NewPhdr.p_flags = ELF::PF_X | ELF::PF_R; 3728 // FIXME: Currently instrumentation is experimental and the runtime data 3729 // is emitted with code, thus everything needs to be writable 3730 if (opts::Instrument) 3731 NewPhdr.p_flags |= ELF::PF_W; 3732 NewPhdr.p_align = BC->PageAlign; 3733 3734 return NewPhdr; 3735 }; 3736 3737 // Copy existing program headers with modifications. 3738 for (const ELF64LE::Phdr &Phdr : cantFail(Obj.program_headers())) { 3739 ELF64LE::Phdr NewPhdr = Phdr; 3740 if (PHDRTableAddress && Phdr.p_type == ELF::PT_PHDR) { 3741 NewPhdr.p_offset = PHDRTableOffset; 3742 NewPhdr.p_vaddr = PHDRTableAddress; 3743 NewPhdr.p_paddr = PHDRTableAddress; 3744 NewPhdr.p_filesz = sizeof(NewPhdr) * Phnum; 3745 NewPhdr.p_memsz = sizeof(NewPhdr) * Phnum; 3746 } else if (Phdr.p_type == ELF::PT_GNU_EH_FRAME) { 3747 ErrorOr<BinarySection &> EHFrameHdrSec = 3748 BC->getUniqueSectionByName(".eh_frame_hdr"); 3749 if (EHFrameHdrSec && EHFrameHdrSec->isAllocatable() && 3750 EHFrameHdrSec->isFinalized()) { 3751 NewPhdr.p_offset = EHFrameHdrSec->getOutputFileOffset(); 3752 NewPhdr.p_vaddr = EHFrameHdrSec->getOutputAddress(); 3753 NewPhdr.p_paddr = EHFrameHdrSec->getOutputAddress(); 3754 NewPhdr.p_filesz = EHFrameHdrSec->getOutputSize(); 3755 NewPhdr.p_memsz = EHFrameHdrSec->getOutputSize(); 3756 } 3757 } else if (opts::UseGnuStack && Phdr.p_type == ELF::PT_GNU_STACK) { 3758 NewPhdr = createNewTextPhdr(); 3759 ModdedGnuStack = true; 3760 } else if (!opts::UseGnuStack && Phdr.p_type == ELF::PT_DYNAMIC) { 3761 // Insert the new header before DYNAMIC. 3762 ELF64LE::Phdr NewTextPhdr = createNewTextPhdr(); 3763 OS.write(reinterpret_cast<const char *>(&NewTextPhdr), 3764 sizeof(NewTextPhdr)); 3765 AddedSegment = true; 3766 } 3767 OS.write(reinterpret_cast<const char *>(&NewPhdr), sizeof(NewPhdr)); 3768 } 3769 3770 if (!opts::UseGnuStack && !AddedSegment) { 3771 // Append the new header to the end of the table. 3772 ELF64LE::Phdr NewTextPhdr = createNewTextPhdr(); 3773 OS.write(reinterpret_cast<const char *>(&NewTextPhdr), sizeof(NewTextPhdr)); 3774 } 3775 3776 assert((!opts::UseGnuStack || ModdedGnuStack) && 3777 "could not find GNU_STACK program header to modify"); 3778 } 3779 3780 namespace { 3781 3782 /// Write padding to \p OS such that its current \p Offset becomes aligned 3783 /// at \p Alignment. Return new (aligned) offset. 3784 uint64_t appendPadding(raw_pwrite_stream &OS, uint64_t Offset, 3785 uint64_t Alignment) { 3786 if (!Alignment) 3787 return Offset; 3788 3789 const uint64_t PaddingSize = 3790 offsetToAlignment(Offset, llvm::Align(Alignment)); 3791 for (unsigned I = 0; I < PaddingSize; ++I) 3792 OS.write((unsigned char)0); 3793 return Offset + PaddingSize; 3794 } 3795 3796 } 3797 3798 void RewriteInstance::rewriteNoteSections() { 3799 auto ELF64LEFile = dyn_cast<ELF64LEObjectFile>(InputFile); 3800 if (!ELF64LEFile) { 3801 errs() << "BOLT-ERROR: only 64-bit LE ELF binaries are supported\n"; 3802 exit(1); 3803 } 3804 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile(); 3805 raw_fd_ostream &OS = Out->os(); 3806 3807 uint64_t NextAvailableOffset = getFileOffsetForAddress(NextAvailableAddress); 3808 assert(NextAvailableOffset >= FirstNonAllocatableOffset && 3809 "next available offset calculation failure"); 3810 OS.seek(NextAvailableOffset); 3811 3812 // Copy over non-allocatable section contents and update file offsets. 3813 for (const ELF64LE::Shdr &Section : cantFail(Obj.sections())) { 3814 if (Section.sh_type == ELF::SHT_NULL) 3815 continue; 3816 if (Section.sh_flags & ELF::SHF_ALLOC) 3817 continue; 3818 3819 StringRef SectionName = 3820 cantFail(Obj.getSectionName(Section), "cannot get section name"); 3821 ErrorOr<BinarySection &> BSec = BC->getUniqueSectionByName(SectionName); 3822 3823 if (shouldStrip(Section, SectionName)) 3824 continue; 3825 3826 // Insert padding as needed. 3827 NextAvailableOffset = 3828 appendPadding(OS, NextAvailableOffset, Section.sh_addralign); 3829 3830 // New section size. 3831 uint64_t Size = 0; 3832 bool DataWritten = false; 3833 uint8_t *SectionData = nullptr; 3834 // Copy over section contents unless it's one of the sections we overwrite. 3835 if (!willOverwriteSection(SectionName)) { 3836 Size = Section.sh_size; 3837 StringRef Dataref = InputFile->getData().substr(Section.sh_offset, Size); 3838 std::string Data; 3839 if (BSec && BSec->getPatcher()) { 3840 Data = BSec->getPatcher()->patchBinary(Dataref); 3841 Dataref = StringRef(Data); 3842 } 3843 3844 // Section was expanded, so need to treat it as overwrite. 3845 if (Size != Dataref.size()) { 3846 BSec = BC->registerOrUpdateNoteSection( 3847 SectionName, copyByteArray(Dataref), Dataref.size()); 3848 Size = 0; 3849 } else { 3850 OS << Dataref; 3851 DataWritten = true; 3852 3853 // Add padding as the section extension might rely on the alignment. 3854 Size = appendPadding(OS, Size, Section.sh_addralign); 3855 } 3856 } 3857 3858 // Perform section post-processing. 3859 if (BSec && !BSec->isAllocatable()) { 3860 assert(BSec->getAlignment() <= Section.sh_addralign && 3861 "alignment exceeds value in file"); 3862 3863 if (BSec->getAllocAddress()) { 3864 assert(!DataWritten && "Writing section twice."); 3865 SectionData = BSec->getOutputData(); 3866 3867 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: " << (Size ? "appending" : "writing") 3868 << " contents to section " << SectionName << '\n'); 3869 OS.write(reinterpret_cast<char *>(SectionData), BSec->getOutputSize()); 3870 Size += BSec->getOutputSize(); 3871 } 3872 3873 BSec->setOutputFileOffset(NextAvailableOffset); 3874 BSec->flushPendingRelocations(OS, 3875 [this] (const MCSymbol *S) { 3876 return getNewValueForSymbol(S->getName()); 3877 }); 3878 } 3879 3880 // Set/modify section info. 3881 BinarySection &NewSection = 3882 BC->registerOrUpdateNoteSection(SectionName, 3883 SectionData, 3884 Size, 3885 Section.sh_addralign, 3886 BSec ? BSec->isReadOnly() : false, 3887 BSec ? BSec->getELFType() 3888 : ELF::SHT_PROGBITS); 3889 NewSection.setOutputAddress(0); 3890 NewSection.setOutputFileOffset(NextAvailableOffset); 3891 3892 NextAvailableOffset += Size; 3893 } 3894 3895 // Write new note sections. 3896 for (BinarySection &Section : BC->nonAllocatableSections()) { 3897 if (Section.getOutputFileOffset() || !Section.getAllocAddress()) 3898 continue; 3899 3900 assert(!Section.hasPendingRelocations() && "cannot have pending relocs"); 3901 3902 NextAvailableOffset = 3903 appendPadding(OS, NextAvailableOffset, Section.getAlignment()); 3904 Section.setOutputFileOffset(NextAvailableOffset); 3905 3906 LLVM_DEBUG( 3907 dbgs() << "BOLT-DEBUG: writing out new section " << Section.getName() 3908 << " of size " << Section.getOutputSize() << " at offset 0x" 3909 << Twine::utohexstr(Section.getOutputFileOffset()) << '\n'); 3910 3911 OS.write(Section.getOutputContents().data(), Section.getOutputSize()); 3912 NextAvailableOffset += Section.getOutputSize(); 3913 } 3914 } 3915 3916 template <typename ELFT> 3917 void RewriteInstance::finalizeSectionStringTable(ELFObjectFile<ELFT> *File) { 3918 using ELFShdrTy = typename ELFT::Shdr; 3919 const ELFFile<ELFT> &Obj = File->getELFFile(); 3920 3921 // Pre-populate section header string table. 3922 for (const ELFShdrTy &Section : cantFail(Obj.sections())) { 3923 StringRef SectionName = 3924 cantFail(Obj.getSectionName(Section), "cannot get section name"); 3925 SHStrTab.add(SectionName); 3926 std::string OutputSectionName = getOutputSectionName(Obj, Section); 3927 if (OutputSectionName != SectionName) 3928 SHStrTabPool.emplace_back(std::move(OutputSectionName)); 3929 } 3930 for (const std::string &Str : SHStrTabPool) 3931 SHStrTab.add(Str); 3932 for (const BinarySection &Section : BC->sections()) 3933 SHStrTab.add(Section.getName()); 3934 SHStrTab.finalize(); 3935 3936 const size_t SHStrTabSize = SHStrTab.getSize(); 3937 uint8_t *DataCopy = new uint8_t[SHStrTabSize]; 3938 memset(DataCopy, 0, SHStrTabSize); 3939 SHStrTab.write(DataCopy); 3940 BC->registerOrUpdateNoteSection(".shstrtab", 3941 DataCopy, 3942 SHStrTabSize, 3943 /*Alignment=*/1, 3944 /*IsReadOnly=*/true, 3945 ELF::SHT_STRTAB); 3946 } 3947 3948 void RewriteInstance::addBoltInfoSection() { 3949 std::string DescStr; 3950 raw_string_ostream DescOS(DescStr); 3951 3952 DescOS << "BOLT revision: " << BoltRevision << ", " 3953 << "command line:"; 3954 for (int I = 0; I < Argc; ++I) 3955 DescOS << " " << Argv[I]; 3956 DescOS.flush(); 3957 3958 // Encode as GNU GOLD VERSION so it is easily printable by 'readelf -n' 3959 const std::string BoltInfo = 3960 BinarySection::encodeELFNote("GNU", DescStr, 4 /*NT_GNU_GOLD_VERSION*/); 3961 BC->registerOrUpdateNoteSection(".note.bolt_info", copyByteArray(BoltInfo), 3962 BoltInfo.size(), 3963 /*Alignment=*/1, 3964 /*IsReadOnly=*/true, ELF::SHT_NOTE); 3965 } 3966 3967 void RewriteInstance::addBATSection() { 3968 BC->registerOrUpdateNoteSection(BoltAddressTranslation::SECTION_NAME, nullptr, 3969 0, 3970 /*Alignment=*/1, 3971 /*IsReadOnly=*/true, ELF::SHT_NOTE); 3972 } 3973 3974 void RewriteInstance::encodeBATSection() { 3975 std::string DescStr; 3976 raw_string_ostream DescOS(DescStr); 3977 3978 BAT->write(DescOS); 3979 DescOS.flush(); 3980 3981 const std::string BoltInfo = 3982 BinarySection::encodeELFNote("BOLT", DescStr, BinarySection::NT_BOLT_BAT); 3983 BC->registerOrUpdateNoteSection(BoltAddressTranslation::SECTION_NAME, 3984 copyByteArray(BoltInfo), BoltInfo.size(), 3985 /*Alignment=*/1, 3986 /*IsReadOnly=*/true, ELF::SHT_NOTE); 3987 } 3988 3989 template <typename ELFObjType, typename ELFShdrTy> 3990 std::string RewriteInstance::getOutputSectionName(const ELFObjType &Obj, 3991 const ELFShdrTy &Section) { 3992 if (Section.sh_type == ELF::SHT_NULL) 3993 return ""; 3994 3995 StringRef SectionName = 3996 cantFail(Obj.getSectionName(Section), "cannot get section name"); 3997 3998 if ((Section.sh_flags & ELF::SHF_ALLOC) && willOverwriteSection(SectionName)) 3999 return (getOrgSecPrefix() + SectionName).str(); 4000 4001 return std::string(SectionName); 4002 } 4003 4004 template <typename ELFShdrTy> 4005 bool RewriteInstance::shouldStrip(const ELFShdrTy &Section, 4006 StringRef SectionName) { 4007 // Strip non-allocatable relocation sections. 4008 if (!(Section.sh_flags & ELF::SHF_ALLOC) && Section.sh_type == ELF::SHT_RELA) 4009 return true; 4010 4011 // Strip debug sections if not updating them. 4012 if (isDebugSection(SectionName) && !opts::UpdateDebugSections) 4013 return true; 4014 4015 // Strip symtab section if needed 4016 if (opts::RemoveSymtab && Section.sh_type == ELF::SHT_SYMTAB) 4017 return true; 4018 4019 return false; 4020 } 4021 4022 template <typename ELFT, typename ELFShdrTy> 4023 std::vector<ELFShdrTy> 4024 RewriteInstance::getOutputSections(ELFObjectFile<ELFT> *File, 4025 std::vector<uint32_t> &NewSectionIndex) { 4026 const ELFFile<ELFT> &Obj = File->getELFFile(); 4027 typename ELFT::ShdrRange Sections = cantFail(Obj.sections()); 4028 4029 // Keep track of section header entries together with their name. 4030 std::vector<std::pair<std::string, ELFShdrTy>> OutputSections; 4031 auto addSection = [&](const std::string &Name, const ELFShdrTy &Section) { 4032 ELFShdrTy NewSection = Section; 4033 NewSection.sh_name = SHStrTab.getOffset(Name); 4034 OutputSections.emplace_back(Name, std::move(NewSection)); 4035 }; 4036 4037 // Copy over entries for original allocatable sections using modified name. 4038 for (const ELFShdrTy &Section : Sections) { 4039 // Always ignore this section. 4040 if (Section.sh_type == ELF::SHT_NULL) { 4041 OutputSections.emplace_back("", Section); 4042 continue; 4043 } 4044 4045 if (!(Section.sh_flags & ELF::SHF_ALLOC)) 4046 continue; 4047 4048 addSection(getOutputSectionName(Obj, Section), Section); 4049 } 4050 4051 for (const BinarySection &Section : BC->allocatableSections()) { 4052 if (!Section.isFinalized()) 4053 continue; 4054 4055 if (Section.getName().startswith(getOrgSecPrefix()) || 4056 Section.isAnonymous()) { 4057 if (opts::Verbosity) 4058 outs() << "BOLT-INFO: not writing section header for section " 4059 << Section.getName() << '\n'; 4060 continue; 4061 } 4062 4063 if (opts::Verbosity >= 1) 4064 outs() << "BOLT-INFO: writing section header for " << Section.getName() 4065 << '\n'; 4066 ELFShdrTy NewSection; 4067 NewSection.sh_type = ELF::SHT_PROGBITS; 4068 NewSection.sh_addr = Section.getOutputAddress(); 4069 NewSection.sh_offset = Section.getOutputFileOffset(); 4070 NewSection.sh_size = Section.getOutputSize(); 4071 NewSection.sh_entsize = 0; 4072 NewSection.sh_flags = Section.getELFFlags(); 4073 NewSection.sh_link = 0; 4074 NewSection.sh_info = 0; 4075 NewSection.sh_addralign = Section.getAlignment(); 4076 addSection(std::string(Section.getName()), NewSection); 4077 } 4078 4079 // Sort all allocatable sections by their offset. 4080 std::stable_sort(OutputSections.begin(), OutputSections.end(), 4081 [] (const std::pair<std::string, ELFShdrTy> &A, 4082 const std::pair<std::string, ELFShdrTy> &B) { 4083 return A.second.sh_offset < B.second.sh_offset; 4084 }); 4085 4086 // Fix section sizes to prevent overlapping. 4087 ELFShdrTy *PrevSection = nullptr; 4088 StringRef PrevSectionName; 4089 for (auto &SectionKV : OutputSections) { 4090 ELFShdrTy &Section = SectionKV.second; 4091 4092 // TBSS section does not take file or memory space. Ignore it for layout 4093 // purposes. 4094 if (Section.sh_type == ELF::SHT_NOBITS && (Section.sh_flags & ELF::SHF_TLS)) 4095 continue; 4096 4097 if (PrevSection && 4098 PrevSection->sh_addr + PrevSection->sh_size > Section.sh_addr) { 4099 if (opts::Verbosity > 1) 4100 outs() << "BOLT-INFO: adjusting size for section " << PrevSectionName 4101 << '\n'; 4102 PrevSection->sh_size = Section.sh_addr > PrevSection->sh_addr 4103 ? Section.sh_addr - PrevSection->sh_addr 4104 : 0; 4105 } 4106 4107 PrevSection = &Section; 4108 PrevSectionName = SectionKV.first; 4109 } 4110 4111 uint64_t LastFileOffset = 0; 4112 4113 // Copy over entries for non-allocatable sections performing necessary 4114 // adjustments. 4115 for (const ELFShdrTy &Section : Sections) { 4116 if (Section.sh_type == ELF::SHT_NULL) 4117 continue; 4118 if (Section.sh_flags & ELF::SHF_ALLOC) 4119 continue; 4120 4121 StringRef SectionName = 4122 cantFail(Obj.getSectionName(Section), "cannot get section name"); 4123 4124 if (shouldStrip(Section, SectionName)) 4125 continue; 4126 4127 ErrorOr<BinarySection &> BSec = BC->getUniqueSectionByName(SectionName); 4128 assert(BSec && "missing section info for non-allocatable section"); 4129 4130 ELFShdrTy NewSection = Section; 4131 NewSection.sh_offset = BSec->getOutputFileOffset(); 4132 NewSection.sh_size = BSec->getOutputSize(); 4133 4134 if (NewSection.sh_type == ELF::SHT_SYMTAB) 4135 NewSection.sh_info = NumLocalSymbols; 4136 4137 addSection(std::string(SectionName), NewSection); 4138 4139 LastFileOffset = BSec->getOutputFileOffset(); 4140 } 4141 4142 // Create entries for new non-allocatable sections. 4143 for (BinarySection &Section : BC->nonAllocatableSections()) { 4144 if (Section.getOutputFileOffset() <= LastFileOffset) 4145 continue; 4146 4147 if (opts::Verbosity >= 1) 4148 outs() << "BOLT-INFO: writing section header for " << Section.getName() 4149 << '\n'; 4150 4151 ELFShdrTy NewSection; 4152 NewSection.sh_type = Section.getELFType(); 4153 NewSection.sh_addr = 0; 4154 NewSection.sh_offset = Section.getOutputFileOffset(); 4155 NewSection.sh_size = Section.getOutputSize(); 4156 NewSection.sh_entsize = 0; 4157 NewSection.sh_flags = Section.getELFFlags(); 4158 NewSection.sh_link = 0; 4159 NewSection.sh_info = 0; 4160 NewSection.sh_addralign = Section.getAlignment(); 4161 4162 addSection(std::string(Section.getName()), NewSection); 4163 } 4164 4165 // Assign indices to sections. 4166 std::unordered_map<std::string, uint64_t> NameToIndex; 4167 for (uint32_t Index = 1; Index < OutputSections.size(); ++Index) { 4168 const std::string &SectionName = OutputSections[Index].first; 4169 NameToIndex[SectionName] = Index; 4170 if (ErrorOr<BinarySection &> Section = 4171 BC->getUniqueSectionByName(SectionName)) 4172 Section->setIndex(Index); 4173 } 4174 4175 // Update section index mapping 4176 NewSectionIndex.clear(); 4177 NewSectionIndex.resize(Sections.size(), 0); 4178 for (const ELFShdrTy &Section : Sections) { 4179 if (Section.sh_type == ELF::SHT_NULL) 4180 continue; 4181 4182 size_t OrgIndex = std::distance(Sections.begin(), &Section); 4183 std::string SectionName = getOutputSectionName(Obj, Section); 4184 4185 // Some sections are stripped 4186 if (!NameToIndex.count(SectionName)) 4187 continue; 4188 4189 NewSectionIndex[OrgIndex] = NameToIndex[SectionName]; 4190 } 4191 4192 std::vector<ELFShdrTy> SectionsOnly(OutputSections.size()); 4193 std::transform(OutputSections.begin(), OutputSections.end(), 4194 SectionsOnly.begin(), 4195 [](std::pair<std::string, ELFShdrTy> &SectionInfo) { 4196 return SectionInfo.second; 4197 }); 4198 4199 return SectionsOnly; 4200 } 4201 4202 // Rewrite section header table inserting new entries as needed. The sections 4203 // header table size itself may affect the offsets of other sections, 4204 // so we are placing it at the end of the binary. 4205 // 4206 // As we rewrite entries we need to track how many sections were inserted 4207 // as it changes the sh_link value. We map old indices to new ones for 4208 // existing sections. 4209 template <typename ELFT> 4210 void RewriteInstance::patchELFSectionHeaderTable(ELFObjectFile<ELFT> *File) { 4211 using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr; 4212 using ELFEhdrTy = typename ELFObjectFile<ELFT>::Elf_Ehdr; 4213 raw_fd_ostream &OS = Out->os(); 4214 const ELFFile<ELFT> &Obj = File->getELFFile(); 4215 4216 std::vector<uint32_t> NewSectionIndex; 4217 std::vector<ELFShdrTy> OutputSections = 4218 getOutputSections(File, NewSectionIndex); 4219 LLVM_DEBUG( 4220 dbgs() << "BOLT-DEBUG: old to new section index mapping:\n"; 4221 for (uint64_t I = 0; I < NewSectionIndex.size(); ++I) 4222 dbgs() << " " << I << " -> " << NewSectionIndex[I] << '\n'; 4223 ); 4224 4225 // Align starting address for section header table. 4226 uint64_t SHTOffset = OS.tell(); 4227 SHTOffset = appendPadding(OS, SHTOffset, sizeof(ELFShdrTy)); 4228 4229 // Write all section header entries while patching section references. 4230 for (ELFShdrTy &Section : OutputSections) { 4231 Section.sh_link = NewSectionIndex[Section.sh_link]; 4232 if (Section.sh_type == ELF::SHT_REL || Section.sh_type == ELF::SHT_RELA) { 4233 if (Section.sh_info) 4234 Section.sh_info = NewSectionIndex[Section.sh_info]; 4235 } 4236 OS.write(reinterpret_cast<const char *>(&Section), sizeof(Section)); 4237 } 4238 4239 // Fix ELF header. 4240 ELFEhdrTy NewEhdr = Obj.getHeader(); 4241 4242 if (BC->HasRelocations) { 4243 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary()) 4244 NewEhdr.e_entry = RtLibrary->getRuntimeStartAddress(); 4245 else 4246 NewEhdr.e_entry = getNewFunctionAddress(NewEhdr.e_entry); 4247 assert((NewEhdr.e_entry || !Obj.getHeader().e_entry) && 4248 "cannot find new address for entry point"); 4249 } 4250 NewEhdr.e_phoff = PHDRTableOffset; 4251 NewEhdr.e_phnum = Phnum; 4252 NewEhdr.e_shoff = SHTOffset; 4253 NewEhdr.e_shnum = OutputSections.size(); 4254 NewEhdr.e_shstrndx = NewSectionIndex[NewEhdr.e_shstrndx]; 4255 OS.pwrite(reinterpret_cast<const char *>(&NewEhdr), sizeof(NewEhdr), 0); 4256 } 4257 4258 template <typename ELFT, typename ELFShdrTy, typename WriteFuncTy, 4259 typename StrTabFuncTy> 4260 void RewriteInstance::updateELFSymbolTable( 4261 ELFObjectFile<ELFT> *File, 4262 bool IsDynSym, 4263 const ELFShdrTy &SymTabSection, 4264 const std::vector<uint32_t> &NewSectionIndex, 4265 WriteFuncTy Write, 4266 StrTabFuncTy AddToStrTab) { 4267 const ELFFile<ELFT> &Obj = File->getELFFile(); 4268 using ELFSymTy = typename ELFObjectFile<ELFT>::Elf_Sym; 4269 4270 StringRef StringSection = 4271 cantFail(Obj.getStringTableForSymtab(SymTabSection)); 4272 4273 unsigned NumHotTextSymsUpdated = 0; 4274 unsigned NumHotDataSymsUpdated = 0; 4275 4276 std::map<const BinaryFunction *, uint64_t> IslandSizes; 4277 auto getConstantIslandSize = [&IslandSizes](const BinaryFunction &BF) { 4278 auto Itr = IslandSizes.find(&BF); 4279 if (Itr != IslandSizes.end()) 4280 return Itr->second; 4281 return IslandSizes[&BF] = BF.estimateConstantIslandSize(); 4282 }; 4283 4284 // Symbols for the new symbol table. 4285 std::vector<ELFSymTy> Symbols; 4286 4287 auto getNewSectionIndex = [&](uint32_t OldIndex) { 4288 assert(OldIndex < NewSectionIndex.size() && "section index out of bounds"); 4289 const uint32_t NewIndex = NewSectionIndex[OldIndex]; 4290 4291 // We may have stripped the section that dynsym was referencing due to 4292 // the linker bug. In that case return the old index avoiding marking 4293 // the symbol as undefined. 4294 if (IsDynSym && NewIndex != OldIndex && NewIndex == ELF::SHN_UNDEF) 4295 return OldIndex; 4296 return NewIndex; 4297 }; 4298 4299 // Add extra symbols for the function. 4300 // 4301 // Note that addExtraSymbols() could be called multiple times for the same 4302 // function with different FunctionSymbol matching the main function entry 4303 // point. 4304 auto addExtraSymbols = [&](const BinaryFunction &Function, 4305 const ELFSymTy &FunctionSymbol) { 4306 if (Function.isFolded()) { 4307 BinaryFunction *ICFParent = Function.getFoldedIntoFunction(); 4308 while (ICFParent->isFolded()) 4309 ICFParent = ICFParent->getFoldedIntoFunction(); 4310 ELFSymTy ICFSymbol = FunctionSymbol; 4311 SmallVector<char, 256> Buf; 4312 ICFSymbol.st_name = 4313 AddToStrTab(Twine(cantFail(FunctionSymbol.getName(StringSection))) 4314 .concat(".icf.0") 4315 .toStringRef(Buf)); 4316 ICFSymbol.st_value = ICFParent->getOutputAddress(); 4317 ICFSymbol.st_size = ICFParent->getOutputSize(); 4318 ICFSymbol.st_shndx = ICFParent->getCodeSection()->getIndex(); 4319 Symbols.emplace_back(ICFSymbol); 4320 } 4321 if (Function.isSplit() && Function.cold().getAddress()) { 4322 ELFSymTy NewColdSym = FunctionSymbol; 4323 SmallVector<char, 256> Buf; 4324 NewColdSym.st_name = 4325 AddToStrTab(Twine(cantFail(FunctionSymbol.getName(StringSection))) 4326 .concat(".cold.0") 4327 .toStringRef(Buf)); 4328 NewColdSym.st_shndx = Function.getColdCodeSection()->getIndex(); 4329 NewColdSym.st_value = Function.cold().getAddress(); 4330 NewColdSym.st_size = Function.cold().getImageSize(); 4331 NewColdSym.setBindingAndType(ELF::STB_LOCAL, ELF::STT_FUNC); 4332 Symbols.emplace_back(NewColdSym); 4333 } 4334 if (Function.hasConstantIsland()) { 4335 uint64_t DataMark = Function.getOutputDataAddress(); 4336 uint64_t CISize = getConstantIslandSize(Function); 4337 uint64_t CodeMark = DataMark + CISize; 4338 ELFSymTy DataMarkSym = FunctionSymbol; 4339 DataMarkSym.st_name = AddToStrTab("$d"); 4340 DataMarkSym.st_value = DataMark; 4341 DataMarkSym.st_size = 0; 4342 DataMarkSym.setType(ELF::STT_NOTYPE); 4343 DataMarkSym.setBinding(ELF::STB_LOCAL); 4344 ELFSymTy CodeMarkSym = DataMarkSym; 4345 CodeMarkSym.st_name = AddToStrTab("$x"); 4346 CodeMarkSym.st_value = CodeMark; 4347 Symbols.emplace_back(DataMarkSym); 4348 Symbols.emplace_back(CodeMarkSym); 4349 } 4350 if (Function.hasConstantIsland() && Function.isSplit()) { 4351 uint64_t DataMark = Function.getOutputColdDataAddress(); 4352 uint64_t CISize = getConstantIslandSize(Function); 4353 uint64_t CodeMark = DataMark + CISize; 4354 ELFSymTy DataMarkSym = FunctionSymbol; 4355 DataMarkSym.st_name = AddToStrTab("$d"); 4356 DataMarkSym.st_value = DataMark; 4357 DataMarkSym.st_size = 0; 4358 DataMarkSym.setType(ELF::STT_NOTYPE); 4359 DataMarkSym.setBinding(ELF::STB_LOCAL); 4360 ELFSymTy CodeMarkSym = DataMarkSym; 4361 CodeMarkSym.st_name = AddToStrTab("$x"); 4362 CodeMarkSym.st_value = CodeMark; 4363 Symbols.emplace_back(DataMarkSym); 4364 Symbols.emplace_back(CodeMarkSym); 4365 } 4366 }; 4367 4368 // For regular (non-dynamic) symbol table, exclude symbols referring 4369 // to non-allocatable sections. 4370 auto shouldStrip = [&](const ELFSymTy &Symbol) { 4371 if (Symbol.isAbsolute() || !Symbol.isDefined()) 4372 return false; 4373 4374 // If we cannot link the symbol to a section, leave it as is. 4375 Expected<const typename ELFT::Shdr *> Section = 4376 Obj.getSection(Symbol.st_shndx); 4377 if (!Section) 4378 return false; 4379 4380 // Remove the section symbol iif the corresponding section was stripped. 4381 if (Symbol.getType() == ELF::STT_SECTION) { 4382 if (!getNewSectionIndex(Symbol.st_shndx)) 4383 return true; 4384 return false; 4385 } 4386 4387 // Symbols in non-allocatable sections are typically remnants of relocations 4388 // emitted under "-emit-relocs" linker option. Delete those as we delete 4389 // relocations against non-allocatable sections. 4390 if (!((*Section)->sh_flags & ELF::SHF_ALLOC)) 4391 return true; 4392 4393 return false; 4394 }; 4395 4396 for (const ELFSymTy &Symbol : cantFail(Obj.symbols(&SymTabSection))) { 4397 // For regular (non-dynamic) symbol table strip unneeded symbols. 4398 if (!IsDynSym && shouldStrip(Symbol)) 4399 continue; 4400 4401 const BinaryFunction *Function = 4402 BC->getBinaryFunctionAtAddress(Symbol.st_value); 4403 // Ignore false function references, e.g. when the section address matches 4404 // the address of the function. 4405 if (Function && Symbol.getType() == ELF::STT_SECTION) 4406 Function = nullptr; 4407 4408 // For non-dynamic symtab, make sure the symbol section matches that of 4409 // the function. It can mismatch e.g. if the symbol is a section marker 4410 // in which case we treat the symbol separately from the function. 4411 // For dynamic symbol table, the section index could be wrong on the input, 4412 // and its value is ignored by the runtime if it's different from 4413 // SHN_UNDEF and SHN_ABS. 4414 if (!IsDynSym && Function && 4415 Symbol.st_shndx != 4416 Function->getOriginSection()->getSectionRef().getIndex()) 4417 Function = nullptr; 4418 4419 // Create a new symbol based on the existing symbol. 4420 ELFSymTy NewSymbol = Symbol; 4421 4422 if (Function) { 4423 // If the symbol matched a function that was not emitted, update the 4424 // corresponding section index but otherwise leave it unchanged. 4425 if (Function->isEmitted()) { 4426 NewSymbol.st_value = Function->getOutputAddress(); 4427 NewSymbol.st_size = Function->getOutputSize(); 4428 NewSymbol.st_shndx = Function->getCodeSection()->getIndex(); 4429 } else if (Symbol.st_shndx < ELF::SHN_LORESERVE) { 4430 NewSymbol.st_shndx = getNewSectionIndex(Symbol.st_shndx); 4431 } 4432 4433 // Add new symbols to the symbol table if necessary. 4434 if (!IsDynSym) 4435 addExtraSymbols(*Function, NewSymbol); 4436 } else { 4437 // Check if the function symbol matches address inside a function, i.e. 4438 // it marks a secondary entry point. 4439 Function = 4440 (Symbol.getType() == ELF::STT_FUNC) 4441 ? BC->getBinaryFunctionContainingAddress(Symbol.st_value, 4442 /*CheckPastEnd=*/false, 4443 /*UseMaxSize=*/true) 4444 : nullptr; 4445 4446 if (Function && Function->isEmitted()) { 4447 const uint64_t OutputAddress = 4448 Function->translateInputToOutputAddress(Symbol.st_value); 4449 4450 NewSymbol.st_value = OutputAddress; 4451 // Force secondary entry points to have zero size. 4452 NewSymbol.st_size = 0; 4453 NewSymbol.st_shndx = 4454 OutputAddress >= Function->cold().getAddress() && 4455 OutputAddress < Function->cold().getImageSize() 4456 ? Function->getColdCodeSection()->getIndex() 4457 : Function->getCodeSection()->getIndex(); 4458 } else { 4459 // Check if the symbol belongs to moved data object and update it. 4460 BinaryData *BD = opts::ReorderData.empty() 4461 ? nullptr 4462 : BC->getBinaryDataAtAddress(Symbol.st_value); 4463 if (BD && BD->isMoved() && !BD->isJumpTable()) { 4464 assert((!BD->getSize() || !Symbol.st_size || 4465 Symbol.st_size == BD->getSize()) && 4466 "sizes must match"); 4467 4468 BinarySection &OutputSection = BD->getOutputSection(); 4469 assert(OutputSection.getIndex()); 4470 LLVM_DEBUG(dbgs() 4471 << "BOLT-DEBUG: moving " << BD->getName() << " from " 4472 << *BC->getSectionNameForAddress(Symbol.st_value) << " (" 4473 << Symbol.st_shndx << ") to " << OutputSection.getName() 4474 << " (" << OutputSection.getIndex() << ")\n"); 4475 NewSymbol.st_shndx = OutputSection.getIndex(); 4476 NewSymbol.st_value = BD->getOutputAddress(); 4477 } else { 4478 // Otherwise just update the section for the symbol. 4479 if (Symbol.st_shndx < ELF::SHN_LORESERVE) 4480 NewSymbol.st_shndx = getNewSectionIndex(Symbol.st_shndx); 4481 } 4482 4483 // Detect local syms in the text section that we didn't update 4484 // and that were preserved by the linker to support relocations against 4485 // .text. Remove them from the symtab. 4486 if (Symbol.getType() == ELF::STT_NOTYPE && 4487 Symbol.getBinding() == ELF::STB_LOCAL && Symbol.st_size == 0) { 4488 if (BC->getBinaryFunctionContainingAddress(Symbol.st_value, 4489 /*CheckPastEnd=*/false, 4490 /*UseMaxSize=*/true)) { 4491 // Can only delete the symbol if not patching. Such symbols should 4492 // not exist in the dynamic symbol table. 4493 assert(!IsDynSym && "cannot delete symbol"); 4494 continue; 4495 } 4496 } 4497 } 4498 } 4499 4500 // Handle special symbols based on their name. 4501 Expected<StringRef> SymbolName = Symbol.getName(StringSection); 4502 assert(SymbolName && "cannot get symbol name"); 4503 4504 auto updateSymbolValue = [&](const StringRef Name, unsigned &IsUpdated) { 4505 NewSymbol.st_value = getNewValueForSymbol(Name); 4506 NewSymbol.st_shndx = ELF::SHN_ABS; 4507 outs() << "BOLT-INFO: setting " << Name << " to 0x" 4508 << Twine::utohexstr(NewSymbol.st_value) << '\n'; 4509 ++IsUpdated; 4510 }; 4511 4512 if (opts::HotText && 4513 (*SymbolName == "__hot_start" || *SymbolName == "__hot_end")) 4514 updateSymbolValue(*SymbolName, NumHotTextSymsUpdated); 4515 4516 if (opts::HotData && 4517 (*SymbolName == "__hot_data_start" || *SymbolName == "__hot_data_end")) 4518 updateSymbolValue(*SymbolName, NumHotDataSymsUpdated); 4519 4520 if (*SymbolName == "_end") { 4521 unsigned Ignored; 4522 updateSymbolValue(*SymbolName, Ignored); 4523 } 4524 4525 if (IsDynSym) 4526 Write((&Symbol - cantFail(Obj.symbols(&SymTabSection)).begin()) * 4527 sizeof(ELFSymTy), 4528 NewSymbol); 4529 else 4530 Symbols.emplace_back(NewSymbol); 4531 } 4532 4533 if (IsDynSym) { 4534 assert(Symbols.empty()); 4535 return; 4536 } 4537 4538 // Add symbols of injected functions 4539 for (BinaryFunction *Function : BC->getInjectedBinaryFunctions()) { 4540 ELFSymTy NewSymbol; 4541 BinarySection *OriginSection = Function->getOriginSection(); 4542 NewSymbol.st_shndx = 4543 OriginSection 4544 ? getNewSectionIndex(OriginSection->getSectionRef().getIndex()) 4545 : Function->getCodeSection()->getIndex(); 4546 NewSymbol.st_value = Function->getOutputAddress(); 4547 NewSymbol.st_name = AddToStrTab(Function->getOneName()); 4548 NewSymbol.st_size = Function->getOutputSize(); 4549 NewSymbol.st_other = 0; 4550 NewSymbol.setBindingAndType(ELF::STB_LOCAL, ELF::STT_FUNC); 4551 Symbols.emplace_back(NewSymbol); 4552 4553 if (Function->isSplit()) { 4554 ELFSymTy NewColdSym = NewSymbol; 4555 NewColdSym.setType(ELF::STT_NOTYPE); 4556 SmallVector<char, 256> Buf; 4557 NewColdSym.st_name = AddToStrTab( 4558 Twine(Function->getPrintName()).concat(".cold.0").toStringRef(Buf)); 4559 NewColdSym.st_value = Function->cold().getAddress(); 4560 NewColdSym.st_size = Function->cold().getImageSize(); 4561 Symbols.emplace_back(NewColdSym); 4562 } 4563 } 4564 4565 assert((!NumHotTextSymsUpdated || NumHotTextSymsUpdated == 2) && 4566 "either none or both __hot_start/__hot_end symbols were expected"); 4567 assert((!NumHotDataSymsUpdated || NumHotDataSymsUpdated == 2) && 4568 "either none or both __hot_data_start/__hot_data_end symbols were " 4569 "expected"); 4570 4571 auto addSymbol = [&](const std::string &Name) { 4572 ELFSymTy Symbol; 4573 Symbol.st_value = getNewValueForSymbol(Name); 4574 Symbol.st_shndx = ELF::SHN_ABS; 4575 Symbol.st_name = AddToStrTab(Name); 4576 Symbol.st_size = 0; 4577 Symbol.st_other = 0; 4578 Symbol.setBindingAndType(ELF::STB_WEAK, ELF::STT_NOTYPE); 4579 4580 outs() << "BOLT-INFO: setting " << Name << " to 0x" 4581 << Twine::utohexstr(Symbol.st_value) << '\n'; 4582 4583 Symbols.emplace_back(Symbol); 4584 }; 4585 4586 if (opts::HotText && !NumHotTextSymsUpdated) { 4587 addSymbol("__hot_start"); 4588 addSymbol("__hot_end"); 4589 } 4590 4591 if (opts::HotData && !NumHotDataSymsUpdated) { 4592 addSymbol("__hot_data_start"); 4593 addSymbol("__hot_data_end"); 4594 } 4595 4596 // Put local symbols at the beginning. 4597 std::stable_sort(Symbols.begin(), Symbols.end(), 4598 [](const ELFSymTy &A, const ELFSymTy &B) { 4599 if (A.getBinding() == ELF::STB_LOCAL && 4600 B.getBinding() != ELF::STB_LOCAL) 4601 return true; 4602 return false; 4603 }); 4604 4605 for (const ELFSymTy &Symbol : Symbols) 4606 Write(0, Symbol); 4607 } 4608 4609 template <typename ELFT> 4610 void RewriteInstance::patchELFSymTabs(ELFObjectFile<ELFT> *File) { 4611 const ELFFile<ELFT> &Obj = File->getELFFile(); 4612 using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr; 4613 using ELFSymTy = typename ELFObjectFile<ELFT>::Elf_Sym; 4614 4615 // Compute a preview of how section indices will change after rewriting, so 4616 // we can properly update the symbol table based on new section indices. 4617 std::vector<uint32_t> NewSectionIndex; 4618 getOutputSections(File, NewSectionIndex); 4619 4620 // Set pointer at the end of the output file, so we can pwrite old symbol 4621 // tables if we need to. 4622 uint64_t NextAvailableOffset = getFileOffsetForAddress(NextAvailableAddress); 4623 assert(NextAvailableOffset >= FirstNonAllocatableOffset && 4624 "next available offset calculation failure"); 4625 Out->os().seek(NextAvailableOffset); 4626 4627 // Update dynamic symbol table. 4628 const ELFShdrTy *DynSymSection = nullptr; 4629 for (const ELFShdrTy &Section : cantFail(Obj.sections())) { 4630 if (Section.sh_type == ELF::SHT_DYNSYM) { 4631 DynSymSection = &Section; 4632 break; 4633 } 4634 } 4635 assert((DynSymSection || BC->IsStaticExecutable) && 4636 "dynamic symbol table expected"); 4637 if (DynSymSection) { 4638 updateELFSymbolTable( 4639 File, 4640 /*IsDynSym=*/true, 4641 *DynSymSection, 4642 NewSectionIndex, 4643 [&](size_t Offset, const ELFSymTy &Sym) { 4644 Out->os().pwrite(reinterpret_cast<const char *>(&Sym), 4645 sizeof(ELFSymTy), 4646 DynSymSection->sh_offset + Offset); 4647 }, 4648 [](StringRef) -> size_t { return 0; }); 4649 } 4650 4651 if (opts::RemoveSymtab) 4652 return; 4653 4654 // (re)create regular symbol table. 4655 const ELFShdrTy *SymTabSection = nullptr; 4656 for (const ELFShdrTy &Section : cantFail(Obj.sections())) { 4657 if (Section.sh_type == ELF::SHT_SYMTAB) { 4658 SymTabSection = &Section; 4659 break; 4660 } 4661 } 4662 if (!SymTabSection) { 4663 errs() << "BOLT-WARNING: no symbol table found\n"; 4664 return; 4665 } 4666 4667 const ELFShdrTy *StrTabSection = 4668 cantFail(Obj.getSection(SymTabSection->sh_link)); 4669 std::string NewContents; 4670 std::string NewStrTab = std::string( 4671 File->getData().substr(StrTabSection->sh_offset, StrTabSection->sh_size)); 4672 StringRef SecName = cantFail(Obj.getSectionName(*SymTabSection)); 4673 StringRef StrSecName = cantFail(Obj.getSectionName(*StrTabSection)); 4674 4675 NumLocalSymbols = 0; 4676 updateELFSymbolTable( 4677 File, 4678 /*IsDynSym=*/false, 4679 *SymTabSection, 4680 NewSectionIndex, 4681 [&](size_t Offset, const ELFSymTy &Sym) { 4682 if (Sym.getBinding() == ELF::STB_LOCAL) 4683 ++NumLocalSymbols; 4684 NewContents.append(reinterpret_cast<const char *>(&Sym), 4685 sizeof(ELFSymTy)); 4686 }, 4687 [&](StringRef Str) { 4688 size_t Idx = NewStrTab.size(); 4689 NewStrTab.append(NameResolver::restore(Str).str()); 4690 NewStrTab.append(1, '\0'); 4691 return Idx; 4692 }); 4693 4694 BC->registerOrUpdateNoteSection(SecName, 4695 copyByteArray(NewContents), 4696 NewContents.size(), 4697 /*Alignment=*/1, 4698 /*IsReadOnly=*/true, 4699 ELF::SHT_SYMTAB); 4700 4701 BC->registerOrUpdateNoteSection(StrSecName, 4702 copyByteArray(NewStrTab), 4703 NewStrTab.size(), 4704 /*Alignment=*/1, 4705 /*IsReadOnly=*/true, 4706 ELF::SHT_STRTAB); 4707 } 4708 4709 template <typename ELFT> 4710 void 4711 RewriteInstance::patchELFAllocatableRelaSections(ELFObjectFile<ELFT> *File) { 4712 using Elf_Rela = typename ELFT::Rela; 4713 raw_fd_ostream &OS = Out->os(); 4714 4715 for (BinarySection &RelaSection : BC->allocatableRelaSections()) { 4716 for (const RelocationRef &Rel : RelaSection.getSectionRef().relocations()) { 4717 uint64_t RType = Rel.getType(); 4718 if (!Relocation::isRelative(RType) && !Relocation::isIRelative(RType)) 4719 continue; 4720 DataRefImpl DRI = Rel.getRawDataRefImpl(); 4721 const Elf_Rela *RelA = File->getRela(DRI); 4722 auto Address = RelA->r_addend; 4723 uint64_t NewAddress = getNewFunctionAddress(Address); 4724 if (!NewAddress) 4725 continue; 4726 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: patching (I)RELATIVE " 4727 << RelaSection.getName() << " entry 0x" 4728 << Twine::utohexstr(Address) << " with 0x" 4729 << Twine::utohexstr(NewAddress) << '\n'); 4730 Elf_Rela NewRelA = *RelA; 4731 NewRelA.r_addend = NewAddress; 4732 OS.pwrite(reinterpret_cast<const char *>(&NewRelA), sizeof(NewRelA), 4733 reinterpret_cast<const char *>(RelA) - File->getData().data()); 4734 } 4735 } 4736 } 4737 4738 template <typename ELFT> 4739 void RewriteInstance::patchELFGOT(ELFObjectFile<ELFT> *File) { 4740 raw_fd_ostream &OS = Out->os(); 4741 4742 SectionRef GOTSection; 4743 for (const SectionRef &Section : File->sections()) { 4744 StringRef SectionName = cantFail(Section.getName()); 4745 if (SectionName == ".got") { 4746 GOTSection = Section; 4747 break; 4748 } 4749 } 4750 if (!GOTSection.getObject()) { 4751 errs() << "BOLT-INFO: no .got section found\n"; 4752 return; 4753 } 4754 4755 StringRef GOTContents = cantFail(GOTSection.getContents()); 4756 for (const uint64_t *GOTEntry = 4757 reinterpret_cast<const uint64_t *>(GOTContents.data()); 4758 GOTEntry < reinterpret_cast<const uint64_t *>(GOTContents.data() + 4759 GOTContents.size()); 4760 ++GOTEntry) { 4761 if (uint64_t NewAddress = getNewFunctionAddress(*GOTEntry)) { 4762 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: patching GOT entry 0x" 4763 << Twine::utohexstr(*GOTEntry) << " with 0x" 4764 << Twine::utohexstr(NewAddress) << '\n'); 4765 OS.pwrite(reinterpret_cast<const char *>(&NewAddress), sizeof(NewAddress), 4766 reinterpret_cast<const char *>(GOTEntry) - 4767 File->getData().data()); 4768 } 4769 } 4770 } 4771 4772 template <typename ELFT> 4773 void RewriteInstance::patchELFDynamic(ELFObjectFile<ELFT> *File) { 4774 if (BC->IsStaticExecutable) 4775 return; 4776 4777 const ELFFile<ELFT> &Obj = File->getELFFile(); 4778 raw_fd_ostream &OS = Out->os(); 4779 4780 using Elf_Phdr = typename ELFFile<ELFT>::Elf_Phdr; 4781 using Elf_Dyn = typename ELFFile<ELFT>::Elf_Dyn; 4782 4783 // Locate DYNAMIC by looking through program headers. 4784 uint64_t DynamicOffset = 0; 4785 const Elf_Phdr *DynamicPhdr = 0; 4786 for (const Elf_Phdr &Phdr : cantFail(Obj.program_headers())) { 4787 if (Phdr.p_type == ELF::PT_DYNAMIC) { 4788 DynamicOffset = Phdr.p_offset; 4789 DynamicPhdr = &Phdr; 4790 assert(Phdr.p_memsz == Phdr.p_filesz && "dynamic sizes should match"); 4791 break; 4792 } 4793 } 4794 assert(DynamicPhdr && "missing dynamic in ELF binary"); 4795 4796 bool ZNowSet = false; 4797 4798 // Go through all dynamic entries and patch functions addresses with 4799 // new ones. 4800 typename ELFT::DynRange DynamicEntries = 4801 cantFail(Obj.dynamicEntries(), "error accessing dynamic table"); 4802 auto DTB = DynamicEntries.begin(); 4803 for (const Elf_Dyn &Dyn : DynamicEntries) { 4804 Elf_Dyn NewDE = Dyn; 4805 bool ShouldPatch = true; 4806 switch (Dyn.d_tag) { 4807 default: 4808 ShouldPatch = false; 4809 break; 4810 case ELF::DT_INIT: 4811 case ELF::DT_FINI: { 4812 if (BC->HasRelocations) { 4813 if (uint64_t NewAddress = getNewFunctionAddress(Dyn.getPtr())) { 4814 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: patching dynamic entry of type " 4815 << Dyn.getTag() << '\n'); 4816 NewDE.d_un.d_ptr = NewAddress; 4817 } 4818 } 4819 RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary(); 4820 if (RtLibrary && Dyn.getTag() == ELF::DT_FINI) { 4821 if (uint64_t Addr = RtLibrary->getRuntimeFiniAddress()) 4822 NewDE.d_un.d_ptr = Addr; 4823 } 4824 if (RtLibrary && Dyn.getTag() == ELF::DT_INIT && !BC->HasInterpHeader) { 4825 if (auto Addr = RtLibrary->getRuntimeStartAddress()) { 4826 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Set DT_INIT to 0x" 4827 << Twine::utohexstr(Addr) << '\n'); 4828 NewDE.d_un.d_ptr = Addr; 4829 } 4830 } 4831 break; 4832 } 4833 case ELF::DT_FLAGS: 4834 if (BC->RequiresZNow) { 4835 NewDE.d_un.d_val |= ELF::DF_BIND_NOW; 4836 ZNowSet = true; 4837 } 4838 break; 4839 case ELF::DT_FLAGS_1: 4840 if (BC->RequiresZNow) { 4841 NewDE.d_un.d_val |= ELF::DF_1_NOW; 4842 ZNowSet = true; 4843 } 4844 break; 4845 } 4846 if (ShouldPatch) 4847 OS.pwrite(reinterpret_cast<const char *>(&NewDE), sizeof(NewDE), 4848 DynamicOffset + (&Dyn - DTB) * sizeof(Dyn)); 4849 } 4850 4851 if (BC->RequiresZNow && !ZNowSet) { 4852 errs() << "BOLT-ERROR: output binary requires immediate relocation " 4853 "processing which depends on DT_FLAGS or DT_FLAGS_1 presence in " 4854 ".dynamic. Please re-link the binary with -znow.\n"; 4855 exit(1); 4856 } 4857 } 4858 4859 template <typename ELFT> 4860 void RewriteInstance::readELFDynamic(ELFObjectFile<ELFT> *File) { 4861 const ELFFile<ELFT> &Obj = File->getELFFile(); 4862 4863 using Elf_Phdr = typename ELFFile<ELFT>::Elf_Phdr; 4864 using Elf_Dyn = typename ELFFile<ELFT>::Elf_Dyn; 4865 4866 // Locate DYNAMIC by looking through program headers. 4867 const Elf_Phdr *DynamicPhdr = 0; 4868 for (const Elf_Phdr &Phdr : cantFail(Obj.program_headers())) { 4869 if (Phdr.p_type == ELF::PT_DYNAMIC) { 4870 DynamicPhdr = &Phdr; 4871 break; 4872 } 4873 } 4874 4875 if (!DynamicPhdr) { 4876 outs() << "BOLT-INFO: static input executable detected\n"; 4877 // TODO: static PIE executable might have dynamic header 4878 BC->IsStaticExecutable = true; 4879 return; 4880 } 4881 4882 assert(DynamicPhdr->p_memsz == DynamicPhdr->p_filesz && 4883 "dynamic section sizes should match"); 4884 4885 // Go through all dynamic entries to locate entries of interest. 4886 typename ELFT::DynRange DynamicEntries = 4887 cantFail(Obj.dynamicEntries(), "error accessing dynamic table"); 4888 4889 for (const Elf_Dyn &Dyn : DynamicEntries) { 4890 switch (Dyn.d_tag) { 4891 case ELF::DT_INIT: 4892 if (!BC->HasInterpHeader) { 4893 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Set start function address\n"); 4894 BC->StartFunctionAddress = Dyn.getPtr(); 4895 } 4896 break; 4897 case ELF::DT_FINI: 4898 BC->FiniFunctionAddress = Dyn.getPtr(); 4899 break; 4900 case ELF::DT_RELA: 4901 DynamicRelocationsAddress = Dyn.getPtr(); 4902 break; 4903 case ELF::DT_RELASZ: 4904 DynamicRelocationsSize = Dyn.getVal(); 4905 break; 4906 case ELF::DT_JMPREL: 4907 PLTRelocationsAddress = Dyn.getPtr(); 4908 break; 4909 case ELF::DT_PLTRELSZ: 4910 PLTRelocationsSize = Dyn.getVal(); 4911 break; 4912 } 4913 } 4914 4915 if (!DynamicRelocationsAddress) 4916 DynamicRelocationsSize = 0; 4917 4918 if (!PLTRelocationsAddress) 4919 PLTRelocationsSize = 0; 4920 } 4921 4922 uint64_t RewriteInstance::getNewFunctionAddress(uint64_t OldAddress) { 4923 const BinaryFunction *Function = BC->getBinaryFunctionAtAddress(OldAddress); 4924 if (!Function) 4925 return 0; 4926 4927 assert(!Function->isFragment() && "cannot get new address for a fragment"); 4928 4929 return Function->getOutputAddress(); 4930 } 4931 4932 void RewriteInstance::rewriteFile() { 4933 std::error_code EC; 4934 Out = std::make_unique<ToolOutputFile>(opts::OutputFilename, EC, 4935 sys::fs::OF_None); 4936 check_error(EC, "cannot create output executable file"); 4937 4938 raw_fd_ostream &OS = Out->os(); 4939 4940 // Copy allocatable part of the input. 4941 OS << InputFile->getData().substr(0, FirstNonAllocatableOffset); 4942 4943 // We obtain an asm-specific writer so that we can emit nops in an 4944 // architecture-specific way at the end of the function. 4945 std::unique_ptr<MCAsmBackend> MAB( 4946 BC->TheTarget->createMCAsmBackend(*BC->STI, *BC->MRI, MCTargetOptions())); 4947 auto Streamer = BC->createStreamer(OS); 4948 // Make sure output stream has enough reserved space, otherwise 4949 // pwrite() will fail. 4950 uint64_t Offset = OS.seek(getFileOffsetForAddress(NextAvailableAddress)); 4951 (void)Offset; 4952 assert(Offset == getFileOffsetForAddress(NextAvailableAddress) && 4953 "error resizing output file"); 4954 4955 // Overwrite functions with fixed output address. This is mostly used by 4956 // non-relocation mode, with one exception: injected functions are covered 4957 // here in both modes. 4958 uint64_t CountOverwrittenFunctions = 0; 4959 uint64_t OverwrittenScore = 0; 4960 for (BinaryFunction *Function : BC->getAllBinaryFunctions()) { 4961 if (Function->getImageAddress() == 0 || Function->getImageSize() == 0) 4962 continue; 4963 4964 if (Function->getImageSize() > Function->getMaxSize()) { 4965 if (opts::Verbosity >= 1) 4966 errs() << "BOLT-WARNING: new function size (0x" 4967 << Twine::utohexstr(Function->getImageSize()) 4968 << ") is larger than maximum allowed size (0x" 4969 << Twine::utohexstr(Function->getMaxSize()) << ") for function " 4970 << *Function << '\n'; 4971 4972 // Remove jump table sections that this function owns in non-reloc mode 4973 // because we don't want to write them anymore. 4974 if (!BC->HasRelocations && opts::JumpTables == JTS_BASIC) { 4975 for (auto &JTI : Function->JumpTables) { 4976 JumpTable *JT = JTI.second; 4977 BinarySection &Section = JT->getOutputSection(); 4978 BC->deregisterSection(Section); 4979 } 4980 } 4981 continue; 4982 } 4983 4984 if (Function->isSplit() && (Function->cold().getImageAddress() == 0 || 4985 Function->cold().getImageSize() == 0)) 4986 continue; 4987 4988 OverwrittenScore += Function->getFunctionScore(); 4989 // Overwrite function in the output file. 4990 if (opts::Verbosity >= 2) 4991 outs() << "BOLT: rewriting function \"" << *Function << "\"\n"; 4992 4993 OS.pwrite(reinterpret_cast<char *>(Function->getImageAddress()), 4994 Function->getImageSize(), Function->getFileOffset()); 4995 4996 // Write nops at the end of the function. 4997 if (Function->getMaxSize() != std::numeric_limits<uint64_t>::max()) { 4998 uint64_t Pos = OS.tell(); 4999 OS.seek(Function->getFileOffset() + Function->getImageSize()); 5000 MAB->writeNopData(OS, Function->getMaxSize() - Function->getImageSize(), 5001 &*BC->STI); 5002 5003 OS.seek(Pos); 5004 } 5005 5006 if (!Function->isSplit()) { 5007 ++CountOverwrittenFunctions; 5008 if (opts::MaxFunctions && 5009 CountOverwrittenFunctions == opts::MaxFunctions) { 5010 outs() << "BOLT: maximum number of functions reached\n"; 5011 break; 5012 } 5013 continue; 5014 } 5015 5016 // Write cold part 5017 if (opts::Verbosity >= 2) 5018 outs() << "BOLT: rewriting function \"" << *Function 5019 << "\" (cold part)\n"; 5020 5021 OS.pwrite(reinterpret_cast<char *>(Function->cold().getImageAddress()), 5022 Function->cold().getImageSize(), 5023 Function->cold().getFileOffset()); 5024 5025 ++CountOverwrittenFunctions; 5026 if (opts::MaxFunctions && CountOverwrittenFunctions == opts::MaxFunctions) { 5027 outs() << "BOLT: maximum number of functions reached\n"; 5028 break; 5029 } 5030 } 5031 5032 // Print function statistics for non-relocation mode. 5033 if (!BC->HasRelocations) { 5034 outs() << "BOLT: " << CountOverwrittenFunctions << " out of " 5035 << BC->getBinaryFunctions().size() 5036 << " functions were overwritten.\n"; 5037 if (BC->TotalScore != 0) { 5038 double Coverage = OverwrittenScore / (double)BC->TotalScore * 100.0; 5039 outs() << format("BOLT-INFO: rewritten functions cover %.2lf", Coverage) 5040 << "% of the execution count of simple functions of " 5041 "this binary\n"; 5042 } 5043 } 5044 5045 if (BC->HasRelocations && opts::TrapOldCode) { 5046 uint64_t SavedPos = OS.tell(); 5047 // Overwrite function body to make sure we never execute these instructions. 5048 for (auto &BFI : BC->getBinaryFunctions()) { 5049 BinaryFunction &BF = BFI.second; 5050 if (!BF.getFileOffset() || !BF.isEmitted()) 5051 continue; 5052 OS.seek(BF.getFileOffset()); 5053 for (unsigned I = 0; I < BF.getMaxSize(); ++I) 5054 OS.write((unsigned char)BC->MIB->getTrapFillValue()); 5055 } 5056 OS.seek(SavedPos); 5057 } 5058 5059 // Write all allocatable sections - reloc-mode text is written here as well 5060 for (BinarySection &Section : BC->allocatableSections()) { 5061 if (!Section.isFinalized() || !Section.getOutputData()) 5062 continue; 5063 5064 if (opts::Verbosity >= 1) 5065 outs() << "BOLT: writing new section " << Section.getName() 5066 << "\n data at 0x" << Twine::utohexstr(Section.getAllocAddress()) 5067 << "\n of size " << Section.getOutputSize() << "\n at offset " 5068 << Section.getOutputFileOffset() << '\n'; 5069 OS.pwrite(reinterpret_cast<const char *>(Section.getOutputData()), 5070 Section.getOutputSize(), Section.getOutputFileOffset()); 5071 } 5072 5073 for (BinarySection &Section : BC->allocatableSections()) 5074 Section.flushPendingRelocations(OS, [this](const MCSymbol *S) { 5075 return getNewValueForSymbol(S->getName()); 5076 }); 5077 5078 // If .eh_frame is present create .eh_frame_hdr. 5079 if (EHFrameSection && EHFrameSection->isFinalized()) 5080 writeEHFrameHeader(); 5081 5082 // Add BOLT Addresses Translation maps to allow profile collection to 5083 // happen in the output binary 5084 if (opts::EnableBAT) 5085 addBATSection(); 5086 5087 // Patch program header table. 5088 patchELFPHDRTable(); 5089 5090 // Finalize memory image of section string table. 5091 finalizeSectionStringTable(); 5092 5093 // Update symbol tables. 5094 patchELFSymTabs(); 5095 5096 patchBuildID(); 5097 5098 if (opts::EnableBAT) 5099 encodeBATSection(); 5100 5101 // Copy non-allocatable sections once allocatable part is finished. 5102 rewriteNoteSections(); 5103 5104 // Patch dynamic section/segment. 5105 patchELFDynamic(); 5106 5107 if (BC->HasRelocations) { 5108 patchELFAllocatableRelaSections(); 5109 patchELFGOT(); 5110 } 5111 5112 // Update ELF book-keeping info. 5113 patchELFSectionHeaderTable(); 5114 5115 if (opts::PrintSections) { 5116 outs() << "BOLT-INFO: Sections after processing:\n"; 5117 BC->printSections(outs()); 5118 } 5119 5120 Out->keep(); 5121 EC = sys::fs::setPermissions(opts::OutputFilename, sys::fs::perms::all_all); 5122 check_error(EC, "cannot set permissions of output file"); 5123 } 5124 5125 void RewriteInstance::writeEHFrameHeader() { 5126 DWARFDebugFrame NewEHFrame(BC->TheTriple->getArch(), true, 5127 EHFrameSection->getOutputAddress()); 5128 Error E = NewEHFrame.parse(DWARFDataExtractor( 5129 EHFrameSection->getOutputContents(), BC->AsmInfo->isLittleEndian(), 5130 BC->AsmInfo->getCodePointerSize())); 5131 check_error(std::move(E), "failed to parse EH frame"); 5132 5133 uint64_t OldEHFrameAddress = 0; 5134 StringRef OldEHFrameContents; 5135 ErrorOr<BinarySection &> OldEHFrameSection = 5136 BC->getUniqueSectionByName(Twine(getOrgSecPrefix(), ".eh_frame").str()); 5137 if (OldEHFrameSection) { 5138 OldEHFrameAddress = OldEHFrameSection->getOutputAddress(); 5139 OldEHFrameContents = OldEHFrameSection->getOutputContents(); 5140 } 5141 DWARFDebugFrame OldEHFrame(BC->TheTriple->getArch(), true, OldEHFrameAddress); 5142 Error Er = OldEHFrame.parse( 5143 DWARFDataExtractor(OldEHFrameContents, BC->AsmInfo->isLittleEndian(), 5144 BC->AsmInfo->getCodePointerSize())); 5145 check_error(std::move(Er), "failed to parse EH frame"); 5146 5147 LLVM_DEBUG(dbgs() << "BOLT: writing a new .eh_frame_hdr\n"); 5148 5149 NextAvailableAddress = 5150 appendPadding(Out->os(), NextAvailableAddress, EHFrameHdrAlign); 5151 5152 const uint64_t EHFrameHdrOutputAddress = NextAvailableAddress; 5153 const uint64_t EHFrameHdrFileOffset = 5154 getFileOffsetForAddress(NextAvailableAddress); 5155 5156 std::vector<char> NewEHFrameHdr = CFIRdWrt->generateEHFrameHeader( 5157 OldEHFrame, NewEHFrame, EHFrameHdrOutputAddress, FailedAddresses); 5158 5159 assert(Out->os().tell() == EHFrameHdrFileOffset && "offset mismatch"); 5160 Out->os().write(NewEHFrameHdr.data(), NewEHFrameHdr.size()); 5161 5162 const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/true, 5163 /*IsText=*/false, 5164 /*IsAllocatable=*/true); 5165 BinarySection &EHFrameHdrSec = BC->registerOrUpdateSection( 5166 ".eh_frame_hdr", ELF::SHT_PROGBITS, Flags, nullptr, NewEHFrameHdr.size(), 5167 /*Alignment=*/1); 5168 EHFrameHdrSec.setOutputFileOffset(EHFrameHdrFileOffset); 5169 EHFrameHdrSec.setOutputAddress(EHFrameHdrOutputAddress); 5170 5171 NextAvailableAddress += EHFrameHdrSec.getOutputSize(); 5172 5173 // Merge new .eh_frame with original so that gdb can locate all FDEs. 5174 if (OldEHFrameSection) { 5175 const uint64_t EHFrameSectionSize = (OldEHFrameSection->getOutputAddress() + 5176 OldEHFrameSection->getOutputSize() - 5177 EHFrameSection->getOutputAddress()); 5178 EHFrameSection = 5179 BC->registerOrUpdateSection(".eh_frame", 5180 EHFrameSection->getELFType(), 5181 EHFrameSection->getELFFlags(), 5182 EHFrameSection->getOutputData(), 5183 EHFrameSectionSize, 5184 EHFrameSection->getAlignment()); 5185 BC->deregisterSection(*OldEHFrameSection); 5186 } 5187 5188 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: size of .eh_frame after merge is " 5189 << EHFrameSection->getOutputSize() << '\n'); 5190 } 5191 5192 uint64_t RewriteInstance::getNewValueForSymbol(const StringRef Name) { 5193 uint64_t Value = RTDyld->getSymbol(Name).getAddress(); 5194 if (Value != 0) 5195 return Value; 5196 5197 // Return the original value if we haven't emitted the symbol. 5198 BinaryData *BD = BC->getBinaryDataByName(Name); 5199 if (!BD) 5200 return 0; 5201 5202 return BD->getAddress(); 5203 } 5204 5205 uint64_t RewriteInstance::getFileOffsetForAddress(uint64_t Address) const { 5206 // Check if it's possibly part of the new segment. 5207 if (Address >= NewTextSegmentAddress) 5208 return Address - NewTextSegmentAddress + NewTextSegmentOffset; 5209 5210 // Find an existing segment that matches the address. 5211 const auto SegmentInfoI = BC->SegmentMapInfo.upper_bound(Address); 5212 if (SegmentInfoI == BC->SegmentMapInfo.begin()) 5213 return 0; 5214 5215 const SegmentInfo &SegmentInfo = std::prev(SegmentInfoI)->second; 5216 if (Address < SegmentInfo.Address || 5217 Address >= SegmentInfo.Address + SegmentInfo.FileSize) 5218 return 0; 5219 5220 return SegmentInfo.FileOffset + Address - SegmentInfo.Address; 5221 } 5222 5223 bool RewriteInstance::willOverwriteSection(StringRef SectionName) { 5224 for (const char *const &OverwriteName : SectionsToOverwrite) 5225 if (SectionName == OverwriteName) 5226 return true; 5227 for (std::string &OverwriteName : DebugSectionsToOverwrite) 5228 if (SectionName == OverwriteName) 5229 return true; 5230 5231 ErrorOr<BinarySection &> Section = BC->getUniqueSectionByName(SectionName); 5232 return Section && Section->isAllocatable() && Section->isFinalized(); 5233 } 5234 5235 bool RewriteInstance::isDebugSection(StringRef SectionName) { 5236 if (SectionName.startswith(".debug_") || SectionName.startswith(".zdebug_") || 5237 SectionName == ".gdb_index" || SectionName == ".stab" || 5238 SectionName == ".stabstr") 5239 return true; 5240 5241 return false; 5242 } 5243 5244 bool RewriteInstance::isKSymtabSection(StringRef SectionName) { 5245 if (SectionName.startswith("__ksymtab")) 5246 return true; 5247 5248 return false; 5249 } 5250