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