[SLP][REVEC] The vectorized result for ShuffleVector may not be ShuffleVectorInst...
[llvm-project.git] / bolt / lib / Rewrite / RewriteInstance.cpp
blob7059a3dd231099beae7cfce4692030adae4b7ee4
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 //===----------------------------------------------------------------------===//
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>
66 #undef DEBUG_TYPE
67 #define DEBUG_TYPE "bolt"
69 using namespace llvm;
70 using namespace object;
71 using namespace bolt;
73 extern cl::opt<uint32_t> X86AlignBranchBoundary;
74 extern cl::opt<bool> X86AlignBranchWithin32BBoundaries;
76 namespace opts {
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;
90 cl::opt<bool> AllowStripped("allow-stripped",
91 cl::desc("allow processing of stripped binaries"),
92 cl::Hidden, cl::cat(BoltCategory));
94 static cl::opt<bool> ForceToDataRelocations(
95 "force-data-relocations",
96 cl::desc("force relocations to data sections to always be processed"),
98 cl::Hidden, cl::cat(BoltCategory));
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));
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));
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));
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));
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));
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));
136 cl::opt<bool>
137 KeepTmp("keep-tmp",
138 cl::desc("preserve intermediate .o file"),
139 cl::Hidden,
140 cl::cat(BoltCategory));
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));
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));
160 static cl::opt<unsigned>
161 MaxFunctions("max-funcs",
162 cl::desc("maximum number of functions to process"), cl::Hidden,
163 cl::cat(BoltCategory));
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));
170 cl::opt<bool> PrintAll("print-all",
171 cl::desc("print functions after each stage"), cl::Hidden,
172 cl::cat(BoltCategory));
174 cl::opt<bool> PrintProfile("print-profile",
175 cl::desc("print functions after attaching profile"),
176 cl::Hidden, cl::cat(BoltCategory));
178 cl::opt<bool> PrintCFG("print-cfg",
179 cl::desc("print functions after CFG construction"),
180 cl::Hidden, cl::cat(BoltCategory));
182 cl::opt<bool> PrintDisasm("print-disasm",
183 cl::desc("print function after disassembly"),
184 cl::Hidden, cl::cat(BoltCategory));
186 static cl::opt<bool>
187 PrintGlobals("print-globals",
188 cl::desc("print global symbols after disassembly"), cl::Hidden,
189 cl::cat(BoltCategory));
191 extern cl::opt<bool> PrintSections;
193 static cl::opt<bool> PrintLoopInfo("print-loops",
194 cl::desc("print loop related information"),
195 cl::Hidden, cl::cat(BoltCategory));
197 static cl::opt<cl::boolOrDefault> RelocationMode(
198 "relocs", cl::desc("use relocations in the binary (default=autodetect)"),
199 cl::cat(BoltCategory));
201 extern cl::opt<std::string> SaveProfile;
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));
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));
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));
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));
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));
235 static cl::opt<bool>
236 SequentialDisassembly("sequential-disassembly",
237 cl::desc("performs disassembly sequentially"),
238 cl::init(false),
239 cl::cat(BoltOptCategory));
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));
245 } // namespace opts
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"};
255 const char RewriteInstance::TimerGroupName[] = "rewrite";
256 const char RewriteInstance::TimerGroupDesc[] = "Rewrite passes";
258 namespace llvm {
259 namespace bolt {
261 extern const char *BoltRevision;
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
277 #ifdef AARCH64_AVAILABLE
278 if (Arch == Triple::aarch64)
279 return createAArch64MCPlusBuilder(Analysis, Info, RegInfo, STI);
280 #endif
282 #ifdef RISCV_AVAILABLE
283 if (Arch == Triple::riscv64)
284 return createRISCVMCPlusBuilder(Analysis, Info, RegInfo, STI);
285 #endif
287 llvm_unreachable("architecture unsupported by MCPlusBuilder");
290 } // namespace bolt
291 } // namespace llvm
293 using ELF64LEPhdrTy = ELF64LEFile::Elf_Phdr;
295 namespace {
297 bool refersToReorderedSection(ErrorOr<BinarySection &> Section) {
298 return llvm::any_of(opts::ReorderData, [&](const std::string &SectionName) {
299 return Section && Section->getName() == SectionName;
303 } // anonymous namespace
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);
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;
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;
339 // Make sure we don't miss any output on core dumps.
340 Stdout.SetUnbuffered();
341 Stderr.SetUnbuffered();
342 LLVM_DEBUG(dbgs().SetUnbuffered());
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));
357 Relocation::Arch = TheTriple.getArch();
358 auto BCOrErr = BinaryContext::createBinaryContext(
359 TheTriple, File->getFileName(), Features.get(), IsPIC,
360 DWARFContext::create(*File, DWARFContext::ProcessDebugRelocations::Ignore,
361 nullptr, opts::DWPPathName,
362 WithColor::defaultErrorHandler,
363 WithColor::defaultWarningHandler),
364 JournalingStreams{Stdout, Stderr});
365 if (Error E = BCOrErr.takeError()) {
366 Err = std::move(E);
367 return;
369 BC = std::move(BCOrErr.get());
370 BC->initializeTarget(std::unique_ptr<MCPlusBuilder>(
371 createMCPlusBuilder(BC->TheTriple->getArch(), BC->MIA.get(),
372 BC->MII.get(), BC->MRI.get(), BC->STI.get())));
374 BAT = std::make_unique<BoltAddressTranslation>();
376 if (opts::UpdateDebugSections)
377 DebugInfoRewriter = std::make_unique<DWARFRewriter>(*BC);
379 if (opts::Instrument)
380 BC->setRuntimeLibrary(std::make_unique<InstrumentationRuntimeLibrary>());
381 else if (opts::Hugify)
382 BC->setRuntimeLibrary(std::make_unique<HugifyRuntimeLibrary>());
385 RewriteInstance::~RewriteInstance() {}
387 Error RewriteInstance::setProfile(StringRef Filename) {
388 if (!sys::fs::exists(Filename))
389 return errorCodeToError(make_error_code(errc::no_such_file_or_directory));
391 if (ProfileReader) {
392 // Already exists
393 return make_error<StringError>(Twine("multiple profiles specified: ") +
394 ProfileReader->getFilename() + " and " +
395 Filename,
396 inconvertibleErrorCode());
399 // Spawn a profile reader based on file contents.
400 if (DataAggregator::checkPerfDataMagic(Filename))
401 ProfileReader = std::make_unique<DataAggregator>(Filename);
402 else if (YAMLProfileReader::isYAML(Filename))
403 ProfileReader = std::make_unique<YAMLProfileReader>(Filename);
404 else
405 ProfileReader = std::make_unique<DataReader>(Filename);
407 return Error::success();
410 /// Return true if the function \p BF should be disassembled.
411 static bool shouldDisassemble(const BinaryFunction &BF) {
412 if (BF.isPseudo())
413 return false;
415 if (opts::processAllFunctions())
416 return true;
418 return !BF.isIgnored();
421 // Return if a section stored in the image falls into a segment address space.
422 // If not, Set \p Overlap to true if there's a partial overlap.
423 template <class ELFT>
424 static bool checkOffsets(const typename ELFT::Phdr &Phdr,
425 const typename ELFT::Shdr &Sec, bool &Overlap) {
426 // SHT_NOBITS sections don't need to have an offset inside the segment.
427 if (Sec.sh_type == ELF::SHT_NOBITS)
428 return true;
430 // Only non-empty sections can be at the end of a segment.
431 uint64_t SectionSize = Sec.sh_size ? Sec.sh_size : 1ull;
432 AddressRange SectionAddressRange((uint64_t)Sec.sh_offset,
433 Sec.sh_offset + SectionSize);
434 AddressRange SegmentAddressRange(Phdr.p_offset,
435 Phdr.p_offset + Phdr.p_filesz);
436 if (SegmentAddressRange.contains(SectionAddressRange))
437 return true;
439 Overlap = SegmentAddressRange.intersects(SectionAddressRange);
440 return false;
443 // Check that an allocatable section belongs to a virtual address
444 // space of a segment.
445 template <class ELFT>
446 static bool checkVMA(const typename ELFT::Phdr &Phdr,
447 const typename ELFT::Shdr &Sec, bool &Overlap) {
448 // Only non-empty sections can be at the end of a segment.
449 uint64_t SectionSize = Sec.sh_size ? Sec.sh_size : 1ull;
450 AddressRange SectionAddressRange((uint64_t)Sec.sh_addr,
451 Sec.sh_addr + SectionSize);
452 AddressRange SegmentAddressRange(Phdr.p_vaddr, Phdr.p_vaddr + Phdr.p_memsz);
454 if (SegmentAddressRange.contains(SectionAddressRange))
455 return true;
456 Overlap = SegmentAddressRange.intersects(SectionAddressRange);
457 return false;
460 void RewriteInstance::markGnuRelroSections() {
461 using ELFT = ELF64LE;
462 using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr;
463 auto ELF64LEFile = cast<ELF64LEObjectFile>(InputFile);
464 const ELFFile<ELFT> &Obj = ELF64LEFile->getELFFile();
466 auto handleSection = [&](const ELFT::Phdr &Phdr, SectionRef SecRef) {
467 BinarySection *BinarySection = BC->getSectionForSectionRef(SecRef);
468 // If the section is non-allocatable, ignore it for GNU_RELRO purposes:
469 // it can't be made read-only after runtime relocations processing.
470 if (!BinarySection || !BinarySection->isAllocatable())
471 return;
472 const ELFShdrTy *Sec = cantFail(Obj.getSection(SecRef.getIndex()));
473 bool ImageOverlap{false}, VMAOverlap{false};
474 bool ImageContains = checkOffsets<ELFT>(Phdr, *Sec, ImageOverlap);
475 bool VMAContains = checkVMA<ELFT>(Phdr, *Sec, VMAOverlap);
476 if (ImageOverlap) {
477 if (opts::Verbosity >= 1)
478 BC->errs() << "BOLT-WARNING: GNU_RELRO segment has partial file offset "
479 << "overlap with section " << BinarySection->getName()
480 << '\n';
481 return;
483 if (VMAOverlap) {
484 if (opts::Verbosity >= 1)
485 BC->errs() << "BOLT-WARNING: GNU_RELRO segment has partial VMA overlap "
486 << "with section " << BinarySection->getName() << '\n';
487 return;
489 if (!ImageContains || !VMAContains)
490 return;
491 BinarySection->setRelro();
492 if (opts::Verbosity >= 1)
493 BC->outs() << "BOLT-INFO: marking " << BinarySection->getName()
494 << " as GNU_RELRO\n";
497 for (const ELFT::Phdr &Phdr : cantFail(Obj.program_headers()))
498 if (Phdr.p_type == ELF::PT_GNU_RELRO)
499 for (SectionRef SecRef : InputFile->sections())
500 handleSection(Phdr, SecRef);
503 Error RewriteInstance::discoverStorage() {
504 NamedRegionTimer T("discoverStorage", "discover storage", TimerGroupName,
505 TimerGroupDesc, opts::TimeRewrite);
507 auto ELF64LEFile = cast<ELF64LEObjectFile>(InputFile);
508 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile();
510 BC->StartFunctionAddress = Obj.getHeader().e_entry;
512 NextAvailableAddress = 0;
513 uint64_t NextAvailableOffset = 0;
514 Expected<ELF64LE::PhdrRange> PHsOrErr = Obj.program_headers();
515 if (Error E = PHsOrErr.takeError())
516 return E;
518 ELF64LE::PhdrRange PHs = PHsOrErr.get();
519 for (const ELF64LE::Phdr &Phdr : PHs) {
520 switch (Phdr.p_type) {
521 case ELF::PT_LOAD:
522 BC->FirstAllocAddress = std::min(BC->FirstAllocAddress,
523 static_cast<uint64_t>(Phdr.p_vaddr));
524 NextAvailableAddress = std::max(NextAvailableAddress,
525 Phdr.p_vaddr + Phdr.p_memsz);
526 NextAvailableOffset = std::max(NextAvailableOffset,
527 Phdr.p_offset + Phdr.p_filesz);
529 BC->SegmentMapInfo[Phdr.p_vaddr] = SegmentInfo{
530 Phdr.p_vaddr, Phdr.p_memsz, Phdr.p_offset,
531 Phdr.p_filesz, Phdr.p_align, ((Phdr.p_flags & ELF::PF_X) != 0)};
532 if (BC->TheTriple->getArch() == llvm::Triple::x86_64 &&
533 Phdr.p_vaddr >= BinaryContext::KernelStartX86_64)
534 BC->IsLinuxKernel = true;
535 break;
536 case ELF::PT_INTERP:
537 BC->HasInterpHeader = true;
538 break;
542 if (BC->IsLinuxKernel)
543 BC->outs() << "BOLT-INFO: Linux kernel binary detected\n";
545 for (const SectionRef &Section : InputFile->sections()) {
546 Expected<StringRef> SectionNameOrErr = Section.getName();
547 if (Error E = SectionNameOrErr.takeError())
548 return E;
549 StringRef SectionName = SectionNameOrErr.get();
550 if (SectionName == BC->getMainCodeSectionName()) {
551 BC->OldTextSectionAddress = Section.getAddress();
552 BC->OldTextSectionSize = Section.getSize();
554 Expected<StringRef> SectionContentsOrErr = Section.getContents();
555 if (Error E = SectionContentsOrErr.takeError())
556 return E;
557 StringRef SectionContents = SectionContentsOrErr.get();
558 BC->OldTextSectionOffset =
559 SectionContents.data() - InputFile->getData().data();
562 if (!opts::HeatmapMode &&
563 !(opts::AggregateOnly && BAT->enabledFor(InputFile)) &&
564 (SectionName.starts_with(getOrgSecPrefix()) ||
565 SectionName == getBOLTTextSectionName()))
566 return createStringError(
567 errc::function_not_supported,
568 "BOLT-ERROR: input file was processed by BOLT. Cannot re-optimize");
571 if (!NextAvailableAddress || !NextAvailableOffset)
572 return createStringError(errc::executable_format_error,
573 "no PT_LOAD pheader seen");
575 BC->outs() << "BOLT-INFO: first alloc address is 0x"
576 << Twine::utohexstr(BC->FirstAllocAddress) << '\n';
578 FirstNonAllocatableOffset = NextAvailableOffset;
580 NextAvailableAddress = alignTo(NextAvailableAddress, BC->PageAlign);
581 NextAvailableOffset = alignTo(NextAvailableOffset, BC->PageAlign);
583 // Hugify: Additional huge page from left side due to
584 // weird ASLR mapping addresses (4KB aligned)
585 if (opts::Hugify && !BC->HasFixedLoadAddress)
586 NextAvailableAddress += BC->PageAlign;
588 if (!opts::UseGnuStack && !BC->IsLinuxKernel) {
589 // This is where the black magic happens. Creating PHDR table in a segment
590 // other than that containing ELF header is tricky. Some loaders and/or
591 // parts of loaders will apply e_phoff from ELF header assuming both are in
592 // the same segment, while others will do the proper calculation.
593 // We create the new PHDR table in such a way that both of the methods
594 // of loading and locating the table work. There's a slight file size
595 // overhead because of that.
597 // NB: bfd's strip command cannot do the above and will corrupt the
598 // binary during the process of stripping non-allocatable sections.
599 if (NextAvailableOffset <= NextAvailableAddress - BC->FirstAllocAddress)
600 NextAvailableOffset = NextAvailableAddress - BC->FirstAllocAddress;
601 else
602 NextAvailableAddress = NextAvailableOffset + BC->FirstAllocAddress;
604 assert(NextAvailableOffset ==
605 NextAvailableAddress - BC->FirstAllocAddress &&
606 "PHDR table address calculation error");
608 BC->outs() << "BOLT-INFO: creating new program header table at address 0x"
609 << Twine::utohexstr(NextAvailableAddress) << ", offset 0x"
610 << Twine::utohexstr(NextAvailableOffset) << '\n';
612 PHDRTableAddress = NextAvailableAddress;
613 PHDRTableOffset = NextAvailableOffset;
615 // Reserve space for 3 extra pheaders.
616 unsigned Phnum = Obj.getHeader().e_phnum;
617 Phnum += 3;
619 NextAvailableAddress += Phnum * sizeof(ELF64LEPhdrTy);
620 NextAvailableOffset += Phnum * sizeof(ELF64LEPhdrTy);
623 // Align at cache line.
624 NextAvailableAddress = alignTo(NextAvailableAddress, 64);
625 NextAvailableOffset = alignTo(NextAvailableOffset, 64);
627 NewTextSegmentAddress = NextAvailableAddress;
628 NewTextSegmentOffset = NextAvailableOffset;
629 BC->LayoutStartAddress = NextAvailableAddress;
631 // Tools such as objcopy can strip section contents but leave header
632 // entries. Check that at least .text is mapped in the file.
633 if (!getFileOffsetForAddress(BC->OldTextSectionAddress))
634 return createStringError(errc::executable_format_error,
635 "BOLT-ERROR: input binary is not a valid ELF "
636 "executable as its text section is not "
637 "mapped to a valid segment");
638 return Error::success();
641 Error RewriteInstance::run() {
642 assert(BC && "failed to create a binary context");
644 BC->outs() << "BOLT-INFO: Target architecture: "
645 << Triple::getArchTypeName(
646 (llvm::Triple::ArchType)InputFile->getArch())
647 << "\n";
648 BC->outs() << "BOLT-INFO: BOLT version: " << BoltRevision << "\n";
650 if (Error E = discoverStorage())
651 return E;
652 if (Error E = readSpecialSections())
653 return E;
654 adjustCommandLineOptions();
655 discoverFileObjects();
657 if (opts::Instrument && !BC->IsStaticExecutable)
658 if (Error E = discoverRtFiniAddress())
659 return E;
661 preprocessProfileData();
663 // Skip disassembling if we have a translation table and we are running an
664 // aggregation job.
665 if (opts::AggregateOnly && BAT->enabledFor(InputFile)) {
666 // YAML profile in BAT mode requires CFG for .bolt.org.text functions
667 if (!opts::SaveProfile.empty() ||
668 opts::ProfileFormat == opts::ProfileFormatKind::PF_YAML) {
669 selectFunctionsToProcess();
670 disassembleFunctions();
671 processMetadataPreCFG();
672 buildFunctionsCFG();
674 processProfileData();
675 return Error::success();
678 selectFunctionsToProcess();
680 readDebugInfo();
682 disassembleFunctions();
684 processMetadataPreCFG();
686 buildFunctionsCFG();
688 processProfileData();
690 // Save input binary metadata if BAT section needs to be emitted
691 if (opts::EnableBAT)
692 BAT->saveMetadata(*BC);
694 postProcessFunctions();
696 processMetadataPostCFG();
698 if (opts::DiffOnly)
699 return Error::success();
701 preregisterSections();
703 runOptimizationPasses();
705 finalizeMetadataPreEmit();
707 emitAndLink();
709 updateMetadata();
711 if (opts::Instrument && !BC->IsStaticExecutable)
712 updateRtFiniReloc();
714 if (opts::OutputFilename == "/dev/null") {
715 BC->outs() << "BOLT-INFO: skipping writing final binary to disk\n";
716 return Error::success();
717 } else if (BC->IsLinuxKernel) {
718 BC->errs() << "BOLT-WARNING: Linux kernel support is experimental\n";
721 // Rewrite allocatable contents and copy non-allocatable parts with mods.
722 rewriteFile();
723 return Error::success();
726 void RewriteInstance::discoverFileObjects() {
727 NamedRegionTimer T("discoverFileObjects", "discover file objects",
728 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
730 // For local symbols we want to keep track of associated FILE symbol name for
731 // disambiguation by combined name.
732 StringRef FileSymbolName;
733 bool SeenFileName = false;
734 struct SymbolRefHash {
735 size_t operator()(SymbolRef const &S) const {
736 return std::hash<decltype(DataRefImpl::p)>{}(S.getRawDataRefImpl().p);
739 std::unordered_map<SymbolRef, StringRef, SymbolRefHash> SymbolToFileName;
740 for (const ELFSymbolRef &Symbol : InputFile->symbols()) {
741 Expected<StringRef> NameOrError = Symbol.getName();
742 if (NameOrError && NameOrError->starts_with("__asan_init")) {
743 BC->errs()
744 << "BOLT-ERROR: input file was compiled or linked with sanitizer "
745 "support. Cannot optimize.\n";
746 exit(1);
748 if (NameOrError && NameOrError->starts_with("__llvm_coverage_mapping")) {
749 BC->errs()
750 << "BOLT-ERROR: input file was compiled or linked with coverage "
751 "support. Cannot optimize.\n";
752 exit(1);
755 if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Undefined)
756 continue;
758 if (cantFail(Symbol.getType()) == SymbolRef::ST_File) {
759 FileSymbols.emplace_back(Symbol);
760 StringRef Name =
761 cantFail(std::move(NameOrError), "cannot get symbol name for file");
762 // Ignore Clang LTO artificial FILE symbol as it is not always generated,
763 // and this uncertainty is causing havoc in function name matching.
764 if (Name == "ld-temp.o")
765 continue;
766 FileSymbolName = Name;
767 SeenFileName = true;
768 continue;
770 if (!FileSymbolName.empty() &&
771 !(cantFail(Symbol.getFlags()) & SymbolRef::SF_Global))
772 SymbolToFileName[Symbol] = FileSymbolName;
775 // Sort symbols in the file by value. Ignore symbols from non-allocatable
776 // sections. We memoize getAddress(), as it has rather high overhead.
777 struct SymbolInfo {
778 uint64_t Address;
779 SymbolRef Symbol;
781 std::vector<SymbolInfo> SortedSymbols;
782 auto isSymbolInMemory = [this](const SymbolRef &Sym) {
783 if (cantFail(Sym.getType()) == SymbolRef::ST_File)
784 return false;
785 if (cantFail(Sym.getFlags()) & SymbolRef::SF_Absolute)
786 return true;
787 if (cantFail(Sym.getFlags()) & SymbolRef::SF_Undefined)
788 return false;
789 BinarySection Section(*BC, *cantFail(Sym.getSection()));
790 return Section.isAllocatable();
792 auto checkSymbolInSection = [this](const SymbolInfo &S) {
793 // Sometimes, we encounter symbols with addresses outside their section. If
794 // such symbols happen to fall into another section, they can interfere with
795 // disassembly. Notably, this occurs with AArch64 marker symbols ($d and $t)
796 // that belong to .eh_frame, but end up pointing into .text.
797 // As a workaround, we ignore all symbols that lie outside their sections.
798 auto Section = cantFail(S.Symbol.getSection());
800 // Accept all absolute symbols.
801 if (Section == InputFile->section_end())
802 return true;
804 uint64_t SecStart = Section->getAddress();
805 uint64_t SecEnd = SecStart + Section->getSize();
806 uint64_t SymEnd = S.Address + ELFSymbolRef(S.Symbol).getSize();
807 if (S.Address >= SecStart && SymEnd <= SecEnd)
808 return true;
810 auto SymType = cantFail(S.Symbol.getType());
811 // Skip warnings for common benign cases.
812 if (opts::Verbosity < 1 && SymType == SymbolRef::ST_Other)
813 return false; // E.g. ELF::STT_TLS.
815 auto SymName = S.Symbol.getName();
816 auto SecName = cantFail(S.Symbol.getSection())->getName();
817 BC->errs() << "BOLT-WARNING: ignoring symbol "
818 << (SymName ? *SymName : "[unnamed]") << " at 0x"
819 << Twine::utohexstr(S.Address) << ", which lies outside "
820 << (SecName ? *SecName : "[unnamed]") << "\n";
822 return false;
824 for (const SymbolRef &Symbol : InputFile->symbols())
825 if (isSymbolInMemory(Symbol)) {
826 SymbolInfo SymInfo{cantFail(Symbol.getAddress()), Symbol};
827 if (checkSymbolInSection(SymInfo))
828 SortedSymbols.push_back(SymInfo);
831 auto CompareSymbols = [this](const SymbolInfo &A, const SymbolInfo &B) {
832 if (A.Address != B.Address)
833 return A.Address < B.Address;
835 const bool AMarker = BC->isMarker(A.Symbol);
836 const bool BMarker = BC->isMarker(B.Symbol);
837 if (AMarker || BMarker) {
838 return AMarker && !BMarker;
841 const auto AType = cantFail(A.Symbol.getType());
842 const auto BType = cantFail(B.Symbol.getType());
843 if (AType == SymbolRef::ST_Function && BType != SymbolRef::ST_Function)
844 return true;
845 if (BType == SymbolRef::ST_Debug && AType != SymbolRef::ST_Debug)
846 return true;
848 return false;
850 llvm::stable_sort(SortedSymbols, CompareSymbols);
852 auto LastSymbol = SortedSymbols.end();
853 if (!SortedSymbols.empty())
854 --LastSymbol;
856 // For aarch64, the ABI defines mapping symbols so we identify data in the
857 // code section (see IHI0056B). $d identifies data contents.
858 // Compilers usually merge multiple data objects in a single $d-$x interval,
859 // but we need every data object to be marked with $d. Because of that we
860 // create a vector of MarkerSyms with all locations of data objects.
862 struct MarkerSym {
863 uint64_t Address;
864 MarkerSymType Type;
867 std::vector<MarkerSym> SortedMarkerSymbols;
868 auto addExtraDataMarkerPerSymbol = [&]() {
869 bool IsData = false;
870 uint64_t LastAddr = 0;
871 for (const auto &SymInfo : SortedSymbols) {
872 if (LastAddr == SymInfo.Address) // don't repeat markers
873 continue;
875 MarkerSymType MarkerType = BC->getMarkerType(SymInfo.Symbol);
876 if (MarkerType != MarkerSymType::NONE) {
877 SortedMarkerSymbols.push_back(MarkerSym{SymInfo.Address, MarkerType});
878 LastAddr = SymInfo.Address;
879 IsData = MarkerType == MarkerSymType::DATA;
880 continue;
883 if (IsData) {
884 SortedMarkerSymbols.push_back({SymInfo.Address, MarkerSymType::DATA});
885 LastAddr = SymInfo.Address;
890 if (BC->isAArch64() || BC->isRISCV()) {
891 addExtraDataMarkerPerSymbol();
892 LastSymbol = std::stable_partition(
893 SortedSymbols.begin(), SortedSymbols.end(),
894 [this](const SymbolInfo &S) { return !BC->isMarker(S.Symbol); });
895 if (!SortedSymbols.empty())
896 --LastSymbol;
899 BinaryFunction *PreviousFunction = nullptr;
900 unsigned AnonymousId = 0;
902 const auto SortedSymbolsEnd =
903 LastSymbol == SortedSymbols.end() ? LastSymbol : std::next(LastSymbol);
904 for (auto Iter = SortedSymbols.begin(); Iter != SortedSymbolsEnd; ++Iter) {
905 const SymbolRef &Symbol = Iter->Symbol;
906 const uint64_t SymbolAddress = Iter->Address;
907 const auto SymbolFlags = cantFail(Symbol.getFlags());
908 const SymbolRef::Type SymbolType = cantFail(Symbol.getType());
910 if (SymbolType == SymbolRef::ST_File)
911 continue;
913 StringRef SymName = cantFail(Symbol.getName(), "cannot get symbol name");
914 if (SymbolAddress == 0) {
915 if (opts::Verbosity >= 1 && SymbolType == SymbolRef::ST_Function)
916 BC->errs() << "BOLT-WARNING: function with 0 address seen\n";
917 continue;
920 // Ignore input hot markers
921 if (SymName == "__hot_start" || SymName == "__hot_end")
922 continue;
924 FileSymRefs.emplace(SymbolAddress, Symbol);
926 // Skip section symbols that will be registered by disassemblePLT().
927 if (SymbolType == SymbolRef::ST_Debug) {
928 ErrorOr<BinarySection &> BSection =
929 BC->getSectionForAddress(SymbolAddress);
930 if (BSection && getPLTSectionInfo(BSection->getName()))
931 continue;
934 /// It is possible we are seeing a globalized local. LLVM might treat it as
935 /// a local if it has a "private global" prefix, e.g. ".L". Thus we have to
936 /// change the prefix to enforce global scope of the symbol.
937 std::string Name =
938 SymName.starts_with(BC->AsmInfo->getPrivateGlobalPrefix())
939 ? "PG" + std::string(SymName)
940 : std::string(SymName);
942 // Disambiguate all local symbols before adding to symbol table.
943 // Since we don't know if we will see a global with the same name,
944 // always modify the local name.
946 // NOTE: the naming convention for local symbols should match
947 // the one we use for profile data.
948 std::string UniqueName;
949 std::string AlternativeName;
950 if (Name.empty()) {
951 UniqueName = "ANONYMOUS." + std::to_string(AnonymousId++);
952 } else if (SymbolFlags & SymbolRef::SF_Global) {
953 if (const BinaryData *BD = BC->getBinaryDataByName(Name)) {
954 if (BD->getSize() == ELFSymbolRef(Symbol).getSize() &&
955 BD->getAddress() == SymbolAddress) {
956 if (opts::Verbosity > 1)
957 BC->errs() << "BOLT-WARNING: ignoring duplicate global symbol "
958 << Name << "\n";
959 // Ignore duplicate entry - possibly a bug in the linker
960 continue;
962 BC->errs() << "BOLT-ERROR: bad input binary, global symbol \"" << Name
963 << "\" is not unique\n";
964 exit(1);
966 UniqueName = Name;
967 } else {
968 // If we have a local file name, we should create 2 variants for the
969 // function name. The reason is that perf profile might have been
970 // collected on a binary that did not have the local file name (e.g. as
971 // a side effect of stripping debug info from the binary):
973 // primary: <function>/<id>
974 // alternative: <function>/<file>/<id2>
976 // The <id> field is used for disambiguation of local symbols since there
977 // could be identical function names coming from identical file names
978 // (e.g. from different directories).
979 std::string AltPrefix;
980 auto SFI = SymbolToFileName.find(Symbol);
981 if (SymbolType == SymbolRef::ST_Function && SFI != SymbolToFileName.end())
982 AltPrefix = Name + "/" + std::string(SFI->second);
984 UniqueName = NR.uniquify(Name);
985 if (!AltPrefix.empty())
986 AlternativeName = NR.uniquify(AltPrefix);
989 uint64_t SymbolSize = ELFSymbolRef(Symbol).getSize();
990 uint64_t SymbolAlignment = Symbol.getAlignment();
992 auto registerName = [&](uint64_t FinalSize) {
993 // Register names even if it's not a function, e.g. for an entry point.
994 BC->registerNameAtAddress(UniqueName, SymbolAddress, FinalSize,
995 SymbolAlignment, SymbolFlags);
996 if (!AlternativeName.empty())
997 BC->registerNameAtAddress(AlternativeName, SymbolAddress, FinalSize,
998 SymbolAlignment, SymbolFlags);
1001 section_iterator Section =
1002 cantFail(Symbol.getSection(), "cannot get symbol section");
1003 if (Section == InputFile->section_end()) {
1004 // Could be an absolute symbol. Used on RISC-V for __global_pointer$ so we
1005 // need to record it to handle relocations against it. For other instances
1006 // of absolute symbols, we record for pretty printing.
1007 LLVM_DEBUG(if (opts::Verbosity > 1) {
1008 dbgs() << "BOLT-INFO: absolute sym " << UniqueName << "\n";
1010 registerName(SymbolSize);
1011 continue;
1014 if (SymName == getBOLTReservedStart() || SymName == getBOLTReservedEnd()) {
1015 registerName(SymbolSize);
1016 continue;
1019 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: considering symbol " << UniqueName
1020 << " for function\n");
1022 if (SymbolAddress == Section->getAddress() + Section->getSize()) {
1023 assert(SymbolSize == 0 &&
1024 "unexpect non-zero sized symbol at end of section");
1025 LLVM_DEBUG(
1026 dbgs()
1027 << "BOLT-DEBUG: rejecting as symbol points to end of its section\n");
1028 registerName(SymbolSize);
1029 continue;
1032 if (!Section->isText()) {
1033 assert(SymbolType != SymbolRef::ST_Function &&
1034 "unexpected function inside non-code section");
1035 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: rejecting as symbol is not in code\n");
1036 registerName(SymbolSize);
1037 continue;
1040 // Assembly functions could be ST_NONE with 0 size. Check that the
1041 // corresponding section is a code section and they are not inside any
1042 // other known function to consider them.
1044 // Sometimes assembly functions are not marked as functions and neither are
1045 // their local labels. The only way to tell them apart is to look at
1046 // symbol scope - global vs local.
1047 if (PreviousFunction && SymbolType != SymbolRef::ST_Function) {
1048 if (PreviousFunction->containsAddress(SymbolAddress)) {
1049 if (PreviousFunction->isSymbolValidInScope(Symbol, SymbolSize)) {
1050 LLVM_DEBUG(dbgs()
1051 << "BOLT-DEBUG: symbol is a function local symbol\n");
1052 } else if (SymbolAddress == PreviousFunction->getAddress() &&
1053 !SymbolSize) {
1054 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring symbol as a marker\n");
1055 } else if (opts::Verbosity > 1) {
1056 BC->errs() << "BOLT-WARNING: symbol " << UniqueName
1057 << " seen in the middle of function " << *PreviousFunction
1058 << ". Could be a new entry.\n";
1060 registerName(SymbolSize);
1061 continue;
1062 } else if (PreviousFunction->getSize() == 0 &&
1063 PreviousFunction->isSymbolValidInScope(Symbol, SymbolSize)) {
1064 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: symbol is a function local symbol\n");
1065 registerName(SymbolSize);
1066 continue;
1070 if (PreviousFunction && PreviousFunction->containsAddress(SymbolAddress) &&
1071 PreviousFunction->getAddress() != SymbolAddress) {
1072 if (PreviousFunction->isSymbolValidInScope(Symbol, SymbolSize)) {
1073 if (opts::Verbosity >= 1)
1074 BC->outs()
1075 << "BOLT-INFO: skipping possibly another entry for function "
1076 << *PreviousFunction << " : " << UniqueName << '\n';
1077 registerName(SymbolSize);
1078 } else {
1079 BC->outs() << "BOLT-INFO: using " << UniqueName
1080 << " as another entry to "
1081 << "function " << *PreviousFunction << '\n';
1083 registerName(0);
1085 PreviousFunction->addEntryPointAtOffset(SymbolAddress -
1086 PreviousFunction->getAddress());
1088 // Remove the symbol from FileSymRefs so that we can skip it from
1089 // in the future.
1090 auto SI = llvm::find_if(
1091 llvm::make_range(FileSymRefs.equal_range(SymbolAddress)),
1092 [&](auto SymIt) { return SymIt.second == Symbol; });
1093 assert(SI != FileSymRefs.end() && "symbol expected to be present");
1094 assert(SI->second == Symbol && "wrong symbol found");
1095 FileSymRefs.erase(SI);
1097 continue;
1100 // Checkout for conflicts with function data from FDEs.
1101 bool IsSimple = true;
1102 auto FDEI = CFIRdWrt->getFDEs().lower_bound(SymbolAddress);
1103 if (FDEI != CFIRdWrt->getFDEs().end()) {
1104 const dwarf::FDE &FDE = *FDEI->second;
1105 if (FDEI->first != SymbolAddress) {
1106 // There's no matching starting address in FDE. Make sure the previous
1107 // FDE does not contain this address.
1108 if (FDEI != CFIRdWrt->getFDEs().begin()) {
1109 --FDEI;
1110 const dwarf::FDE &PrevFDE = *FDEI->second;
1111 uint64_t PrevStart = PrevFDE.getInitialLocation();
1112 uint64_t PrevLength = PrevFDE.getAddressRange();
1113 if (SymbolAddress > PrevStart &&
1114 SymbolAddress < PrevStart + PrevLength) {
1115 BC->errs() << "BOLT-ERROR: function " << UniqueName
1116 << " is in conflict with FDE ["
1117 << Twine::utohexstr(PrevStart) << ", "
1118 << Twine::utohexstr(PrevStart + PrevLength)
1119 << "). Skipping.\n";
1120 IsSimple = false;
1123 } else if (FDE.getAddressRange() != SymbolSize) {
1124 if (SymbolSize) {
1125 // Function addresses match but sizes differ.
1126 BC->errs() << "BOLT-WARNING: sizes differ for function " << UniqueName
1127 << ". FDE : " << FDE.getAddressRange()
1128 << "; symbol table : " << SymbolSize
1129 << ". Using max size.\n";
1131 SymbolSize = std::max(SymbolSize, FDE.getAddressRange());
1132 if (BC->getBinaryDataAtAddress(SymbolAddress)) {
1133 BC->setBinaryDataSize(SymbolAddress, SymbolSize);
1134 } else {
1135 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: No BD @ 0x"
1136 << Twine::utohexstr(SymbolAddress) << "\n");
1141 BinaryFunction *BF = nullptr;
1142 // Since function may not have yet obtained its real size, do a search
1143 // using the list of registered functions instead of calling
1144 // getBinaryFunctionAtAddress().
1145 auto BFI = BC->getBinaryFunctions().find(SymbolAddress);
1146 if (BFI != BC->getBinaryFunctions().end()) {
1147 BF = &BFI->second;
1148 // Duplicate the function name. Make sure everything matches before we add
1149 // an alternative name.
1150 if (SymbolSize != BF->getSize()) {
1151 if (opts::Verbosity >= 1) {
1152 if (SymbolSize && BF->getSize())
1153 BC->errs() << "BOLT-WARNING: size mismatch for duplicate entries "
1154 << *BF << " and " << UniqueName << '\n';
1155 BC->outs() << "BOLT-INFO: adjusting size of function " << *BF
1156 << " old " << BF->getSize() << " new " << SymbolSize
1157 << "\n";
1159 BF->setSize(std::max(SymbolSize, BF->getSize()));
1160 BC->setBinaryDataSize(SymbolAddress, BF->getSize());
1162 BF->addAlternativeName(UniqueName);
1163 } else {
1164 ErrorOr<BinarySection &> Section =
1165 BC->getSectionForAddress(SymbolAddress);
1166 // Skip symbols from invalid sections
1167 if (!Section) {
1168 BC->errs() << "BOLT-WARNING: " << UniqueName << " (0x"
1169 << Twine::utohexstr(SymbolAddress)
1170 << ") does not have any section\n";
1171 continue;
1174 // Skip symbols from zero-sized sections.
1175 if (!Section->getSize())
1176 continue;
1178 BF = BC->createBinaryFunction(UniqueName, *Section, SymbolAddress,
1179 SymbolSize);
1180 if (!IsSimple)
1181 BF->setSimple(false);
1184 // Check if it's a cold function fragment.
1185 if (FunctionFragmentTemplate.match(SymName)) {
1186 static bool PrintedWarning = false;
1187 if (!PrintedWarning) {
1188 PrintedWarning = true;
1189 BC->errs() << "BOLT-WARNING: split function detected on input : "
1190 << SymName;
1191 if (BC->HasRelocations)
1192 BC->errs() << ". The support is limited in relocation mode\n";
1193 else
1194 BC->errs() << '\n';
1196 BC->HasSplitFunctions = true;
1197 BF->IsFragment = true;
1200 if (!AlternativeName.empty())
1201 BF->addAlternativeName(AlternativeName);
1203 registerName(SymbolSize);
1204 PreviousFunction = BF;
1207 // Read dynamic relocation first as their presence affects the way we process
1208 // static relocations. E.g. we will ignore a static relocation at an address
1209 // that is a subject to dynamic relocation processing.
1210 processDynamicRelocations();
1212 // Process PLT section.
1213 disassemblePLT();
1215 // See if we missed any functions marked by FDE.
1216 for (const auto &FDEI : CFIRdWrt->getFDEs()) {
1217 const uint64_t Address = FDEI.first;
1218 const dwarf::FDE *FDE = FDEI.second;
1219 const BinaryFunction *BF = BC->getBinaryFunctionAtAddress(Address);
1220 if (BF)
1221 continue;
1223 BF = BC->getBinaryFunctionContainingAddress(Address);
1224 if (BF) {
1225 BC->errs() << "BOLT-WARNING: FDE [0x" << Twine::utohexstr(Address)
1226 << ", 0x" << Twine::utohexstr(Address + FDE->getAddressRange())
1227 << ") conflicts with function " << *BF << '\n';
1228 continue;
1231 if (opts::Verbosity >= 1)
1232 BC->errs() << "BOLT-WARNING: FDE [0x" << Twine::utohexstr(Address)
1233 << ", 0x" << Twine::utohexstr(Address + FDE->getAddressRange())
1234 << ") has no corresponding symbol table entry\n";
1236 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(Address);
1237 assert(Section && "cannot get section for address from FDE");
1238 std::string FunctionName =
1239 "__BOLT_FDE_FUNCat" + Twine::utohexstr(Address).str();
1240 BC->createBinaryFunction(FunctionName, *Section, Address,
1241 FDE->getAddressRange());
1244 BC->setHasSymbolsWithFileName(SeenFileName);
1246 // Now that all the functions were created - adjust their boundaries.
1247 adjustFunctionBoundaries();
1249 // Annotate functions with code/data markers in AArch64
1250 for (auto ISym = SortedMarkerSymbols.begin();
1251 ISym != SortedMarkerSymbols.end(); ++ISym) {
1253 auto *BF =
1254 BC->getBinaryFunctionContainingAddress(ISym->Address, true, true);
1256 if (!BF) {
1257 // Stray marker
1258 continue;
1260 const auto EntryOffset = ISym->Address - BF->getAddress();
1261 if (ISym->Type == MarkerSymType::CODE) {
1262 BF->markCodeAtOffset(EntryOffset);
1263 continue;
1265 if (ISym->Type == MarkerSymType::DATA) {
1266 BF->markDataAtOffset(EntryOffset);
1267 BC->AddressToConstantIslandMap[ISym->Address] = BF;
1268 continue;
1270 llvm_unreachable("Unknown marker");
1273 if (BC->isAArch64()) {
1274 // Check for dynamic relocations that might be contained in
1275 // constant islands.
1276 for (const BinarySection &Section : BC->allocatableSections()) {
1277 const uint64_t SectionAddress = Section.getAddress();
1278 for (const Relocation &Rel : Section.dynamicRelocations()) {
1279 const uint64_t RelAddress = SectionAddress + Rel.Offset;
1280 BinaryFunction *BF =
1281 BC->getBinaryFunctionContainingAddress(RelAddress,
1282 /*CheckPastEnd*/ false,
1283 /*UseMaxSize*/ true);
1284 if (BF) {
1285 assert(Rel.isRelative() && "Expected relative relocation for island");
1286 BC->logBOLTErrorsAndQuitOnFatal(
1287 BF->markIslandDynamicRelocationAtAddress(RelAddress));
1293 if (!BC->IsLinuxKernel) {
1294 // Read all relocations now that we have binary functions mapped.
1295 processRelocations();
1298 registerFragments();
1299 FileSymbols.clear();
1300 FileSymRefs.clear();
1302 discoverBOLTReserved();
1305 void RewriteInstance::discoverBOLTReserved() {
1306 BinaryData *StartBD = BC->getBinaryDataByName(getBOLTReservedStart());
1307 BinaryData *EndBD = BC->getBinaryDataByName(getBOLTReservedEnd());
1308 if (!StartBD != !EndBD) {
1309 BC->errs() << "BOLT-ERROR: one of the symbols is missing from the binary: "
1310 << getBOLTReservedStart() << ", " << getBOLTReservedEnd()
1311 << '\n';
1312 exit(1);
1315 if (!StartBD)
1316 return;
1318 if (StartBD->getAddress() >= EndBD->getAddress()) {
1319 BC->errs() << "BOLT-ERROR: invalid reserved space boundaries\n";
1320 exit(1);
1322 BC->BOLTReserved = AddressRange(StartBD->getAddress(), EndBD->getAddress());
1323 BC->outs() << "BOLT-INFO: using reserved space for allocating new sections\n";
1325 PHDRTableOffset = 0;
1326 PHDRTableAddress = 0;
1327 NewTextSegmentAddress = 0;
1328 NewTextSegmentOffset = 0;
1329 NextAvailableAddress = BC->BOLTReserved.start();
1332 Error RewriteInstance::discoverRtFiniAddress() {
1333 // Use DT_FINI if it's available.
1334 if (BC->FiniAddress) {
1335 BC->FiniFunctionAddress = BC->FiniAddress;
1336 return Error::success();
1339 if (!BC->FiniArrayAddress || !BC->FiniArraySize) {
1340 return createStringError(
1341 std::errc::not_supported,
1342 "Instrumentation needs either DT_FINI or DT_FINI_ARRAY");
1345 if (*BC->FiniArraySize < BC->AsmInfo->getCodePointerSize()) {
1346 return createStringError(std::errc::not_supported,
1347 "Need at least 1 DT_FINI_ARRAY slot");
1350 ErrorOr<BinarySection &> FiniArraySection =
1351 BC->getSectionForAddress(*BC->FiniArrayAddress);
1352 if (auto EC = FiniArraySection.getError())
1353 return errorCodeToError(EC);
1355 if (const Relocation *Reloc = FiniArraySection->getDynamicRelocationAt(0)) {
1356 BC->FiniFunctionAddress = Reloc->Addend;
1357 return Error::success();
1360 if (const Relocation *Reloc = FiniArraySection->getRelocationAt(0)) {
1361 BC->FiniFunctionAddress = Reloc->Value;
1362 return Error::success();
1365 return createStringError(std::errc::not_supported,
1366 "No relocation for first DT_FINI_ARRAY slot");
1369 void RewriteInstance::updateRtFiniReloc() {
1370 // Updating DT_FINI is handled by patchELFDynamic.
1371 if (BC->FiniAddress)
1372 return;
1374 const RuntimeLibrary *RT = BC->getRuntimeLibrary();
1375 if (!RT || !RT->getRuntimeFiniAddress())
1376 return;
1378 assert(BC->FiniArrayAddress && BC->FiniArraySize &&
1379 "inconsistent .fini_array state");
1381 ErrorOr<BinarySection &> FiniArraySection =
1382 BC->getSectionForAddress(*BC->FiniArrayAddress);
1383 assert(FiniArraySection && ".fini_array removed");
1385 if (std::optional<Relocation> Reloc =
1386 FiniArraySection->takeDynamicRelocationAt(0)) {
1387 assert(Reloc->Addend == BC->FiniFunctionAddress &&
1388 "inconsistent .fini_array dynamic relocation");
1389 Reloc->Addend = RT->getRuntimeFiniAddress();
1390 FiniArraySection->addDynamicRelocation(*Reloc);
1393 // Update the static relocation by adding a pending relocation which will get
1394 // patched when flushPendingRelocations is called in rewriteFile. Note that
1395 // flushPendingRelocations will calculate the value to patch as
1396 // "Symbol + Addend". Since we don't have a symbol, just set the addend to the
1397 // desired value.
1398 FiniArraySection->addPendingRelocation(Relocation{
1399 /*Offset*/ 0, /*Symbol*/ nullptr, /*Type*/ Relocation::getAbs64(),
1400 /*Addend*/ RT->getRuntimeFiniAddress(), /*Value*/ 0});
1403 void RewriteInstance::registerFragments() {
1404 if (!BC->HasSplitFunctions)
1405 return;
1407 // Process fragments with ambiguous parents separately as they are typically a
1408 // vanishing minority of cases and require expensive symbol table lookups.
1409 std::vector<std::pair<StringRef, BinaryFunction *>> AmbiguousFragments;
1410 for (auto &BFI : BC->getBinaryFunctions()) {
1411 BinaryFunction &Function = BFI.second;
1412 if (!Function.isFragment())
1413 continue;
1414 for (StringRef Name : Function.getNames()) {
1415 StringRef BaseName = NR.restore(Name);
1416 const bool IsGlobal = BaseName == Name;
1417 SmallVector<StringRef> Matches;
1418 if (!FunctionFragmentTemplate.match(BaseName, &Matches))
1419 continue;
1420 StringRef ParentName = Matches[1];
1421 const BinaryData *BD = BC->getBinaryDataByName(ParentName);
1422 const uint64_t NumPossibleLocalParents =
1423 NR.getUniquifiedNameCount(ParentName);
1424 // The most common case: single local parent fragment.
1425 if (!BD && NumPossibleLocalParents == 1) {
1426 BD = BC->getBinaryDataByName(NR.getUniqueName(ParentName, 1));
1427 } else if (BD && (!NumPossibleLocalParents || IsGlobal)) {
1428 // Global parent and either no local candidates (second most common), or
1429 // the fragment is global as well (uncommon).
1430 } else {
1431 // Any other case: need to disambiguate using FILE symbols.
1432 AmbiguousFragments.emplace_back(ParentName, &Function);
1433 continue;
1435 if (BD) {
1436 BinaryFunction *BF = BC->getFunctionForSymbol(BD->getSymbol());
1437 if (BF) {
1438 BC->registerFragment(Function, *BF);
1439 continue;
1442 BC->errs() << "BOLT-ERROR: parent function not found for " << Function
1443 << '\n';
1444 exit(1);
1448 if (AmbiguousFragments.empty())
1449 return;
1451 if (!BC->hasSymbolsWithFileName()) {
1452 BC->errs() << "BOLT-ERROR: input file has split functions but does not "
1453 "have FILE symbols. If the binary was stripped, preserve "
1454 "FILE symbols with --keep-file-symbols strip option\n";
1455 exit(1);
1458 // The first global symbol is identified by the symbol table sh_info value.
1459 // Used as local symbol search stopping point.
1460 auto *ELF64LEFile = cast<ELF64LEObjectFile>(InputFile);
1461 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile();
1462 auto *SymTab = llvm::find_if(cantFail(Obj.sections()), [](const auto &Sec) {
1463 return Sec.sh_type == ELF::SHT_SYMTAB;
1465 assert(SymTab);
1466 // Symtab sh_info contains the value one greater than the symbol table index
1467 // of the last local symbol.
1468 ELFSymbolRef LocalSymEnd = ELF64LEFile->toSymbolRef(SymTab, SymTab->sh_info);
1470 for (auto &Fragment : AmbiguousFragments) {
1471 const StringRef &ParentName = Fragment.first;
1472 BinaryFunction *BF = Fragment.second;
1473 const uint64_t Address = BF->getAddress();
1475 // Get fragment's own symbol
1476 const auto SymIt = llvm::find_if(
1477 llvm::make_range(FileSymRefs.equal_range(Address)), [&](auto SI) {
1478 StringRef Name = cantFail(SI.second.getName());
1479 return Name.contains(ParentName);
1481 if (SymIt == FileSymRefs.end()) {
1482 BC->errs()
1483 << "BOLT-ERROR: symbol lookup failed for function at address 0x"
1484 << Twine::utohexstr(Address) << '\n';
1485 exit(1);
1488 // Find containing FILE symbol
1489 ELFSymbolRef Symbol = SymIt->second;
1490 auto FSI = llvm::upper_bound(FileSymbols, Symbol);
1491 if (FSI == FileSymbols.begin()) {
1492 BC->errs() << "BOLT-ERROR: owning FILE symbol not found for symbol "
1493 << cantFail(Symbol.getName()) << '\n';
1494 exit(1);
1497 ELFSymbolRef StopSymbol = LocalSymEnd;
1498 if (FSI != FileSymbols.end())
1499 StopSymbol = *FSI;
1501 uint64_t ParentAddress{0};
1503 // BOLT split fragment symbols are emitted just before the main function
1504 // symbol.
1505 for (ELFSymbolRef NextSymbol = Symbol; NextSymbol < StopSymbol;
1506 NextSymbol.moveNext()) {
1507 StringRef Name = cantFail(NextSymbol.getName());
1508 if (Name == ParentName) {
1509 ParentAddress = cantFail(NextSymbol.getValue());
1510 goto registerParent;
1512 if (Name.starts_with(ParentName))
1513 // With multi-way splitting, there are multiple fragments with different
1514 // suffixes. Parent follows the last fragment.
1515 continue;
1516 break;
1519 // Iterate over local file symbols and check symbol names to match parent.
1520 for (ELFSymbolRef Symbol(FSI[-1]); Symbol < StopSymbol; Symbol.moveNext()) {
1521 if (cantFail(Symbol.getName()) == ParentName) {
1522 ParentAddress = cantFail(Symbol.getAddress());
1523 break;
1527 registerParent:
1528 // No local parent is found, use global parent function.
1529 if (!ParentAddress)
1530 if (BinaryData *ParentBD = BC->getBinaryDataByName(ParentName))
1531 ParentAddress = ParentBD->getAddress();
1533 if (BinaryFunction *ParentBF =
1534 BC->getBinaryFunctionAtAddress(ParentAddress)) {
1535 BC->registerFragment(*BF, *ParentBF);
1536 continue;
1538 BC->errs() << "BOLT-ERROR: parent function not found for " << *BF << '\n';
1539 exit(1);
1543 void RewriteInstance::createPLTBinaryFunction(uint64_t TargetAddress,
1544 uint64_t EntryAddress,
1545 uint64_t EntrySize) {
1546 if (!TargetAddress)
1547 return;
1549 auto setPLTSymbol = [&](BinaryFunction *BF, StringRef Name) {
1550 const unsigned PtrSize = BC->AsmInfo->getCodePointerSize();
1551 MCSymbol *TargetSymbol = BC->registerNameAtAddress(
1552 Name.str() + "@GOT", TargetAddress, PtrSize, PtrSize);
1553 BF->setPLTSymbol(TargetSymbol);
1556 BinaryFunction *BF = BC->getBinaryFunctionAtAddress(EntryAddress);
1557 if (BF && BC->isAArch64()) {
1558 // Handle IFUNC trampoline with symbol
1559 setPLTSymbol(BF, BF->getOneName());
1560 return;
1563 const Relocation *Rel = BC->getDynamicRelocationAt(TargetAddress);
1564 if (!Rel)
1565 return;
1567 MCSymbol *Symbol = Rel->Symbol;
1568 if (!Symbol) {
1569 if (BC->isRISCV() || !Rel->Addend || !Rel->isIRelative())
1570 return;
1572 // IFUNC trampoline without symbol
1573 BinaryFunction *TargetBF = BC->getBinaryFunctionAtAddress(Rel->Addend);
1574 if (!TargetBF) {
1575 BC->errs()
1576 << "BOLT-WARNING: Expected BF to be presented as IFUNC resolver at "
1577 << Twine::utohexstr(Rel->Addend) << ", skipping\n";
1578 return;
1581 Symbol = TargetBF->getSymbol();
1584 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(EntryAddress);
1585 assert(Section && "cannot get section for address");
1586 if (!BF)
1587 BF = BC->createBinaryFunction(Symbol->getName().str() + "@PLT", *Section,
1588 EntryAddress, 0, EntrySize,
1589 Section->getAlignment());
1590 else
1591 BF->addAlternativeName(Symbol->getName().str() + "@PLT");
1592 setPLTSymbol(BF, Symbol->getName());
1595 void RewriteInstance::disassemblePLTInstruction(const BinarySection &Section,
1596 uint64_t InstrOffset,
1597 MCInst &Instruction,
1598 uint64_t &InstrSize) {
1599 const uint64_t SectionAddress = Section.getAddress();
1600 const uint64_t SectionSize = Section.getSize();
1601 StringRef PLTContents = Section.getContents();
1602 ArrayRef<uint8_t> PLTData(
1603 reinterpret_cast<const uint8_t *>(PLTContents.data()), SectionSize);
1605 const uint64_t InstrAddr = SectionAddress + InstrOffset;
1606 if (!BC->DisAsm->getInstruction(Instruction, InstrSize,
1607 PLTData.slice(InstrOffset), InstrAddr,
1608 nulls())) {
1609 BC->errs()
1610 << "BOLT-ERROR: unable to disassemble instruction in PLT section "
1611 << Section.getName() << formatv(" at offset {0:x}\n", InstrOffset);
1612 exit(1);
1616 void RewriteInstance::disassemblePLTSectionAArch64(BinarySection &Section) {
1617 const uint64_t SectionAddress = Section.getAddress();
1618 const uint64_t SectionSize = Section.getSize();
1620 uint64_t InstrOffset = 0;
1621 // Locate new plt entry
1622 while (InstrOffset < SectionSize) {
1623 InstructionListType Instructions;
1624 MCInst Instruction;
1625 uint64_t EntryOffset = InstrOffset;
1626 uint64_t EntrySize = 0;
1627 uint64_t InstrSize;
1628 // Loop through entry instructions
1629 while (InstrOffset < SectionSize) {
1630 disassemblePLTInstruction(Section, InstrOffset, Instruction, InstrSize);
1631 EntrySize += InstrSize;
1632 if (!BC->MIB->isIndirectBranch(Instruction)) {
1633 Instructions.emplace_back(Instruction);
1634 InstrOffset += InstrSize;
1635 continue;
1638 const uint64_t EntryAddress = SectionAddress + EntryOffset;
1639 const uint64_t TargetAddress = BC->MIB->analyzePLTEntry(
1640 Instruction, Instructions.begin(), Instructions.end(), EntryAddress);
1642 createPLTBinaryFunction(TargetAddress, EntryAddress, EntrySize);
1643 break;
1646 // Branch instruction
1647 InstrOffset += InstrSize;
1649 // Skip nops if any
1650 while (InstrOffset < SectionSize) {
1651 disassemblePLTInstruction(Section, InstrOffset, Instruction, InstrSize);
1652 if (!BC->MIB->isNoop(Instruction))
1653 break;
1655 InstrOffset += InstrSize;
1660 void RewriteInstance::disassemblePLTSectionRISCV(BinarySection &Section) {
1661 const uint64_t SectionAddress = Section.getAddress();
1662 const uint64_t SectionSize = Section.getSize();
1663 StringRef PLTContents = Section.getContents();
1664 ArrayRef<uint8_t> PLTData(
1665 reinterpret_cast<const uint8_t *>(PLTContents.data()), SectionSize);
1667 auto disassembleInstruction = [&](uint64_t InstrOffset, MCInst &Instruction,
1668 uint64_t &InstrSize) {
1669 const uint64_t InstrAddr = SectionAddress + InstrOffset;
1670 if (!BC->DisAsm->getInstruction(Instruction, InstrSize,
1671 PLTData.slice(InstrOffset), InstrAddr,
1672 nulls())) {
1673 BC->errs()
1674 << "BOLT-ERROR: unable to disassemble instruction in PLT section "
1675 << Section.getName() << " at offset 0x"
1676 << Twine::utohexstr(InstrOffset) << '\n';
1677 exit(1);
1681 // Skip the first special entry since no relocation points to it.
1682 uint64_t InstrOffset = 32;
1684 while (InstrOffset < SectionSize) {
1685 InstructionListType Instructions;
1686 MCInst Instruction;
1687 const uint64_t EntryOffset = InstrOffset;
1688 const uint64_t EntrySize = 16;
1689 uint64_t InstrSize;
1691 while (InstrOffset < EntryOffset + EntrySize) {
1692 disassembleInstruction(InstrOffset, Instruction, InstrSize);
1693 Instructions.emplace_back(Instruction);
1694 InstrOffset += InstrSize;
1697 const uint64_t EntryAddress = SectionAddress + EntryOffset;
1698 const uint64_t TargetAddress = BC->MIB->analyzePLTEntry(
1699 Instruction, Instructions.begin(), Instructions.end(), EntryAddress);
1701 createPLTBinaryFunction(TargetAddress, EntryAddress, EntrySize);
1705 void RewriteInstance::disassemblePLTSectionX86(BinarySection &Section,
1706 uint64_t EntrySize) {
1707 const uint64_t SectionAddress = Section.getAddress();
1708 const uint64_t SectionSize = Section.getSize();
1710 for (uint64_t EntryOffset = 0; EntryOffset + EntrySize <= SectionSize;
1711 EntryOffset += EntrySize) {
1712 MCInst Instruction;
1713 uint64_t InstrSize, InstrOffset = EntryOffset;
1714 while (InstrOffset < EntryOffset + EntrySize) {
1715 disassemblePLTInstruction(Section, InstrOffset, Instruction, InstrSize);
1716 // Check if the entry size needs adjustment.
1717 if (EntryOffset == 0 && BC->MIB->isTerminateBranch(Instruction) &&
1718 EntrySize == 8)
1719 EntrySize = 16;
1721 if (BC->MIB->isIndirectBranch(Instruction))
1722 break;
1724 InstrOffset += InstrSize;
1727 if (InstrOffset + InstrSize > EntryOffset + EntrySize)
1728 continue;
1730 uint64_t TargetAddress;
1731 if (!BC->MIB->evaluateMemOperandTarget(Instruction, TargetAddress,
1732 SectionAddress + InstrOffset,
1733 InstrSize)) {
1734 BC->errs() << "BOLT-ERROR: error evaluating PLT instruction at offset 0x"
1735 << Twine::utohexstr(SectionAddress + InstrOffset) << '\n';
1736 exit(1);
1739 createPLTBinaryFunction(TargetAddress, SectionAddress + EntryOffset,
1740 EntrySize);
1744 void RewriteInstance::disassemblePLT() {
1745 auto analyzeOnePLTSection = [&](BinarySection &Section, uint64_t EntrySize) {
1746 if (BC->isAArch64())
1747 return disassemblePLTSectionAArch64(Section);
1748 if (BC->isRISCV())
1749 return disassemblePLTSectionRISCV(Section);
1750 if (BC->isX86())
1751 return disassemblePLTSectionX86(Section, EntrySize);
1752 llvm_unreachable("Unmplemented PLT");
1755 for (BinarySection &Section : BC->allocatableSections()) {
1756 const PLTSectionInfo *PLTSI = getPLTSectionInfo(Section.getName());
1757 if (!PLTSI)
1758 continue;
1760 analyzeOnePLTSection(Section, PLTSI->EntrySize);
1762 BinaryFunction *PltBF;
1763 auto BFIter = BC->getBinaryFunctions().find(Section.getAddress());
1764 if (BFIter != BC->getBinaryFunctions().end()) {
1765 PltBF = &BFIter->second;
1766 } else {
1767 // If we did not register any function at the start of the section,
1768 // then it must be a general PLT entry. Add a function at the location.
1769 PltBF = BC->createBinaryFunction(
1770 "__BOLT_PSEUDO_" + Section.getName().str(), Section,
1771 Section.getAddress(), 0, PLTSI->EntrySize, Section.getAlignment());
1773 PltBF->setPseudo(true);
1777 void RewriteInstance::adjustFunctionBoundaries() {
1778 for (auto BFI = BC->getBinaryFunctions().begin(),
1779 BFE = BC->getBinaryFunctions().end();
1780 BFI != BFE; ++BFI) {
1781 BinaryFunction &Function = BFI->second;
1782 const BinaryFunction *NextFunction = nullptr;
1783 if (std::next(BFI) != BFE)
1784 NextFunction = &std::next(BFI)->second;
1786 // Check if there's a symbol or a function with a larger address in the
1787 // same section. If there is - it determines the maximum size for the
1788 // current function. Otherwise, it is the size of a containing section
1789 // the defines it.
1791 // NOTE: ignore some symbols that could be tolerated inside the body
1792 // of a function.
1793 auto NextSymRefI = FileSymRefs.upper_bound(Function.getAddress());
1794 while (NextSymRefI != FileSymRefs.end()) {
1795 SymbolRef &Symbol = NextSymRefI->second;
1796 const uint64_t SymbolAddress = NextSymRefI->first;
1797 const uint64_t SymbolSize = ELFSymbolRef(Symbol).getSize();
1799 if (NextFunction && SymbolAddress >= NextFunction->getAddress())
1800 break;
1802 if (!Function.isSymbolValidInScope(Symbol, SymbolSize))
1803 break;
1805 // Skip basic block labels. This happens on RISC-V with linker relaxation
1806 // enabled because every branch needs a relocation and corresponding
1807 // symbol. We don't want to add such symbols as entry points.
1808 const auto PrivateLabelPrefix = BC->AsmInfo->getPrivateLabelPrefix();
1809 if (!PrivateLabelPrefix.empty() &&
1810 cantFail(Symbol.getName()).starts_with(PrivateLabelPrefix)) {
1811 ++NextSymRefI;
1812 continue;
1815 // This is potentially another entry point into the function.
1816 uint64_t EntryOffset = NextSymRefI->first - Function.getAddress();
1817 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding entry point to function "
1818 << Function << " at offset 0x"
1819 << Twine::utohexstr(EntryOffset) << '\n');
1820 Function.addEntryPointAtOffset(EntryOffset);
1822 ++NextSymRefI;
1825 // Function runs at most till the end of the containing section.
1826 uint64_t NextObjectAddress = Function.getOriginSection()->getEndAddress();
1827 // Or till the next object marked by a symbol.
1828 if (NextSymRefI != FileSymRefs.end())
1829 NextObjectAddress = std::min(NextSymRefI->first, NextObjectAddress);
1831 // Or till the next function not marked by a symbol.
1832 if (NextFunction)
1833 NextObjectAddress =
1834 std::min(NextFunction->getAddress(), NextObjectAddress);
1836 const uint64_t MaxSize = NextObjectAddress - Function.getAddress();
1837 if (MaxSize < Function.getSize()) {
1838 BC->errs() << "BOLT-ERROR: symbol seen in the middle of the function "
1839 << Function << ". Skipping.\n";
1840 Function.setSimple(false);
1841 Function.setMaxSize(Function.getSize());
1842 continue;
1844 Function.setMaxSize(MaxSize);
1845 if (!Function.getSize() && Function.isSimple()) {
1846 // Some assembly functions have their size set to 0, use the max
1847 // size as their real size.
1848 if (opts::Verbosity >= 1)
1849 BC->outs() << "BOLT-INFO: setting size of function " << Function
1850 << " to " << Function.getMaxSize() << " (was 0)\n";
1851 Function.setSize(Function.getMaxSize());
1856 void RewriteInstance::relocateEHFrameSection() {
1857 assert(EHFrameSection && "Non-empty .eh_frame section expected.");
1859 BinarySection *RelocatedEHFrameSection =
1860 getSection(".relocated" + getEHFrameSectionName());
1861 assert(RelocatedEHFrameSection &&
1862 "Relocated eh_frame section should be preregistered.");
1863 DWARFDataExtractor DE(EHFrameSection->getContents(),
1864 BC->AsmInfo->isLittleEndian(),
1865 BC->AsmInfo->getCodePointerSize());
1866 auto createReloc = [&](uint64_t Value, uint64_t Offset, uint64_t DwarfType) {
1867 if (DwarfType == dwarf::DW_EH_PE_omit)
1868 return;
1870 // Only fix references that are relative to other locations.
1871 if (!(DwarfType & dwarf::DW_EH_PE_pcrel) &&
1872 !(DwarfType & dwarf::DW_EH_PE_textrel) &&
1873 !(DwarfType & dwarf::DW_EH_PE_funcrel) &&
1874 !(DwarfType & dwarf::DW_EH_PE_datarel))
1875 return;
1877 if (!(DwarfType & dwarf::DW_EH_PE_sdata4))
1878 return;
1880 uint64_t RelType;
1881 switch (DwarfType & 0x0f) {
1882 default:
1883 llvm_unreachable("unsupported DWARF encoding type");
1884 case dwarf::DW_EH_PE_sdata4:
1885 case dwarf::DW_EH_PE_udata4:
1886 RelType = Relocation::getPC32();
1887 Offset -= 4;
1888 break;
1889 case dwarf::DW_EH_PE_sdata8:
1890 case dwarf::DW_EH_PE_udata8:
1891 RelType = Relocation::getPC64();
1892 Offset -= 8;
1893 break;
1896 // Create a relocation against an absolute value since the goal is to
1897 // preserve the contents of the section independent of the new values
1898 // of referenced symbols.
1899 RelocatedEHFrameSection->addRelocation(Offset, nullptr, RelType, Value);
1902 Error E = EHFrameParser::parse(DE, EHFrameSection->getAddress(), createReloc);
1903 check_error(std::move(E), "failed to patch EH frame");
1906 Error RewriteInstance::readSpecialSections() {
1907 NamedRegionTimer T("readSpecialSections", "read special sections",
1908 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
1910 bool HasTextRelocations = false;
1911 bool HasSymbolTable = false;
1912 bool HasDebugInfo = false;
1914 // Process special sections.
1915 for (const SectionRef &Section : InputFile->sections()) {
1916 Expected<StringRef> SectionNameOrErr = Section.getName();
1917 check_error(SectionNameOrErr.takeError(), "cannot get section name");
1918 StringRef SectionName = *SectionNameOrErr;
1920 if (Error E = Section.getContents().takeError())
1921 return E;
1922 BC->registerSection(Section);
1923 LLVM_DEBUG(
1924 dbgs() << "BOLT-DEBUG: registering section " << SectionName << " @ 0x"
1925 << Twine::utohexstr(Section.getAddress()) << ":0x"
1926 << Twine::utohexstr(Section.getAddress() + Section.getSize())
1927 << "\n");
1928 if (isDebugSection(SectionName))
1929 HasDebugInfo = true;
1932 // Set IsRelro section attribute based on PT_GNU_RELRO segment.
1933 markGnuRelroSections();
1935 if (HasDebugInfo && !opts::UpdateDebugSections && !opts::AggregateOnly) {
1936 BC->errs() << "BOLT-WARNING: debug info will be stripped from the binary. "
1937 "Use -update-debug-sections to keep it.\n";
1940 HasTextRelocations = (bool)BC->getUniqueSectionByName(
1941 ".rela" + std::string(BC->getMainCodeSectionName()));
1942 HasSymbolTable = (bool)BC->getUniqueSectionByName(".symtab");
1943 EHFrameSection = BC->getUniqueSectionByName(".eh_frame");
1945 if (ErrorOr<BinarySection &> BATSec =
1946 BC->getUniqueSectionByName(BoltAddressTranslation::SECTION_NAME)) {
1947 BC->HasBATSection = true;
1948 // Do not read BAT when plotting a heatmap
1949 if (!opts::HeatmapMode) {
1950 if (std::error_code EC = BAT->parse(BC->outs(), BATSec->getContents())) {
1951 BC->errs() << "BOLT-ERROR: failed to parse BOLT address translation "
1952 "table.\n";
1953 exit(1);
1958 if (opts::PrintSections) {
1959 BC->outs() << "BOLT-INFO: Sections from original binary:\n";
1960 BC->printSections(BC->outs());
1963 if (opts::RelocationMode == cl::BOU_TRUE && !HasTextRelocations) {
1964 BC->errs()
1965 << "BOLT-ERROR: relocations against code are missing from the input "
1966 "file. Cannot proceed in relocations mode (-relocs).\n";
1967 exit(1);
1970 BC->HasRelocations =
1971 HasTextRelocations && (opts::RelocationMode != cl::BOU_FALSE);
1973 if (BC->IsLinuxKernel && BC->HasRelocations) {
1974 BC->outs() << "BOLT-INFO: disabling relocation mode for Linux kernel\n";
1975 BC->HasRelocations = false;
1978 BC->IsStripped = !HasSymbolTable;
1980 if (BC->IsStripped && !opts::AllowStripped) {
1981 BC->errs()
1982 << "BOLT-ERROR: stripped binaries are not supported. If you know "
1983 "what you're doing, use --allow-stripped to proceed";
1984 exit(1);
1987 // Force non-relocation mode for heatmap generation
1988 if (opts::HeatmapMode)
1989 BC->HasRelocations = false;
1991 if (BC->HasRelocations)
1992 BC->outs() << "BOLT-INFO: enabling " << (opts::StrictMode ? "strict " : "")
1993 << "relocation mode\n";
1995 // Read EH frame for function boundaries info.
1996 Expected<const DWARFDebugFrame *> EHFrameOrError = BC->DwCtx->getEHFrame();
1997 if (!EHFrameOrError)
1998 report_error("expected valid eh_frame section", EHFrameOrError.takeError());
1999 CFIRdWrt.reset(new CFIReaderWriter(*BC, *EHFrameOrError.get()));
2001 processSectionMetadata();
2003 // Read .dynamic/PT_DYNAMIC.
2004 return readELFDynamic();
2007 void RewriteInstance::adjustCommandLineOptions() {
2008 if (BC->isAArch64() && !BC->HasRelocations)
2009 BC->errs() << "BOLT-WARNING: non-relocation mode for AArch64 is not fully "
2010 "supported\n";
2012 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary())
2013 RtLibrary->adjustCommandLineOptions(*BC);
2015 if (BC->isX86() && BC->MAB->allowAutoPadding()) {
2016 if (!BC->HasRelocations) {
2017 BC->errs()
2018 << "BOLT-ERROR: cannot apply mitigations for Intel JCC erratum in "
2019 "non-relocation mode\n";
2020 exit(1);
2022 BC->outs()
2023 << "BOLT-WARNING: using mitigation for Intel JCC erratum, layout "
2024 "may take several minutes\n";
2027 if (opts::SplitEH && !BC->HasRelocations) {
2028 BC->errs() << "BOLT-WARNING: disabling -split-eh in non-relocation mode\n";
2029 opts::SplitEH = false;
2032 if (opts::StrictMode && !BC->HasRelocations) {
2033 BC->errs()
2034 << "BOLT-WARNING: disabling strict mode (-strict) in non-relocation "
2035 "mode\n";
2036 opts::StrictMode = false;
2039 if (BC->HasRelocations && opts::AggregateOnly &&
2040 !opts::StrictMode.getNumOccurrences()) {
2041 BC->outs() << "BOLT-INFO: enabling strict relocation mode for aggregation "
2042 "purposes\n";
2043 opts::StrictMode = true;
2046 if (!BC->HasRelocations &&
2047 opts::ReorderFunctions != ReorderFunctions::RT_NONE) {
2048 BC->errs() << "BOLT-ERROR: function reordering only works when "
2049 << "relocations are enabled\n";
2050 exit(1);
2053 if (opts::Instrument ||
2054 (opts::ReorderFunctions != ReorderFunctions::RT_NONE &&
2055 !opts::HotText.getNumOccurrences())) {
2056 opts::HotText = true;
2057 } else if (opts::HotText && !BC->HasRelocations) {
2058 BC->errs() << "BOLT-WARNING: hot text is disabled in non-relocation mode\n";
2059 opts::HotText = false;
2062 if (opts::HotText && opts::HotTextMoveSections.getNumOccurrences() == 0) {
2063 opts::HotTextMoveSections.addValue(".stub");
2064 opts::HotTextMoveSections.addValue(".mover");
2065 opts::HotTextMoveSections.addValue(".never_hugify");
2068 if (opts::UseOldText && !BC->OldTextSectionAddress) {
2069 BC->errs()
2070 << "BOLT-WARNING: cannot use old .text as the section was not found"
2071 "\n";
2072 opts::UseOldText = false;
2074 if (opts::UseOldText && !BC->HasRelocations) {
2075 BC->errs() << "BOLT-WARNING: cannot use old .text in non-relocation mode\n";
2076 opts::UseOldText = false;
2079 if (!opts::AlignText.getNumOccurrences())
2080 opts::AlignText = BC->PageAlign;
2082 if (opts::AlignText < opts::AlignFunctions)
2083 opts::AlignText = (unsigned)opts::AlignFunctions;
2085 if (BC->isX86() && opts::Lite.getNumOccurrences() == 0 && !opts::StrictMode &&
2086 !opts::UseOldText)
2087 opts::Lite = true;
2089 if (opts::Lite && opts::UseOldText) {
2090 BC->errs() << "BOLT-WARNING: cannot combine -lite with -use-old-text. "
2091 "Disabling -use-old-text.\n";
2092 opts::UseOldText = false;
2095 if (opts::Lite && opts::StrictMode) {
2096 BC->errs()
2097 << "BOLT-ERROR: -strict and -lite cannot be used at the same time\n";
2098 exit(1);
2101 if (opts::Lite)
2102 BC->outs() << "BOLT-INFO: enabling lite mode\n";
2104 if (BC->IsLinuxKernel) {
2105 if (!opts::KeepNops.getNumOccurrences())
2106 opts::KeepNops = true;
2108 // Linux kernel may resume execution after a trap instruction in some cases.
2109 if (!opts::TerminalTrap.getNumOccurrences())
2110 opts::TerminalTrap = false;
2114 namespace {
2115 template <typename ELFT>
2116 int64_t getRelocationAddend(const ELFObjectFile<ELFT> *Obj,
2117 const RelocationRef &RelRef) {
2118 using ELFShdrTy = typename ELFT::Shdr;
2119 using Elf_Rela = typename ELFT::Rela;
2120 int64_t Addend = 0;
2121 const ELFFile<ELFT> &EF = Obj->getELFFile();
2122 DataRefImpl Rel = RelRef.getRawDataRefImpl();
2123 const ELFShdrTy *RelocationSection = cantFail(EF.getSection(Rel.d.a));
2124 switch (RelocationSection->sh_type) {
2125 default:
2126 llvm_unreachable("unexpected relocation section type");
2127 case ELF::SHT_REL:
2128 break;
2129 case ELF::SHT_RELA: {
2130 const Elf_Rela *RelA = Obj->getRela(Rel);
2131 Addend = RelA->r_addend;
2132 break;
2136 return Addend;
2139 int64_t getRelocationAddend(const ELFObjectFileBase *Obj,
2140 const RelocationRef &Rel) {
2141 return getRelocationAddend(cast<ELF64LEObjectFile>(Obj), Rel);
2144 template <typename ELFT>
2145 uint32_t getRelocationSymbol(const ELFObjectFile<ELFT> *Obj,
2146 const RelocationRef &RelRef) {
2147 using ELFShdrTy = typename ELFT::Shdr;
2148 uint32_t Symbol = 0;
2149 const ELFFile<ELFT> &EF = Obj->getELFFile();
2150 DataRefImpl Rel = RelRef.getRawDataRefImpl();
2151 const ELFShdrTy *RelocationSection = cantFail(EF.getSection(Rel.d.a));
2152 switch (RelocationSection->sh_type) {
2153 default:
2154 llvm_unreachable("unexpected relocation section type");
2155 case ELF::SHT_REL:
2156 Symbol = Obj->getRel(Rel)->getSymbol(EF.isMips64EL());
2157 break;
2158 case ELF::SHT_RELA:
2159 Symbol = Obj->getRela(Rel)->getSymbol(EF.isMips64EL());
2160 break;
2163 return Symbol;
2166 uint32_t getRelocationSymbol(const ELFObjectFileBase *Obj,
2167 const RelocationRef &Rel) {
2168 return getRelocationSymbol(cast<ELF64LEObjectFile>(Obj), Rel);
2170 } // anonymous namespace
2172 bool RewriteInstance::analyzeRelocation(
2173 const RelocationRef &Rel, uint64_t &RType, std::string &SymbolName,
2174 bool &IsSectionRelocation, uint64_t &SymbolAddress, int64_t &Addend,
2175 uint64_t &ExtractedValue, bool &Skip) const {
2176 Skip = false;
2177 if (!Relocation::isSupported(RType))
2178 return false;
2180 auto IsWeakReference = [](const SymbolRef &Symbol) {
2181 Expected<uint32_t> SymFlagsOrErr = Symbol.getFlags();
2182 if (!SymFlagsOrErr)
2183 return false;
2184 return (*SymFlagsOrErr & SymbolRef::SF_Undefined) &&
2185 (*SymFlagsOrErr & SymbolRef::SF_Weak);
2188 const bool IsAArch64 = BC->isAArch64();
2190 const size_t RelSize = Relocation::getSizeForType(RType);
2192 ErrorOr<uint64_t> Value =
2193 BC->getUnsignedValueAtAddress(Rel.getOffset(), RelSize);
2194 assert(Value && "failed to extract relocated value");
2195 if ((Skip = Relocation::skipRelocationProcess(RType, *Value)))
2196 return true;
2198 ExtractedValue = Relocation::extractValue(RType, *Value, Rel.getOffset());
2199 Addend = getRelocationAddend(InputFile, Rel);
2201 const bool IsPCRelative = Relocation::isPCRelative(RType);
2202 const uint64_t PCRelOffset = IsPCRelative && !IsAArch64 ? Rel.getOffset() : 0;
2203 bool SkipVerification = false;
2204 auto SymbolIter = Rel.getSymbol();
2205 if (SymbolIter == InputFile->symbol_end()) {
2206 SymbolAddress = ExtractedValue - Addend + PCRelOffset;
2207 MCSymbol *RelSymbol =
2208 BC->getOrCreateGlobalSymbol(SymbolAddress, "RELSYMat");
2209 SymbolName = std::string(RelSymbol->getName());
2210 IsSectionRelocation = false;
2211 } else {
2212 const SymbolRef &Symbol = *SymbolIter;
2213 SymbolName = std::string(cantFail(Symbol.getName()));
2214 SymbolAddress = cantFail(Symbol.getAddress());
2215 SkipVerification = (cantFail(Symbol.getType()) == SymbolRef::ST_Other);
2216 // Section symbols are marked as ST_Debug.
2217 IsSectionRelocation = (cantFail(Symbol.getType()) == SymbolRef::ST_Debug);
2218 // Check for PLT entry registered with symbol name
2219 if (!SymbolAddress && !IsWeakReference(Symbol) &&
2220 (IsAArch64 || BC->isRISCV())) {
2221 const BinaryData *BD = BC->getPLTBinaryDataByName(SymbolName);
2222 SymbolAddress = BD ? BD->getAddress() : 0;
2225 // For PIE or dynamic libs, the linker may choose not to put the relocation
2226 // result at the address if it is a X86_64_64 one because it will emit a
2227 // dynamic relocation (X86_RELATIVE) for the dynamic linker and loader to
2228 // resolve it at run time. The static relocation result goes as the addend
2229 // of the dynamic relocation in this case. We can't verify these cases.
2230 // FIXME: perhaps we can try to find if it really emitted a corresponding
2231 // RELATIVE relocation at this offset with the correct value as the addend.
2232 if (!BC->HasFixedLoadAddress && RelSize == 8)
2233 SkipVerification = true;
2235 if (IsSectionRelocation && !IsAArch64) {
2236 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(SymbolAddress);
2237 assert(Section && "section expected for section relocation");
2238 SymbolName = "section " + std::string(Section->getName());
2239 // Convert section symbol relocations to regular relocations inside
2240 // non-section symbols.
2241 if (Section->containsAddress(ExtractedValue) && !IsPCRelative) {
2242 SymbolAddress = ExtractedValue;
2243 Addend = 0;
2244 } else {
2245 Addend = ExtractedValue - (SymbolAddress - PCRelOffset);
2249 // If no symbol has been found or if it is a relocation requiring the
2250 // creation of a GOT entry, do not link against the symbol but against
2251 // whatever address was extracted from the instruction itself. We are
2252 // not creating a GOT entry as this was already processed by the linker.
2253 // For GOT relocs, do not subtract addend as the addend does not refer
2254 // to this instruction's target, but it refers to the target in the GOT
2255 // entry.
2256 if (Relocation::isGOT(RType)) {
2257 Addend = 0;
2258 SymbolAddress = ExtractedValue + PCRelOffset;
2259 } else if (Relocation::isTLS(RType)) {
2260 SkipVerification = true;
2261 } else if (!SymbolAddress) {
2262 assert(!IsSectionRelocation);
2263 if (ExtractedValue || Addend == 0 || IsPCRelative) {
2264 SymbolAddress =
2265 truncateToSize(ExtractedValue - Addend + PCRelOffset, RelSize);
2266 } else {
2267 // This is weird case. The extracted value is zero but the addend is
2268 // non-zero and the relocation is not pc-rel. Using the previous logic,
2269 // the SymbolAddress would end up as a huge number. Seen in
2270 // exceptions_pic.test.
2271 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: relocation @ 0x"
2272 << Twine::utohexstr(Rel.getOffset())
2273 << " value does not match addend for "
2274 << "relocation to undefined symbol.\n");
2275 return true;
2279 auto verifyExtractedValue = [&]() {
2280 if (SkipVerification)
2281 return true;
2283 if (IsAArch64 || BC->isRISCV())
2284 return true;
2286 if (SymbolName == "__hot_start" || SymbolName == "__hot_end")
2287 return true;
2289 if (RType == ELF::R_X86_64_PLT32)
2290 return true;
2292 return truncateToSize(ExtractedValue, RelSize) ==
2293 truncateToSize(SymbolAddress + Addend - PCRelOffset, RelSize);
2296 (void)verifyExtractedValue;
2297 assert(verifyExtractedValue() && "mismatched extracted relocation value");
2299 return true;
2302 void RewriteInstance::processDynamicRelocations() {
2303 // Read .relr.dyn section containing compressed R_*_RELATIVE relocations.
2304 if (DynamicRelrSize > 0) {
2305 ErrorOr<BinarySection &> DynamicRelrSectionOrErr =
2306 BC->getSectionForAddress(*DynamicRelrAddress);
2307 if (!DynamicRelrSectionOrErr)
2308 report_error("unable to find section corresponding to DT_RELR",
2309 DynamicRelrSectionOrErr.getError());
2310 if (DynamicRelrSectionOrErr->getSize() != DynamicRelrSize)
2311 report_error("section size mismatch for DT_RELRSZ",
2312 errc::executable_format_error);
2313 readDynamicRelrRelocations(*DynamicRelrSectionOrErr);
2316 // Read relocations for PLT - DT_JMPREL.
2317 if (PLTRelocationsSize > 0) {
2318 ErrorOr<BinarySection &> PLTRelSectionOrErr =
2319 BC->getSectionForAddress(*PLTRelocationsAddress);
2320 if (!PLTRelSectionOrErr)
2321 report_error("unable to find section corresponding to DT_JMPREL",
2322 PLTRelSectionOrErr.getError());
2323 if (PLTRelSectionOrErr->getSize() != PLTRelocationsSize)
2324 report_error("section size mismatch for DT_PLTRELSZ",
2325 errc::executable_format_error);
2326 readDynamicRelocations(PLTRelSectionOrErr->getSectionRef(),
2327 /*IsJmpRel*/ true);
2330 // The rest of dynamic relocations - DT_RELA.
2331 // The static executable might have .rela.dyn secion and not have PT_DYNAMIC
2332 if (!DynamicRelocationsSize && BC->IsStaticExecutable) {
2333 ErrorOr<BinarySection &> DynamicRelSectionOrErr =
2334 BC->getUniqueSectionByName(getRelaDynSectionName());
2335 if (DynamicRelSectionOrErr) {
2336 DynamicRelocationsAddress = DynamicRelSectionOrErr->getAddress();
2337 DynamicRelocationsSize = DynamicRelSectionOrErr->getSize();
2338 const SectionRef &SectionRef = DynamicRelSectionOrErr->getSectionRef();
2339 DynamicRelativeRelocationsCount = std::distance(
2340 SectionRef.relocation_begin(), SectionRef.relocation_end());
2344 if (DynamicRelocationsSize > 0) {
2345 ErrorOr<BinarySection &> DynamicRelSectionOrErr =
2346 BC->getSectionForAddress(*DynamicRelocationsAddress);
2347 if (!DynamicRelSectionOrErr)
2348 report_error("unable to find section corresponding to DT_RELA",
2349 DynamicRelSectionOrErr.getError());
2350 auto DynamicRelSectionSize = DynamicRelSectionOrErr->getSize();
2351 // On RISC-V DT_RELASZ seems to include both .rela.dyn and .rela.plt
2352 if (DynamicRelocationsSize == DynamicRelSectionSize + PLTRelocationsSize)
2353 DynamicRelocationsSize = DynamicRelSectionSize;
2354 if (DynamicRelSectionSize != DynamicRelocationsSize)
2355 report_error("section size mismatch for DT_RELASZ",
2356 errc::executable_format_error);
2357 readDynamicRelocations(DynamicRelSectionOrErr->getSectionRef(),
2358 /*IsJmpRel*/ false);
2362 void RewriteInstance::processRelocations() {
2363 if (!BC->HasRelocations)
2364 return;
2366 for (const SectionRef &Section : InputFile->sections()) {
2367 section_iterator SecIter = cantFail(Section.getRelocatedSection());
2368 if (SecIter == InputFile->section_end())
2369 continue;
2370 if (BinarySection(*BC, Section).isAllocatable())
2371 continue;
2373 readRelocations(Section);
2376 if (NumFailedRelocations)
2377 BC->errs() << "BOLT-WARNING: Failed to analyze " << NumFailedRelocations
2378 << " relocations\n";
2381 void RewriteInstance::readDynamicRelocations(const SectionRef &Section,
2382 bool IsJmpRel) {
2383 assert(BinarySection(*BC, Section).isAllocatable() && "allocatable expected");
2385 LLVM_DEBUG({
2386 StringRef SectionName = cantFail(Section.getName());
2387 dbgs() << "BOLT-DEBUG: reading relocations for section " << SectionName
2388 << ":\n";
2391 for (const RelocationRef &Rel : Section.relocations()) {
2392 const uint64_t RType = Rel.getType();
2393 if (Relocation::isNone(RType))
2394 continue;
2396 StringRef SymbolName = "<none>";
2397 MCSymbol *Symbol = nullptr;
2398 uint64_t SymbolAddress = 0;
2399 const uint64_t Addend = getRelocationAddend(InputFile, Rel);
2401 symbol_iterator SymbolIter = Rel.getSymbol();
2402 if (SymbolIter != InputFile->symbol_end()) {
2403 SymbolName = cantFail(SymbolIter->getName());
2404 BinaryData *BD = BC->getBinaryDataByName(SymbolName);
2405 Symbol = BD ? BD->getSymbol()
2406 : BC->getOrCreateUndefinedGlobalSymbol(SymbolName);
2407 SymbolAddress = cantFail(SymbolIter->getAddress());
2408 (void)SymbolAddress;
2411 LLVM_DEBUG(
2412 SmallString<16> TypeName;
2413 Rel.getTypeName(TypeName);
2414 dbgs() << "BOLT-DEBUG: dynamic relocation at 0x"
2415 << Twine::utohexstr(Rel.getOffset()) << " : " << TypeName
2416 << " : " << SymbolName << " : " << Twine::utohexstr(SymbolAddress)
2417 << " : + 0x" << Twine::utohexstr(Addend) << '\n'
2420 if (IsJmpRel)
2421 IsJmpRelocation[RType] = true;
2423 if (Symbol)
2424 SymbolIndex[Symbol] = getRelocationSymbol(InputFile, Rel);
2426 BC->addDynamicRelocation(Rel.getOffset(), Symbol, RType, Addend);
2430 void RewriteInstance::readDynamicRelrRelocations(BinarySection &Section) {
2431 assert(Section.isAllocatable() && "allocatable expected");
2433 LLVM_DEBUG({
2434 StringRef SectionName = Section.getName();
2435 dbgs() << "BOLT-DEBUG: reading relocations in section " << SectionName
2436 << ":\n";
2439 const uint64_t RType = Relocation::getRelative();
2440 const uint8_t PSize = BC->AsmInfo->getCodePointerSize();
2441 const uint64_t MaxDelta = ((CHAR_BIT * DynamicRelrEntrySize) - 1) * PSize;
2443 auto ExtractAddendValue = [&](uint64_t Address) -> uint64_t {
2444 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(Address);
2445 assert(Section && "cannot get section for data address from RELR");
2446 DataExtractor DE = DataExtractor(Section->getContents(),
2447 BC->AsmInfo->isLittleEndian(), PSize);
2448 uint64_t Offset = Address - Section->getAddress();
2449 return DE.getUnsigned(&Offset, PSize);
2452 auto AddRelocation = [&](uint64_t Address) {
2453 uint64_t Addend = ExtractAddendValue(Address);
2454 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: R_*_RELATIVE relocation at 0x"
2455 << Twine::utohexstr(Address) << " to 0x"
2456 << Twine::utohexstr(Addend) << '\n';);
2457 BC->addDynamicRelocation(Address, nullptr, RType, Addend);
2460 DataExtractor DE = DataExtractor(Section.getContents(),
2461 BC->AsmInfo->isLittleEndian(), PSize);
2462 uint64_t Offset = 0, Address = 0;
2463 uint64_t RelrCount = DynamicRelrSize / DynamicRelrEntrySize;
2464 while (RelrCount--) {
2465 assert(DE.isValidOffset(Offset));
2466 uint64_t Entry = DE.getUnsigned(&Offset, DynamicRelrEntrySize);
2467 if ((Entry & 1) == 0) {
2468 AddRelocation(Entry);
2469 Address = Entry + PSize;
2470 } else {
2471 const uint64_t StartAddress = Address;
2472 while (Entry >>= 1) {
2473 if (Entry & 1)
2474 AddRelocation(Address);
2476 Address += PSize;
2479 Address = StartAddress + MaxDelta;
2484 void RewriteInstance::printRelocationInfo(const RelocationRef &Rel,
2485 StringRef SymbolName,
2486 uint64_t SymbolAddress,
2487 uint64_t Addend,
2488 uint64_t ExtractedValue) const {
2489 SmallString<16> TypeName;
2490 Rel.getTypeName(TypeName);
2491 const uint64_t Address = SymbolAddress + Addend;
2492 const uint64_t Offset = Rel.getOffset();
2493 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(SymbolAddress);
2494 BinaryFunction *Func =
2495 BC->getBinaryFunctionContainingAddress(Offset, false, BC->isAArch64());
2496 dbgs() << formatv("Relocation: offset = {0:x}; type = {1}; value = {2:x}; ",
2497 Offset, TypeName, ExtractedValue)
2498 << formatv("symbol = {0} ({1}); symbol address = {2:x}; ", SymbolName,
2499 Section ? Section->getName() : "", SymbolAddress)
2500 << formatv("addend = {0:x}; address = {1:x}; in = ", Addend, Address);
2501 if (Func)
2502 dbgs() << Func->getPrintName();
2503 else
2504 dbgs() << BC->getSectionForAddress(Rel.getOffset())->getName();
2505 dbgs() << '\n';
2508 void RewriteInstance::readRelocations(const SectionRef &Section) {
2509 LLVM_DEBUG({
2510 StringRef SectionName = cantFail(Section.getName());
2511 dbgs() << "BOLT-DEBUG: reading relocations for section " << SectionName
2512 << ":\n";
2514 if (BinarySection(*BC, Section).isAllocatable()) {
2515 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring runtime relocations\n");
2516 return;
2518 section_iterator SecIter = cantFail(Section.getRelocatedSection());
2519 assert(SecIter != InputFile->section_end() && "relocated section expected");
2520 SectionRef RelocatedSection = *SecIter;
2522 StringRef RelocatedSectionName = cantFail(RelocatedSection.getName());
2523 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: relocated section is "
2524 << RelocatedSectionName << '\n');
2526 if (!BinarySection(*BC, RelocatedSection).isAllocatable()) {
2527 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring relocations against "
2528 << "non-allocatable section\n");
2529 return;
2531 const bool SkipRelocs = StringSwitch<bool>(RelocatedSectionName)
2532 .Cases(".plt", ".rela.plt", ".got.plt",
2533 ".eh_frame", ".gcc_except_table", true)
2534 .Default(false);
2535 if (SkipRelocs) {
2536 LLVM_DEBUG(
2537 dbgs() << "BOLT-DEBUG: ignoring relocations against known section\n");
2538 return;
2541 for (const RelocationRef &Rel : Section.relocations())
2542 handleRelocation(RelocatedSection, Rel);
2545 void RewriteInstance::handleRelocation(const SectionRef &RelocatedSection,
2546 const RelocationRef &Rel) {
2547 const bool IsAArch64 = BC->isAArch64();
2548 const bool IsFromCode = RelocatedSection.isText();
2550 SmallString<16> TypeName;
2551 Rel.getTypeName(TypeName);
2552 uint64_t RType = Rel.getType();
2553 if (Relocation::skipRelocationType(RType))
2554 return;
2556 // Adjust the relocation type as the linker might have skewed it.
2557 if (BC->isX86() && (RType & ELF::R_X86_64_converted_reloc_bit)) {
2558 if (opts::Verbosity >= 1)
2559 dbgs() << "BOLT-WARNING: ignoring R_X86_64_converted_reloc_bit\n";
2560 RType &= ~ELF::R_X86_64_converted_reloc_bit;
2563 if (Relocation::isTLS(RType)) {
2564 // No special handling required for TLS relocations on X86.
2565 if (BC->isX86())
2566 return;
2568 // The non-got related TLS relocations on AArch64 and RISC-V also could be
2569 // skipped.
2570 if (!Relocation::isGOT(RType))
2571 return;
2574 if (!IsAArch64 && BC->getDynamicRelocationAt(Rel.getOffset())) {
2575 LLVM_DEBUG({
2576 dbgs() << formatv("BOLT-DEBUG: address {0:x} has a ", Rel.getOffset())
2577 << "dynamic relocation against it. Ignoring static relocation.\n";
2579 return;
2582 std::string SymbolName;
2583 uint64_t SymbolAddress;
2584 int64_t Addend;
2585 uint64_t ExtractedValue;
2586 bool IsSectionRelocation;
2587 bool Skip;
2588 if (!analyzeRelocation(Rel, RType, SymbolName, IsSectionRelocation,
2589 SymbolAddress, Addend, ExtractedValue, Skip)) {
2590 LLVM_DEBUG({
2591 dbgs() << "BOLT-WARNING: failed to analyze relocation @ offset = "
2592 << formatv("{0:x}; type name = {1}\n", Rel.getOffset(), TypeName);
2594 ++NumFailedRelocations;
2595 return;
2598 if (Skip) {
2599 LLVM_DEBUG({
2600 dbgs() << "BOLT-DEBUG: skipping relocation @ offset = "
2601 << formatv("{0:x}; type name = {1}\n", Rel.getOffset(), TypeName);
2603 return;
2606 const uint64_t Address = SymbolAddress + Addend;
2608 LLVM_DEBUG({
2609 dbgs() << "BOLT-DEBUG: ";
2610 printRelocationInfo(Rel, SymbolName, SymbolAddress, Addend, ExtractedValue);
2613 BinaryFunction *ContainingBF = nullptr;
2614 if (IsFromCode) {
2615 ContainingBF =
2616 BC->getBinaryFunctionContainingAddress(Rel.getOffset(),
2617 /*CheckPastEnd*/ false,
2618 /*UseMaxSize*/ true);
2619 assert(ContainingBF && "cannot find function for address in code");
2620 if (!IsAArch64 && !ContainingBF->containsAddress(Rel.getOffset())) {
2621 if (opts::Verbosity >= 1)
2622 BC->outs() << formatv(
2623 "BOLT-INFO: {0} has relocations in padding area\n", *ContainingBF);
2624 ContainingBF->setSize(ContainingBF->getMaxSize());
2625 ContainingBF->setSimple(false);
2626 return;
2630 MCSymbol *ReferencedSymbol = nullptr;
2631 if (!IsSectionRelocation) {
2632 if (BinaryData *BD = BC->getBinaryDataByName(SymbolName))
2633 ReferencedSymbol = BD->getSymbol();
2634 else if (BC->isGOTSymbol(SymbolName))
2635 if (BinaryData *BD = BC->getGOTSymbol())
2636 ReferencedSymbol = BD->getSymbol();
2639 ErrorOr<BinarySection &> ReferencedSection{std::errc::bad_address};
2640 symbol_iterator SymbolIter = Rel.getSymbol();
2641 if (SymbolIter != InputFile->symbol_end()) {
2642 SymbolRef Symbol = *SymbolIter;
2643 section_iterator Section =
2644 cantFail(Symbol.getSection(), "cannot get symbol section");
2645 if (Section != InputFile->section_end()) {
2646 Expected<StringRef> SectionName = Section->getName();
2647 if (SectionName && !SectionName->empty())
2648 ReferencedSection = BC->getUniqueSectionByName(*SectionName);
2649 } else if (BC->isRISCV() && ReferencedSymbol && ContainingBF &&
2650 (cantFail(Symbol.getFlags()) & SymbolRef::SF_Absolute)) {
2651 // This might be a relocation for an ABS symbols like __global_pointer$ on
2652 // RISC-V
2653 ContainingBF->addRelocation(Rel.getOffset(), ReferencedSymbol,
2654 Rel.getType(), 0,
2655 cantFail(Symbol.getValue()));
2656 return;
2660 if (!ReferencedSection)
2661 ReferencedSection = BC->getSectionForAddress(SymbolAddress);
2663 const bool IsToCode = ReferencedSection && ReferencedSection->isText();
2665 // Special handling of PC-relative relocations.
2666 if (BC->isX86() && Relocation::isPCRelative(RType)) {
2667 if (!IsFromCode && IsToCode) {
2668 // PC-relative relocations from data to code are tricky since the
2669 // original information is typically lost after linking, even with
2670 // '--emit-relocs'. Such relocations are normally used by PIC-style
2671 // jump tables and they reference both the jump table and jump
2672 // targets by computing the difference between the two. If we blindly
2673 // apply the relocation, it will appear that it references an arbitrary
2674 // location in the code, possibly in a different function from the one
2675 // containing the jump table.
2677 // For that reason, we only register the fact that there is a
2678 // PC-relative relocation at a given address against the code.
2679 // The actual referenced label/address will be determined during jump
2680 // table analysis.
2681 BC->addPCRelativeDataRelocation(Rel.getOffset());
2682 } else if (ContainingBF && !IsSectionRelocation && ReferencedSymbol) {
2683 // If we know the referenced symbol, register the relocation from
2684 // the code. It's required to properly handle cases where
2685 // "symbol + addend" references an object different from "symbol".
2686 ContainingBF->addRelocation(Rel.getOffset(), ReferencedSymbol, RType,
2687 Addend, ExtractedValue);
2688 } else {
2689 LLVM_DEBUG({
2690 dbgs() << "BOLT-DEBUG: not creating PC-relative relocation at"
2691 << formatv("{0:x} for {1}\n", Rel.getOffset(), SymbolName);
2695 return;
2698 bool ForceRelocation = BC->forceSymbolRelocations(SymbolName);
2699 if ((BC->isAArch64() || BC->isRISCV()) && Relocation::isGOT(RType))
2700 ForceRelocation = true;
2702 if (!ReferencedSection && !ForceRelocation) {
2703 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: cannot determine referenced section.\n");
2704 return;
2707 // Occasionally we may see a reference past the last byte of the function
2708 // typically as a result of __builtin_unreachable(). Check it here.
2709 BinaryFunction *ReferencedBF = BC->getBinaryFunctionContainingAddress(
2710 Address, /*CheckPastEnd*/ true, /*UseMaxSize*/ IsAArch64);
2712 if (!IsSectionRelocation) {
2713 if (BinaryFunction *BF =
2714 BC->getBinaryFunctionContainingAddress(SymbolAddress)) {
2715 if (BF != ReferencedBF) {
2716 // It's possible we are referencing a function without referencing any
2717 // code, e.g. when taking a bitmask action on a function address.
2718 BC->errs()
2719 << "BOLT-WARNING: non-standard function reference (e.g. bitmask)"
2720 << formatv(" detected against function {0} from ", *BF);
2721 if (IsFromCode)
2722 BC->errs() << formatv("function {0}\n", *ContainingBF);
2723 else
2724 BC->errs() << formatv("data section at {0:x}\n", Rel.getOffset());
2725 LLVM_DEBUG(printRelocationInfo(Rel, SymbolName, SymbolAddress, Addend,
2726 ExtractedValue));
2727 ReferencedBF = BF;
2730 } else if (ReferencedBF) {
2731 assert(ReferencedSection && "section expected for section relocation");
2732 if (*ReferencedBF->getOriginSection() != *ReferencedSection) {
2733 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring false function reference\n");
2734 ReferencedBF = nullptr;
2738 // Workaround for a member function pointer de-virtualization bug. We check
2739 // if a non-pc-relative relocation in the code is pointing to (fptr - 1).
2740 if (IsToCode && ContainingBF && !Relocation::isPCRelative(RType) &&
2741 (!ReferencedBF || (ReferencedBF->getAddress() != Address))) {
2742 if (const BinaryFunction *RogueBF =
2743 BC->getBinaryFunctionAtAddress(Address + 1)) {
2744 // Do an extra check that the function was referenced previously.
2745 // It's a linear search, but it should rarely happen.
2746 auto CheckReloc = [&](const Relocation &Rel) {
2747 return Rel.Symbol == RogueBF->getSymbol() &&
2748 !Relocation::isPCRelative(Rel.Type);
2750 bool Found = llvm::any_of(
2751 llvm::make_second_range(ContainingBF->Relocations), CheckReloc);
2753 if (Found) {
2754 BC->errs()
2755 << "BOLT-WARNING: detected possible compiler de-virtualization "
2756 "bug: -1 addend used with non-pc-relative relocation against "
2757 << formatv("function {0} in function {1}\n", *RogueBF,
2758 *ContainingBF);
2759 return;
2764 if (ForceRelocation) {
2765 std::string Name =
2766 Relocation::isGOT(RType) ? "__BOLT_got_zero" : SymbolName;
2767 ReferencedSymbol = BC->registerNameAtAddress(Name, 0, 0, 0);
2768 SymbolAddress = 0;
2769 if (Relocation::isGOT(RType))
2770 Addend = Address;
2771 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: forcing relocation against symbol "
2772 << SymbolName << " with addend " << Addend << '\n');
2773 } else if (ReferencedBF) {
2774 ReferencedSymbol = ReferencedBF->getSymbol();
2775 uint64_t RefFunctionOffset = 0;
2777 // Adjust the point of reference to a code location inside a function.
2778 if (ReferencedBF->containsAddress(Address, /*UseMaxSize = */ true)) {
2779 RefFunctionOffset = Address - ReferencedBF->getAddress();
2780 if (Relocation::isInstructionReference(RType)) {
2781 // Instruction labels are created while disassembling so we just leave
2782 // the symbol empty for now. Since the extracted value is typically
2783 // unrelated to the referenced symbol (e.g., %pcrel_lo in RISC-V
2784 // references an instruction but the patched value references the low
2785 // bits of a data address), we set the extracted value to the symbol
2786 // address in order to be able to correctly reconstruct the reference
2787 // later.
2788 ReferencedSymbol = nullptr;
2789 ExtractedValue = Address;
2790 } else if (RefFunctionOffset) {
2791 if (ContainingBF && ContainingBF != ReferencedBF) {
2792 ReferencedSymbol =
2793 ReferencedBF->addEntryPointAtOffset(RefFunctionOffset);
2794 } else {
2795 ReferencedSymbol =
2796 ReferencedBF->getOrCreateLocalLabel(Address,
2797 /*CreatePastEnd =*/true);
2799 // If ContainingBF != nullptr, it equals ReferencedBF (see
2800 // if-condition above) so we're handling a relocation from a function
2801 // to itself. RISC-V uses such relocations for branches, for example.
2802 // These should not be registered as externally references offsets.
2803 if (!ContainingBF)
2804 ReferencedBF->registerReferencedOffset(RefFunctionOffset);
2806 if (opts::Verbosity > 1 &&
2807 BinarySection(*BC, RelocatedSection).isWritable())
2808 BC->errs()
2809 << "BOLT-WARNING: writable reference into the middle of the "
2810 << formatv("function {0} detected at address {1:x}\n",
2811 *ReferencedBF, Rel.getOffset());
2813 SymbolAddress = Address;
2814 Addend = 0;
2816 LLVM_DEBUG({
2817 dbgs() << " referenced function " << *ReferencedBF;
2818 if (Address != ReferencedBF->getAddress())
2819 dbgs() << formatv(" at offset {0:x}", RefFunctionOffset);
2820 dbgs() << '\n';
2822 } else {
2823 if (IsToCode && SymbolAddress) {
2824 // This can happen e.g. with PIC-style jump tables.
2825 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: no corresponding function for "
2826 "relocation against code\n");
2829 // In AArch64 there are zero reasons to keep a reference to the
2830 // "original" symbol plus addend. The original symbol is probably just a
2831 // section symbol. If we are here, this means we are probably accessing
2832 // data, so it is imperative to keep the original address.
2833 if (IsAArch64) {
2834 SymbolName = formatv("SYMBOLat{0:x}", Address);
2835 SymbolAddress = Address;
2836 Addend = 0;
2839 if (BinaryData *BD = BC->getBinaryDataContainingAddress(SymbolAddress)) {
2840 // Note: this assertion is trying to check sanity of BinaryData objects
2841 // but AArch64 has inferred and incomplete object locations coming from
2842 // GOT/TLS or any other non-trivial relocation (that requires creation
2843 // of sections and whose symbol address is not really what should be
2844 // encoded in the instruction). So we essentially disabled this check
2845 // for AArch64 and live with bogus names for objects.
2846 assert((IsAArch64 || IsSectionRelocation ||
2847 BD->nameStartsWith(SymbolName) ||
2848 BD->nameStartsWith("PG" + SymbolName) ||
2849 (BD->nameStartsWith("ANONYMOUS") &&
2850 (BD->getSectionName().starts_with(".plt") ||
2851 BD->getSectionName().ends_with(".plt")))) &&
2852 "BOLT symbol names of all non-section relocations must match up "
2853 "with symbol names referenced in the relocation");
2855 if (IsSectionRelocation)
2856 BC->markAmbiguousRelocations(*BD, Address);
2858 ReferencedSymbol = BD->getSymbol();
2859 Addend += (SymbolAddress - BD->getAddress());
2860 SymbolAddress = BD->getAddress();
2861 assert(Address == SymbolAddress + Addend);
2862 } else {
2863 // These are mostly local data symbols but undefined symbols
2864 // in relocation sections can get through here too, from .plt.
2865 assert(
2866 (IsAArch64 || BC->isRISCV() || IsSectionRelocation ||
2867 BC->getSectionNameForAddress(SymbolAddress)->starts_with(".plt")) &&
2868 "known symbols should not resolve to anonymous locals");
2870 if (IsSectionRelocation) {
2871 ReferencedSymbol =
2872 BC->getOrCreateGlobalSymbol(SymbolAddress, "SYMBOLat");
2873 } else {
2874 SymbolRef Symbol = *Rel.getSymbol();
2875 const uint64_t SymbolSize =
2876 IsAArch64 ? 0 : ELFSymbolRef(Symbol).getSize();
2877 const uint64_t SymbolAlignment = IsAArch64 ? 1 : Symbol.getAlignment();
2878 const uint32_t SymbolFlags = cantFail(Symbol.getFlags());
2879 std::string Name;
2880 if (SymbolFlags & SymbolRef::SF_Global) {
2881 Name = SymbolName;
2882 } else {
2883 if (StringRef(SymbolName)
2884 .starts_with(BC->AsmInfo->getPrivateGlobalPrefix()))
2885 Name = NR.uniquify("PG" + SymbolName);
2886 else
2887 Name = NR.uniquify(SymbolName);
2889 ReferencedSymbol = BC->registerNameAtAddress(
2890 Name, SymbolAddress, SymbolSize, SymbolAlignment, SymbolFlags);
2893 if (IsSectionRelocation) {
2894 BinaryData *BD = BC->getBinaryDataByName(ReferencedSymbol->getName());
2895 BC->markAmbiguousRelocations(*BD, Address);
2900 auto checkMaxDataRelocations = [&]() {
2901 ++NumDataRelocations;
2902 LLVM_DEBUG(if (opts::MaxDataRelocations &&
2903 NumDataRelocations + 1 == opts::MaxDataRelocations) {
2904 dbgs() << "BOLT-DEBUG: processing ending on data relocation "
2905 << NumDataRelocations << ": ";
2906 printRelocationInfo(Rel, ReferencedSymbol->getName(), SymbolAddress,
2907 Addend, ExtractedValue);
2910 return (!opts::MaxDataRelocations ||
2911 NumDataRelocations < opts::MaxDataRelocations);
2914 if ((ReferencedSection && refersToReorderedSection(ReferencedSection)) ||
2915 (opts::ForceToDataRelocations && checkMaxDataRelocations()) ||
2916 // RISC-V has ADD/SUB data-to-data relocations
2917 BC->isRISCV())
2918 ForceRelocation = true;
2920 if (IsFromCode)
2921 ContainingBF->addRelocation(Rel.getOffset(), ReferencedSymbol, RType,
2922 Addend, ExtractedValue);
2923 else if (IsToCode || ForceRelocation)
2924 BC->addRelocation(Rel.getOffset(), ReferencedSymbol, RType, Addend,
2925 ExtractedValue);
2926 else
2927 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring relocation from data to data\n");
2930 void RewriteInstance::selectFunctionsToProcess() {
2931 // Extend the list of functions to process or skip from a file.
2932 auto populateFunctionNames = [](cl::opt<std::string> &FunctionNamesFile,
2933 cl::list<std::string> &FunctionNames) {
2934 if (FunctionNamesFile.empty())
2935 return;
2936 std::ifstream FuncsFile(FunctionNamesFile, std::ios::in);
2937 std::string FuncName;
2938 while (std::getline(FuncsFile, FuncName))
2939 FunctionNames.push_back(FuncName);
2941 populateFunctionNames(opts::FunctionNamesFile, opts::ForceFunctionNames);
2942 populateFunctionNames(opts::SkipFunctionNamesFile, opts::SkipFunctionNames);
2943 populateFunctionNames(opts::FunctionNamesFileNR, opts::ForceFunctionNamesNR);
2945 // Make a set of functions to process to speed up lookups.
2946 std::unordered_set<std::string> ForceFunctionsNR(
2947 opts::ForceFunctionNamesNR.begin(), opts::ForceFunctionNamesNR.end());
2949 if ((!opts::ForceFunctionNames.empty() ||
2950 !opts::ForceFunctionNamesNR.empty()) &&
2951 !opts::SkipFunctionNames.empty()) {
2952 BC->errs()
2953 << "BOLT-ERROR: cannot select functions to process and skip at the "
2954 "same time. Please use only one type of selection.\n";
2955 exit(1);
2958 uint64_t LiteThresholdExecCount = 0;
2959 if (opts::LiteThresholdPct) {
2960 if (opts::LiteThresholdPct > 100)
2961 opts::LiteThresholdPct = 100;
2963 std::vector<const BinaryFunction *> TopFunctions;
2964 for (auto &BFI : BC->getBinaryFunctions()) {
2965 const BinaryFunction &Function = BFI.second;
2966 if (ProfileReader->mayHaveProfileData(Function))
2967 TopFunctions.push_back(&Function);
2969 llvm::sort(
2970 TopFunctions, [](const BinaryFunction *A, const BinaryFunction *B) {
2971 return A->getKnownExecutionCount() < B->getKnownExecutionCount();
2974 size_t Index = TopFunctions.size() * opts::LiteThresholdPct / 100;
2975 if (Index)
2976 --Index;
2977 LiteThresholdExecCount = TopFunctions[Index]->getKnownExecutionCount();
2978 BC->outs() << "BOLT-INFO: limiting processing to functions with at least "
2979 << LiteThresholdExecCount << " invocations\n";
2981 LiteThresholdExecCount = std::max(
2982 LiteThresholdExecCount, static_cast<uint64_t>(opts::LiteThresholdCount));
2984 StringSet<> ReorderFunctionsUserSet;
2985 StringSet<> ReorderFunctionsLTOCommonSet;
2986 if (opts::ReorderFunctions == ReorderFunctions::RT_USER) {
2987 std::vector<std::string> FunctionNames;
2988 BC->logBOLTErrorsAndQuitOnFatal(
2989 ReorderFunctions::readFunctionOrderFile(FunctionNames));
2990 for (const std::string &Function : FunctionNames) {
2991 ReorderFunctionsUserSet.insert(Function);
2992 if (std::optional<StringRef> LTOCommonName = getLTOCommonName(Function))
2993 ReorderFunctionsLTOCommonSet.insert(*LTOCommonName);
2997 uint64_t NumFunctionsToProcess = 0;
2998 auto mustSkip = [&](const BinaryFunction &Function) {
2999 if (opts::MaxFunctions.getNumOccurrences() &&
3000 NumFunctionsToProcess >= opts::MaxFunctions)
3001 return true;
3002 for (std::string &Name : opts::SkipFunctionNames)
3003 if (Function.hasNameRegex(Name))
3004 return true;
3006 return false;
3009 auto shouldProcess = [&](const BinaryFunction &Function) {
3010 if (mustSkip(Function))
3011 return false;
3013 // If the list is not empty, only process functions from the list.
3014 if (!opts::ForceFunctionNames.empty() || !ForceFunctionsNR.empty()) {
3015 // Regex check (-funcs and -funcs-file options).
3016 for (std::string &Name : opts::ForceFunctionNames)
3017 if (Function.hasNameRegex(Name))
3018 return true;
3020 // Non-regex check (-funcs-no-regex and -funcs-file-no-regex).
3021 for (const StringRef Name : Function.getNames())
3022 if (ForceFunctionsNR.count(Name.str()))
3023 return true;
3025 return false;
3028 if (opts::Lite) {
3029 // Forcibly include functions specified in the -function-order file.
3030 if (opts::ReorderFunctions == ReorderFunctions::RT_USER) {
3031 for (const StringRef Name : Function.getNames())
3032 if (ReorderFunctionsUserSet.contains(Name))
3033 return true;
3034 for (const StringRef Name : Function.getNames())
3035 if (std::optional<StringRef> LTOCommonName = getLTOCommonName(Name))
3036 if (ReorderFunctionsLTOCommonSet.contains(*LTOCommonName))
3037 return true;
3040 if (ProfileReader && !ProfileReader->mayHaveProfileData(Function))
3041 return false;
3043 if (Function.getKnownExecutionCount() < LiteThresholdExecCount)
3044 return false;
3047 return true;
3050 for (auto &BFI : BC->getBinaryFunctions()) {
3051 BinaryFunction &Function = BFI.second;
3053 // Pseudo functions are explicitly marked by us not to be processed.
3054 if (Function.isPseudo()) {
3055 Function.IsIgnored = true;
3056 Function.HasExternalRefRelocations = true;
3057 continue;
3060 // Decide what to do with fragments after parent functions are processed.
3061 if (Function.isFragment())
3062 continue;
3064 if (!shouldProcess(Function)) {
3065 if (opts::Verbosity >= 1) {
3066 BC->outs() << "BOLT-INFO: skipping processing " << Function
3067 << " per user request\n";
3069 Function.setIgnored();
3070 } else {
3071 ++NumFunctionsToProcess;
3072 if (opts::MaxFunctions.getNumOccurrences() &&
3073 NumFunctionsToProcess == opts::MaxFunctions)
3074 BC->outs() << "BOLT-INFO: processing ending on " << Function << '\n';
3078 if (!BC->HasSplitFunctions)
3079 return;
3081 // Fragment overrides:
3082 // - If the fragment must be skipped, then the parent must be skipped as well.
3083 // Otherwise, fragment should follow the parent function:
3084 // - if the parent is skipped, skip fragment,
3085 // - if the parent is processed, process the fragment(s) as well.
3086 for (auto &BFI : BC->getBinaryFunctions()) {
3087 BinaryFunction &Function = BFI.second;
3088 if (!Function.isFragment())
3089 continue;
3090 if (mustSkip(Function)) {
3091 for (BinaryFunction *Parent : Function.ParentFragments) {
3092 if (opts::Verbosity >= 1) {
3093 BC->outs() << "BOLT-INFO: skipping processing " << *Parent
3094 << " together with fragment function\n";
3096 Parent->setIgnored();
3097 --NumFunctionsToProcess;
3099 Function.setIgnored();
3100 continue;
3103 bool IgnoredParent =
3104 llvm::any_of(Function.ParentFragments, [&](BinaryFunction *Parent) {
3105 return Parent->isIgnored();
3107 if (IgnoredParent) {
3108 if (opts::Verbosity >= 1) {
3109 BC->outs() << "BOLT-INFO: skipping processing " << Function
3110 << " together with parent function\n";
3112 Function.setIgnored();
3113 } else {
3114 ++NumFunctionsToProcess;
3115 if (opts::Verbosity >= 1) {
3116 BC->outs() << "BOLT-INFO: processing " << Function
3117 << " as a sibling of non-ignored function\n";
3119 if (opts::MaxFunctions && NumFunctionsToProcess == opts::MaxFunctions)
3120 BC->outs() << "BOLT-INFO: processing ending on " << Function << '\n';
3125 void RewriteInstance::readDebugInfo() {
3126 NamedRegionTimer T("readDebugInfo", "read debug info", TimerGroupName,
3127 TimerGroupDesc, opts::TimeRewrite);
3128 if (!opts::UpdateDebugSections)
3129 return;
3131 BC->preprocessDebugInfo();
3134 void RewriteInstance::preprocessProfileData() {
3135 if (!ProfileReader)
3136 return;
3138 NamedRegionTimer T("preprocessprofile", "pre-process profile data",
3139 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3141 BC->outs() << "BOLT-INFO: pre-processing profile using "
3142 << ProfileReader->getReaderName() << '\n';
3144 if (BAT->enabledFor(InputFile)) {
3145 BC->outs() << "BOLT-INFO: profile collection done on a binary already "
3146 "processed by BOLT\n";
3147 ProfileReader->setBAT(&*BAT);
3150 if (Error E = ProfileReader->preprocessProfile(*BC.get()))
3151 report_error("cannot pre-process profile", std::move(E));
3153 if (!BC->hasSymbolsWithFileName() && ProfileReader->hasLocalsWithFileName() &&
3154 !opts::AllowStripped) {
3155 BC->errs()
3156 << "BOLT-ERROR: input binary does not have local file symbols "
3157 "but profile data includes function names with embedded file "
3158 "names. It appears that the input binary was stripped while a "
3159 "profiled binary was not. If you know what you are doing and "
3160 "wish to proceed, use -allow-stripped option.\n";
3161 exit(1);
3165 void RewriteInstance::initializeMetadataManager() {
3166 if (BC->IsLinuxKernel)
3167 MetadataManager.registerRewriter(createLinuxKernelRewriter(*BC));
3169 MetadataManager.registerRewriter(createBuildIDRewriter(*BC));
3171 MetadataManager.registerRewriter(createPseudoProbeRewriter(*BC));
3173 MetadataManager.registerRewriter(createSDTRewriter(*BC));
3176 void RewriteInstance::processSectionMetadata() {
3177 NamedRegionTimer T("processmetadata-section", "process section metadata",
3178 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3179 initializeMetadataManager();
3181 MetadataManager.runSectionInitializers();
3184 void RewriteInstance::processMetadataPreCFG() {
3185 NamedRegionTimer T("processmetadata-precfg", "process metadata pre-CFG",
3186 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3187 MetadataManager.runInitializersPreCFG();
3189 processProfileDataPreCFG();
3192 void RewriteInstance::processMetadataPostCFG() {
3193 NamedRegionTimer T("processmetadata-postcfg", "process metadata post-CFG",
3194 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3195 MetadataManager.runInitializersPostCFG();
3198 void RewriteInstance::processProfileDataPreCFG() {
3199 if (!ProfileReader)
3200 return;
3202 NamedRegionTimer T("processprofile-precfg", "process profile data pre-CFG",
3203 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3205 if (Error E = ProfileReader->readProfilePreCFG(*BC.get()))
3206 report_error("cannot read profile pre-CFG", std::move(E));
3209 void RewriteInstance::processProfileData() {
3210 if (!ProfileReader)
3211 return;
3213 NamedRegionTimer T("processprofile", "process profile data", TimerGroupName,
3214 TimerGroupDesc, opts::TimeRewrite);
3216 if (Error E = ProfileReader->readProfile(*BC.get()))
3217 report_error("cannot read profile", std::move(E));
3219 if (opts::PrintProfile || opts::PrintAll) {
3220 for (auto &BFI : BC->getBinaryFunctions()) {
3221 BinaryFunction &Function = BFI.second;
3222 if (Function.empty())
3223 continue;
3225 Function.print(BC->outs(), "after attaching profile");
3229 if (!opts::SaveProfile.empty() && !BAT->enabledFor(InputFile)) {
3230 YAMLProfileWriter PW(opts::SaveProfile);
3231 PW.writeProfile(*this);
3233 if (opts::AggregateOnly &&
3234 opts::ProfileFormat == opts::ProfileFormatKind::PF_YAML &&
3235 !BAT->enabledFor(InputFile)) {
3236 YAMLProfileWriter PW(opts::OutputFilename);
3237 PW.writeProfile(*this);
3240 // Release memory used by profile reader.
3241 ProfileReader.reset();
3243 if (opts::AggregateOnly) {
3244 PrintProgramStats PPS(&*BAT);
3245 BC->logBOLTErrorsAndQuitOnFatal(PPS.runOnFunctions(*BC));
3246 TimerGroup::printAll(outs());
3247 exit(0);
3251 void RewriteInstance::disassembleFunctions() {
3252 NamedRegionTimer T("disassembleFunctions", "disassemble functions",
3253 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3254 for (auto &BFI : BC->getBinaryFunctions()) {
3255 BinaryFunction &Function = BFI.second;
3257 ErrorOr<ArrayRef<uint8_t>> FunctionData = Function.getData();
3258 if (!FunctionData) {
3259 BC->errs() << "BOLT-ERROR: corresponding section is non-executable or "
3260 << "empty for function " << Function << '\n';
3261 exit(1);
3264 // Treat zero-sized functions as non-simple ones.
3265 if (Function.getSize() == 0) {
3266 Function.setSimple(false);
3267 continue;
3270 // Offset of the function in the file.
3271 const auto *FileBegin =
3272 reinterpret_cast<const uint8_t *>(InputFile->getData().data());
3273 Function.setFileOffset(FunctionData->begin() - FileBegin);
3275 if (!shouldDisassemble(Function)) {
3276 NamedRegionTimer T("scan", "scan functions", "buildfuncs",
3277 "Scan Binary Functions", opts::TimeBuild);
3278 Function.scanExternalRefs();
3279 Function.setSimple(false);
3280 continue;
3283 bool DisasmFailed{false};
3284 handleAllErrors(Function.disassemble(), [&](const BOLTError &E) {
3285 DisasmFailed = true;
3286 if (E.isFatal()) {
3287 E.log(BC->errs());
3288 exit(1);
3290 if (opts::processAllFunctions()) {
3291 BC->errs() << BC->generateBugReportMessage(
3292 "function cannot be properly disassembled. "
3293 "Unable to continue in relocation mode.",
3294 Function);
3295 exit(1);
3297 if (opts::Verbosity >= 1)
3298 BC->outs() << "BOLT-INFO: could not disassemble function " << Function
3299 << ". Will ignore.\n";
3300 // Forcefully ignore the function.
3301 Function.setIgnored();
3304 if (DisasmFailed)
3305 continue;
3307 if (opts::PrintAll || opts::PrintDisasm)
3308 Function.print(BC->outs(), "after disassembly");
3311 BC->processInterproceduralReferences();
3312 BC->populateJumpTables();
3314 for (auto &BFI : BC->getBinaryFunctions()) {
3315 BinaryFunction &Function = BFI.second;
3317 if (!shouldDisassemble(Function))
3318 continue;
3320 Function.postProcessEntryPoints();
3321 Function.postProcessJumpTables();
3324 BC->clearJumpTableTempData();
3325 BC->adjustCodePadding();
3327 for (auto &BFI : BC->getBinaryFunctions()) {
3328 BinaryFunction &Function = BFI.second;
3330 if (!shouldDisassemble(Function))
3331 continue;
3333 if (!Function.isSimple()) {
3334 assert((!BC->HasRelocations || Function.getSize() == 0 ||
3335 Function.hasIndirectTargetToSplitFragment()) &&
3336 "unexpected non-simple function in relocation mode");
3337 continue;
3340 // Fill in CFI information for this function
3341 if (!Function.trapsOnEntry() && !CFIRdWrt->fillCFIInfoFor(Function)) {
3342 if (BC->HasRelocations) {
3343 BC->errs() << BC->generateBugReportMessage("unable to fill CFI.",
3344 Function);
3345 exit(1);
3346 } else {
3347 BC->errs() << "BOLT-WARNING: unable to fill CFI for function "
3348 << Function << ". Skipping.\n";
3349 Function.setSimple(false);
3350 continue;
3354 // Parse LSDA.
3355 if (Function.getLSDAAddress() != 0 &&
3356 !BC->getFragmentsToSkip().count(&Function)) {
3357 ErrorOr<BinarySection &> LSDASection =
3358 BC->getSectionForAddress(Function.getLSDAAddress());
3359 check_error(LSDASection.getError(), "failed to get LSDA section");
3360 ArrayRef<uint8_t> LSDAData = ArrayRef<uint8_t>(
3361 LSDASection->getData(), LSDASection->getContents().size());
3362 BC->logBOLTErrorsAndQuitOnFatal(
3363 Function.parseLSDA(LSDAData, LSDASection->getAddress()));
3368 void RewriteInstance::buildFunctionsCFG() {
3369 NamedRegionTimer T("buildCFG", "buildCFG", "buildfuncs",
3370 "Build Binary Functions", opts::TimeBuild);
3372 // Create annotation indices to allow lock-free execution
3373 BC->MIB->getOrCreateAnnotationIndex("JTIndexReg");
3374 BC->MIB->getOrCreateAnnotationIndex("NOP");
3376 ParallelUtilities::WorkFuncWithAllocTy WorkFun =
3377 [&](BinaryFunction &BF, MCPlusBuilder::AllocatorIdTy AllocId) {
3378 bool HadErrors{false};
3379 handleAllErrors(BF.buildCFG(AllocId), [&](const BOLTError &E) {
3380 if (!E.getMessage().empty())
3381 E.log(BC->errs());
3382 if (E.isFatal())
3383 exit(1);
3384 HadErrors = true;
3387 if (HadErrors)
3388 return;
3390 if (opts::PrintAll) {
3391 auto L = BC->scopeLock();
3392 BF.print(BC->outs(), "while building cfg");
3396 ParallelUtilities::PredicateTy SkipPredicate = [&](const BinaryFunction &BF) {
3397 return !shouldDisassemble(BF) || !BF.isSimple();
3400 ParallelUtilities::runOnEachFunctionWithUniqueAllocId(
3401 *BC, ParallelUtilities::SchedulingPolicy::SP_INST_LINEAR, WorkFun,
3402 SkipPredicate, "disassembleFunctions-buildCFG",
3403 /*ForceSequential*/ opts::SequentialDisassembly || opts::PrintAll);
3405 BC->postProcessSymbolTable();
3408 void RewriteInstance::postProcessFunctions() {
3409 // We mark fragments as non-simple here, not during disassembly,
3410 // So we can build their CFGs.
3411 BC->skipMarkedFragments();
3412 BC->clearFragmentsToSkip();
3414 BC->TotalScore = 0;
3415 BC->SumExecutionCount = 0;
3416 for (auto &BFI : BC->getBinaryFunctions()) {
3417 BinaryFunction &Function = BFI.second;
3419 // Set function as non-simple if it has dynamic relocations
3420 // in constant island, we don't want this function to be optimized
3421 // e.g. function splitting is unsupported.
3422 if (Function.hasDynamicRelocationAtIsland())
3423 Function.setSimple(false);
3425 if (Function.empty())
3426 continue;
3428 Function.postProcessCFG();
3430 if (opts::PrintAll || opts::PrintCFG)
3431 Function.print(BC->outs(), "after building cfg");
3433 if (opts::DumpDotAll)
3434 Function.dumpGraphForPass("00_build-cfg");
3436 if (opts::PrintLoopInfo) {
3437 Function.calculateLoopInfo();
3438 Function.printLoopInfo(BC->outs());
3441 BC->TotalScore += Function.getFunctionScore();
3442 BC->SumExecutionCount += Function.getKnownExecutionCount();
3445 if (opts::PrintGlobals) {
3446 BC->outs() << "BOLT-INFO: Global symbols:\n";
3447 BC->printGlobalSymbols(BC->outs());
3451 void RewriteInstance::runOptimizationPasses() {
3452 NamedRegionTimer T("runOptimizationPasses", "run optimization passes",
3453 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3454 BC->logBOLTErrorsAndQuitOnFatal(BinaryFunctionPassManager::runAllPasses(*BC));
3457 void RewriteInstance::preregisterSections() {
3458 // Preregister sections before emission to set their order in the output.
3459 const unsigned ROFlags = BinarySection::getFlags(/*IsReadOnly*/ true,
3460 /*IsText*/ false,
3461 /*IsAllocatable*/ true);
3462 if (BinarySection *EHFrameSection = getSection(getEHFrameSectionName())) {
3463 // New .eh_frame.
3464 BC->registerOrUpdateSection(getNewSecPrefix() + getEHFrameSectionName(),
3465 ELF::SHT_PROGBITS, ROFlags);
3466 // Fully register a relocatable copy of the original .eh_frame.
3467 BC->registerSection(".relocated.eh_frame", *EHFrameSection);
3469 BC->registerOrUpdateSection(getNewSecPrefix() + ".gcc_except_table",
3470 ELF::SHT_PROGBITS, ROFlags);
3471 BC->registerOrUpdateSection(getNewSecPrefix() + ".rodata", ELF::SHT_PROGBITS,
3472 ROFlags);
3473 BC->registerOrUpdateSection(getNewSecPrefix() + ".rodata.cold",
3474 ELF::SHT_PROGBITS, ROFlags);
3477 void RewriteInstance::emitAndLink() {
3478 NamedRegionTimer T("emitAndLink", "emit and link", TimerGroupName,
3479 TimerGroupDesc, opts::TimeRewrite);
3481 SmallString<0> ObjectBuffer;
3482 raw_svector_ostream OS(ObjectBuffer);
3484 // Implicitly MCObjectStreamer takes ownership of MCAsmBackend (MAB)
3485 // and MCCodeEmitter (MCE). ~MCObjectStreamer() will delete these
3486 // two instances.
3487 std::unique_ptr<MCStreamer> Streamer = BC->createStreamer(OS);
3489 if (EHFrameSection) {
3490 if (opts::UseOldText || opts::StrictMode) {
3491 // The section is going to be regenerated from scratch.
3492 // Empty the contents, but keep the section reference.
3493 EHFrameSection->clearContents();
3494 } else {
3495 // Make .eh_frame relocatable.
3496 relocateEHFrameSection();
3500 emitBinaryContext(*Streamer, *BC, getOrgSecPrefix());
3502 Streamer->finish();
3503 if (Streamer->getContext().hadError()) {
3504 BC->errs() << "BOLT-ERROR: Emission failed.\n";
3505 exit(1);
3508 if (opts::KeepTmp) {
3509 SmallString<128> OutObjectPath;
3510 sys::fs::getPotentiallyUniqueTempFileName("output", "o", OutObjectPath);
3511 std::error_code EC;
3512 raw_fd_ostream FOS(OutObjectPath, EC);
3513 check_error(EC, "cannot create output object file");
3514 FOS << ObjectBuffer;
3515 BC->outs()
3516 << "BOLT-INFO: intermediary output object file saved for debugging "
3517 "purposes: "
3518 << OutObjectPath << "\n";
3521 ErrorOr<BinarySection &> TextSection =
3522 BC->getUniqueSectionByName(BC->getMainCodeSectionName());
3523 if (BC->HasRelocations && TextSection)
3524 BC->renameSection(*TextSection,
3525 getOrgSecPrefix() + BC->getMainCodeSectionName());
3527 //////////////////////////////////////////////////////////////////////////////
3528 // Assign addresses to new sections.
3529 //////////////////////////////////////////////////////////////////////////////
3531 // Get output object as ObjectFile.
3532 std::unique_ptr<MemoryBuffer> ObjectMemBuffer =
3533 MemoryBuffer::getMemBuffer(ObjectBuffer, "in-memory object file", false);
3535 auto EFMM = std::make_unique<ExecutableFileMemoryManager>(*BC);
3536 EFMM->setNewSecPrefix(getNewSecPrefix());
3537 EFMM->setOrgSecPrefix(getOrgSecPrefix());
3539 Linker = std::make_unique<JITLinkLinker>(*BC, std::move(EFMM));
3540 Linker->loadObject(ObjectMemBuffer->getMemBufferRef(),
3541 [this](auto MapSection) { mapFileSections(MapSection); });
3543 // Update output addresses based on the new section map and
3544 // layout. Only do this for the object created by ourselves.
3545 updateOutputValues(*Linker);
3547 if (opts::UpdateDebugSections) {
3548 DebugInfoRewriter->updateLineTableOffsets(
3549 static_cast<MCObjectStreamer &>(*Streamer).getAssembler());
3552 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary())
3553 RtLibrary->link(*BC, ToolPath, *Linker, [this](auto MapSection) {
3554 // Map newly registered sections.
3555 this->mapAllocatableSections(MapSection);
3558 // Once the code is emitted, we can rename function sections to actual
3559 // output sections and de-register sections used for emission.
3560 for (BinaryFunction *Function : BC->getAllBinaryFunctions()) {
3561 ErrorOr<BinarySection &> Section = Function->getCodeSection();
3562 if (Section &&
3563 (Function->getImageAddress() == 0 || Function->getImageSize() == 0))
3564 continue;
3566 // Restore origin section for functions that were emitted or supposed to
3567 // be emitted to patch sections.
3568 if (Section)
3569 BC->deregisterSection(*Section);
3570 assert(Function->getOriginSectionName() && "expected origin section");
3571 Function->CodeSectionName = Function->getOriginSectionName()->str();
3572 for (const FunctionFragment &FF :
3573 Function->getLayout().getSplitFragments()) {
3574 if (ErrorOr<BinarySection &> ColdSection =
3575 Function->getCodeSection(FF.getFragmentNum()))
3576 BC->deregisterSection(*ColdSection);
3578 if (Function->getLayout().isSplit())
3579 Function->setColdCodeSectionName(getBOLTTextSectionName());
3582 if (opts::PrintCacheMetrics) {
3583 BC->outs() << "BOLT-INFO: cache metrics after emitting functions:\n";
3584 CacheMetrics::printAll(BC->outs(), BC->getSortedFunctions());
3588 void RewriteInstance::finalizeMetadataPreEmit() {
3589 NamedRegionTimer T("finalizemetadata-preemit", "finalize metadata pre-emit",
3590 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3591 MetadataManager.runFinalizersPreEmit();
3594 void RewriteInstance::updateMetadata() {
3595 NamedRegionTimer T("updatemetadata-postemit", "update metadata post-emit",
3596 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3597 MetadataManager.runFinalizersAfterEmit();
3599 if (opts::UpdateDebugSections) {
3600 NamedRegionTimer T("updateDebugInfo", "update debug info", TimerGroupName,
3601 TimerGroupDesc, opts::TimeRewrite);
3602 DebugInfoRewriter->updateDebugInfo();
3605 if (opts::WriteBoltInfoSection)
3606 addBoltInfoSection();
3609 void RewriteInstance::mapFileSections(BOLTLinker::SectionMapper MapSection) {
3610 BC->deregisterUnusedSections();
3612 // If no new .eh_frame was written, remove relocated original .eh_frame.
3613 BinarySection *RelocatedEHFrameSection =
3614 getSection(".relocated" + getEHFrameSectionName());
3615 if (RelocatedEHFrameSection && RelocatedEHFrameSection->hasValidSectionID()) {
3616 BinarySection *NewEHFrameSection =
3617 getSection(getNewSecPrefix() + getEHFrameSectionName());
3618 if (!NewEHFrameSection || !NewEHFrameSection->isFinalized()) {
3619 // JITLink will still have to process relocations for the section, hence
3620 // we need to assign it the address that wouldn't result in relocation
3621 // processing failure.
3622 MapSection(*RelocatedEHFrameSection, NextAvailableAddress);
3623 BC->deregisterSection(*RelocatedEHFrameSection);
3627 mapCodeSections(MapSection);
3629 // Map the rest of the sections.
3630 mapAllocatableSections(MapSection);
3632 if (!BC->BOLTReserved.empty()) {
3633 const uint64_t AllocatedSize =
3634 NextAvailableAddress - BC->BOLTReserved.start();
3635 if (BC->BOLTReserved.size() < AllocatedSize) {
3636 BC->errs() << "BOLT-ERROR: reserved space (" << BC->BOLTReserved.size()
3637 << " byte" << (BC->BOLTReserved.size() == 1 ? "" : "s")
3638 << ") is smaller than required for new allocations ("
3639 << AllocatedSize << " bytes)\n";
3640 exit(1);
3645 std::vector<BinarySection *> RewriteInstance::getCodeSections() {
3646 std::vector<BinarySection *> CodeSections;
3647 for (BinarySection &Section : BC->textSections())
3648 if (Section.hasValidSectionID())
3649 CodeSections.emplace_back(&Section);
3651 auto compareSections = [&](const BinarySection *A, const BinarySection *B) {
3652 // If both A and B have names starting with ".text.cold", then
3653 // - if opts::HotFunctionsAtEnd is true, we want order
3654 // ".text.cold.T", ".text.cold.T-1", ... ".text.cold.1", ".text.cold"
3655 // - if opts::HotFunctionsAtEnd is false, we want order
3656 // ".text.cold", ".text.cold.1", ... ".text.cold.T-1", ".text.cold.T"
3657 if (A->getName().starts_with(BC->getColdCodeSectionName()) &&
3658 B->getName().starts_with(BC->getColdCodeSectionName())) {
3659 if (A->getName().size() != B->getName().size())
3660 return (opts::HotFunctionsAtEnd)
3661 ? (A->getName().size() > B->getName().size())
3662 : (A->getName().size() < B->getName().size());
3663 return (opts::HotFunctionsAtEnd) ? (A->getName() > B->getName())
3664 : (A->getName() < B->getName());
3667 // Place movers before anything else.
3668 if (A->getName() == BC->getHotTextMoverSectionName())
3669 return true;
3670 if (B->getName() == BC->getHotTextMoverSectionName())
3671 return false;
3673 // Depending on opts::HotFunctionsAtEnd, place main and warm sections in
3674 // order.
3675 if (opts::HotFunctionsAtEnd) {
3676 if (B->getName() == BC->getMainCodeSectionName())
3677 return true;
3678 if (A->getName() == BC->getMainCodeSectionName())
3679 return false;
3680 return (B->getName() == BC->getWarmCodeSectionName());
3681 } else {
3682 if (A->getName() == BC->getMainCodeSectionName())
3683 return true;
3684 if (B->getName() == BC->getMainCodeSectionName())
3685 return false;
3686 return (A->getName() == BC->getWarmCodeSectionName());
3690 // Determine the order of sections.
3691 llvm::stable_sort(CodeSections, compareSections);
3693 return CodeSections;
3696 void RewriteInstance::mapCodeSections(BOLTLinker::SectionMapper MapSection) {
3697 if (BC->HasRelocations) {
3698 // Map sections for functions with pre-assigned addresses.
3699 for (BinaryFunction *InjectedFunction : BC->getInjectedBinaryFunctions()) {
3700 const uint64_t OutputAddress = InjectedFunction->getOutputAddress();
3701 if (!OutputAddress)
3702 continue;
3704 ErrorOr<BinarySection &> FunctionSection =
3705 InjectedFunction->getCodeSection();
3706 assert(FunctionSection && "function should have section");
3707 FunctionSection->setOutputAddress(OutputAddress);
3708 MapSection(*FunctionSection, OutputAddress);
3709 InjectedFunction->setImageAddress(FunctionSection->getAllocAddress());
3710 InjectedFunction->setImageSize(FunctionSection->getOutputSize());
3713 // Populate the list of sections to be allocated.
3714 std::vector<BinarySection *> CodeSections = getCodeSections();
3716 // Remove sections that were pre-allocated (patch sections).
3717 llvm::erase_if(CodeSections, [](BinarySection *Section) {
3718 return Section->getOutputAddress();
3720 LLVM_DEBUG(dbgs() << "Code sections in the order of output:\n";
3721 for (const BinarySection *Section : CodeSections)
3722 dbgs() << Section->getName() << '\n';
3725 uint64_t PaddingSize = 0; // size of padding required at the end
3727 // Allocate sections starting at a given Address.
3728 auto allocateAt = [&](uint64_t Address) {
3729 const char *LastNonColdSectionName = BC->HasWarmSection
3730 ? BC->getWarmCodeSectionName()
3731 : BC->getMainCodeSectionName();
3732 for (BinarySection *Section : CodeSections) {
3733 Address = alignTo(Address, Section->getAlignment());
3734 Section->setOutputAddress(Address);
3735 Address += Section->getOutputSize();
3737 // Hugify: Additional huge page from right side due to
3738 // weird ASLR mapping addresses (4KB aligned)
3739 if (opts::Hugify && !BC->HasFixedLoadAddress &&
3740 Section->getName() == LastNonColdSectionName)
3741 Address = alignTo(Address, Section->getAlignment());
3744 // Make sure we allocate enough space for huge pages.
3745 ErrorOr<BinarySection &> TextSection =
3746 BC->getUniqueSectionByName(LastNonColdSectionName);
3747 if (opts::HotText && TextSection && TextSection->hasValidSectionID()) {
3748 uint64_t HotTextEnd =
3749 TextSection->getOutputAddress() + TextSection->getOutputSize();
3750 HotTextEnd = alignTo(HotTextEnd, BC->PageAlign);
3751 if (HotTextEnd > Address) {
3752 PaddingSize = HotTextEnd - Address;
3753 Address = HotTextEnd;
3756 return Address;
3759 // Check if we can fit code in the original .text
3760 bool AllocationDone = false;
3761 if (opts::UseOldText) {
3762 const uint64_t CodeSize =
3763 allocateAt(BC->OldTextSectionAddress) - BC->OldTextSectionAddress;
3765 if (CodeSize <= BC->OldTextSectionSize) {
3766 BC->outs() << "BOLT-INFO: using original .text for new code with 0x"
3767 << Twine::utohexstr(opts::AlignText) << " alignment\n";
3768 AllocationDone = true;
3769 } else {
3770 BC->errs()
3771 << "BOLT-WARNING: original .text too small to fit the new code"
3772 << " using 0x" << Twine::utohexstr(opts::AlignText)
3773 << " alignment. " << CodeSize << " bytes needed, have "
3774 << BC->OldTextSectionSize << " bytes available.\n";
3775 opts::UseOldText = false;
3779 if (!AllocationDone)
3780 NextAvailableAddress = allocateAt(NextAvailableAddress);
3782 // Do the mapping for ORC layer based on the allocation.
3783 for (BinarySection *Section : CodeSections) {
3784 LLVM_DEBUG(
3785 dbgs() << "BOLT: mapping " << Section->getName() << " at 0x"
3786 << Twine::utohexstr(Section->getAllocAddress()) << " to 0x"
3787 << Twine::utohexstr(Section->getOutputAddress()) << '\n');
3788 MapSection(*Section, Section->getOutputAddress());
3789 Section->setOutputFileOffset(
3790 getFileOffsetForAddress(Section->getOutputAddress()));
3793 // Check if we need to insert a padding section for hot text.
3794 if (PaddingSize && !opts::UseOldText)
3795 BC->outs() << "BOLT-INFO: padding code to 0x"
3796 << Twine::utohexstr(NextAvailableAddress)
3797 << " to accommodate hot text\n";
3799 return;
3802 // Processing in non-relocation mode.
3803 uint64_t NewTextSectionStartAddress = NextAvailableAddress;
3805 for (auto &BFI : BC->getBinaryFunctions()) {
3806 BinaryFunction &Function = BFI.second;
3807 if (!Function.isEmitted())
3808 continue;
3810 ErrorOr<BinarySection &> FuncSection = Function.getCodeSection();
3811 assert(FuncSection && "cannot find section for function");
3812 FuncSection->setOutputAddress(Function.getAddress());
3813 LLVM_DEBUG(dbgs() << "BOLT: mapping 0x"
3814 << Twine::utohexstr(FuncSection->getAllocAddress())
3815 << " to 0x" << Twine::utohexstr(Function.getAddress())
3816 << '\n');
3817 MapSection(*FuncSection, Function.getAddress());
3818 Function.setImageAddress(FuncSection->getAllocAddress());
3819 Function.setImageSize(FuncSection->getOutputSize());
3820 assert(Function.getImageSize() <= Function.getMaxSize() &&
3821 "Unexpected large function");
3823 // Map jump tables if updating in-place.
3824 if (opts::JumpTables == JTS_BASIC) {
3825 for (auto &JTI : Function.JumpTables) {
3826 JumpTable *JT = JTI.second;
3827 BinarySection &Section = JT->getOutputSection();
3828 Section.setOutputAddress(JT->getAddress());
3829 Section.setOutputFileOffset(getFileOffsetForAddress(JT->getAddress()));
3830 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: mapping JT " << Section.getName()
3831 << " to 0x" << Twine::utohexstr(JT->getAddress())
3832 << '\n');
3833 MapSection(Section, JT->getAddress());
3837 if (!Function.isSplit())
3838 continue;
3840 assert(Function.getLayout().isHotColdSplit() &&
3841 "Cannot allocate more than two fragments per function in "
3842 "non-relocation mode.");
3844 FunctionFragment &FF =
3845 Function.getLayout().getFragment(FragmentNum::cold());
3846 ErrorOr<BinarySection &> ColdSection =
3847 Function.getCodeSection(FF.getFragmentNum());
3848 assert(ColdSection && "cannot find section for cold part");
3849 // Cold fragments are aligned at 16 bytes.
3850 NextAvailableAddress = alignTo(NextAvailableAddress, 16);
3851 FF.setAddress(NextAvailableAddress);
3852 FF.setImageAddress(ColdSection->getAllocAddress());
3853 FF.setImageSize(ColdSection->getOutputSize());
3854 FF.setFileOffset(getFileOffsetForAddress(NextAvailableAddress));
3855 ColdSection->setOutputAddress(FF.getAddress());
3857 LLVM_DEBUG(
3858 dbgs() << formatv(
3859 "BOLT: mapping cold fragment {0:x+} to {1:x+} with size {2:x+}\n",
3860 FF.getImageAddress(), FF.getAddress(), FF.getImageSize()));
3861 MapSection(*ColdSection, FF.getAddress());
3863 NextAvailableAddress += FF.getImageSize();
3866 // Add the new text section aggregating all existing code sections.
3867 // This is pseudo-section that serves a purpose of creating a corresponding
3868 // entry in section header table.
3869 const uint64_t NewTextSectionSize =
3870 NextAvailableAddress - NewTextSectionStartAddress;
3871 if (NewTextSectionSize) {
3872 const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/true,
3873 /*IsText=*/true,
3874 /*IsAllocatable=*/true);
3875 BinarySection &Section =
3876 BC->registerOrUpdateSection(getBOLTTextSectionName(),
3877 ELF::SHT_PROGBITS,
3878 Flags,
3879 /*Data=*/nullptr,
3880 NewTextSectionSize,
3881 16);
3882 Section.setOutputAddress(NewTextSectionStartAddress);
3883 Section.setOutputFileOffset(
3884 getFileOffsetForAddress(NewTextSectionStartAddress));
3888 void RewriteInstance::mapAllocatableSections(
3889 BOLTLinker::SectionMapper MapSection) {
3891 if (opts::UseOldText || opts::StrictMode) {
3892 auto tryRewriteSection = [&](BinarySection &OldSection,
3893 BinarySection &NewSection) {
3894 if (OldSection.getSize() < NewSection.getOutputSize())
3895 return;
3897 BC->outs() << "BOLT-INFO: rewriting " << OldSection.getName()
3898 << " in-place\n";
3900 NewSection.setOutputAddress(OldSection.getAddress());
3901 NewSection.setOutputFileOffset(OldSection.getInputFileOffset());
3902 MapSection(NewSection, OldSection.getAddress());
3904 // Pad contents with zeros.
3905 NewSection.addPadding(OldSection.getSize() - NewSection.getOutputSize());
3907 // Prevent the original section name from appearing in the section header
3908 // table.
3909 OldSection.setAnonymous(true);
3912 if (EHFrameSection) {
3913 BinarySection *NewEHFrameSection =
3914 getSection(getNewSecPrefix() + getEHFrameSectionName());
3915 assert(NewEHFrameSection && "New contents expected for .eh_frame");
3916 tryRewriteSection(*EHFrameSection, *NewEHFrameSection);
3918 BinarySection *EHSection = getSection(".gcc_except_table");
3919 BinarySection *NewEHSection =
3920 getSection(getNewSecPrefix() + ".gcc_except_table");
3921 if (EHSection) {
3922 assert(NewEHSection && "New contents expected for .gcc_except_table");
3923 tryRewriteSection(*EHSection, *NewEHSection);
3927 // Allocate read-only sections first, then writable sections.
3928 enum : uint8_t { ST_READONLY, ST_READWRITE };
3929 for (uint8_t SType = ST_READONLY; SType <= ST_READWRITE; ++SType) {
3930 const uint64_t LastNextAvailableAddress = NextAvailableAddress;
3931 if (SType == ST_READWRITE) {
3932 // Align R+W segment to regular page size
3933 NextAvailableAddress = alignTo(NextAvailableAddress, BC->RegularPageSize);
3934 NewWritableSegmentAddress = NextAvailableAddress;
3937 for (BinarySection &Section : BC->allocatableSections()) {
3938 if (Section.isLinkOnly())
3939 continue;
3941 if (!Section.hasValidSectionID())
3942 continue;
3944 if (Section.isWritable() == (SType == ST_READONLY))
3945 continue;
3947 if (Section.getOutputAddress()) {
3948 LLVM_DEBUG({
3949 dbgs() << "BOLT-DEBUG: section " << Section.getName()
3950 << " is already mapped at 0x"
3951 << Twine::utohexstr(Section.getOutputAddress()) << '\n';
3953 continue;
3956 if (Section.hasSectionRef()) {
3957 LLVM_DEBUG({
3958 dbgs() << "BOLT-DEBUG: mapping original section " << Section.getName()
3959 << " to 0x" << Twine::utohexstr(Section.getAddress()) << '\n';
3961 Section.setOutputAddress(Section.getAddress());
3962 Section.setOutputFileOffset(Section.getInputFileOffset());
3963 MapSection(Section, Section.getAddress());
3964 } else {
3965 NextAvailableAddress =
3966 alignTo(NextAvailableAddress, Section.getAlignment());
3967 LLVM_DEBUG({
3968 dbgs() << "BOLT: mapping section " << Section.getName() << " (0x"
3969 << Twine::utohexstr(Section.getAllocAddress()) << ") to 0x"
3970 << Twine::utohexstr(NextAvailableAddress) << ":0x"
3971 << Twine::utohexstr(NextAvailableAddress +
3972 Section.getOutputSize())
3973 << '\n';
3976 MapSection(Section, NextAvailableAddress);
3977 Section.setOutputAddress(NextAvailableAddress);
3978 Section.setOutputFileOffset(
3979 getFileOffsetForAddress(NextAvailableAddress));
3981 NextAvailableAddress += Section.getOutputSize();
3985 if (SType == ST_READONLY) {
3986 if (PHDRTableAddress) {
3987 // Segment size includes the size of the PHDR area.
3988 NewTextSegmentSize = NextAvailableAddress - PHDRTableAddress;
3989 } else if (NewTextSegmentAddress) {
3990 // Existing PHDR table would be updated.
3991 NewTextSegmentSize = NextAvailableAddress - NewTextSegmentAddress;
3993 } else if (SType == ST_READWRITE) {
3994 NewWritableSegmentSize = NextAvailableAddress - NewWritableSegmentAddress;
3995 // Restore NextAvailableAddress if no new writable sections
3996 if (!NewWritableSegmentSize)
3997 NextAvailableAddress = LastNextAvailableAddress;
4002 void RewriteInstance::updateOutputValues(const BOLTLinker &Linker) {
4003 if (std::optional<AddressMap> Map = AddressMap::parse(*BC))
4004 BC->setIOAddressMap(std::move(*Map));
4006 for (BinaryFunction *Function : BC->getAllBinaryFunctions())
4007 Function->updateOutputValues(Linker);
4010 void RewriteInstance::patchELFPHDRTable() {
4011 auto ELF64LEFile = cast<ELF64LEObjectFile>(InputFile);
4012 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile();
4013 raw_fd_ostream &OS = Out->os();
4015 // Write/re-write program headers.
4016 Phnum = Obj.getHeader().e_phnum;
4017 if (PHDRTableOffset) {
4018 // Writing new pheader table and adding one new entry for R+X segment.
4019 Phnum += 1;
4020 if (NewWritableSegmentSize) {
4021 // Adding one more entry for R+W segment.
4022 Phnum += 1;
4024 } else {
4025 assert(!PHDRTableAddress && "unexpected address for program header table");
4026 PHDRTableOffset = Obj.getHeader().e_phoff;
4027 if (NewWritableSegmentSize) {
4028 BC->errs() << "BOLT-ERROR: unable to add writable segment\n";
4029 exit(1);
4033 // NOTE Currently .eh_frame_hdr appends to the last segment, recalculate
4034 // last segments size based on the NextAvailableAddress variable.
4035 if (!NewWritableSegmentSize) {
4036 if (PHDRTableAddress)
4037 NewTextSegmentSize = NextAvailableAddress - PHDRTableAddress;
4038 else if (NewTextSegmentAddress)
4039 NewTextSegmentSize = NextAvailableAddress - NewTextSegmentAddress;
4040 } else {
4041 NewWritableSegmentSize = NextAvailableAddress - NewWritableSegmentAddress;
4044 const uint64_t SavedPos = OS.tell();
4045 OS.seek(PHDRTableOffset);
4047 auto createNewTextPhdr = [&]() {
4048 ELF64LEPhdrTy NewPhdr;
4049 NewPhdr.p_type = ELF::PT_LOAD;
4050 if (PHDRTableAddress) {
4051 NewPhdr.p_offset = PHDRTableOffset;
4052 NewPhdr.p_vaddr = PHDRTableAddress;
4053 NewPhdr.p_paddr = PHDRTableAddress;
4054 } else {
4055 NewPhdr.p_offset = NewTextSegmentOffset;
4056 NewPhdr.p_vaddr = NewTextSegmentAddress;
4057 NewPhdr.p_paddr = NewTextSegmentAddress;
4059 NewPhdr.p_filesz = NewTextSegmentSize;
4060 NewPhdr.p_memsz = NewTextSegmentSize;
4061 NewPhdr.p_flags = ELF::PF_X | ELF::PF_R;
4062 if (opts::Instrument) {
4063 // FIXME: Currently instrumentation is experimental and the runtime data
4064 // is emitted with code, thus everything needs to be writable.
4065 NewPhdr.p_flags |= ELF::PF_W;
4067 NewPhdr.p_align = BC->PageAlign;
4069 return NewPhdr;
4072 auto writeNewSegmentPhdrs = [&]() {
4073 if (PHDRTableAddress || NewTextSegmentSize) {
4074 ELF64LE::Phdr NewPhdr = createNewTextPhdr();
4075 OS.write(reinterpret_cast<const char *>(&NewPhdr), sizeof(NewPhdr));
4078 if (NewWritableSegmentSize) {
4079 ELF64LEPhdrTy NewPhdr;
4080 NewPhdr.p_type = ELF::PT_LOAD;
4081 NewPhdr.p_offset = getFileOffsetForAddress(NewWritableSegmentAddress);
4082 NewPhdr.p_vaddr = NewWritableSegmentAddress;
4083 NewPhdr.p_paddr = NewWritableSegmentAddress;
4084 NewPhdr.p_filesz = NewWritableSegmentSize;
4085 NewPhdr.p_memsz = NewWritableSegmentSize;
4086 NewPhdr.p_align = BC->RegularPageSize;
4087 NewPhdr.p_flags = ELF::PF_R | ELF::PF_W;
4088 OS.write(reinterpret_cast<const char *>(&NewPhdr), sizeof(NewPhdr));
4092 bool ModdedGnuStack = false;
4093 bool AddedSegment = false;
4095 // Copy existing program headers with modifications.
4096 for (const ELF64LE::Phdr &Phdr : cantFail(Obj.program_headers())) {
4097 ELF64LE::Phdr NewPhdr = Phdr;
4098 switch (Phdr.p_type) {
4099 case ELF::PT_PHDR:
4100 if (PHDRTableAddress) {
4101 NewPhdr.p_offset = PHDRTableOffset;
4102 NewPhdr.p_vaddr = PHDRTableAddress;
4103 NewPhdr.p_paddr = PHDRTableAddress;
4104 NewPhdr.p_filesz = sizeof(NewPhdr) * Phnum;
4105 NewPhdr.p_memsz = sizeof(NewPhdr) * Phnum;
4107 break;
4108 case ELF::PT_GNU_EH_FRAME: {
4109 ErrorOr<BinarySection &> EHFrameHdrSec = BC->getUniqueSectionByName(
4110 getNewSecPrefix() + getEHFrameHdrSectionName());
4111 if (EHFrameHdrSec && EHFrameHdrSec->isAllocatable() &&
4112 EHFrameHdrSec->isFinalized()) {
4113 NewPhdr.p_offset = EHFrameHdrSec->getOutputFileOffset();
4114 NewPhdr.p_vaddr = EHFrameHdrSec->getOutputAddress();
4115 NewPhdr.p_paddr = EHFrameHdrSec->getOutputAddress();
4116 NewPhdr.p_filesz = EHFrameHdrSec->getOutputSize();
4117 NewPhdr.p_memsz = EHFrameHdrSec->getOutputSize();
4119 break;
4121 case ELF::PT_GNU_STACK:
4122 if (opts::UseGnuStack) {
4123 // Overwrite the header with the new text segment header.
4124 NewPhdr = createNewTextPhdr();
4125 ModdedGnuStack = true;
4127 break;
4128 case ELF::PT_DYNAMIC:
4129 if (!opts::UseGnuStack) {
4130 // Insert new headers before DYNAMIC.
4131 writeNewSegmentPhdrs();
4132 AddedSegment = true;
4134 break;
4136 OS.write(reinterpret_cast<const char *>(&NewPhdr), sizeof(NewPhdr));
4139 if (!opts::UseGnuStack && !AddedSegment) {
4140 // Append new headers to the end of the table.
4141 writeNewSegmentPhdrs();
4144 if (opts::UseGnuStack && !ModdedGnuStack) {
4145 BC->errs()
4146 << "BOLT-ERROR: could not find PT_GNU_STACK program header to modify\n";
4147 exit(1);
4150 OS.seek(SavedPos);
4153 namespace {
4155 /// Write padding to \p OS such that its current \p Offset becomes aligned
4156 /// at \p Alignment. Return new (aligned) offset.
4157 uint64_t appendPadding(raw_pwrite_stream &OS, uint64_t Offset,
4158 uint64_t Alignment) {
4159 if (!Alignment)
4160 return Offset;
4162 const uint64_t PaddingSize =
4163 offsetToAlignment(Offset, llvm::Align(Alignment));
4164 for (unsigned I = 0; I < PaddingSize; ++I)
4165 OS.write((unsigned char)0);
4166 return Offset + PaddingSize;
4171 void RewriteInstance::rewriteNoteSections() {
4172 auto ELF64LEFile = cast<ELF64LEObjectFile>(InputFile);
4173 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile();
4174 raw_fd_ostream &OS = Out->os();
4176 uint64_t NextAvailableOffset = std::max(
4177 getFileOffsetForAddress(NextAvailableAddress), FirstNonAllocatableOffset);
4178 OS.seek(NextAvailableOffset);
4180 // Copy over non-allocatable section contents and update file offsets.
4181 for (const ELF64LE::Shdr &Section : cantFail(Obj.sections())) {
4182 if (Section.sh_type == ELF::SHT_NULL)
4183 continue;
4184 if (Section.sh_flags & ELF::SHF_ALLOC)
4185 continue;
4187 SectionRef SecRef = ELF64LEFile->toSectionRef(&Section);
4188 BinarySection *BSec = BC->getSectionForSectionRef(SecRef);
4189 assert(BSec && !BSec->isAllocatable() &&
4190 "Matching non-allocatable BinarySection should exist.");
4192 StringRef SectionName =
4193 cantFail(Obj.getSectionName(Section), "cannot get section name");
4194 if (shouldStrip(Section, SectionName))
4195 continue;
4197 // Insert padding as needed.
4198 NextAvailableOffset =
4199 appendPadding(OS, NextAvailableOffset, Section.sh_addralign);
4201 // New section size.
4202 uint64_t Size = 0;
4203 bool DataWritten = false;
4204 // Copy over section contents unless it's one of the sections we overwrite.
4205 if (!willOverwriteSection(SectionName)) {
4206 Size = Section.sh_size;
4207 StringRef Dataref = InputFile->getData().substr(Section.sh_offset, Size);
4208 std::string Data;
4209 if (BSec->getPatcher()) {
4210 Data = BSec->getPatcher()->patchBinary(Dataref);
4211 Dataref = StringRef(Data);
4214 // Section was expanded, so need to treat it as overwrite.
4215 if (Size != Dataref.size()) {
4216 BSec = &BC->registerOrUpdateNoteSection(
4217 SectionName, copyByteArray(Dataref), Dataref.size());
4218 Size = 0;
4219 } else {
4220 OS << Dataref;
4221 DataWritten = true;
4223 // Add padding as the section extension might rely on the alignment.
4224 Size = appendPadding(OS, Size, Section.sh_addralign);
4228 // Perform section post-processing.
4229 assert(BSec->getAlignment() <= Section.sh_addralign &&
4230 "alignment exceeds value in file");
4232 if (BSec->getAllocAddress()) {
4233 assert(!DataWritten && "Writing section twice.");
4234 (void)DataWritten;
4235 Size += BSec->write(OS);
4238 BSec->setOutputFileOffset(NextAvailableOffset);
4239 BSec->flushPendingRelocations(OS, [this](const MCSymbol *S) {
4240 return getNewValueForSymbol(S->getName());
4243 // Section contents are no longer needed, but we need to update the size so
4244 // that it will be reflected in the section header table.
4245 BSec->updateContents(nullptr, Size);
4247 NextAvailableOffset += Size;
4250 // Write new note sections.
4251 for (BinarySection &Section : BC->nonAllocatableSections()) {
4252 if (Section.getOutputFileOffset() || !Section.getAllocAddress())
4253 continue;
4255 assert(!Section.hasPendingRelocations() && "cannot have pending relocs");
4257 NextAvailableOffset =
4258 appendPadding(OS, NextAvailableOffset, Section.getAlignment());
4259 Section.setOutputFileOffset(NextAvailableOffset);
4261 LLVM_DEBUG(
4262 dbgs() << "BOLT-DEBUG: writing out new section " << Section.getName()
4263 << " of size " << Section.getOutputSize() << " at offset 0x"
4264 << Twine::utohexstr(Section.getOutputFileOffset()) << '\n');
4266 NextAvailableOffset += Section.write(OS);
4270 template <typename ELFT>
4271 void RewriteInstance::finalizeSectionStringTable(ELFObjectFile<ELFT> *File) {
4272 // Pre-populate section header string table.
4273 for (const BinarySection &Section : BC->sections())
4274 if (!Section.isAnonymous())
4275 SHStrTab.add(Section.getOutputName());
4276 SHStrTab.finalize();
4278 const size_t SHStrTabSize = SHStrTab.getSize();
4279 uint8_t *DataCopy = new uint8_t[SHStrTabSize];
4280 memset(DataCopy, 0, SHStrTabSize);
4281 SHStrTab.write(DataCopy);
4282 BC->registerOrUpdateNoteSection(".shstrtab",
4283 DataCopy,
4284 SHStrTabSize,
4285 /*Alignment=*/1,
4286 /*IsReadOnly=*/true,
4287 ELF::SHT_STRTAB);
4290 void RewriteInstance::addBoltInfoSection() {
4291 std::string DescStr;
4292 raw_string_ostream DescOS(DescStr);
4294 DescOS << "BOLT revision: " << BoltRevision << ", "
4295 << "command line:";
4296 for (int I = 0; I < Argc; ++I)
4297 DescOS << " " << Argv[I];
4299 // Encode as GNU GOLD VERSION so it is easily printable by 'readelf -n'
4300 const std::string BoltInfo =
4301 BinarySection::encodeELFNote("GNU", DescStr, 4 /*NT_GNU_GOLD_VERSION*/);
4302 BC->registerOrUpdateNoteSection(".note.bolt_info", copyByteArray(BoltInfo),
4303 BoltInfo.size(),
4304 /*Alignment=*/1,
4305 /*IsReadOnly=*/true, ELF::SHT_NOTE);
4308 void RewriteInstance::addBATSection() {
4309 BC->registerOrUpdateNoteSection(BoltAddressTranslation::SECTION_NAME, nullptr,
4311 /*Alignment=*/1,
4312 /*IsReadOnly=*/true, ELF::SHT_NOTE);
4315 void RewriteInstance::encodeBATSection() {
4316 std::string DescStr;
4317 raw_string_ostream DescOS(DescStr);
4319 BAT->write(*BC, DescOS);
4321 const std::string BoltInfo =
4322 BinarySection::encodeELFNote("BOLT", DescStr, BinarySection::NT_BOLT_BAT);
4323 BC->registerOrUpdateNoteSection(BoltAddressTranslation::SECTION_NAME,
4324 copyByteArray(BoltInfo), BoltInfo.size(),
4325 /*Alignment=*/1,
4326 /*IsReadOnly=*/true, ELF::SHT_NOTE);
4327 BC->outs() << "BOLT-INFO: BAT section size (bytes): " << BoltInfo.size()
4328 << '\n';
4331 template <typename ELFShdrTy>
4332 bool RewriteInstance::shouldStrip(const ELFShdrTy &Section,
4333 StringRef SectionName) {
4334 // Strip non-allocatable relocation sections.
4335 if (!(Section.sh_flags & ELF::SHF_ALLOC) && Section.sh_type == ELF::SHT_RELA)
4336 return true;
4338 // Strip debug sections if not updating them.
4339 if (isDebugSection(SectionName) && !opts::UpdateDebugSections)
4340 return true;
4342 // Strip symtab section if needed
4343 if (opts::RemoveSymtab && Section.sh_type == ELF::SHT_SYMTAB)
4344 return true;
4346 return false;
4349 template <typename ELFT>
4350 std::vector<typename object::ELFObjectFile<ELFT>::Elf_Shdr>
4351 RewriteInstance::getOutputSections(ELFObjectFile<ELFT> *File,
4352 std::vector<uint32_t> &NewSectionIndex) {
4353 using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr;
4354 const ELFFile<ELFT> &Obj = File->getELFFile();
4355 typename ELFT::ShdrRange Sections = cantFail(Obj.sections());
4357 // Keep track of section header entries attached to the corresponding section.
4358 std::vector<std::pair<BinarySection *, ELFShdrTy>> OutputSections;
4359 auto addSection = [&](const ELFShdrTy &Section, BinarySection &BinSec) {
4360 ELFShdrTy NewSection = Section;
4361 NewSection.sh_name = SHStrTab.getOffset(BinSec.getOutputName());
4362 OutputSections.emplace_back(&BinSec, std::move(NewSection));
4365 // Copy over entries for original allocatable sections using modified name.
4366 for (const ELFShdrTy &Section : Sections) {
4367 // Always ignore this section.
4368 if (Section.sh_type == ELF::SHT_NULL) {
4369 OutputSections.emplace_back(nullptr, Section);
4370 continue;
4373 if (!(Section.sh_flags & ELF::SHF_ALLOC))
4374 continue;
4376 SectionRef SecRef = File->toSectionRef(&Section);
4377 BinarySection *BinSec = BC->getSectionForSectionRef(SecRef);
4378 assert(BinSec && "Matching BinarySection should exist.");
4380 // Exclude anonymous sections.
4381 if (BinSec->isAnonymous())
4382 continue;
4384 addSection(Section, *BinSec);
4387 for (BinarySection &Section : BC->allocatableSections()) {
4388 if (!Section.isFinalized())
4389 continue;
4391 if (Section.hasSectionRef() || Section.isAnonymous()) {
4392 if (opts::Verbosity)
4393 BC->outs() << "BOLT-INFO: not writing section header for section "
4394 << Section.getOutputName() << '\n';
4395 continue;
4398 if (opts::Verbosity >= 1)
4399 BC->outs() << "BOLT-INFO: writing section header for "
4400 << Section.getOutputName() << '\n';
4401 ELFShdrTy NewSection;
4402 NewSection.sh_type = ELF::SHT_PROGBITS;
4403 NewSection.sh_addr = Section.getOutputAddress();
4404 NewSection.sh_offset = Section.getOutputFileOffset();
4405 NewSection.sh_size = Section.getOutputSize();
4406 NewSection.sh_entsize = 0;
4407 NewSection.sh_flags = Section.getELFFlags();
4408 NewSection.sh_link = 0;
4409 NewSection.sh_info = 0;
4410 NewSection.sh_addralign = Section.getAlignment();
4411 addSection(NewSection, Section);
4414 // Sort all allocatable sections by their offset.
4415 llvm::stable_sort(OutputSections, [](const auto &A, const auto &B) {
4416 return A.second.sh_offset < B.second.sh_offset;
4419 // Fix section sizes to prevent overlapping.
4420 ELFShdrTy *PrevSection = nullptr;
4421 BinarySection *PrevBinSec = nullptr;
4422 for (auto &SectionKV : OutputSections) {
4423 ELFShdrTy &Section = SectionKV.second;
4425 // Ignore NOBITS sections as they don't take any space in the file.
4426 if (Section.sh_type == ELF::SHT_NOBITS)
4427 continue;
4429 // Note that address continuity is not guaranteed as sections could be
4430 // placed in different loadable segments.
4431 if (PrevSection &&
4432 PrevSection->sh_offset + PrevSection->sh_size > Section.sh_offset) {
4433 if (opts::Verbosity > 1)
4434 BC->outs() << "BOLT-INFO: adjusting size for section "
4435 << PrevBinSec->getOutputName() << '\n';
4436 PrevSection->sh_size = Section.sh_offset - PrevSection->sh_offset;
4439 PrevSection = &Section;
4440 PrevBinSec = SectionKV.first;
4443 uint64_t LastFileOffset = 0;
4445 // Copy over entries for non-allocatable sections performing necessary
4446 // adjustments.
4447 for (const ELFShdrTy &Section : Sections) {
4448 if (Section.sh_type == ELF::SHT_NULL)
4449 continue;
4450 if (Section.sh_flags & ELF::SHF_ALLOC)
4451 continue;
4453 StringRef SectionName =
4454 cantFail(Obj.getSectionName(Section), "cannot get section name");
4456 if (shouldStrip(Section, SectionName))
4457 continue;
4459 SectionRef SecRef = File->toSectionRef(&Section);
4460 BinarySection *BinSec = BC->getSectionForSectionRef(SecRef);
4461 assert(BinSec && "Matching BinarySection should exist.");
4463 ELFShdrTy NewSection = Section;
4464 NewSection.sh_offset = BinSec->getOutputFileOffset();
4465 NewSection.sh_size = BinSec->getOutputSize();
4467 if (NewSection.sh_type == ELF::SHT_SYMTAB)
4468 NewSection.sh_info = NumLocalSymbols;
4470 addSection(NewSection, *BinSec);
4472 LastFileOffset = BinSec->getOutputFileOffset();
4475 // Create entries for new non-allocatable sections.
4476 for (BinarySection &Section : BC->nonAllocatableSections()) {
4477 if (Section.getOutputFileOffset() <= LastFileOffset)
4478 continue;
4480 if (opts::Verbosity >= 1)
4481 BC->outs() << "BOLT-INFO: writing section header for "
4482 << Section.getOutputName() << '\n';
4484 ELFShdrTy NewSection;
4485 NewSection.sh_type = Section.getELFType();
4486 NewSection.sh_addr = 0;
4487 NewSection.sh_offset = Section.getOutputFileOffset();
4488 NewSection.sh_size = Section.getOutputSize();
4489 NewSection.sh_entsize = 0;
4490 NewSection.sh_flags = Section.getELFFlags();
4491 NewSection.sh_link = 0;
4492 NewSection.sh_info = 0;
4493 NewSection.sh_addralign = Section.getAlignment();
4495 addSection(NewSection, Section);
4498 // Assign indices to sections.
4499 std::unordered_map<std::string, uint64_t> NameToIndex;
4500 for (uint32_t Index = 1; Index < OutputSections.size(); ++Index)
4501 OutputSections[Index].first->setIndex(Index);
4503 // Update section index mapping
4504 NewSectionIndex.clear();
4505 NewSectionIndex.resize(Sections.size(), 0);
4506 for (const ELFShdrTy &Section : Sections) {
4507 if (Section.sh_type == ELF::SHT_NULL)
4508 continue;
4510 size_t OrgIndex = std::distance(Sections.begin(), &Section);
4512 SectionRef SecRef = File->toSectionRef(&Section);
4513 BinarySection *BinSec = BC->getSectionForSectionRef(SecRef);
4514 assert(BinSec && "BinarySection should exist for an input section.");
4516 // Some sections are stripped
4517 if (!BinSec->hasValidIndex())
4518 continue;
4520 NewSectionIndex[OrgIndex] = BinSec->getIndex();
4523 std::vector<ELFShdrTy> SectionsOnly(OutputSections.size());
4524 llvm::copy(llvm::make_second_range(OutputSections), SectionsOnly.begin());
4526 return SectionsOnly;
4529 // Rewrite section header table inserting new entries as needed. The sections
4530 // header table size itself may affect the offsets of other sections,
4531 // so we are placing it at the end of the binary.
4533 // As we rewrite entries we need to track how many sections were inserted
4534 // as it changes the sh_link value. We map old indices to new ones for
4535 // existing sections.
4536 template <typename ELFT>
4537 void RewriteInstance::patchELFSectionHeaderTable(ELFObjectFile<ELFT> *File) {
4538 using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr;
4539 using ELFEhdrTy = typename ELFObjectFile<ELFT>::Elf_Ehdr;
4540 raw_fd_ostream &OS = Out->os();
4541 const ELFFile<ELFT> &Obj = File->getELFFile();
4543 // Mapping from old section indices to new ones
4544 std::vector<uint32_t> NewSectionIndex;
4545 std::vector<ELFShdrTy> OutputSections =
4546 getOutputSections(File, NewSectionIndex);
4547 LLVM_DEBUG(
4548 dbgs() << "BOLT-DEBUG: old to new section index mapping:\n";
4549 for (uint64_t I = 0; I < NewSectionIndex.size(); ++I)
4550 dbgs() << " " << I << " -> " << NewSectionIndex[I] << '\n';
4553 // Align starting address for section header table. There's no architecutal
4554 // need to align this, it is just for pleasant human readability.
4555 uint64_t SHTOffset = OS.tell();
4556 SHTOffset = appendPadding(OS, SHTOffset, 16);
4558 // Write all section header entries while patching section references.
4559 for (ELFShdrTy &Section : OutputSections) {
4560 Section.sh_link = NewSectionIndex[Section.sh_link];
4561 if (Section.sh_type == ELF::SHT_REL || Section.sh_type == ELF::SHT_RELA)
4562 Section.sh_info = NewSectionIndex[Section.sh_info];
4563 OS.write(reinterpret_cast<const char *>(&Section), sizeof(Section));
4566 // Fix ELF header.
4567 ELFEhdrTy NewEhdr = Obj.getHeader();
4569 if (BC->HasRelocations) {
4570 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary())
4571 NewEhdr.e_entry = RtLibrary->getRuntimeStartAddress();
4572 else
4573 NewEhdr.e_entry = getNewFunctionAddress(NewEhdr.e_entry);
4574 assert((NewEhdr.e_entry || !Obj.getHeader().e_entry) &&
4575 "cannot find new address for entry point");
4577 if (PHDRTableOffset) {
4578 NewEhdr.e_phoff = PHDRTableOffset;
4579 NewEhdr.e_phnum = Phnum;
4581 NewEhdr.e_shoff = SHTOffset;
4582 NewEhdr.e_shnum = OutputSections.size();
4583 NewEhdr.e_shstrndx = NewSectionIndex[NewEhdr.e_shstrndx];
4584 OS.pwrite(reinterpret_cast<const char *>(&NewEhdr), sizeof(NewEhdr), 0);
4587 template <typename ELFT, typename WriteFuncTy, typename StrTabFuncTy>
4588 void RewriteInstance::updateELFSymbolTable(
4589 ELFObjectFile<ELFT> *File, bool IsDynSym,
4590 const typename object::ELFObjectFile<ELFT>::Elf_Shdr &SymTabSection,
4591 const std::vector<uint32_t> &NewSectionIndex, WriteFuncTy Write,
4592 StrTabFuncTy AddToStrTab) {
4593 const ELFFile<ELFT> &Obj = File->getELFFile();
4594 using ELFSymTy = typename ELFObjectFile<ELFT>::Elf_Sym;
4596 StringRef StringSection =
4597 cantFail(Obj.getStringTableForSymtab(SymTabSection));
4599 unsigned NumHotTextSymsUpdated = 0;
4600 unsigned NumHotDataSymsUpdated = 0;
4602 std::map<const BinaryFunction *, uint64_t> IslandSizes;
4603 auto getConstantIslandSize = [&IslandSizes](const BinaryFunction &BF) {
4604 auto Itr = IslandSizes.find(&BF);
4605 if (Itr != IslandSizes.end())
4606 return Itr->second;
4607 return IslandSizes[&BF] = BF.estimateConstantIslandSize();
4610 // Symbols for the new symbol table.
4611 std::vector<ELFSymTy> Symbols;
4613 bool EmittedColdFileSymbol = false;
4615 auto getNewSectionIndex = [&](uint32_t OldIndex) {
4616 // For dynamic symbol table, the section index could be wrong on the input,
4617 // and its value is ignored by the runtime if it's different from
4618 // SHN_UNDEF and SHN_ABS.
4619 // However, we still need to update dynamic symbol table, so return a
4620 // section index, even though the index is broken.
4621 if (IsDynSym && OldIndex >= NewSectionIndex.size())
4622 return OldIndex;
4624 assert(OldIndex < NewSectionIndex.size() && "section index out of bounds");
4625 const uint32_t NewIndex = NewSectionIndex[OldIndex];
4627 // We may have stripped the section that dynsym was referencing due to
4628 // the linker bug. In that case return the old index avoiding marking
4629 // the symbol as undefined.
4630 if (IsDynSym && NewIndex != OldIndex && NewIndex == ELF::SHN_UNDEF)
4631 return OldIndex;
4632 return NewIndex;
4635 // Get the extra symbol name of a split fragment; used in addExtraSymbols.
4636 auto getSplitSymbolName = [&](const FunctionFragment &FF,
4637 const ELFSymTy &FunctionSymbol) {
4638 SmallString<256> SymbolName;
4639 if (BC->HasWarmSection)
4640 SymbolName =
4641 formatv("{0}.{1}", cantFail(FunctionSymbol.getName(StringSection)),
4642 FF.getFragmentNum() == FragmentNum::warm() ? "warm" : "cold");
4643 else
4644 SymbolName = formatv("{0}.cold.{1}",
4645 cantFail(FunctionSymbol.getName(StringSection)),
4646 FF.getFragmentNum().get() - 1);
4647 return SymbolName;
4650 // Add extra symbols for the function.
4652 // Note that addExtraSymbols() could be called multiple times for the same
4653 // function with different FunctionSymbol matching the main function entry
4654 // point.
4655 auto addExtraSymbols = [&](const BinaryFunction &Function,
4656 const ELFSymTy &FunctionSymbol) {
4657 if (Function.isFolded()) {
4658 BinaryFunction *ICFParent = Function.getFoldedIntoFunction();
4659 while (ICFParent->isFolded())
4660 ICFParent = ICFParent->getFoldedIntoFunction();
4661 ELFSymTy ICFSymbol = FunctionSymbol;
4662 SmallVector<char, 256> Buf;
4663 ICFSymbol.st_name =
4664 AddToStrTab(Twine(cantFail(FunctionSymbol.getName(StringSection)))
4665 .concat(".icf.0")
4666 .toStringRef(Buf));
4667 ICFSymbol.st_value = ICFParent->getOutputAddress();
4668 ICFSymbol.st_size = ICFParent->getOutputSize();
4669 ICFSymbol.st_shndx = ICFParent->getCodeSection()->getIndex();
4670 Symbols.emplace_back(ICFSymbol);
4672 if (Function.isSplit()) {
4673 // Prepend synthetic FILE symbol to prevent local cold fragments from
4674 // colliding with existing symbols with the same name.
4675 if (!EmittedColdFileSymbol &&
4676 FunctionSymbol.getBinding() == ELF::STB_GLOBAL) {
4677 ELFSymTy FileSymbol;
4678 FileSymbol.st_shndx = ELF::SHN_ABS;
4679 FileSymbol.st_name = AddToStrTab(getBOLTFileSymbolName());
4680 FileSymbol.st_value = 0;
4681 FileSymbol.st_size = 0;
4682 FileSymbol.st_other = 0;
4683 FileSymbol.setBindingAndType(ELF::STB_LOCAL, ELF::STT_FILE);
4684 Symbols.emplace_back(FileSymbol);
4685 EmittedColdFileSymbol = true;
4687 for (const FunctionFragment &FF :
4688 Function.getLayout().getSplitFragments()) {
4689 if (FF.getAddress()) {
4690 ELFSymTy NewColdSym = FunctionSymbol;
4691 const SmallString<256> SymbolName =
4692 getSplitSymbolName(FF, FunctionSymbol);
4693 NewColdSym.st_name = AddToStrTab(SymbolName);
4694 NewColdSym.st_shndx =
4695 Function.getCodeSection(FF.getFragmentNum())->getIndex();
4696 NewColdSym.st_value = FF.getAddress();
4697 NewColdSym.st_size = FF.getImageSize();
4698 NewColdSym.setBindingAndType(ELF::STB_LOCAL, ELF::STT_FUNC);
4699 Symbols.emplace_back(NewColdSym);
4703 if (Function.hasConstantIsland()) {
4704 uint64_t DataMark = Function.getOutputDataAddress();
4705 uint64_t CISize = getConstantIslandSize(Function);
4706 uint64_t CodeMark = DataMark + CISize;
4707 ELFSymTy DataMarkSym = FunctionSymbol;
4708 DataMarkSym.st_name = AddToStrTab("$d");
4709 DataMarkSym.st_value = DataMark;
4710 DataMarkSym.st_size = 0;
4711 DataMarkSym.setType(ELF::STT_NOTYPE);
4712 DataMarkSym.setBinding(ELF::STB_LOCAL);
4713 ELFSymTy CodeMarkSym = DataMarkSym;
4714 CodeMarkSym.st_name = AddToStrTab("$x");
4715 CodeMarkSym.st_value = CodeMark;
4716 Symbols.emplace_back(DataMarkSym);
4717 Symbols.emplace_back(CodeMarkSym);
4719 if (Function.hasConstantIsland() && Function.isSplit()) {
4720 uint64_t DataMark = Function.getOutputColdDataAddress();
4721 uint64_t CISize = getConstantIslandSize(Function);
4722 uint64_t CodeMark = DataMark + CISize;
4723 ELFSymTy DataMarkSym = FunctionSymbol;
4724 DataMarkSym.st_name = AddToStrTab("$d");
4725 DataMarkSym.st_value = DataMark;
4726 DataMarkSym.st_size = 0;
4727 DataMarkSym.setType(ELF::STT_NOTYPE);
4728 DataMarkSym.setBinding(ELF::STB_LOCAL);
4729 ELFSymTy CodeMarkSym = DataMarkSym;
4730 CodeMarkSym.st_name = AddToStrTab("$x");
4731 CodeMarkSym.st_value = CodeMark;
4732 Symbols.emplace_back(DataMarkSym);
4733 Symbols.emplace_back(CodeMarkSym);
4737 // For regular (non-dynamic) symbol table, exclude symbols referring
4738 // to non-allocatable sections.
4739 auto shouldStrip = [&](const ELFSymTy &Symbol) {
4740 if (Symbol.isAbsolute() || !Symbol.isDefined())
4741 return false;
4743 // If we cannot link the symbol to a section, leave it as is.
4744 Expected<const typename ELFT::Shdr *> Section =
4745 Obj.getSection(Symbol.st_shndx);
4746 if (!Section)
4747 return false;
4749 // Remove the section symbol iif the corresponding section was stripped.
4750 if (Symbol.getType() == ELF::STT_SECTION) {
4751 if (!getNewSectionIndex(Symbol.st_shndx))
4752 return true;
4753 return false;
4756 // Symbols in non-allocatable sections are typically remnants of relocations
4757 // emitted under "-emit-relocs" linker option. Delete those as we delete
4758 // relocations against non-allocatable sections.
4759 if (!((*Section)->sh_flags & ELF::SHF_ALLOC))
4760 return true;
4762 return false;
4765 for (const ELFSymTy &Symbol : cantFail(Obj.symbols(&SymTabSection))) {
4766 // For regular (non-dynamic) symbol table strip unneeded symbols.
4767 if (!IsDynSym && shouldStrip(Symbol))
4768 continue;
4770 const BinaryFunction *Function =
4771 BC->getBinaryFunctionAtAddress(Symbol.st_value);
4772 // Ignore false function references, e.g. when the section address matches
4773 // the address of the function.
4774 if (Function && Symbol.getType() == ELF::STT_SECTION)
4775 Function = nullptr;
4777 // For non-dynamic symtab, make sure the symbol section matches that of
4778 // the function. It can mismatch e.g. if the symbol is a section marker
4779 // in which case we treat the symbol separately from the function.
4780 // For dynamic symbol table, the section index could be wrong on the input,
4781 // and its value is ignored by the runtime if it's different from
4782 // SHN_UNDEF and SHN_ABS.
4783 if (!IsDynSym && Function &&
4784 Symbol.st_shndx !=
4785 Function->getOriginSection()->getSectionRef().getIndex())
4786 Function = nullptr;
4788 // Create a new symbol based on the existing symbol.
4789 ELFSymTy NewSymbol = Symbol;
4791 // Handle special symbols based on their name.
4792 Expected<StringRef> SymbolName = Symbol.getName(StringSection);
4793 assert(SymbolName && "cannot get symbol name");
4795 auto updateSymbolValue = [&](const StringRef Name,
4796 std::optional<uint64_t> Value = std::nullopt) {
4797 NewSymbol.st_value = Value ? *Value : getNewValueForSymbol(Name);
4798 NewSymbol.st_shndx = ELF::SHN_ABS;
4799 BC->outs() << "BOLT-INFO: setting " << Name << " to 0x"
4800 << Twine::utohexstr(NewSymbol.st_value) << '\n';
4803 if (*SymbolName == "__hot_start" || *SymbolName == "__hot_end") {
4804 if (opts::HotText) {
4805 updateSymbolValue(*SymbolName);
4806 ++NumHotTextSymsUpdated;
4808 goto registerSymbol;
4811 if (*SymbolName == "__hot_data_start" || *SymbolName == "__hot_data_end") {
4812 if (opts::HotData) {
4813 updateSymbolValue(*SymbolName);
4814 ++NumHotDataSymsUpdated;
4816 goto registerSymbol;
4819 if (*SymbolName == "_end") {
4820 if (NextAvailableAddress > Symbol.st_value)
4821 updateSymbolValue(*SymbolName, NextAvailableAddress);
4822 goto registerSymbol;
4825 if (Function) {
4826 // If the symbol matched a function that was not emitted, update the
4827 // corresponding section index but otherwise leave it unchanged.
4828 if (Function->isEmitted()) {
4829 NewSymbol.st_value = Function->getOutputAddress();
4830 NewSymbol.st_size = Function->getOutputSize();
4831 NewSymbol.st_shndx = Function->getCodeSection()->getIndex();
4832 } else if (Symbol.st_shndx < ELF::SHN_LORESERVE) {
4833 NewSymbol.st_shndx = getNewSectionIndex(Symbol.st_shndx);
4836 // Add new symbols to the symbol table if necessary.
4837 if (!IsDynSym)
4838 addExtraSymbols(*Function, NewSymbol);
4839 } else {
4840 // Check if the function symbol matches address inside a function, i.e.
4841 // it marks a secondary entry point.
4842 Function =
4843 (Symbol.getType() == ELF::STT_FUNC)
4844 ? BC->getBinaryFunctionContainingAddress(Symbol.st_value,
4845 /*CheckPastEnd=*/false,
4846 /*UseMaxSize=*/true)
4847 : nullptr;
4849 if (Function && Function->isEmitted()) {
4850 assert(Function->getLayout().isHotColdSplit() &&
4851 "Adding symbols based on cold fragment when there are more than "
4852 "2 fragments");
4853 const uint64_t OutputAddress =
4854 Function->translateInputToOutputAddress(Symbol.st_value);
4856 NewSymbol.st_value = OutputAddress;
4857 // Force secondary entry points to have zero size.
4858 NewSymbol.st_size = 0;
4860 // Find fragment containing entrypoint
4861 FunctionLayout::fragment_const_iterator FF = llvm::find_if(
4862 Function->getLayout().fragments(), [&](const FunctionFragment &FF) {
4863 uint64_t Lo = FF.getAddress();
4864 uint64_t Hi = Lo + FF.getImageSize();
4865 return Lo <= OutputAddress && OutputAddress < Hi;
4868 if (FF == Function->getLayout().fragment_end()) {
4869 assert(
4870 OutputAddress >= Function->getCodeSection()->getOutputAddress() &&
4871 OutputAddress < (Function->getCodeSection()->getOutputAddress() +
4872 Function->getCodeSection()->getOutputSize()) &&
4873 "Cannot locate fragment containing secondary entrypoint");
4874 FF = Function->getLayout().fragment_begin();
4877 NewSymbol.st_shndx =
4878 Function->getCodeSection(FF->getFragmentNum())->getIndex();
4879 } else {
4880 // Check if the symbol belongs to moved data object and update it.
4881 BinaryData *BD = opts::ReorderData.empty()
4882 ? nullptr
4883 : BC->getBinaryDataAtAddress(Symbol.st_value);
4884 if (BD && BD->isMoved() && !BD->isJumpTable()) {
4885 assert((!BD->getSize() || !Symbol.st_size ||
4886 Symbol.st_size == BD->getSize()) &&
4887 "sizes must match");
4889 BinarySection &OutputSection = BD->getOutputSection();
4890 assert(OutputSection.getIndex());
4891 LLVM_DEBUG(dbgs()
4892 << "BOLT-DEBUG: moving " << BD->getName() << " from "
4893 << *BC->getSectionNameForAddress(Symbol.st_value) << " ("
4894 << Symbol.st_shndx << ") to " << OutputSection.getName()
4895 << " (" << OutputSection.getIndex() << ")\n");
4896 NewSymbol.st_shndx = OutputSection.getIndex();
4897 NewSymbol.st_value = BD->getOutputAddress();
4898 } else {
4899 // Otherwise just update the section for the symbol.
4900 if (Symbol.st_shndx < ELF::SHN_LORESERVE)
4901 NewSymbol.st_shndx = getNewSectionIndex(Symbol.st_shndx);
4904 // Detect local syms in the text section that we didn't update
4905 // and that were preserved by the linker to support relocations against
4906 // .text. Remove them from the symtab.
4907 if (Symbol.getType() == ELF::STT_NOTYPE &&
4908 Symbol.getBinding() == ELF::STB_LOCAL && Symbol.st_size == 0) {
4909 if (BC->getBinaryFunctionContainingAddress(Symbol.st_value,
4910 /*CheckPastEnd=*/false,
4911 /*UseMaxSize=*/true)) {
4912 // Can only delete the symbol if not patching. Such symbols should
4913 // not exist in the dynamic symbol table.
4914 assert(!IsDynSym && "cannot delete symbol");
4915 continue;
4921 registerSymbol:
4922 if (IsDynSym)
4923 Write((&Symbol - cantFail(Obj.symbols(&SymTabSection)).begin()) *
4924 sizeof(ELFSymTy),
4925 NewSymbol);
4926 else
4927 Symbols.emplace_back(NewSymbol);
4930 if (IsDynSym) {
4931 assert(Symbols.empty());
4932 return;
4935 // Add symbols of injected functions
4936 for (BinaryFunction *Function : BC->getInjectedBinaryFunctions()) {
4937 ELFSymTy NewSymbol;
4938 BinarySection *OriginSection = Function->getOriginSection();
4939 NewSymbol.st_shndx =
4940 OriginSection
4941 ? getNewSectionIndex(OriginSection->getSectionRef().getIndex())
4942 : Function->getCodeSection()->getIndex();
4943 NewSymbol.st_value = Function->getOutputAddress();
4944 NewSymbol.st_name = AddToStrTab(Function->getOneName());
4945 NewSymbol.st_size = Function->getOutputSize();
4946 NewSymbol.st_other = 0;
4947 NewSymbol.setBindingAndType(ELF::STB_LOCAL, ELF::STT_FUNC);
4948 Symbols.emplace_back(NewSymbol);
4950 if (Function->isSplit()) {
4951 assert(Function->getLayout().isHotColdSplit() &&
4952 "Adding symbols based on cold fragment when there are more than "
4953 "2 fragments");
4954 ELFSymTy NewColdSym = NewSymbol;
4955 NewColdSym.setType(ELF::STT_NOTYPE);
4956 SmallVector<char, 256> Buf;
4957 NewColdSym.st_name = AddToStrTab(
4958 Twine(Function->getPrintName()).concat(".cold.0").toStringRef(Buf));
4959 const FunctionFragment &ColdFF =
4960 Function->getLayout().getFragment(FragmentNum::cold());
4961 NewColdSym.st_value = ColdFF.getAddress();
4962 NewColdSym.st_size = ColdFF.getImageSize();
4963 Symbols.emplace_back(NewColdSym);
4967 auto AddSymbol = [&](const StringRef &Name, uint64_t Address) {
4968 if (!Address)
4969 return;
4971 ELFSymTy Symbol;
4972 Symbol.st_value = Address;
4973 Symbol.st_shndx = ELF::SHN_ABS;
4974 Symbol.st_name = AddToStrTab(Name);
4975 Symbol.st_size = 0;
4976 Symbol.st_other = 0;
4977 Symbol.setBindingAndType(ELF::STB_WEAK, ELF::STT_NOTYPE);
4979 BC->outs() << "BOLT-INFO: setting " << Name << " to 0x"
4980 << Twine::utohexstr(Symbol.st_value) << '\n';
4982 Symbols.emplace_back(Symbol);
4985 // Add runtime library start and fini address symbols
4986 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary()) {
4987 AddSymbol("__bolt_runtime_start", RtLibrary->getRuntimeStartAddress());
4988 AddSymbol("__bolt_runtime_fini", RtLibrary->getRuntimeFiniAddress());
4991 assert((!NumHotTextSymsUpdated || NumHotTextSymsUpdated == 2) &&
4992 "either none or both __hot_start/__hot_end symbols were expected");
4993 assert((!NumHotDataSymsUpdated || NumHotDataSymsUpdated == 2) &&
4994 "either none or both __hot_data_start/__hot_data_end symbols were "
4995 "expected");
4997 auto AddEmittedSymbol = [&](const StringRef &Name) {
4998 AddSymbol(Name, getNewValueForSymbol(Name));
5001 if (opts::HotText && !NumHotTextSymsUpdated) {
5002 AddEmittedSymbol("__hot_start");
5003 AddEmittedSymbol("__hot_end");
5006 if (opts::HotData && !NumHotDataSymsUpdated) {
5007 AddEmittedSymbol("__hot_data_start");
5008 AddEmittedSymbol("__hot_data_end");
5011 // Put local symbols at the beginning.
5012 llvm::stable_sort(Symbols, [](const ELFSymTy &A, const ELFSymTy &B) {
5013 if (A.getBinding() == ELF::STB_LOCAL && B.getBinding() != ELF::STB_LOCAL)
5014 return true;
5015 return false;
5018 for (const ELFSymTy &Symbol : Symbols)
5019 Write(0, Symbol);
5022 template <typename ELFT>
5023 void RewriteInstance::patchELFSymTabs(ELFObjectFile<ELFT> *File) {
5024 const ELFFile<ELFT> &Obj = File->getELFFile();
5025 using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr;
5026 using ELFSymTy = typename ELFObjectFile<ELFT>::Elf_Sym;
5028 // Compute a preview of how section indices will change after rewriting, so
5029 // we can properly update the symbol table based on new section indices.
5030 std::vector<uint32_t> NewSectionIndex;
5031 getOutputSections(File, NewSectionIndex);
5033 // Update dynamic symbol table.
5034 const ELFShdrTy *DynSymSection = nullptr;
5035 for (const ELFShdrTy &Section : cantFail(Obj.sections())) {
5036 if (Section.sh_type == ELF::SHT_DYNSYM) {
5037 DynSymSection = &Section;
5038 break;
5041 assert((DynSymSection || BC->IsStaticExecutable) &&
5042 "dynamic symbol table expected");
5043 if (DynSymSection) {
5044 updateELFSymbolTable(
5045 File,
5046 /*IsDynSym=*/true,
5047 *DynSymSection,
5048 NewSectionIndex,
5049 [&](size_t Offset, const ELFSymTy &Sym) {
5050 Out->os().pwrite(reinterpret_cast<const char *>(&Sym),
5051 sizeof(ELFSymTy),
5052 DynSymSection->sh_offset + Offset);
5054 [](StringRef) -> size_t { return 0; });
5057 if (opts::RemoveSymtab)
5058 return;
5060 // (re)create regular symbol table.
5061 const ELFShdrTy *SymTabSection = nullptr;
5062 for (const ELFShdrTy &Section : cantFail(Obj.sections())) {
5063 if (Section.sh_type == ELF::SHT_SYMTAB) {
5064 SymTabSection = &Section;
5065 break;
5068 if (!SymTabSection) {
5069 BC->errs() << "BOLT-WARNING: no symbol table found\n";
5070 return;
5073 const ELFShdrTy *StrTabSection =
5074 cantFail(Obj.getSection(SymTabSection->sh_link));
5075 std::string NewContents;
5076 std::string NewStrTab = std::string(
5077 File->getData().substr(StrTabSection->sh_offset, StrTabSection->sh_size));
5078 StringRef SecName = cantFail(Obj.getSectionName(*SymTabSection));
5079 StringRef StrSecName = cantFail(Obj.getSectionName(*StrTabSection));
5081 NumLocalSymbols = 0;
5082 updateELFSymbolTable(
5083 File,
5084 /*IsDynSym=*/false,
5085 *SymTabSection,
5086 NewSectionIndex,
5087 [&](size_t Offset, const ELFSymTy &Sym) {
5088 if (Sym.getBinding() == ELF::STB_LOCAL)
5089 ++NumLocalSymbols;
5090 NewContents.append(reinterpret_cast<const char *>(&Sym),
5091 sizeof(ELFSymTy));
5093 [&](StringRef Str) {
5094 size_t Idx = NewStrTab.size();
5095 NewStrTab.append(NameResolver::restore(Str).str());
5096 NewStrTab.append(1, '\0');
5097 return Idx;
5100 BC->registerOrUpdateNoteSection(SecName,
5101 copyByteArray(NewContents),
5102 NewContents.size(),
5103 /*Alignment=*/1,
5104 /*IsReadOnly=*/true,
5105 ELF::SHT_SYMTAB);
5107 BC->registerOrUpdateNoteSection(StrSecName,
5108 copyByteArray(NewStrTab),
5109 NewStrTab.size(),
5110 /*Alignment=*/1,
5111 /*IsReadOnly=*/true,
5112 ELF::SHT_STRTAB);
5115 template <typename ELFT>
5116 void RewriteInstance::patchELFAllocatableRelrSection(
5117 ELFObjectFile<ELFT> *File) {
5118 if (!DynamicRelrAddress)
5119 return;
5121 raw_fd_ostream &OS = Out->os();
5122 const uint8_t PSize = BC->AsmInfo->getCodePointerSize();
5123 const uint64_t MaxDelta = ((CHAR_BIT * DynamicRelrEntrySize) - 1) * PSize;
5125 auto FixAddend = [&](const BinarySection &Section, const Relocation &Rel,
5126 uint64_t FileOffset) {
5127 // Fix relocation symbol value in place if no static relocation found
5128 // on the same address. We won't check the BF relocations here since it
5129 // is rare case and no optimization is required.
5130 if (Section.getRelocationAt(Rel.Offset))
5131 return;
5133 // No fixup needed if symbol address was not changed
5134 const uint64_t Addend = getNewFunctionOrDataAddress(Rel.Addend);
5135 if (!Addend)
5136 return;
5138 OS.pwrite(reinterpret_cast<const char *>(&Addend), PSize, FileOffset);
5141 // Fill new relative relocation offsets set
5142 std::set<uint64_t> RelOffsets;
5143 for (const BinarySection &Section : BC->allocatableSections()) {
5144 const uint64_t SectionInputAddress = Section.getAddress();
5145 uint64_t SectionAddress = Section.getOutputAddress();
5146 if (!SectionAddress)
5147 SectionAddress = SectionInputAddress;
5149 for (const Relocation &Rel : Section.dynamicRelocations()) {
5150 if (!Rel.isRelative())
5151 continue;
5153 uint64_t RelOffset =
5154 getNewFunctionOrDataAddress(SectionInputAddress + Rel.Offset);
5156 RelOffset = RelOffset == 0 ? SectionAddress + Rel.Offset : RelOffset;
5157 assert((RelOffset & 1) == 0 && "Wrong relocation offset");
5158 RelOffsets.emplace(RelOffset);
5159 FixAddend(Section, Rel, RelOffset);
5163 ErrorOr<BinarySection &> Section =
5164 BC->getSectionForAddress(*DynamicRelrAddress);
5165 assert(Section && "cannot get .relr.dyn section");
5166 assert(Section->isRelr() && "Expected section to be SHT_RELR type");
5167 uint64_t RelrDynOffset = Section->getInputFileOffset();
5168 const uint64_t RelrDynEndOffset = RelrDynOffset + Section->getSize();
5170 auto WriteRelr = [&](uint64_t Value) {
5171 if (RelrDynOffset + DynamicRelrEntrySize > RelrDynEndOffset) {
5172 BC->errs() << "BOLT-ERROR: Offset overflow for relr.dyn section\n";
5173 exit(1);
5176 OS.pwrite(reinterpret_cast<const char *>(&Value), DynamicRelrEntrySize,
5177 RelrDynOffset);
5178 RelrDynOffset += DynamicRelrEntrySize;
5181 for (auto RelIt = RelOffsets.begin(); RelIt != RelOffsets.end();) {
5182 WriteRelr(*RelIt);
5183 uint64_t Base = *RelIt++ + PSize;
5184 while (1) {
5185 uint64_t Bitmap = 0;
5186 for (; RelIt != RelOffsets.end(); ++RelIt) {
5187 const uint64_t Delta = *RelIt - Base;
5188 if (Delta >= MaxDelta || Delta % PSize)
5189 break;
5191 Bitmap |= (1ULL << (Delta / PSize));
5194 if (!Bitmap)
5195 break;
5197 WriteRelr((Bitmap << 1) | 1);
5198 Base += MaxDelta;
5202 // Fill the rest of the section with empty bitmap value
5203 while (RelrDynOffset != RelrDynEndOffset)
5204 WriteRelr(1);
5207 template <typename ELFT>
5208 void
5209 RewriteInstance::patchELFAllocatableRelaSections(ELFObjectFile<ELFT> *File) {
5210 using Elf_Rela = typename ELFT::Rela;
5211 raw_fd_ostream &OS = Out->os();
5212 const ELFFile<ELFT> &EF = File->getELFFile();
5214 uint64_t RelDynOffset = 0, RelDynEndOffset = 0;
5215 uint64_t RelPltOffset = 0, RelPltEndOffset = 0;
5217 auto setSectionFileOffsets = [&](uint64_t Address, uint64_t &Start,
5218 uint64_t &End) {
5219 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(Address);
5220 assert(Section && "cannot get relocation section");
5221 Start = Section->getInputFileOffset();
5222 End = Start + Section->getSize();
5225 if (!DynamicRelocationsAddress && !PLTRelocationsAddress)
5226 return;
5228 if (DynamicRelocationsAddress)
5229 setSectionFileOffsets(*DynamicRelocationsAddress, RelDynOffset,
5230 RelDynEndOffset);
5232 if (PLTRelocationsAddress)
5233 setSectionFileOffsets(*PLTRelocationsAddress, RelPltOffset,
5234 RelPltEndOffset);
5236 DynamicRelativeRelocationsCount = 0;
5238 auto writeRela = [&OS](const Elf_Rela *RelA, uint64_t &Offset) {
5239 OS.pwrite(reinterpret_cast<const char *>(RelA), sizeof(*RelA), Offset);
5240 Offset += sizeof(*RelA);
5243 auto writeRelocations = [&](bool PatchRelative) {
5244 for (BinarySection &Section : BC->allocatableSections()) {
5245 const uint64_t SectionInputAddress = Section.getAddress();
5246 uint64_t SectionAddress = Section.getOutputAddress();
5247 if (!SectionAddress)
5248 SectionAddress = SectionInputAddress;
5250 for (const Relocation &Rel : Section.dynamicRelocations()) {
5251 const bool IsRelative = Rel.isRelative();
5252 if (PatchRelative != IsRelative)
5253 continue;
5255 if (IsRelative)
5256 ++DynamicRelativeRelocationsCount;
5258 Elf_Rela NewRelA;
5259 MCSymbol *Symbol = Rel.Symbol;
5260 uint32_t SymbolIdx = 0;
5261 uint64_t Addend = Rel.Addend;
5262 uint64_t RelOffset =
5263 getNewFunctionOrDataAddress(SectionInputAddress + Rel.Offset);
5265 RelOffset = RelOffset == 0 ? SectionAddress + Rel.Offset : RelOffset;
5266 if (Rel.Symbol) {
5267 SymbolIdx = getOutputDynamicSymbolIndex(Symbol);
5268 } else {
5269 // Usually this case is used for R_*_(I)RELATIVE relocations
5270 const uint64_t Address = getNewFunctionOrDataAddress(Addend);
5271 if (Address)
5272 Addend = Address;
5275 NewRelA.setSymbolAndType(SymbolIdx, Rel.Type, EF.isMips64EL());
5276 NewRelA.r_offset = RelOffset;
5277 NewRelA.r_addend = Addend;
5279 const bool IsJmpRel = IsJmpRelocation.contains(Rel.Type);
5280 uint64_t &Offset = IsJmpRel ? RelPltOffset : RelDynOffset;
5281 const uint64_t &EndOffset =
5282 IsJmpRel ? RelPltEndOffset : RelDynEndOffset;
5283 if (!Offset || !EndOffset) {
5284 BC->errs() << "BOLT-ERROR: Invalid offsets for dynamic relocation\n";
5285 exit(1);
5288 if (Offset + sizeof(NewRelA) > EndOffset) {
5289 BC->errs() << "BOLT-ERROR: Offset overflow for dynamic relocation\n";
5290 exit(1);
5293 writeRela(&NewRelA, Offset);
5298 // Place R_*_RELATIVE relocations in RELA section if RELR is not presented.
5299 // The dynamic linker expects all R_*_RELATIVE relocations in RELA
5300 // to be emitted first.
5301 if (!DynamicRelrAddress)
5302 writeRelocations(/* PatchRelative */ true);
5303 writeRelocations(/* PatchRelative */ false);
5305 auto fillNone = [&](uint64_t &Offset, uint64_t EndOffset) {
5306 if (!Offset)
5307 return;
5309 typename ELFObjectFile<ELFT>::Elf_Rela RelA;
5310 RelA.setSymbolAndType(0, Relocation::getNone(), EF.isMips64EL());
5311 RelA.r_offset = 0;
5312 RelA.r_addend = 0;
5313 while (Offset < EndOffset)
5314 writeRela(&RelA, Offset);
5316 assert(Offset == EndOffset && "Unexpected section overflow");
5319 // Fill the rest of the sections with R_*_NONE relocations
5320 fillNone(RelDynOffset, RelDynEndOffset);
5321 fillNone(RelPltOffset, RelPltEndOffset);
5324 template <typename ELFT>
5325 void RewriteInstance::patchELFGOT(ELFObjectFile<ELFT> *File) {
5326 raw_fd_ostream &OS = Out->os();
5328 SectionRef GOTSection;
5329 for (const SectionRef &Section : File->sections()) {
5330 StringRef SectionName = cantFail(Section.getName());
5331 if (SectionName == ".got") {
5332 GOTSection = Section;
5333 break;
5336 if (!GOTSection.getObject()) {
5337 if (!BC->IsStaticExecutable)
5338 BC->errs() << "BOLT-INFO: no .got section found\n";
5339 return;
5342 StringRef GOTContents = cantFail(GOTSection.getContents());
5343 for (const uint64_t *GOTEntry =
5344 reinterpret_cast<const uint64_t *>(GOTContents.data());
5345 GOTEntry < reinterpret_cast<const uint64_t *>(GOTContents.data() +
5346 GOTContents.size());
5347 ++GOTEntry) {
5348 if (uint64_t NewAddress = getNewFunctionAddress(*GOTEntry)) {
5349 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: patching GOT entry 0x"
5350 << Twine::utohexstr(*GOTEntry) << " with 0x"
5351 << Twine::utohexstr(NewAddress) << '\n');
5352 OS.pwrite(reinterpret_cast<const char *>(&NewAddress), sizeof(NewAddress),
5353 reinterpret_cast<const char *>(GOTEntry) -
5354 File->getData().data());
5359 template <typename ELFT>
5360 void RewriteInstance::patchELFDynamic(ELFObjectFile<ELFT> *File) {
5361 if (BC->IsStaticExecutable)
5362 return;
5364 const ELFFile<ELFT> &Obj = File->getELFFile();
5365 raw_fd_ostream &OS = Out->os();
5367 using Elf_Phdr = typename ELFFile<ELFT>::Elf_Phdr;
5368 using Elf_Dyn = typename ELFFile<ELFT>::Elf_Dyn;
5370 // Locate DYNAMIC by looking through program headers.
5371 uint64_t DynamicOffset = 0;
5372 const Elf_Phdr *DynamicPhdr = nullptr;
5373 for (const Elf_Phdr &Phdr : cantFail(Obj.program_headers())) {
5374 if (Phdr.p_type == ELF::PT_DYNAMIC) {
5375 DynamicOffset = Phdr.p_offset;
5376 DynamicPhdr = &Phdr;
5377 assert(Phdr.p_memsz == Phdr.p_filesz && "dynamic sizes should match");
5378 break;
5381 assert(DynamicPhdr && "missing dynamic in ELF binary");
5383 bool ZNowSet = false;
5385 // Go through all dynamic entries and patch functions addresses with
5386 // new ones.
5387 typename ELFT::DynRange DynamicEntries =
5388 cantFail(Obj.dynamicEntries(), "error accessing dynamic table");
5389 auto DTB = DynamicEntries.begin();
5390 for (const Elf_Dyn &Dyn : DynamicEntries) {
5391 Elf_Dyn NewDE = Dyn;
5392 bool ShouldPatch = true;
5393 switch (Dyn.d_tag) {
5394 default:
5395 ShouldPatch = false;
5396 break;
5397 case ELF::DT_RELACOUNT:
5398 NewDE.d_un.d_val = DynamicRelativeRelocationsCount;
5399 break;
5400 case ELF::DT_INIT:
5401 case ELF::DT_FINI: {
5402 if (BC->HasRelocations) {
5403 if (uint64_t NewAddress = getNewFunctionAddress(Dyn.getPtr())) {
5404 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: patching dynamic entry of type "
5405 << Dyn.getTag() << '\n');
5406 NewDE.d_un.d_ptr = NewAddress;
5409 RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary();
5410 if (RtLibrary && Dyn.getTag() == ELF::DT_FINI) {
5411 if (uint64_t Addr = RtLibrary->getRuntimeFiniAddress())
5412 NewDE.d_un.d_ptr = Addr;
5414 if (RtLibrary && Dyn.getTag() == ELF::DT_INIT && !BC->HasInterpHeader) {
5415 if (auto Addr = RtLibrary->getRuntimeStartAddress()) {
5416 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Set DT_INIT to 0x"
5417 << Twine::utohexstr(Addr) << '\n');
5418 NewDE.d_un.d_ptr = Addr;
5421 break;
5423 case ELF::DT_FLAGS:
5424 if (BC->RequiresZNow) {
5425 NewDE.d_un.d_val |= ELF::DF_BIND_NOW;
5426 ZNowSet = true;
5428 break;
5429 case ELF::DT_FLAGS_1:
5430 if (BC->RequiresZNow) {
5431 NewDE.d_un.d_val |= ELF::DF_1_NOW;
5432 ZNowSet = true;
5434 break;
5436 if (ShouldPatch)
5437 OS.pwrite(reinterpret_cast<const char *>(&NewDE), sizeof(NewDE),
5438 DynamicOffset + (&Dyn - DTB) * sizeof(Dyn));
5441 if (BC->RequiresZNow && !ZNowSet) {
5442 BC->errs()
5443 << "BOLT-ERROR: output binary requires immediate relocation "
5444 "processing which depends on DT_FLAGS or DT_FLAGS_1 presence in "
5445 ".dynamic. Please re-link the binary with -znow.\n";
5446 exit(1);
5450 template <typename ELFT>
5451 Error RewriteInstance::readELFDynamic(ELFObjectFile<ELFT> *File) {
5452 const ELFFile<ELFT> &Obj = File->getELFFile();
5454 using Elf_Phdr = typename ELFFile<ELFT>::Elf_Phdr;
5455 using Elf_Dyn = typename ELFFile<ELFT>::Elf_Dyn;
5457 // Locate DYNAMIC by looking through program headers.
5458 const Elf_Phdr *DynamicPhdr = nullptr;
5459 for (const Elf_Phdr &Phdr : cantFail(Obj.program_headers())) {
5460 if (Phdr.p_type == ELF::PT_DYNAMIC) {
5461 DynamicPhdr = &Phdr;
5462 break;
5466 if (!DynamicPhdr) {
5467 BC->outs() << "BOLT-INFO: static input executable detected\n";
5468 // TODO: static PIE executable might have dynamic header
5469 BC->IsStaticExecutable = true;
5470 return Error::success();
5473 if (DynamicPhdr->p_memsz != DynamicPhdr->p_filesz)
5474 return createStringError(errc::executable_format_error,
5475 "dynamic section sizes should match");
5477 // Go through all dynamic entries to locate entries of interest.
5478 auto DynamicEntriesOrErr = Obj.dynamicEntries();
5479 if (!DynamicEntriesOrErr)
5480 return DynamicEntriesOrErr.takeError();
5481 typename ELFT::DynRange DynamicEntries = DynamicEntriesOrErr.get();
5483 for (const Elf_Dyn &Dyn : DynamicEntries) {
5484 switch (Dyn.d_tag) {
5485 case ELF::DT_INIT:
5486 if (!BC->HasInterpHeader) {
5487 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Set start function address\n");
5488 BC->StartFunctionAddress = Dyn.getPtr();
5490 break;
5491 case ELF::DT_FINI:
5492 BC->FiniAddress = Dyn.getPtr();
5493 break;
5494 case ELF::DT_FINI_ARRAY:
5495 BC->FiniArrayAddress = Dyn.getPtr();
5496 break;
5497 case ELF::DT_FINI_ARRAYSZ:
5498 BC->FiniArraySize = Dyn.getPtr();
5499 break;
5500 case ELF::DT_RELA:
5501 DynamicRelocationsAddress = Dyn.getPtr();
5502 break;
5503 case ELF::DT_RELASZ:
5504 DynamicRelocationsSize = Dyn.getVal();
5505 break;
5506 case ELF::DT_JMPREL:
5507 PLTRelocationsAddress = Dyn.getPtr();
5508 break;
5509 case ELF::DT_PLTRELSZ:
5510 PLTRelocationsSize = Dyn.getVal();
5511 break;
5512 case ELF::DT_RELACOUNT:
5513 DynamicRelativeRelocationsCount = Dyn.getVal();
5514 break;
5515 case ELF::DT_RELR:
5516 DynamicRelrAddress = Dyn.getPtr();
5517 break;
5518 case ELF::DT_RELRSZ:
5519 DynamicRelrSize = Dyn.getVal();
5520 break;
5521 case ELF::DT_RELRENT:
5522 DynamicRelrEntrySize = Dyn.getVal();
5523 break;
5527 if (!DynamicRelocationsAddress || !DynamicRelocationsSize) {
5528 DynamicRelocationsAddress.reset();
5529 DynamicRelocationsSize = 0;
5532 if (!PLTRelocationsAddress || !PLTRelocationsSize) {
5533 PLTRelocationsAddress.reset();
5534 PLTRelocationsSize = 0;
5537 if (!DynamicRelrAddress || !DynamicRelrSize) {
5538 DynamicRelrAddress.reset();
5539 DynamicRelrSize = 0;
5540 } else if (!DynamicRelrEntrySize) {
5541 BC->errs() << "BOLT-ERROR: expected DT_RELRENT to be presented "
5542 << "in DYNAMIC section\n";
5543 exit(1);
5544 } else if (DynamicRelrSize % DynamicRelrEntrySize) {
5545 BC->errs() << "BOLT-ERROR: expected RELR table size to be divisible "
5546 << "by RELR entry size\n";
5547 exit(1);
5550 return Error::success();
5553 uint64_t RewriteInstance::getNewFunctionAddress(uint64_t OldAddress) {
5554 const BinaryFunction *Function = BC->getBinaryFunctionAtAddress(OldAddress);
5555 if (!Function)
5556 return 0;
5558 return Function->getOutputAddress();
5561 uint64_t RewriteInstance::getNewFunctionOrDataAddress(uint64_t OldAddress) {
5562 if (uint64_t Function = getNewFunctionAddress(OldAddress))
5563 return Function;
5565 const BinaryData *BD = BC->getBinaryDataAtAddress(OldAddress);
5566 if (BD && BD->isMoved())
5567 return BD->getOutputAddress();
5569 if (const BinaryFunction *BF =
5570 BC->getBinaryFunctionContainingAddress(OldAddress)) {
5571 if (BF->isEmitted()) {
5572 // If OldAddress is the another entry point of
5573 // the function, then BOLT could get the new address.
5574 if (BF->isMultiEntry()) {
5575 for (const BinaryBasicBlock &BB : *BF)
5576 if (BB.isEntryPoint() &&
5577 (BF->getAddress() + BB.getOffset()) == OldAddress)
5578 return BF->getOutputAddress() + BB.getOffset();
5580 BC->errs() << "BOLT-ERROR: unable to get new address corresponding to "
5581 "input address 0x"
5582 << Twine::utohexstr(OldAddress) << " in function " << *BF
5583 << ". Consider adding this function to --skip-funcs=...\n";
5584 exit(1);
5588 return 0;
5591 void RewriteInstance::rewriteFile() {
5592 std::error_code EC;
5593 Out = std::make_unique<ToolOutputFile>(opts::OutputFilename, EC,
5594 sys::fs::OF_None);
5595 check_error(EC, "cannot create output executable file");
5597 raw_fd_ostream &OS = Out->os();
5599 // Copy allocatable part of the input.
5600 OS << InputFile->getData().substr(0, FirstNonAllocatableOffset);
5602 auto Streamer = BC->createStreamer(OS);
5603 // Make sure output stream has enough reserved space, otherwise
5604 // pwrite() will fail.
5605 uint64_t Offset = std::max(getFileOffsetForAddress(NextAvailableAddress),
5606 FirstNonAllocatableOffset);
5607 Offset = OS.seek(Offset);
5608 assert((Offset != (uint64_t)-1) && "Error resizing output file");
5610 // Overwrite functions with fixed output address. This is mostly used by
5611 // non-relocation mode, with one exception: injected functions are covered
5612 // here in both modes.
5613 uint64_t CountOverwrittenFunctions = 0;
5614 uint64_t OverwrittenScore = 0;
5615 for (BinaryFunction *Function : BC->getAllBinaryFunctions()) {
5616 if (Function->getImageAddress() == 0 || Function->getImageSize() == 0)
5617 continue;
5619 if (Function->getImageSize() > Function->getMaxSize()) {
5620 assert(!BC->isX86() && "Unexpected large function.");
5621 if (opts::Verbosity >= 1)
5622 BC->errs() << "BOLT-WARNING: new function size (0x"
5623 << Twine::utohexstr(Function->getImageSize())
5624 << ") is larger than maximum allowed size (0x"
5625 << Twine::utohexstr(Function->getMaxSize())
5626 << ") for function " << *Function << '\n';
5628 // Remove jump table sections that this function owns in non-reloc mode
5629 // because we don't want to write them anymore.
5630 if (!BC->HasRelocations && opts::JumpTables == JTS_BASIC) {
5631 for (auto &JTI : Function->JumpTables) {
5632 JumpTable *JT = JTI.second;
5633 BinarySection &Section = JT->getOutputSection();
5634 BC->deregisterSection(Section);
5637 continue;
5640 const auto HasAddress = [](const FunctionFragment &FF) {
5641 return FF.empty() ||
5642 (FF.getImageAddress() != 0 && FF.getImageSize() != 0);
5644 const bool SplitFragmentsHaveAddress =
5645 llvm::all_of(Function->getLayout().getSplitFragments(), HasAddress);
5646 if (Function->isSplit() && !SplitFragmentsHaveAddress) {
5647 const auto HasNoAddress = [](const FunctionFragment &FF) {
5648 return FF.getImageAddress() == 0 && FF.getImageSize() == 0;
5650 assert(llvm::all_of(Function->getLayout().getSplitFragments(),
5651 HasNoAddress) &&
5652 "Some split fragments have an address while others do not");
5653 (void)HasNoAddress;
5654 continue;
5657 OverwrittenScore += Function->getFunctionScore();
5658 ++CountOverwrittenFunctions;
5660 // Overwrite function in the output file.
5661 if (opts::Verbosity >= 2)
5662 BC->outs() << "BOLT: rewriting function \"" << *Function << "\"\n";
5664 OS.pwrite(reinterpret_cast<char *>(Function->getImageAddress()),
5665 Function->getImageSize(), Function->getFileOffset());
5667 // Write nops at the end of the function.
5668 if (Function->getMaxSize() != std::numeric_limits<uint64_t>::max()) {
5669 uint64_t Pos = OS.tell();
5670 OS.seek(Function->getFileOffset() + Function->getImageSize());
5671 BC->MAB->writeNopData(
5672 OS, Function->getMaxSize() - Function->getImageSize(), &*BC->STI);
5674 OS.seek(Pos);
5677 if (!Function->isSplit())
5678 continue;
5680 // Write cold part
5681 if (opts::Verbosity >= 2) {
5682 BC->outs() << formatv("BOLT: rewriting function \"{0}\" (split parts)\n",
5683 *Function);
5686 for (const FunctionFragment &FF :
5687 Function->getLayout().getSplitFragments()) {
5688 OS.pwrite(reinterpret_cast<char *>(FF.getImageAddress()),
5689 FF.getImageSize(), FF.getFileOffset());
5693 // Print function statistics for non-relocation mode.
5694 if (!BC->HasRelocations) {
5695 BC->outs() << "BOLT: " << CountOverwrittenFunctions << " out of "
5696 << BC->getBinaryFunctions().size()
5697 << " functions were overwritten.\n";
5698 if (BC->TotalScore != 0) {
5699 double Coverage = OverwrittenScore / (double)BC->TotalScore * 100.0;
5700 BC->outs() << format("BOLT-INFO: rewritten functions cover %.2lf",
5701 Coverage)
5702 << "% of the execution count of simple functions of "
5703 "this binary\n";
5707 if (BC->HasRelocations && opts::TrapOldCode) {
5708 uint64_t SavedPos = OS.tell();
5709 // Overwrite function body to make sure we never execute these instructions.
5710 for (auto &BFI : BC->getBinaryFunctions()) {
5711 BinaryFunction &BF = BFI.second;
5712 if (!BF.getFileOffset() || !BF.isEmitted())
5713 continue;
5714 OS.seek(BF.getFileOffset());
5715 StringRef TrapInstr = BC->MIB->getTrapFillValue();
5716 unsigned NInstr = BF.getMaxSize() / TrapInstr.size();
5717 for (unsigned I = 0; I < NInstr; ++I)
5718 OS.write(TrapInstr.data(), TrapInstr.size());
5720 OS.seek(SavedPos);
5723 // Write all allocatable sections - reloc-mode text is written here as well
5724 for (BinarySection &Section : BC->allocatableSections()) {
5725 if (!Section.isFinalized() || !Section.getOutputData())
5726 continue;
5727 if (Section.isLinkOnly())
5728 continue;
5730 if (opts::Verbosity >= 1)
5731 BC->outs() << "BOLT: writing new section " << Section.getName()
5732 << "\n data at 0x"
5733 << Twine::utohexstr(Section.getAllocAddress()) << "\n of size "
5734 << Section.getOutputSize() << "\n at offset "
5735 << Section.getOutputFileOffset() << '\n';
5736 OS.seek(Section.getOutputFileOffset());
5737 Section.write(OS);
5740 for (BinarySection &Section : BC->allocatableSections())
5741 Section.flushPendingRelocations(OS, [this](const MCSymbol *S) {
5742 return getNewValueForSymbol(S->getName());
5745 // If .eh_frame is present create .eh_frame_hdr.
5746 if (EHFrameSection)
5747 writeEHFrameHeader();
5749 // Add BOLT Addresses Translation maps to allow profile collection to
5750 // happen in the output binary
5751 if (opts::EnableBAT)
5752 addBATSection();
5754 // Patch program header table.
5755 if (!BC->IsLinuxKernel)
5756 patchELFPHDRTable();
5758 // Finalize memory image of section string table.
5759 finalizeSectionStringTable();
5761 // Update symbol tables.
5762 patchELFSymTabs();
5764 if (opts::EnableBAT)
5765 encodeBATSection();
5767 // Copy non-allocatable sections once allocatable part is finished.
5768 rewriteNoteSections();
5770 if (BC->HasRelocations) {
5771 patchELFAllocatableRelaSections();
5772 patchELFAllocatableRelrSection();
5773 patchELFGOT();
5776 // Patch dynamic section/segment.
5777 patchELFDynamic();
5779 // Update ELF book-keeping info.
5780 patchELFSectionHeaderTable();
5782 if (opts::PrintSections) {
5783 BC->outs() << "BOLT-INFO: Sections after processing:\n";
5784 BC->printSections(BC->outs());
5787 Out->keep();
5788 EC = sys::fs::setPermissions(
5789 opts::OutputFilename,
5790 static_cast<sys::fs::perms>(sys::fs::perms::all_all &
5791 ~sys::fs::getUmask()));
5792 check_error(EC, "cannot set permissions of output file");
5795 void RewriteInstance::writeEHFrameHeader() {
5796 BinarySection *NewEHFrameSection =
5797 getSection(getNewSecPrefix() + getEHFrameSectionName());
5799 // No need to update the header if no new .eh_frame was created.
5800 if (!NewEHFrameSection)
5801 return;
5803 DWARFDebugFrame NewEHFrame(BC->TheTriple->getArch(), true,
5804 NewEHFrameSection->getOutputAddress());
5805 Error E = NewEHFrame.parse(DWARFDataExtractor(
5806 NewEHFrameSection->getOutputContents(), BC->AsmInfo->isLittleEndian(),
5807 BC->AsmInfo->getCodePointerSize()));
5808 check_error(std::move(E), "failed to parse EH frame");
5810 uint64_t RelocatedEHFrameAddress = 0;
5811 StringRef RelocatedEHFrameContents;
5812 BinarySection *RelocatedEHFrameSection =
5813 getSection(".relocated" + getEHFrameSectionName());
5814 if (RelocatedEHFrameSection) {
5815 RelocatedEHFrameAddress = RelocatedEHFrameSection->getOutputAddress();
5816 RelocatedEHFrameContents = RelocatedEHFrameSection->getOutputContents();
5818 DWARFDebugFrame RelocatedEHFrame(BC->TheTriple->getArch(), true,
5819 RelocatedEHFrameAddress);
5820 Error Er = RelocatedEHFrame.parse(DWARFDataExtractor(
5821 RelocatedEHFrameContents, BC->AsmInfo->isLittleEndian(),
5822 BC->AsmInfo->getCodePointerSize()));
5823 check_error(std::move(Er), "failed to parse EH frame");
5825 LLVM_DEBUG(dbgs() << "BOLT: writing a new " << getEHFrameHdrSectionName()
5826 << '\n');
5828 // Try to overwrite the original .eh_frame_hdr if the size permits.
5829 uint64_t EHFrameHdrOutputAddress = 0;
5830 uint64_t EHFrameHdrFileOffset = 0;
5831 std::vector<char> NewEHFrameHdr;
5832 BinarySection *OldEHFrameHdrSection = getSection(getEHFrameHdrSectionName());
5833 if (OldEHFrameHdrSection) {
5834 NewEHFrameHdr = CFIRdWrt->generateEHFrameHeader(
5835 RelocatedEHFrame, NewEHFrame, OldEHFrameHdrSection->getAddress());
5836 if (NewEHFrameHdr.size() <= OldEHFrameHdrSection->getSize()) {
5837 BC->outs() << "BOLT-INFO: rewriting " << getEHFrameHdrSectionName()
5838 << " in-place\n";
5839 EHFrameHdrOutputAddress = OldEHFrameHdrSection->getAddress();
5840 EHFrameHdrFileOffset = OldEHFrameHdrSection->getInputFileOffset();
5841 } else {
5842 OldEHFrameHdrSection->setOutputName(getOrgSecPrefix() +
5843 getEHFrameHdrSectionName());
5844 OldEHFrameHdrSection = nullptr;
5848 // If there was not enough space, allocate more memory for .eh_frame_hdr.
5849 if (!OldEHFrameHdrSection) {
5850 NextAvailableAddress =
5851 appendPadding(Out->os(), NextAvailableAddress, EHFrameHdrAlign);
5853 EHFrameHdrOutputAddress = NextAvailableAddress;
5854 EHFrameHdrFileOffset = getFileOffsetForAddress(NextAvailableAddress);
5856 NewEHFrameHdr = CFIRdWrt->generateEHFrameHeader(
5857 RelocatedEHFrame, NewEHFrame, EHFrameHdrOutputAddress);
5859 NextAvailableAddress += NewEHFrameHdr.size();
5860 if (!BC->BOLTReserved.empty() &&
5861 (NextAvailableAddress > BC->BOLTReserved.end())) {
5862 BC->errs() << "BOLT-ERROR: unable to fit " << getEHFrameHdrSectionName()
5863 << " into reserved space\n";
5864 exit(1);
5867 // Create a new entry in the section header table.
5868 const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/true,
5869 /*IsText=*/false,
5870 /*IsAllocatable=*/true);
5871 BinarySection &EHFrameHdrSec = BC->registerOrUpdateSection(
5872 getNewSecPrefix() + getEHFrameHdrSectionName(), ELF::SHT_PROGBITS,
5873 Flags, nullptr, NewEHFrameHdr.size(), /*Alignment=*/1);
5874 EHFrameHdrSec.setOutputFileOffset(EHFrameHdrFileOffset);
5875 EHFrameHdrSec.setOutputAddress(EHFrameHdrOutputAddress);
5876 EHFrameHdrSec.setOutputName(getEHFrameHdrSectionName());
5879 Out->os().seek(EHFrameHdrFileOffset);
5880 Out->os().write(NewEHFrameHdr.data(), NewEHFrameHdr.size());
5882 // Pad the contents if overwriting in-place.
5883 if (OldEHFrameHdrSection)
5884 Out->os().write_zeros(OldEHFrameHdrSection->getSize() -
5885 NewEHFrameHdr.size());
5887 // Merge new .eh_frame with the relocated original so that gdb can locate all
5888 // FDEs.
5889 if (RelocatedEHFrameSection) {
5890 const uint64_t NewEHFrameSectionSize =
5891 RelocatedEHFrameSection->getOutputAddress() +
5892 RelocatedEHFrameSection->getOutputSize() -
5893 NewEHFrameSection->getOutputAddress();
5894 NewEHFrameSection->updateContents(NewEHFrameSection->getOutputData(),
5895 NewEHFrameSectionSize);
5896 BC->deregisterSection(*RelocatedEHFrameSection);
5899 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: size of .eh_frame after merge is "
5900 << NewEHFrameSection->getOutputSize() << '\n');
5903 uint64_t RewriteInstance::getNewValueForSymbol(const StringRef Name) {
5904 auto Value = Linker->lookupSymbol(Name);
5905 if (Value)
5906 return *Value;
5908 // Return the original value if we haven't emitted the symbol.
5909 BinaryData *BD = BC->getBinaryDataByName(Name);
5910 if (!BD)
5911 return 0;
5913 return BD->getAddress();
5916 uint64_t RewriteInstance::getFileOffsetForAddress(uint64_t Address) const {
5917 // Check if it's possibly part of the new segment.
5918 if (NewTextSegmentAddress && Address >= NewTextSegmentAddress)
5919 return Address - NewTextSegmentAddress + NewTextSegmentOffset;
5921 // Find an existing segment that matches the address.
5922 const auto SegmentInfoI = BC->SegmentMapInfo.upper_bound(Address);
5923 if (SegmentInfoI == BC->SegmentMapInfo.begin())
5924 return 0;
5926 const SegmentInfo &SegmentInfo = std::prev(SegmentInfoI)->second;
5927 if (Address < SegmentInfo.Address ||
5928 Address >= SegmentInfo.Address + SegmentInfo.FileSize)
5929 return 0;
5931 return SegmentInfo.FileOffset + Address - SegmentInfo.Address;
5934 bool RewriteInstance::willOverwriteSection(StringRef SectionName) {
5935 if (llvm::is_contained(SectionsToOverwrite, SectionName))
5936 return true;
5937 if (llvm::is_contained(DebugSectionsToOverwrite, SectionName))
5938 return true;
5940 ErrorOr<BinarySection &> Section = BC->getUniqueSectionByName(SectionName);
5941 return Section && Section->isAllocatable() && Section->isFinalized();
5944 bool RewriteInstance::isDebugSection(StringRef SectionName) {
5945 if (SectionName.starts_with(".debug_") ||
5946 SectionName.starts_with(".zdebug_") || SectionName == ".gdb_index" ||
5947 SectionName == ".stab" || SectionName == ".stabstr")
5948 return true;
5950 return false;