Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / bolt / lib / Rewrite / RewriteInstance.cpp
blob0d78c9b75e03d322736f0ce9dd570e7007df852f
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/CacheMetrics.h"
21 #include "bolt/Passes/ReorderFunctions.h"
22 #include "bolt/Profile/BoltAddressTranslation.h"
23 #include "bolt/Profile/DataAggregator.h"
24 #include "bolt/Profile/DataReader.h"
25 #include "bolt/Profile/YAMLProfileReader.h"
26 #include "bolt/Profile/YAMLProfileWriter.h"
27 #include "bolt/Rewrite/BinaryPassManager.h"
28 #include "bolt/Rewrite/DWARFRewriter.h"
29 #include "bolt/Rewrite/ExecutableFileMemoryManager.h"
30 #include "bolt/Rewrite/JITLinkLinker.h"
31 #include "bolt/Rewrite/MetadataRewriters.h"
32 #include "bolt/RuntimeLibs/HugifyRuntimeLibrary.h"
33 #include "bolt/RuntimeLibs/InstrumentationRuntimeLibrary.h"
34 #include "bolt/Utils/CommandLineOpts.h"
35 #include "bolt/Utils/Utils.h"
36 #include "llvm/ADT/AddressRanges.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
39 #include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
40 #include "llvm/MC/MCAsmBackend.h"
41 #include "llvm/MC/MCAsmInfo.h"
42 #include "llvm/MC/MCAsmLayout.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/Regex.h"
58 #include "llvm/Support/Timer.h"
59 #include "llvm/Support/ToolOutputFile.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include <algorithm>
62 #include <fstream>
63 #include <memory>
64 #include <optional>
65 #include <system_error>
67 #undef DEBUG_TYPE
68 #define DEBUG_TYPE "bolt"
70 using namespace llvm;
71 using namespace object;
72 using namespace bolt;
74 extern cl::opt<uint32_t> X86AlignBranchBoundary;
75 extern cl::opt<bool> X86AlignBranchWithin32BBoundaries;
77 namespace opts {
79 extern cl::opt<MacroFusionType> AlignMacroOpFusion;
80 extern cl::list<std::string> HotTextMoveSections;
81 extern cl::opt<bool> Hugify;
82 extern cl::opt<bool> Instrument;
83 extern cl::opt<JumpTableSupportLevel> JumpTables;
84 extern cl::list<std::string> ReorderData;
85 extern cl::opt<bolt::ReorderFunctions::ReorderType> ReorderFunctions;
86 extern cl::opt<bool> TimeBuild;
88 cl::opt<bool> AllowStripped("allow-stripped",
89 cl::desc("allow processing of stripped binaries"),
90 cl::Hidden, cl::cat(BoltCategory));
92 static cl::opt<bool> ForceToDataRelocations(
93 "force-data-relocations",
94 cl::desc("force relocations to data sections to always be processed"),
96 cl::Hidden, cl::cat(BoltCategory));
98 cl::opt<std::string>
99 BoltID("bolt-id",
100 cl::desc("add any string to tag this execution in the "
101 "output binary via bolt info section"),
102 cl::cat(BoltCategory));
104 cl::opt<bool> DumpDotAll(
105 "dump-dot-all",
106 cl::desc("dump function CFGs to graphviz format after each stage;"
107 "enable '-print-loops' for color-coded blocks"),
108 cl::Hidden, cl::cat(BoltCategory));
110 static cl::list<std::string>
111 ForceFunctionNames("funcs",
112 cl::CommaSeparated,
113 cl::desc("limit optimizations to functions from the list"),
114 cl::value_desc("func1,func2,func3,..."),
115 cl::Hidden,
116 cl::cat(BoltCategory));
118 static cl::opt<std::string>
119 FunctionNamesFile("funcs-file",
120 cl::desc("file with list of functions to optimize"),
121 cl::Hidden,
122 cl::cat(BoltCategory));
124 static cl::list<std::string> ForceFunctionNamesNR(
125 "funcs-no-regex", cl::CommaSeparated,
126 cl::desc("limit optimizations to functions from the list (non-regex)"),
127 cl::value_desc("func1,func2,func3,..."), cl::Hidden, cl::cat(BoltCategory));
129 static cl::opt<std::string> FunctionNamesFileNR(
130 "funcs-file-no-regex",
131 cl::desc("file with list of functions to optimize (non-regex)"), cl::Hidden,
132 cl::cat(BoltCategory));
134 cl::opt<bool>
135 KeepTmp("keep-tmp",
136 cl::desc("preserve intermediate .o file"),
137 cl::Hidden,
138 cl::cat(BoltCategory));
140 cl::opt<bool> Lite("lite", cl::desc("skip processing of cold functions"),
141 cl::cat(BoltCategory));
143 static cl::opt<unsigned>
144 LiteThresholdPct("lite-threshold-pct",
145 cl::desc("threshold (in percent) for selecting functions to process in lite "
146 "mode. Higher threshold means fewer functions to process. E.g "
147 "threshold of 90 means only top 10 percent of functions with "
148 "profile will be processed."),
149 cl::init(0),
150 cl::ZeroOrMore,
151 cl::Hidden,
152 cl::cat(BoltOptCategory));
154 static cl::opt<unsigned> LiteThresholdCount(
155 "lite-threshold-count",
156 cl::desc("similar to '-lite-threshold-pct' but specify threshold using "
157 "absolute function call count. I.e. limit processing to functions "
158 "executed at least the specified number of times."),
159 cl::init(0), cl::Hidden, cl::cat(BoltOptCategory));
161 static cl::opt<unsigned>
162 MaxFunctions("max-funcs",
163 cl::desc("maximum number of functions to process"), cl::Hidden,
164 cl::cat(BoltCategory));
166 static cl::opt<unsigned> MaxDataRelocations(
167 "max-data-relocations",
168 cl::desc("maximum number of data relocations to process"), cl::Hidden,
169 cl::cat(BoltCategory));
171 cl::opt<bool> PrintAll("print-all",
172 cl::desc("print functions after each stage"), cl::Hidden,
173 cl::cat(BoltCategory));
175 cl::opt<bool> PrintProfile("print-profile",
176 cl::desc("print functions after attaching profile"),
177 cl::Hidden, cl::cat(BoltCategory));
179 cl::opt<bool> PrintCFG("print-cfg",
180 cl::desc("print functions after CFG construction"),
181 cl::Hidden, cl::cat(BoltCategory));
183 cl::opt<bool> PrintDisasm("print-disasm",
184 cl::desc("print function after disassembly"),
185 cl::Hidden, cl::cat(BoltCategory));
187 static cl::opt<bool>
188 PrintGlobals("print-globals",
189 cl::desc("print global symbols after disassembly"), cl::Hidden,
190 cl::cat(BoltCategory));
192 extern cl::opt<bool> PrintSections;
194 static cl::opt<bool> PrintLoopInfo("print-loops",
195 cl::desc("print loop related information"),
196 cl::Hidden, cl::cat(BoltCategory));
198 static cl::opt<cl::boolOrDefault> RelocationMode(
199 "relocs", cl::desc("use relocations in the binary (default=autodetect)"),
200 cl::cat(BoltCategory));
202 static cl::opt<std::string>
203 SaveProfile("w",
204 cl::desc("save recorded profile to a file"),
205 cl::cat(BoltOutputCategory));
207 static cl::list<std::string>
208 SkipFunctionNames("skip-funcs",
209 cl::CommaSeparated,
210 cl::desc("list of functions to skip"),
211 cl::value_desc("func1,func2,func3,..."),
212 cl::Hidden,
213 cl::cat(BoltCategory));
215 static cl::opt<std::string>
216 SkipFunctionNamesFile("skip-funcs-file",
217 cl::desc("file with list of functions to skip"),
218 cl::Hidden,
219 cl::cat(BoltCategory));
221 cl::opt<bool>
222 TrapOldCode("trap-old-code",
223 cl::desc("insert traps in old function bodies (relocation mode)"),
224 cl::Hidden,
225 cl::cat(BoltCategory));
227 static cl::opt<std::string> DWPPathName("dwp",
228 cl::desc("Path and name to DWP file."),
229 cl::Hidden, cl::init(""),
230 cl::cat(BoltCategory));
232 static cl::opt<bool>
233 UseGnuStack("use-gnu-stack",
234 cl::desc("use GNU_STACK program header for new segment (workaround for "
235 "issues with strip/objcopy)"),
236 cl::ZeroOrMore,
237 cl::cat(BoltCategory));
239 static cl::opt<bool>
240 TimeRewrite("time-rewrite",
241 cl::desc("print time spent in rewriting passes"), cl::Hidden,
242 cl::cat(BoltCategory));
244 static cl::opt<bool>
245 SequentialDisassembly("sequential-disassembly",
246 cl::desc("performs disassembly sequentially"),
247 cl::init(false),
248 cl::cat(BoltOptCategory));
250 static cl::opt<bool> WriteBoltInfoSection(
251 "bolt-info", cl::desc("write bolt info section in the output binary"),
252 cl::init(true), cl::Hidden, cl::cat(BoltOutputCategory));
254 } // namespace opts
256 // FIXME: implement a better way to mark sections for replacement.
257 constexpr const char *RewriteInstance::SectionsToOverwrite[];
258 std::vector<std::string> RewriteInstance::DebugSectionsToOverwrite = {
259 ".debug_abbrev", ".debug_aranges", ".debug_line", ".debug_line_str",
260 ".debug_loc", ".debug_loclists", ".debug_ranges", ".debug_rnglists",
261 ".gdb_index", ".debug_addr", ".debug_abbrev", ".debug_info",
262 ".debug_types", ".pseudo_probe"};
264 const char RewriteInstance::TimerGroupName[] = "rewrite";
265 const char RewriteInstance::TimerGroupDesc[] = "Rewrite passes";
267 namespace llvm {
268 namespace bolt {
270 extern const char *BoltRevision;
272 MCPlusBuilder *createMCPlusBuilder(const Triple::ArchType Arch,
273 const MCInstrAnalysis *Analysis,
274 const MCInstrInfo *Info,
275 const MCRegisterInfo *RegInfo,
276 const MCSubtargetInfo *STI) {
277 #ifdef X86_AVAILABLE
278 if (Arch == Triple::x86_64)
279 return createX86MCPlusBuilder(Analysis, Info, RegInfo, STI);
280 #endif
282 #ifdef AARCH64_AVAILABLE
283 if (Arch == Triple::aarch64)
284 return createAArch64MCPlusBuilder(Analysis, Info, RegInfo, STI);
285 #endif
287 #ifdef RISCV_AVAILABLE
288 if (Arch == Triple::riscv64)
289 return createRISCVMCPlusBuilder(Analysis, Info, RegInfo, STI);
290 #endif
292 llvm_unreachable("architecture unsupported by MCPlusBuilder");
295 } // namespace bolt
296 } // namespace llvm
298 using ELF64LEPhdrTy = ELF64LEFile::Elf_Phdr;
300 namespace {
302 bool refersToReorderedSection(ErrorOr<BinarySection &> Section) {
303 return llvm::any_of(opts::ReorderData, [&](const std::string &SectionName) {
304 return Section && Section->getName() == SectionName;
308 } // anonymous namespace
310 Expected<std::unique_ptr<RewriteInstance>>
311 RewriteInstance::create(ELFObjectFileBase *File, const int Argc,
312 const char *const *Argv, StringRef ToolPath) {
313 Error Err = Error::success();
314 auto RI = std::make_unique<RewriteInstance>(File, Argc, Argv, ToolPath, Err);
315 if (Err)
316 return std::move(Err);
317 return std::move(RI);
320 RewriteInstance::RewriteInstance(ELFObjectFileBase *File, const int Argc,
321 const char *const *Argv, StringRef ToolPath,
322 Error &Err)
323 : InputFile(File), Argc(Argc), Argv(Argv), ToolPath(ToolPath),
324 SHStrTab(StringTableBuilder::ELF) {
325 ErrorAsOutParameter EAO(&Err);
326 auto ELF64LEFile = dyn_cast<ELF64LEObjectFile>(InputFile);
327 if (!ELF64LEFile) {
328 Err = createStringError(errc::not_supported,
329 "Only 64-bit LE ELF binaries are supported");
330 return;
333 bool IsPIC = false;
334 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile();
335 if (Obj.getHeader().e_type != ELF::ET_EXEC) {
336 outs() << "BOLT-INFO: shared object or position-independent executable "
337 "detected\n";
338 IsPIC = true;
341 auto BCOrErr = BinaryContext::createBinaryContext(
342 File, IsPIC,
343 DWARFContext::create(*File, DWARFContext::ProcessDebugRelocations::Ignore,
344 nullptr, opts::DWPPathName,
345 WithColor::defaultErrorHandler,
346 WithColor::defaultWarningHandler));
347 if (Error E = BCOrErr.takeError()) {
348 Err = std::move(E);
349 return;
351 BC = std::move(BCOrErr.get());
352 BC->initializeTarget(std::unique_ptr<MCPlusBuilder>(
353 createMCPlusBuilder(BC->TheTriple->getArch(), BC->MIA.get(),
354 BC->MII.get(), BC->MRI.get(), BC->STI.get())));
356 BAT = std::make_unique<BoltAddressTranslation>();
358 if (opts::UpdateDebugSections)
359 DebugInfoRewriter = std::make_unique<DWARFRewriter>(*BC);
361 if (opts::Instrument)
362 BC->setRuntimeLibrary(std::make_unique<InstrumentationRuntimeLibrary>());
363 else if (opts::Hugify)
364 BC->setRuntimeLibrary(std::make_unique<HugifyRuntimeLibrary>());
367 RewriteInstance::~RewriteInstance() {}
369 Error RewriteInstance::setProfile(StringRef Filename) {
370 if (!sys::fs::exists(Filename))
371 return errorCodeToError(make_error_code(errc::no_such_file_or_directory));
373 if (ProfileReader) {
374 // Already exists
375 return make_error<StringError>(Twine("multiple profiles specified: ") +
376 ProfileReader->getFilename() + " and " +
377 Filename,
378 inconvertibleErrorCode());
381 // Spawn a profile reader based on file contents.
382 if (DataAggregator::checkPerfDataMagic(Filename))
383 ProfileReader = std::make_unique<DataAggregator>(Filename);
384 else if (YAMLProfileReader::isYAML(Filename))
385 ProfileReader = std::make_unique<YAMLProfileReader>(Filename);
386 else
387 ProfileReader = std::make_unique<DataReader>(Filename);
389 return Error::success();
392 /// Return true if the function \p BF should be disassembled.
393 static bool shouldDisassemble(const BinaryFunction &BF) {
394 if (BF.isPseudo())
395 return false;
397 if (opts::processAllFunctions())
398 return true;
400 return !BF.isIgnored();
403 // Return if a section stored in the image falls into a segment address space.
404 // If not, Set \p Overlap to true if there's a partial overlap.
405 template <class ELFT>
406 static bool checkOffsets(const typename ELFT::Phdr &Phdr,
407 const typename ELFT::Shdr &Sec, bool &Overlap) {
408 // SHT_NOBITS sections don't need to have an offset inside the segment.
409 if (Sec.sh_type == ELF::SHT_NOBITS)
410 return true;
412 // Only non-empty sections can be at the end of a segment.
413 uint64_t SectionSize = Sec.sh_size ? Sec.sh_size : 1ull;
414 AddressRange SectionAddressRange((uint64_t)Sec.sh_offset,
415 Sec.sh_offset + SectionSize);
416 AddressRange SegmentAddressRange(Phdr.p_offset,
417 Phdr.p_offset + Phdr.p_filesz);
418 if (SegmentAddressRange.contains(SectionAddressRange))
419 return true;
421 Overlap = SegmentAddressRange.intersects(SectionAddressRange);
422 return false;
425 // Check that an allocatable section belongs to a virtual address
426 // space of a segment.
427 template <class ELFT>
428 static bool checkVMA(const typename ELFT::Phdr &Phdr,
429 const typename ELFT::Shdr &Sec, bool &Overlap) {
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_addr,
433 Sec.sh_addr + SectionSize);
434 AddressRange SegmentAddressRange(Phdr.p_vaddr, Phdr.p_vaddr + Phdr.p_memsz);
436 if (SegmentAddressRange.contains(SectionAddressRange))
437 return true;
438 Overlap = SegmentAddressRange.intersects(SectionAddressRange);
439 return false;
442 void RewriteInstance::markGnuRelroSections() {
443 using ELFT = ELF64LE;
444 using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr;
445 auto ELF64LEFile = cast<ELF64LEObjectFile>(InputFile);
446 const ELFFile<ELFT> &Obj = ELF64LEFile->getELFFile();
448 auto handleSection = [&](const ELFT::Phdr &Phdr, SectionRef SecRef) {
449 BinarySection *BinarySection = BC->getSectionForSectionRef(SecRef);
450 // If the section is non-allocatable, ignore it for GNU_RELRO purposes:
451 // it can't be made read-only after runtime relocations processing.
452 if (!BinarySection || !BinarySection->isAllocatable())
453 return;
454 const ELFShdrTy *Sec = cantFail(Obj.getSection(SecRef.getIndex()));
455 bool ImageOverlap{false}, VMAOverlap{false};
456 bool ImageContains = checkOffsets<ELFT>(Phdr, *Sec, ImageOverlap);
457 bool VMAContains = checkVMA<ELFT>(Phdr, *Sec, VMAOverlap);
458 if (ImageOverlap) {
459 if (opts::Verbosity >= 1)
460 errs() << "BOLT-WARNING: GNU_RELRO segment has partial file offset "
461 << "overlap with section " << BinarySection->getName() << '\n';
462 return;
464 if (VMAOverlap) {
465 if (opts::Verbosity >= 1)
466 errs() << "BOLT-WARNING: GNU_RELRO segment has partial VMA overlap "
467 << "with section " << BinarySection->getName() << '\n';
468 return;
470 if (!ImageContains || !VMAContains)
471 return;
472 BinarySection->setRelro();
473 if (opts::Verbosity >= 1)
474 outs() << "BOLT-INFO: marking " << BinarySection->getName()
475 << " as GNU_RELRO\n";
478 for (const ELFT::Phdr &Phdr : cantFail(Obj.program_headers()))
479 if (Phdr.p_type == ELF::PT_GNU_RELRO)
480 for (SectionRef SecRef : InputFile->sections())
481 handleSection(Phdr, SecRef);
484 Error RewriteInstance::discoverStorage() {
485 NamedRegionTimer T("discoverStorage", "discover storage", TimerGroupName,
486 TimerGroupDesc, opts::TimeRewrite);
488 auto ELF64LEFile = cast<ELF64LEObjectFile>(InputFile);
489 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile();
491 BC->StartFunctionAddress = Obj.getHeader().e_entry;
493 NextAvailableAddress = 0;
494 uint64_t NextAvailableOffset = 0;
495 Expected<ELF64LE::PhdrRange> PHsOrErr = Obj.program_headers();
496 if (Error E = PHsOrErr.takeError())
497 return E;
499 ELF64LE::PhdrRange PHs = PHsOrErr.get();
500 for (const ELF64LE::Phdr &Phdr : PHs) {
501 switch (Phdr.p_type) {
502 case ELF::PT_LOAD:
503 BC->FirstAllocAddress = std::min(BC->FirstAllocAddress,
504 static_cast<uint64_t>(Phdr.p_vaddr));
505 NextAvailableAddress = std::max(NextAvailableAddress,
506 Phdr.p_vaddr + Phdr.p_memsz);
507 NextAvailableOffset = std::max(NextAvailableOffset,
508 Phdr.p_offset + Phdr.p_filesz);
510 BC->SegmentMapInfo[Phdr.p_vaddr] = SegmentInfo{Phdr.p_vaddr,
511 Phdr.p_memsz,
512 Phdr.p_offset,
513 Phdr.p_filesz,
514 Phdr.p_align};
515 break;
516 case ELF::PT_INTERP:
517 BC->HasInterpHeader = true;
518 break;
522 for (const SectionRef &Section : InputFile->sections()) {
523 Expected<StringRef> SectionNameOrErr = Section.getName();
524 if (Error E = SectionNameOrErr.takeError())
525 return E;
526 StringRef SectionName = SectionNameOrErr.get();
527 if (SectionName == ".text") {
528 BC->OldTextSectionAddress = Section.getAddress();
529 BC->OldTextSectionSize = Section.getSize();
531 Expected<StringRef> SectionContentsOrErr = Section.getContents();
532 if (Error E = SectionContentsOrErr.takeError())
533 return E;
534 StringRef SectionContents = SectionContentsOrErr.get();
535 BC->OldTextSectionOffset =
536 SectionContents.data() - InputFile->getData().data();
539 if (!opts::HeatmapMode &&
540 !(opts::AggregateOnly && BAT->enabledFor(InputFile)) &&
541 (SectionName.startswith(getOrgSecPrefix()) ||
542 SectionName == getBOLTTextSectionName()))
543 return createStringError(
544 errc::function_not_supported,
545 "BOLT-ERROR: input file was processed by BOLT. Cannot re-optimize");
548 if (!NextAvailableAddress || !NextAvailableOffset)
549 return createStringError(errc::executable_format_error,
550 "no PT_LOAD pheader seen");
552 outs() << "BOLT-INFO: first alloc address is 0x"
553 << Twine::utohexstr(BC->FirstAllocAddress) << '\n';
555 FirstNonAllocatableOffset = NextAvailableOffset;
557 NextAvailableAddress = alignTo(NextAvailableAddress, BC->PageAlign);
558 NextAvailableOffset = alignTo(NextAvailableOffset, BC->PageAlign);
560 // Hugify: Additional huge page from left side due to
561 // weird ASLR mapping addresses (4KB aligned)
562 if (opts::Hugify && !BC->HasFixedLoadAddress)
563 NextAvailableAddress += BC->PageAlign;
565 if (!opts::UseGnuStack) {
566 // This is where the black magic happens. Creating PHDR table in a segment
567 // other than that containing ELF header is tricky. Some loaders and/or
568 // parts of loaders will apply e_phoff from ELF header assuming both are in
569 // the same segment, while others will do the proper calculation.
570 // We create the new PHDR table in such a way that both of the methods
571 // of loading and locating the table work. There's a slight file size
572 // overhead because of that.
574 // NB: bfd's strip command cannot do the above and will corrupt the
575 // binary during the process of stripping non-allocatable sections.
576 if (NextAvailableOffset <= NextAvailableAddress - BC->FirstAllocAddress)
577 NextAvailableOffset = NextAvailableAddress - BC->FirstAllocAddress;
578 else
579 NextAvailableAddress = NextAvailableOffset + BC->FirstAllocAddress;
581 assert(NextAvailableOffset ==
582 NextAvailableAddress - BC->FirstAllocAddress &&
583 "PHDR table address calculation error");
585 outs() << "BOLT-INFO: creating new program header table at address 0x"
586 << Twine::utohexstr(NextAvailableAddress) << ", offset 0x"
587 << Twine::utohexstr(NextAvailableOffset) << '\n';
589 PHDRTableAddress = NextAvailableAddress;
590 PHDRTableOffset = NextAvailableOffset;
592 // Reserve space for 3 extra pheaders.
593 unsigned Phnum = Obj.getHeader().e_phnum;
594 Phnum += 3;
596 NextAvailableAddress += Phnum * sizeof(ELF64LEPhdrTy);
597 NextAvailableOffset += Phnum * sizeof(ELF64LEPhdrTy);
600 // Align at cache line.
601 NextAvailableAddress = alignTo(NextAvailableAddress, 64);
602 NextAvailableOffset = alignTo(NextAvailableOffset, 64);
604 NewTextSegmentAddress = NextAvailableAddress;
605 NewTextSegmentOffset = NextAvailableOffset;
606 BC->LayoutStartAddress = NextAvailableAddress;
608 // Tools such as objcopy can strip section contents but leave header
609 // entries. Check that at least .text is mapped in the file.
610 if (!getFileOffsetForAddress(BC->OldTextSectionAddress))
611 return createStringError(errc::executable_format_error,
612 "BOLT-ERROR: input binary is not a valid ELF "
613 "executable as its text section is not "
614 "mapped to a valid segment");
615 return Error::success();
618 void RewriteInstance::parseBuildID() {
619 if (!BuildIDSection)
620 return;
622 StringRef Buf = BuildIDSection->getContents();
624 // Reading notes section (see Portable Formats Specification, Version 1.1,
625 // pg 2-5, section "Note Section").
626 DataExtractor DE = DataExtractor(Buf, true, 8);
627 uint64_t Offset = 0;
628 if (!DE.isValidOffset(Offset))
629 return;
630 uint32_t NameSz = DE.getU32(&Offset);
631 if (!DE.isValidOffset(Offset))
632 return;
633 uint32_t DescSz = DE.getU32(&Offset);
634 if (!DE.isValidOffset(Offset))
635 return;
636 uint32_t Type = DE.getU32(&Offset);
638 LLVM_DEBUG(dbgs() << "NameSz = " << NameSz << "; DescSz = " << DescSz
639 << "; Type = " << Type << "\n");
641 // Type 3 is a GNU build-id note section
642 if (Type != 3)
643 return;
645 StringRef Name = Buf.slice(Offset, Offset + NameSz);
646 Offset = alignTo(Offset + NameSz, 4);
647 if (Name.substr(0, 3) != "GNU")
648 return;
650 BuildID = Buf.slice(Offset, Offset + DescSz);
653 std::optional<std::string> RewriteInstance::getPrintableBuildID() const {
654 if (BuildID.empty())
655 return std::nullopt;
657 std::string Str;
658 raw_string_ostream OS(Str);
659 const unsigned char *CharIter = BuildID.bytes_begin();
660 while (CharIter != BuildID.bytes_end()) {
661 if (*CharIter < 0x10)
662 OS << "0";
663 OS << Twine::utohexstr(*CharIter);
664 ++CharIter;
666 return OS.str();
669 void RewriteInstance::patchBuildID() {
670 raw_fd_ostream &OS = Out->os();
672 if (BuildID.empty())
673 return;
675 size_t IDOffset = BuildIDSection->getContents().rfind(BuildID);
676 assert(IDOffset != StringRef::npos && "failed to patch build-id");
678 uint64_t FileOffset = getFileOffsetForAddress(BuildIDSection->getAddress());
679 if (!FileOffset) {
680 errs() << "BOLT-WARNING: Non-allocatable build-id will not be updated.\n";
681 return;
684 char LastIDByte = BuildID[BuildID.size() - 1];
685 LastIDByte ^= 1;
686 OS.pwrite(&LastIDByte, 1, FileOffset + IDOffset + BuildID.size() - 1);
688 outs() << "BOLT-INFO: patched build-id (flipped last bit)\n";
691 Error RewriteInstance::run() {
692 assert(BC && "failed to create a binary context");
694 outs() << "BOLT-INFO: Target architecture: "
695 << Triple::getArchTypeName(
696 (llvm::Triple::ArchType)InputFile->getArch())
697 << "\n";
698 outs() << "BOLT-INFO: BOLT version: " << BoltRevision << "\n";
700 if (Error E = discoverStorage())
701 return E;
702 if (Error E = readSpecialSections())
703 return E;
704 adjustCommandLineOptions();
705 discoverFileObjects();
707 preprocessProfileData();
709 // Skip disassembling if we have a translation table and we are running an
710 // aggregation job.
711 if (opts::AggregateOnly && BAT->enabledFor(InputFile)) {
712 processProfileData();
713 return Error::success();
716 selectFunctionsToProcess();
718 readDebugInfo();
720 disassembleFunctions();
722 processMetadataPreCFG();
724 buildFunctionsCFG();
726 processProfileData();
728 postProcessFunctions();
730 processMetadataPostCFG();
732 if (opts::DiffOnly)
733 return Error::success();
735 preregisterSections();
737 runOptimizationPasses();
739 emitAndLink();
741 updateMetadata();
743 if (opts::LinuxKernelMode) {
744 errs() << "BOLT-WARNING: not writing the output file for Linux Kernel\n";
745 return Error::success();
746 } else if (opts::OutputFilename == "/dev/null") {
747 outs() << "BOLT-INFO: skipping writing final binary to disk\n";
748 return Error::success();
751 // Rewrite allocatable contents and copy non-allocatable parts with mods.
752 rewriteFile();
753 return Error::success();
756 void RewriteInstance::discoverFileObjects() {
757 NamedRegionTimer T("discoverFileObjects", "discover file objects",
758 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
760 // For local symbols we want to keep track of associated FILE symbol name for
761 // disambiguation by combined name.
762 StringRef FileSymbolName;
763 bool SeenFileName = false;
764 struct SymbolRefHash {
765 size_t operator()(SymbolRef const &S) const {
766 return std::hash<decltype(DataRefImpl::p)>{}(S.getRawDataRefImpl().p);
769 std::unordered_map<SymbolRef, StringRef, SymbolRefHash> SymbolToFileName;
770 for (const ELFSymbolRef &Symbol : InputFile->symbols()) {
771 Expected<StringRef> NameOrError = Symbol.getName();
772 if (NameOrError && NameOrError->startswith("__asan_init")) {
773 errs() << "BOLT-ERROR: input file was compiled or linked with sanitizer "
774 "support. Cannot optimize.\n";
775 exit(1);
777 if (NameOrError && NameOrError->startswith("__llvm_coverage_mapping")) {
778 errs() << "BOLT-ERROR: input file was compiled or linked with coverage "
779 "support. Cannot optimize.\n";
780 exit(1);
783 if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Undefined)
784 continue;
786 if (cantFail(Symbol.getType()) == SymbolRef::ST_File) {
787 StringRef Name =
788 cantFail(std::move(NameOrError), "cannot get symbol name for file");
789 // Ignore Clang LTO artificial FILE symbol as it is not always generated,
790 // and this uncertainty is causing havoc in function name matching.
791 if (Name == "ld-temp.o")
792 continue;
793 FileSymbolName = Name;
794 SeenFileName = true;
795 continue;
797 if (!FileSymbolName.empty() &&
798 !(cantFail(Symbol.getFlags()) & SymbolRef::SF_Global))
799 SymbolToFileName[Symbol] = FileSymbolName;
802 // Sort symbols in the file by value. Ignore symbols from non-allocatable
803 // sections. We memoize getAddress(), as it has rather high overhead.
804 struct SymbolInfo {
805 uint64_t Address;
806 SymbolRef Symbol;
808 std::vector<SymbolInfo> SortedSymbols;
809 auto isSymbolInMemory = [this](const SymbolRef &Sym) {
810 if (cantFail(Sym.getType()) == SymbolRef::ST_File)
811 return false;
812 if (cantFail(Sym.getFlags()) & SymbolRef::SF_Absolute)
813 return true;
814 if (cantFail(Sym.getFlags()) & SymbolRef::SF_Undefined)
815 return false;
816 BinarySection Section(*BC, *cantFail(Sym.getSection()));
817 return Section.isAllocatable();
819 for (const SymbolRef &Symbol : InputFile->symbols())
820 if (isSymbolInMemory(Symbol))
821 SortedSymbols.push_back({cantFail(Symbol.getAddress()), Symbol});
823 auto CompareSymbols = [this](const SymbolInfo &A, const SymbolInfo &B) {
824 if (A.Address != B.Address)
825 return A.Address < B.Address;
827 const bool AMarker = BC->isMarker(A.Symbol);
828 const bool BMarker = BC->isMarker(B.Symbol);
829 if (AMarker || BMarker) {
830 return AMarker && !BMarker;
833 const auto AType = cantFail(A.Symbol.getType());
834 const auto BType = cantFail(B.Symbol.getType());
835 if (AType == SymbolRef::ST_Function && BType != SymbolRef::ST_Function)
836 return true;
837 if (BType == SymbolRef::ST_Debug && AType != SymbolRef::ST_Debug)
838 return true;
840 return false;
842 llvm::stable_sort(SortedSymbols, CompareSymbols);
844 auto LastSymbol = SortedSymbols.end();
845 if (!SortedSymbols.empty())
846 --LastSymbol;
848 // For aarch64, the ABI defines mapping symbols so we identify data in the
849 // code section (see IHI0056B). $d identifies data contents.
850 // Compilers usually merge multiple data objects in a single $d-$x interval,
851 // but we need every data object to be marked with $d. Because of that we
852 // create a vector of MarkerSyms with all locations of data objects.
854 struct MarkerSym {
855 uint64_t Address;
856 MarkerSymType Type;
859 std::vector<MarkerSym> SortedMarkerSymbols;
860 auto addExtraDataMarkerPerSymbol = [&]() {
861 bool IsData = false;
862 uint64_t LastAddr = 0;
863 for (const auto &SymInfo : SortedSymbols) {
864 if (LastAddr == SymInfo.Address) // don't repeat markers
865 continue;
867 MarkerSymType MarkerType = BC->getMarkerType(SymInfo.Symbol);
868 if (MarkerType != MarkerSymType::NONE) {
869 SortedMarkerSymbols.push_back(MarkerSym{SymInfo.Address, MarkerType});
870 LastAddr = SymInfo.Address;
871 IsData = MarkerType == MarkerSymType::DATA;
872 continue;
875 if (IsData) {
876 SortedMarkerSymbols.push_back({SymInfo.Address, MarkerSymType::DATA});
877 LastAddr = SymInfo.Address;
882 if (BC->isAArch64() || BC->isRISCV()) {
883 addExtraDataMarkerPerSymbol();
884 LastSymbol = std::stable_partition(
885 SortedSymbols.begin(), SortedSymbols.end(),
886 [this](const SymbolInfo &S) { return !BC->isMarker(S.Symbol); });
887 if (!SortedSymbols.empty())
888 --LastSymbol;
891 BinaryFunction *PreviousFunction = nullptr;
892 unsigned AnonymousId = 0;
894 // Regex object for matching cold fragments.
895 const Regex ColdFragment(".*\\.cold(\\.[0-9]+)?");
897 const auto SortedSymbolsEnd =
898 LastSymbol == SortedSymbols.end() ? LastSymbol : std::next(LastSymbol);
899 for (auto Iter = SortedSymbols.begin(); Iter != SortedSymbolsEnd; ++Iter) {
900 const SymbolRef &Symbol = Iter->Symbol;
901 const uint64_t SymbolAddress = Iter->Address;
902 const auto SymbolFlags = cantFail(Symbol.getFlags());
903 const SymbolRef::Type SymbolType = cantFail(Symbol.getType());
905 if (SymbolType == SymbolRef::ST_File)
906 continue;
908 StringRef SymName = cantFail(Symbol.getName(), "cannot get symbol name");
909 if (SymbolAddress == 0) {
910 if (opts::Verbosity >= 1 && SymbolType == SymbolRef::ST_Function)
911 errs() << "BOLT-WARNING: function with 0 address seen\n";
912 continue;
915 // Ignore input hot markers
916 if (SymName == "__hot_start" || SymName == "__hot_end")
917 continue;
919 FileSymRefs[SymbolAddress] = Symbol;
921 // Skip section symbols that will be registered by disassemblePLT().
922 if (SymbolType == SymbolRef::ST_Debug) {
923 ErrorOr<BinarySection &> BSection =
924 BC->getSectionForAddress(SymbolAddress);
925 if (BSection && getPLTSectionInfo(BSection->getName()))
926 continue;
929 /// It is possible we are seeing a globalized local. LLVM might treat it as
930 /// a local if it has a "private global" prefix, e.g. ".L". Thus we have to
931 /// change the prefix to enforce global scope of the symbol.
932 std::string Name = SymName.startswith(BC->AsmInfo->getPrivateGlobalPrefix())
933 ? "PG" + std::string(SymName)
934 : std::string(SymName);
936 // Disambiguate all local symbols before adding to symbol table.
937 // Since we don't know if we will see a global with the same name,
938 // always modify the local name.
940 // NOTE: the naming convention for local symbols should match
941 // the one we use for profile data.
942 std::string UniqueName;
943 std::string AlternativeName;
944 if (Name.empty()) {
945 UniqueName = "ANONYMOUS." + std::to_string(AnonymousId++);
946 } else if (SymbolFlags & SymbolRef::SF_Global) {
947 if (const BinaryData *BD = BC->getBinaryDataByName(Name)) {
948 if (BD->getSize() == ELFSymbolRef(Symbol).getSize() &&
949 BD->getAddress() == SymbolAddress) {
950 if (opts::Verbosity > 1)
951 errs() << "BOLT-WARNING: ignoring duplicate global symbol " << Name
952 << "\n";
953 // Ignore duplicate entry - possibly a bug in the linker
954 continue;
956 errs() << "BOLT-ERROR: bad input binary, global symbol \"" << Name
957 << "\" is not unique\n";
958 exit(1);
960 UniqueName = Name;
961 } else {
962 // If we have a local file name, we should create 2 variants for the
963 // function name. The reason is that perf profile might have been
964 // collected on a binary that did not have the local file name (e.g. as
965 // a side effect of stripping debug info from the binary):
967 // primary: <function>/<id>
968 // alternative: <function>/<file>/<id2>
970 // The <id> field is used for disambiguation of local symbols since there
971 // could be identical function names coming from identical file names
972 // (e.g. from different directories).
973 std::string AltPrefix;
974 auto SFI = SymbolToFileName.find(Symbol);
975 if (SymbolType == SymbolRef::ST_Function && SFI != SymbolToFileName.end())
976 AltPrefix = Name + "/" + std::string(SFI->second);
978 UniqueName = NR.uniquify(Name);
979 if (!AltPrefix.empty())
980 AlternativeName = NR.uniquify(AltPrefix);
983 uint64_t SymbolSize = ELFSymbolRef(Symbol).getSize();
984 uint64_t SymbolAlignment = Symbol.getAlignment();
986 auto registerName = [&](uint64_t FinalSize) {
987 // Register names even if it's not a function, e.g. for an entry point.
988 BC->registerNameAtAddress(UniqueName, SymbolAddress, FinalSize,
989 SymbolAlignment, SymbolFlags);
990 if (!AlternativeName.empty())
991 BC->registerNameAtAddress(AlternativeName, SymbolAddress, FinalSize,
992 SymbolAlignment, SymbolFlags);
995 section_iterator Section =
996 cantFail(Symbol.getSection(), "cannot get symbol section");
997 if (Section == InputFile->section_end()) {
998 // Could be an absolute symbol. Used on RISC-V for __global_pointer$ so we
999 // need to record it to handle relocations against it. For other instances
1000 // of absolute symbols, we record for pretty printing.
1001 LLVM_DEBUG(if (opts::Verbosity > 1) {
1002 dbgs() << "BOLT-INFO: absolute sym " << UniqueName << "\n";
1004 registerName(SymbolSize);
1005 continue;
1008 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: considering symbol " << UniqueName
1009 << " for function\n");
1011 if (SymbolAddress == Section->getAddress() + Section->getSize()) {
1012 assert(SymbolSize == 0 &&
1013 "unexpect non-zero sized symbol at end of section");
1014 LLVM_DEBUG(
1015 dbgs()
1016 << "BOLT-DEBUG: rejecting as symbol points to end of its section\n");
1017 registerName(SymbolSize);
1018 continue;
1021 if (!Section->isText()) {
1022 assert(SymbolType != SymbolRef::ST_Function &&
1023 "unexpected function inside non-code section");
1024 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: rejecting as symbol is not in code\n");
1025 registerName(SymbolSize);
1026 continue;
1029 // Assembly functions could be ST_NONE with 0 size. Check that the
1030 // corresponding section is a code section and they are not inside any
1031 // other known function to consider them.
1033 // Sometimes assembly functions are not marked as functions and neither are
1034 // their local labels. The only way to tell them apart is to look at
1035 // symbol scope - global vs local.
1036 if (PreviousFunction && SymbolType != SymbolRef::ST_Function) {
1037 if (PreviousFunction->containsAddress(SymbolAddress)) {
1038 if (PreviousFunction->isSymbolValidInScope(Symbol, SymbolSize)) {
1039 LLVM_DEBUG(dbgs()
1040 << "BOLT-DEBUG: symbol is a function local symbol\n");
1041 } else if (SymbolAddress == PreviousFunction->getAddress() &&
1042 !SymbolSize) {
1043 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring symbol as a marker\n");
1044 } else if (opts::Verbosity > 1) {
1045 errs() << "BOLT-WARNING: symbol " << UniqueName
1046 << " seen in the middle of function " << *PreviousFunction
1047 << ". Could be a new entry.\n";
1049 registerName(SymbolSize);
1050 continue;
1051 } else if (PreviousFunction->getSize() == 0 &&
1052 PreviousFunction->isSymbolValidInScope(Symbol, SymbolSize)) {
1053 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: symbol is a function local symbol\n");
1054 registerName(SymbolSize);
1055 continue;
1059 if (PreviousFunction && PreviousFunction->containsAddress(SymbolAddress) &&
1060 PreviousFunction->getAddress() != SymbolAddress) {
1061 if (PreviousFunction->isSymbolValidInScope(Symbol, SymbolSize)) {
1062 if (opts::Verbosity >= 1)
1063 outs() << "BOLT-INFO: skipping possibly another entry for function "
1064 << *PreviousFunction << " : " << UniqueName << '\n';
1065 registerName(SymbolSize);
1066 } else {
1067 outs() << "BOLT-INFO: using " << UniqueName << " as another entry to "
1068 << "function " << *PreviousFunction << '\n';
1070 registerName(0);
1072 PreviousFunction->addEntryPointAtOffset(SymbolAddress -
1073 PreviousFunction->getAddress());
1075 // Remove the symbol from FileSymRefs so that we can skip it from
1076 // in the future.
1077 auto SI = FileSymRefs.find(SymbolAddress);
1078 assert(SI != FileSymRefs.end() && "symbol expected to be present");
1079 assert(SI->second == Symbol && "wrong symbol found");
1080 FileSymRefs.erase(SI);
1082 continue;
1085 // Checkout for conflicts with function data from FDEs.
1086 bool IsSimple = true;
1087 auto FDEI = CFIRdWrt->getFDEs().lower_bound(SymbolAddress);
1088 if (FDEI != CFIRdWrt->getFDEs().end()) {
1089 const dwarf::FDE &FDE = *FDEI->second;
1090 if (FDEI->first != SymbolAddress) {
1091 // There's no matching starting address in FDE. Make sure the previous
1092 // FDE does not contain this address.
1093 if (FDEI != CFIRdWrt->getFDEs().begin()) {
1094 --FDEI;
1095 const dwarf::FDE &PrevFDE = *FDEI->second;
1096 uint64_t PrevStart = PrevFDE.getInitialLocation();
1097 uint64_t PrevLength = PrevFDE.getAddressRange();
1098 if (SymbolAddress > PrevStart &&
1099 SymbolAddress < PrevStart + PrevLength) {
1100 errs() << "BOLT-ERROR: function " << UniqueName
1101 << " is in conflict with FDE ["
1102 << Twine::utohexstr(PrevStart) << ", "
1103 << Twine::utohexstr(PrevStart + PrevLength)
1104 << "). Skipping.\n";
1105 IsSimple = false;
1108 } else if (FDE.getAddressRange() != SymbolSize) {
1109 if (SymbolSize) {
1110 // Function addresses match but sizes differ.
1111 errs() << "BOLT-WARNING: sizes differ for function " << UniqueName
1112 << ". FDE : " << FDE.getAddressRange()
1113 << "; symbol table : " << SymbolSize << ". Using max size.\n";
1115 SymbolSize = std::max(SymbolSize, FDE.getAddressRange());
1116 if (BC->getBinaryDataAtAddress(SymbolAddress)) {
1117 BC->setBinaryDataSize(SymbolAddress, SymbolSize);
1118 } else {
1119 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: No BD @ 0x"
1120 << Twine::utohexstr(SymbolAddress) << "\n");
1125 BinaryFunction *BF = nullptr;
1126 // Since function may not have yet obtained its real size, do a search
1127 // using the list of registered functions instead of calling
1128 // getBinaryFunctionAtAddress().
1129 auto BFI = BC->getBinaryFunctions().find(SymbolAddress);
1130 if (BFI != BC->getBinaryFunctions().end()) {
1131 BF = &BFI->second;
1132 // Duplicate the function name. Make sure everything matches before we add
1133 // an alternative name.
1134 if (SymbolSize != BF->getSize()) {
1135 if (opts::Verbosity >= 1) {
1136 if (SymbolSize && BF->getSize())
1137 errs() << "BOLT-WARNING: size mismatch for duplicate entries "
1138 << *BF << " and " << UniqueName << '\n';
1139 outs() << "BOLT-INFO: adjusting size of function " << *BF << " old "
1140 << BF->getSize() << " new " << SymbolSize << "\n";
1142 BF->setSize(std::max(SymbolSize, BF->getSize()));
1143 BC->setBinaryDataSize(SymbolAddress, BF->getSize());
1145 BF->addAlternativeName(UniqueName);
1146 } else {
1147 ErrorOr<BinarySection &> Section =
1148 BC->getSectionForAddress(SymbolAddress);
1149 // Skip symbols from invalid sections
1150 if (!Section) {
1151 errs() << "BOLT-WARNING: " << UniqueName << " (0x"
1152 << Twine::utohexstr(SymbolAddress)
1153 << ") does not have any section\n";
1154 continue;
1157 // Skip symbols from zero-sized sections.
1158 if (!Section->getSize())
1159 continue;
1161 BF = BC->createBinaryFunction(UniqueName, *Section, SymbolAddress,
1162 SymbolSize);
1163 if (!IsSimple)
1164 BF->setSimple(false);
1167 // Check if it's a cold function fragment.
1168 if (ColdFragment.match(SymName)) {
1169 static bool PrintedWarning = false;
1170 if (!PrintedWarning) {
1171 PrintedWarning = true;
1172 errs() << "BOLT-WARNING: split function detected on input : "
1173 << SymName;
1174 if (BC->HasRelocations)
1175 errs() << ". The support is limited in relocation mode\n";
1176 else
1177 errs() << '\n';
1179 BC->HasSplitFunctions = true;
1180 BF->IsFragment = true;
1183 if (!AlternativeName.empty())
1184 BF->addAlternativeName(AlternativeName);
1186 registerName(SymbolSize);
1187 PreviousFunction = BF;
1190 // Read dynamic relocation first as their presence affects the way we process
1191 // static relocations. E.g. we will ignore a static relocation at an address
1192 // that is a subject to dynamic relocation processing.
1193 processDynamicRelocations();
1195 // Process PLT section.
1196 disassemblePLT();
1198 // See if we missed any functions marked by FDE.
1199 for (const auto &FDEI : CFIRdWrt->getFDEs()) {
1200 const uint64_t Address = FDEI.first;
1201 const dwarf::FDE *FDE = FDEI.second;
1202 const BinaryFunction *BF = BC->getBinaryFunctionAtAddress(Address);
1203 if (BF)
1204 continue;
1206 BF = BC->getBinaryFunctionContainingAddress(Address);
1207 if (BF) {
1208 errs() << "BOLT-WARNING: FDE [0x" << Twine::utohexstr(Address) << ", 0x"
1209 << Twine::utohexstr(Address + FDE->getAddressRange())
1210 << ") conflicts with function " << *BF << '\n';
1211 continue;
1214 if (opts::Verbosity >= 1)
1215 errs() << "BOLT-WARNING: FDE [0x" << Twine::utohexstr(Address) << ", 0x"
1216 << Twine::utohexstr(Address + FDE->getAddressRange())
1217 << ") has no corresponding symbol table entry\n";
1219 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(Address);
1220 assert(Section && "cannot get section for address from FDE");
1221 std::string FunctionName =
1222 "__BOLT_FDE_FUNCat" + Twine::utohexstr(Address).str();
1223 BC->createBinaryFunction(FunctionName, *Section, Address,
1224 FDE->getAddressRange());
1227 BC->setHasSymbolsWithFileName(SeenFileName);
1229 // Now that all the functions were created - adjust their boundaries.
1230 adjustFunctionBoundaries();
1232 // Annotate functions with code/data markers in AArch64
1233 for (auto ISym = SortedMarkerSymbols.begin();
1234 ISym != SortedMarkerSymbols.end(); ++ISym) {
1236 auto *BF =
1237 BC->getBinaryFunctionContainingAddress(ISym->Address, true, true);
1239 if (!BF) {
1240 // Stray marker
1241 continue;
1243 const auto EntryOffset = ISym->Address - BF->getAddress();
1244 if (ISym->Type == MarkerSymType::CODE) {
1245 BF->markCodeAtOffset(EntryOffset);
1246 continue;
1248 if (ISym->Type == MarkerSymType::DATA) {
1249 BF->markDataAtOffset(EntryOffset);
1250 BC->AddressToConstantIslandMap[ISym->Address] = BF;
1251 continue;
1253 llvm_unreachable("Unknown marker");
1256 if (BC->isAArch64()) {
1257 // Check for dynamic relocations that might be contained in
1258 // constant islands.
1259 for (const BinarySection &Section : BC->allocatableSections()) {
1260 const uint64_t SectionAddress = Section.getAddress();
1261 for (const Relocation &Rel : Section.dynamicRelocations()) {
1262 const uint64_t RelAddress = SectionAddress + Rel.Offset;
1263 BinaryFunction *BF =
1264 BC->getBinaryFunctionContainingAddress(RelAddress,
1265 /*CheckPastEnd*/ false,
1266 /*UseMaxSize*/ true);
1267 if (BF) {
1268 assert(Rel.isRelative() && "Expected relative relocation for island");
1269 BF->markIslandDynamicRelocationAtAddress(RelAddress);
1275 if (!opts::LinuxKernelMode) {
1276 // Read all relocations now that we have binary functions mapped.
1277 processRelocations();
1280 registerFragments();
1283 void RewriteInstance::registerFragments() {
1284 if (!BC->HasSplitFunctions)
1285 return;
1287 for (auto &BFI : BC->getBinaryFunctions()) {
1288 BinaryFunction &Function = BFI.second;
1289 if (!Function.isFragment())
1290 continue;
1291 unsigned ParentsFound = 0;
1292 for (StringRef Name : Function.getNames()) {
1293 StringRef BaseName, Suffix;
1294 std::tie(BaseName, Suffix) = Name.split('/');
1295 const size_t ColdSuffixPos = BaseName.find(".cold");
1296 if (ColdSuffixPos == StringRef::npos)
1297 continue;
1298 // For cold function with local (foo.cold/1) symbol, prefer a parent with
1299 // local symbol as well (foo/1) over global symbol (foo).
1300 std::string ParentName = BaseName.substr(0, ColdSuffixPos).str();
1301 const BinaryData *BD = BC->getBinaryDataByName(ParentName);
1302 if (Suffix != "") {
1303 ParentName.append(Twine("/", Suffix).str());
1304 const BinaryData *BDLocal = BC->getBinaryDataByName(ParentName);
1305 if (BDLocal || !BD)
1306 BD = BDLocal;
1308 if (!BD) {
1309 if (opts::Verbosity >= 1)
1310 outs() << "BOLT-INFO: parent function not found for " << Name << "\n";
1311 continue;
1313 const uint64_t Address = BD->getAddress();
1314 BinaryFunction *BF = BC->getBinaryFunctionAtAddress(Address);
1315 if (!BF) {
1316 if (opts::Verbosity >= 1)
1317 outs() << formatv("BOLT-INFO: parent function not found at {0:x}\n",
1318 Address);
1319 continue;
1321 BC->registerFragment(Function, *BF);
1322 ++ParentsFound;
1324 if (!ParentsFound) {
1325 errs() << "BOLT-ERROR: parent function not found for " << Function
1326 << '\n';
1327 exit(1);
1332 void RewriteInstance::createPLTBinaryFunction(uint64_t TargetAddress,
1333 uint64_t EntryAddress,
1334 uint64_t EntrySize) {
1335 if (!TargetAddress)
1336 return;
1338 auto setPLTSymbol = [&](BinaryFunction *BF, StringRef Name) {
1339 const unsigned PtrSize = BC->AsmInfo->getCodePointerSize();
1340 MCSymbol *TargetSymbol = BC->registerNameAtAddress(
1341 Name.str() + "@GOT", TargetAddress, PtrSize, PtrSize);
1342 BF->setPLTSymbol(TargetSymbol);
1345 BinaryFunction *BF = BC->getBinaryFunctionAtAddress(EntryAddress);
1346 if (BF && BC->isAArch64()) {
1347 // Handle IFUNC trampoline
1348 setPLTSymbol(BF, BF->getOneName());
1349 return;
1352 const Relocation *Rel = BC->getDynamicRelocationAt(TargetAddress);
1353 if (!Rel || !Rel->Symbol)
1354 return;
1356 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(EntryAddress);
1357 assert(Section && "cannot get section for address");
1358 if (!BF)
1359 BF = BC->createBinaryFunction(Rel->Symbol->getName().str() + "@PLT",
1360 *Section, EntryAddress, 0, EntrySize,
1361 Section->getAlignment());
1362 else
1363 BF->addAlternativeName(Rel->Symbol->getName().str() + "@PLT");
1364 setPLTSymbol(BF, Rel->Symbol->getName());
1367 void RewriteInstance::disassemblePLTSectionAArch64(BinarySection &Section) {
1368 const uint64_t SectionAddress = Section.getAddress();
1369 const uint64_t SectionSize = Section.getSize();
1370 StringRef PLTContents = Section.getContents();
1371 ArrayRef<uint8_t> PLTData(
1372 reinterpret_cast<const uint8_t *>(PLTContents.data()), SectionSize);
1374 auto disassembleInstruction = [&](uint64_t InstrOffset, MCInst &Instruction,
1375 uint64_t &InstrSize) {
1376 const uint64_t InstrAddr = SectionAddress + InstrOffset;
1377 if (!BC->DisAsm->getInstruction(Instruction, InstrSize,
1378 PLTData.slice(InstrOffset), InstrAddr,
1379 nulls())) {
1380 errs() << "BOLT-ERROR: unable to disassemble instruction in PLT section "
1381 << Section.getName() << " at offset 0x"
1382 << Twine::utohexstr(InstrOffset) << '\n';
1383 exit(1);
1387 uint64_t InstrOffset = 0;
1388 // Locate new plt entry
1389 while (InstrOffset < SectionSize) {
1390 InstructionListType Instructions;
1391 MCInst Instruction;
1392 uint64_t EntryOffset = InstrOffset;
1393 uint64_t EntrySize = 0;
1394 uint64_t InstrSize;
1395 // Loop through entry instructions
1396 while (InstrOffset < SectionSize) {
1397 disassembleInstruction(InstrOffset, Instruction, InstrSize);
1398 EntrySize += InstrSize;
1399 if (!BC->MIB->isIndirectBranch(Instruction)) {
1400 Instructions.emplace_back(Instruction);
1401 InstrOffset += InstrSize;
1402 continue;
1405 const uint64_t EntryAddress = SectionAddress + EntryOffset;
1406 const uint64_t TargetAddress = BC->MIB->analyzePLTEntry(
1407 Instruction, Instructions.begin(), Instructions.end(), EntryAddress);
1409 createPLTBinaryFunction(TargetAddress, EntryAddress, EntrySize);
1410 break;
1413 // Branch instruction
1414 InstrOffset += InstrSize;
1416 // Skip nops if any
1417 while (InstrOffset < SectionSize) {
1418 disassembleInstruction(InstrOffset, Instruction, InstrSize);
1419 if (!BC->MIB->isNoop(Instruction))
1420 break;
1422 InstrOffset += InstrSize;
1427 void RewriteInstance::disassemblePLTSectionRISCV(BinarySection &Section) {
1428 const uint64_t SectionAddress = Section.getAddress();
1429 const uint64_t SectionSize = Section.getSize();
1430 StringRef PLTContents = Section.getContents();
1431 ArrayRef<uint8_t> PLTData(
1432 reinterpret_cast<const uint8_t *>(PLTContents.data()), SectionSize);
1434 auto disassembleInstruction = [&](uint64_t InstrOffset, MCInst &Instruction,
1435 uint64_t &InstrSize) {
1436 const uint64_t InstrAddr = SectionAddress + InstrOffset;
1437 if (!BC->DisAsm->getInstruction(Instruction, InstrSize,
1438 PLTData.slice(InstrOffset), InstrAddr,
1439 nulls())) {
1440 errs() << "BOLT-ERROR: unable to disassemble instruction in PLT section "
1441 << Section.getName() << " at offset 0x"
1442 << Twine::utohexstr(InstrOffset) << '\n';
1443 exit(1);
1447 // Skip the first special entry since no relocation points to it.
1448 uint64_t InstrOffset = 32;
1450 while (InstrOffset < SectionSize) {
1451 InstructionListType Instructions;
1452 MCInst Instruction;
1453 const uint64_t EntryOffset = InstrOffset;
1454 const uint64_t EntrySize = 16;
1455 uint64_t InstrSize;
1457 while (InstrOffset < EntryOffset + EntrySize) {
1458 disassembleInstruction(InstrOffset, Instruction, InstrSize);
1459 Instructions.emplace_back(Instruction);
1460 InstrOffset += InstrSize;
1463 const uint64_t EntryAddress = SectionAddress + EntryOffset;
1464 const uint64_t TargetAddress = BC->MIB->analyzePLTEntry(
1465 Instruction, Instructions.begin(), Instructions.end(), EntryAddress);
1467 createPLTBinaryFunction(TargetAddress, EntryAddress, EntrySize);
1471 void RewriteInstance::disassemblePLTSectionX86(BinarySection &Section,
1472 uint64_t EntrySize) {
1473 const uint64_t SectionAddress = Section.getAddress();
1474 const uint64_t SectionSize = Section.getSize();
1475 StringRef PLTContents = Section.getContents();
1476 ArrayRef<uint8_t> PLTData(
1477 reinterpret_cast<const uint8_t *>(PLTContents.data()), SectionSize);
1479 auto disassembleInstruction = [&](uint64_t InstrOffset, MCInst &Instruction,
1480 uint64_t &InstrSize) {
1481 const uint64_t InstrAddr = SectionAddress + InstrOffset;
1482 if (!BC->DisAsm->getInstruction(Instruction, InstrSize,
1483 PLTData.slice(InstrOffset), InstrAddr,
1484 nulls())) {
1485 errs() << "BOLT-ERROR: unable to disassemble instruction in PLT section "
1486 << Section.getName() << " at offset 0x"
1487 << Twine::utohexstr(InstrOffset) << '\n';
1488 exit(1);
1492 for (uint64_t EntryOffset = 0; EntryOffset + EntrySize <= SectionSize;
1493 EntryOffset += EntrySize) {
1494 MCInst Instruction;
1495 uint64_t InstrSize, InstrOffset = EntryOffset;
1496 while (InstrOffset < EntryOffset + EntrySize) {
1497 disassembleInstruction(InstrOffset, Instruction, InstrSize);
1498 // Check if the entry size needs adjustment.
1499 if (EntryOffset == 0 && BC->MIB->isTerminateBranch(Instruction) &&
1500 EntrySize == 8)
1501 EntrySize = 16;
1503 if (BC->MIB->isIndirectBranch(Instruction))
1504 break;
1506 InstrOffset += InstrSize;
1509 if (InstrOffset + InstrSize > EntryOffset + EntrySize)
1510 continue;
1512 uint64_t TargetAddress;
1513 if (!BC->MIB->evaluateMemOperandTarget(Instruction, TargetAddress,
1514 SectionAddress + InstrOffset,
1515 InstrSize)) {
1516 errs() << "BOLT-ERROR: error evaluating PLT instruction at offset 0x"
1517 << Twine::utohexstr(SectionAddress + InstrOffset) << '\n';
1518 exit(1);
1521 createPLTBinaryFunction(TargetAddress, SectionAddress + EntryOffset,
1522 EntrySize);
1526 void RewriteInstance::disassemblePLT() {
1527 auto analyzeOnePLTSection = [&](BinarySection &Section, uint64_t EntrySize) {
1528 if (BC->isAArch64())
1529 return disassemblePLTSectionAArch64(Section);
1530 if (BC->isRISCV())
1531 return disassemblePLTSectionRISCV(Section);
1532 return disassemblePLTSectionX86(Section, EntrySize);
1535 for (BinarySection &Section : BC->allocatableSections()) {
1536 const PLTSectionInfo *PLTSI = getPLTSectionInfo(Section.getName());
1537 if (!PLTSI)
1538 continue;
1540 analyzeOnePLTSection(Section, PLTSI->EntrySize);
1542 BinaryFunction *PltBF;
1543 auto BFIter = BC->getBinaryFunctions().find(Section.getAddress());
1544 if (BFIter != BC->getBinaryFunctions().end()) {
1545 PltBF = &BFIter->second;
1546 } else {
1547 // If we did not register any function at the start of the section,
1548 // then it must be a general PLT entry. Add a function at the location.
1549 PltBF = BC->createBinaryFunction(
1550 "__BOLT_PSEUDO_" + Section.getName().str(), Section,
1551 Section.getAddress(), 0, PLTSI->EntrySize, Section.getAlignment());
1553 PltBF->setPseudo(true);
1557 void RewriteInstance::adjustFunctionBoundaries() {
1558 for (auto BFI = BC->getBinaryFunctions().begin(),
1559 BFE = BC->getBinaryFunctions().end();
1560 BFI != BFE; ++BFI) {
1561 BinaryFunction &Function = BFI->second;
1562 const BinaryFunction *NextFunction = nullptr;
1563 if (std::next(BFI) != BFE)
1564 NextFunction = &std::next(BFI)->second;
1566 // Check if there's a symbol or a function with a larger address in the
1567 // same section. If there is - it determines the maximum size for the
1568 // current function. Otherwise, it is the size of a containing section
1569 // the defines it.
1571 // NOTE: ignore some symbols that could be tolerated inside the body
1572 // of a function.
1573 auto NextSymRefI = FileSymRefs.upper_bound(Function.getAddress());
1574 while (NextSymRefI != FileSymRefs.end()) {
1575 SymbolRef &Symbol = NextSymRefI->second;
1576 const uint64_t SymbolAddress = NextSymRefI->first;
1577 const uint64_t SymbolSize = ELFSymbolRef(Symbol).getSize();
1579 if (NextFunction && SymbolAddress >= NextFunction->getAddress())
1580 break;
1582 if (!Function.isSymbolValidInScope(Symbol, SymbolSize))
1583 break;
1585 // Ignore unnamed symbols. Used, for example, by debugging info on RISC-V.
1586 if (BC->isRISCV() && cantFail(Symbol.getName()).empty()) {
1587 ++NextSymRefI;
1588 continue;
1591 // Skip basic block labels. This happens on RISC-V with linker relaxation
1592 // enabled because every branch needs a relocation and corresponding
1593 // symbol. We don't want to add such symbols as entry points.
1594 const auto PrivateLabelPrefix = BC->AsmInfo->getPrivateLabelPrefix();
1595 if (!PrivateLabelPrefix.empty() &&
1596 cantFail(Symbol.getName()).starts_with(PrivateLabelPrefix)) {
1597 ++NextSymRefI;
1598 continue;
1601 // This is potentially another entry point into the function.
1602 uint64_t EntryOffset = NextSymRefI->first - Function.getAddress();
1603 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding entry point to function "
1604 << Function << " at offset 0x"
1605 << Twine::utohexstr(EntryOffset) << '\n');
1606 Function.addEntryPointAtOffset(EntryOffset);
1608 ++NextSymRefI;
1611 // Function runs at most till the end of the containing section.
1612 uint64_t NextObjectAddress = Function.getOriginSection()->getEndAddress();
1613 // Or till the next object marked by a symbol.
1614 if (NextSymRefI != FileSymRefs.end())
1615 NextObjectAddress = std::min(NextSymRefI->first, NextObjectAddress);
1617 // Or till the next function not marked by a symbol.
1618 if (NextFunction)
1619 NextObjectAddress =
1620 std::min(NextFunction->getAddress(), NextObjectAddress);
1622 const uint64_t MaxSize = NextObjectAddress - Function.getAddress();
1623 if (MaxSize < Function.getSize()) {
1624 errs() << "BOLT-ERROR: symbol seen in the middle of the function "
1625 << Function << ". Skipping.\n";
1626 Function.setSimple(false);
1627 Function.setMaxSize(Function.getSize());
1628 continue;
1630 Function.setMaxSize(MaxSize);
1631 if (!Function.getSize() && Function.isSimple()) {
1632 // Some assembly functions have their size set to 0, use the max
1633 // size as their real size.
1634 if (opts::Verbosity >= 1)
1635 outs() << "BOLT-INFO: setting size of function " << Function << " to "
1636 << Function.getMaxSize() << " (was 0)\n";
1637 Function.setSize(Function.getMaxSize());
1642 void RewriteInstance::relocateEHFrameSection() {
1643 assert(EHFrameSection && "Non-empty .eh_frame section expected.");
1645 BinarySection *RelocatedEHFrameSection =
1646 getSection(".relocated" + getEHFrameSectionName());
1647 assert(RelocatedEHFrameSection &&
1648 "Relocated eh_frame section should be preregistered.");
1649 DWARFDataExtractor DE(EHFrameSection->getContents(),
1650 BC->AsmInfo->isLittleEndian(),
1651 BC->AsmInfo->getCodePointerSize());
1652 auto createReloc = [&](uint64_t Value, uint64_t Offset, uint64_t DwarfType) {
1653 if (DwarfType == dwarf::DW_EH_PE_omit)
1654 return;
1656 // Only fix references that are relative to other locations.
1657 if (!(DwarfType & dwarf::DW_EH_PE_pcrel) &&
1658 !(DwarfType & dwarf::DW_EH_PE_textrel) &&
1659 !(DwarfType & dwarf::DW_EH_PE_funcrel) &&
1660 !(DwarfType & dwarf::DW_EH_PE_datarel))
1661 return;
1663 if (!(DwarfType & dwarf::DW_EH_PE_sdata4))
1664 return;
1666 uint64_t RelType;
1667 switch (DwarfType & 0x0f) {
1668 default:
1669 llvm_unreachable("unsupported DWARF encoding type");
1670 case dwarf::DW_EH_PE_sdata4:
1671 case dwarf::DW_EH_PE_udata4:
1672 RelType = Relocation::getPC32();
1673 Offset -= 4;
1674 break;
1675 case dwarf::DW_EH_PE_sdata8:
1676 case dwarf::DW_EH_PE_udata8:
1677 RelType = Relocation::getPC64();
1678 Offset -= 8;
1679 break;
1682 // Create a relocation against an absolute value since the goal is to
1683 // preserve the contents of the section independent of the new values
1684 // of referenced symbols.
1685 RelocatedEHFrameSection->addRelocation(Offset, nullptr, RelType, Value);
1688 Error E = EHFrameParser::parse(DE, EHFrameSection->getAddress(), createReloc);
1689 check_error(std::move(E), "failed to patch EH frame");
1692 ArrayRef<uint8_t> RewriteInstance::getLSDAData() {
1693 return ArrayRef<uint8_t>(LSDASection->getData(),
1694 LSDASection->getContents().size());
1697 uint64_t RewriteInstance::getLSDAAddress() { return LSDASection->getAddress(); }
1699 Error RewriteInstance::readSpecialSections() {
1700 NamedRegionTimer T("readSpecialSections", "read special sections",
1701 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
1703 bool HasTextRelocations = false;
1704 bool HasSymbolTable = false;
1705 bool HasDebugInfo = false;
1707 // Process special sections.
1708 for (const SectionRef &Section : InputFile->sections()) {
1709 Expected<StringRef> SectionNameOrErr = Section.getName();
1710 check_error(SectionNameOrErr.takeError(), "cannot get section name");
1711 StringRef SectionName = *SectionNameOrErr;
1713 if (Error E = Section.getContents().takeError())
1714 return E;
1715 BC->registerSection(Section);
1716 LLVM_DEBUG(
1717 dbgs() << "BOLT-DEBUG: registering section " << SectionName << " @ 0x"
1718 << Twine::utohexstr(Section.getAddress()) << ":0x"
1719 << Twine::utohexstr(Section.getAddress() + Section.getSize())
1720 << "\n");
1721 if (isDebugSection(SectionName))
1722 HasDebugInfo = true;
1723 if (isKSymtabSection(SectionName))
1724 opts::LinuxKernelMode = true;
1727 // Set IsRelro section attribute based on PT_GNU_RELRO segment.
1728 markGnuRelroSections();
1730 if (HasDebugInfo && !opts::UpdateDebugSections && !opts::AggregateOnly) {
1731 errs() << "BOLT-WARNING: debug info will be stripped from the binary. "
1732 "Use -update-debug-sections to keep it.\n";
1735 HasTextRelocations = (bool)BC->getUniqueSectionByName(".rela.text");
1736 HasSymbolTable = (bool)BC->getUniqueSectionByName(".symtab");
1737 LSDASection = BC->getUniqueSectionByName(".gcc_except_table");
1738 EHFrameSection = BC->getUniqueSectionByName(".eh_frame");
1739 BuildIDSection = BC->getUniqueSectionByName(".note.gnu.build-id");
1741 if (ErrorOr<BinarySection &> BATSec =
1742 BC->getUniqueSectionByName(BoltAddressTranslation::SECTION_NAME)) {
1743 // Do not read BAT when plotting a heatmap
1744 if (!opts::HeatmapMode) {
1745 if (std::error_code EC = BAT->parse(BATSec->getContents())) {
1746 errs() << "BOLT-ERROR: failed to parse BOLT address translation "
1747 "table.\n";
1748 exit(1);
1753 if (opts::PrintSections) {
1754 outs() << "BOLT-INFO: Sections from original binary:\n";
1755 BC->printSections(outs());
1758 if (opts::RelocationMode == cl::BOU_TRUE && !HasTextRelocations) {
1759 errs() << "BOLT-ERROR: relocations against code are missing from the input "
1760 "file. Cannot proceed in relocations mode (-relocs).\n";
1761 exit(1);
1764 BC->HasRelocations =
1765 HasTextRelocations && (opts::RelocationMode != cl::BOU_FALSE);
1767 BC->IsStripped = !HasSymbolTable;
1769 if (BC->IsStripped && !opts::AllowStripped) {
1770 errs() << "BOLT-ERROR: stripped binaries are not supported. If you know "
1771 "what you're doing, use --allow-stripped to proceed";
1772 exit(1);
1775 // Force non-relocation mode for heatmap generation
1776 if (opts::HeatmapMode)
1777 BC->HasRelocations = false;
1779 if (BC->HasRelocations)
1780 outs() << "BOLT-INFO: enabling " << (opts::StrictMode ? "strict " : "")
1781 << "relocation mode\n";
1783 // Read EH frame for function boundaries info.
1784 Expected<const DWARFDebugFrame *> EHFrameOrError = BC->DwCtx->getEHFrame();
1785 if (!EHFrameOrError)
1786 report_error("expected valid eh_frame section", EHFrameOrError.takeError());
1787 CFIRdWrt.reset(new CFIReaderWriter(*EHFrameOrError.get()));
1789 // Parse build-id
1790 parseBuildID();
1791 if (std::optional<std::string> FileBuildID = getPrintableBuildID())
1792 BC->setFileBuildID(*FileBuildID);
1794 // Read .dynamic/PT_DYNAMIC.
1795 return readELFDynamic();
1798 void RewriteInstance::adjustCommandLineOptions() {
1799 if (BC->isAArch64() && !BC->HasRelocations)
1800 errs() << "BOLT-WARNING: non-relocation mode for AArch64 is not fully "
1801 "supported\n";
1803 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary())
1804 RtLibrary->adjustCommandLineOptions(*BC);
1806 if (opts::AlignMacroOpFusion != MFT_NONE && !BC->isX86()) {
1807 outs() << "BOLT-INFO: disabling -align-macro-fusion on non-x86 platform\n";
1808 opts::AlignMacroOpFusion = MFT_NONE;
1811 if (BC->isX86() && BC->MAB->allowAutoPadding()) {
1812 if (!BC->HasRelocations) {
1813 errs() << "BOLT-ERROR: cannot apply mitigations for Intel JCC erratum in "
1814 "non-relocation mode\n";
1815 exit(1);
1817 outs() << "BOLT-WARNING: using mitigation for Intel JCC erratum, layout "
1818 "may take several minutes\n";
1819 opts::AlignMacroOpFusion = MFT_NONE;
1822 if (opts::AlignMacroOpFusion != MFT_NONE && !BC->HasRelocations) {
1823 outs() << "BOLT-INFO: disabling -align-macro-fusion in non-relocation "
1824 "mode\n";
1825 opts::AlignMacroOpFusion = MFT_NONE;
1828 if (opts::SplitEH && !BC->HasRelocations) {
1829 errs() << "BOLT-WARNING: disabling -split-eh in non-relocation mode\n";
1830 opts::SplitEH = false;
1833 if (opts::StrictMode && !BC->HasRelocations) {
1834 errs() << "BOLT-WARNING: disabling strict mode (-strict) in non-relocation "
1835 "mode\n";
1836 opts::StrictMode = false;
1839 if (BC->HasRelocations && opts::AggregateOnly &&
1840 !opts::StrictMode.getNumOccurrences()) {
1841 outs() << "BOLT-INFO: enabling strict relocation mode for aggregation "
1842 "purposes\n";
1843 opts::StrictMode = true;
1846 if (BC->isX86() && BC->HasRelocations &&
1847 opts::AlignMacroOpFusion == MFT_HOT && !ProfileReader) {
1848 outs() << "BOLT-INFO: enabling -align-macro-fusion=all since no profile "
1849 "was specified\n";
1850 opts::AlignMacroOpFusion = MFT_ALL;
1853 if (!BC->HasRelocations &&
1854 opts::ReorderFunctions != ReorderFunctions::RT_NONE) {
1855 errs() << "BOLT-ERROR: function reordering only works when "
1856 << "relocations are enabled\n";
1857 exit(1);
1860 if (opts::Instrument ||
1861 (opts::ReorderFunctions != ReorderFunctions::RT_NONE &&
1862 !opts::HotText.getNumOccurrences())) {
1863 opts::HotText = true;
1864 } else if (opts::HotText && !BC->HasRelocations) {
1865 errs() << "BOLT-WARNING: hot text is disabled in non-relocation mode\n";
1866 opts::HotText = false;
1869 if (opts::HotText && opts::HotTextMoveSections.getNumOccurrences() == 0) {
1870 opts::HotTextMoveSections.addValue(".stub");
1871 opts::HotTextMoveSections.addValue(".mover");
1872 opts::HotTextMoveSections.addValue(".never_hugify");
1875 if (opts::UseOldText && !BC->OldTextSectionAddress) {
1876 errs() << "BOLT-WARNING: cannot use old .text as the section was not found"
1877 "\n";
1878 opts::UseOldText = false;
1880 if (opts::UseOldText && !BC->HasRelocations) {
1881 errs() << "BOLT-WARNING: cannot use old .text in non-relocation mode\n";
1882 opts::UseOldText = false;
1885 if (!opts::AlignText.getNumOccurrences())
1886 opts::AlignText = BC->PageAlign;
1888 if (opts::AlignText < opts::AlignFunctions)
1889 opts::AlignText = (unsigned)opts::AlignFunctions;
1891 if (BC->isX86() && opts::Lite.getNumOccurrences() == 0 && !opts::StrictMode &&
1892 !opts::UseOldText)
1893 opts::Lite = true;
1895 if (opts::Lite && opts::UseOldText) {
1896 errs() << "BOLT-WARNING: cannot combine -lite with -use-old-text. "
1897 "Disabling -use-old-text.\n";
1898 opts::UseOldText = false;
1901 if (opts::Lite && opts::StrictMode) {
1902 errs() << "BOLT-ERROR: -strict and -lite cannot be used at the same time\n";
1903 exit(1);
1906 if (opts::Lite)
1907 outs() << "BOLT-INFO: enabling lite mode\n";
1909 if (!opts::SaveProfile.empty() && BAT->enabledFor(InputFile)) {
1910 errs() << "BOLT-ERROR: unable to save profile in YAML format for input "
1911 "file processed by BOLT. Please remove -w option and use branch "
1912 "profile.\n";
1913 exit(1);
1917 namespace {
1918 template <typename ELFT>
1919 int64_t getRelocationAddend(const ELFObjectFile<ELFT> *Obj,
1920 const RelocationRef &RelRef) {
1921 using ELFShdrTy = typename ELFT::Shdr;
1922 using Elf_Rela = typename ELFT::Rela;
1923 int64_t Addend = 0;
1924 const ELFFile<ELFT> &EF = Obj->getELFFile();
1925 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1926 const ELFShdrTy *RelocationSection = cantFail(EF.getSection(Rel.d.a));
1927 switch (RelocationSection->sh_type) {
1928 default:
1929 llvm_unreachable("unexpected relocation section type");
1930 case ELF::SHT_REL:
1931 break;
1932 case ELF::SHT_RELA: {
1933 const Elf_Rela *RelA = Obj->getRela(Rel);
1934 Addend = RelA->r_addend;
1935 break;
1939 return Addend;
1942 int64_t getRelocationAddend(const ELFObjectFileBase *Obj,
1943 const RelocationRef &Rel) {
1944 return getRelocationAddend(cast<ELF64LEObjectFile>(Obj), Rel);
1947 template <typename ELFT>
1948 uint32_t getRelocationSymbol(const ELFObjectFile<ELFT> *Obj,
1949 const RelocationRef &RelRef) {
1950 using ELFShdrTy = typename ELFT::Shdr;
1951 uint32_t Symbol = 0;
1952 const ELFFile<ELFT> &EF = Obj->getELFFile();
1953 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1954 const ELFShdrTy *RelocationSection = cantFail(EF.getSection(Rel.d.a));
1955 switch (RelocationSection->sh_type) {
1956 default:
1957 llvm_unreachable("unexpected relocation section type");
1958 case ELF::SHT_REL:
1959 Symbol = Obj->getRel(Rel)->getSymbol(EF.isMips64EL());
1960 break;
1961 case ELF::SHT_RELA:
1962 Symbol = Obj->getRela(Rel)->getSymbol(EF.isMips64EL());
1963 break;
1966 return Symbol;
1969 uint32_t getRelocationSymbol(const ELFObjectFileBase *Obj,
1970 const RelocationRef &Rel) {
1971 return getRelocationSymbol(cast<ELF64LEObjectFile>(Obj), Rel);
1973 } // anonymous namespace
1975 bool RewriteInstance::analyzeRelocation(
1976 const RelocationRef &Rel, uint64_t &RType, std::string &SymbolName,
1977 bool &IsSectionRelocation, uint64_t &SymbolAddress, int64_t &Addend,
1978 uint64_t &ExtractedValue, bool &Skip) const {
1979 Skip = false;
1980 if (!Relocation::isSupported(RType))
1981 return false;
1983 const bool IsAArch64 = BC->isAArch64();
1985 const size_t RelSize = Relocation::getSizeForType(RType);
1987 ErrorOr<uint64_t> Value =
1988 BC->getUnsignedValueAtAddress(Rel.getOffset(), RelSize);
1989 assert(Value && "failed to extract relocated value");
1990 if ((Skip = Relocation::skipRelocationProcess(RType, *Value)))
1991 return true;
1993 ExtractedValue = Relocation::extractValue(RType, *Value, Rel.getOffset());
1994 Addend = getRelocationAddend(InputFile, Rel);
1996 const bool IsPCRelative = Relocation::isPCRelative(RType);
1997 const uint64_t PCRelOffset = IsPCRelative && !IsAArch64 ? Rel.getOffset() : 0;
1998 bool SkipVerification = false;
1999 auto SymbolIter = Rel.getSymbol();
2000 if (SymbolIter == InputFile->symbol_end()) {
2001 SymbolAddress = ExtractedValue - Addend + PCRelOffset;
2002 MCSymbol *RelSymbol =
2003 BC->getOrCreateGlobalSymbol(SymbolAddress, "RELSYMat");
2004 SymbolName = std::string(RelSymbol->getName());
2005 IsSectionRelocation = false;
2006 } else {
2007 const SymbolRef &Symbol = *SymbolIter;
2008 SymbolName = std::string(cantFail(Symbol.getName()));
2009 SymbolAddress = cantFail(Symbol.getAddress());
2010 SkipVerification = (cantFail(Symbol.getType()) == SymbolRef::ST_Other);
2011 // Section symbols are marked as ST_Debug.
2012 IsSectionRelocation = (cantFail(Symbol.getType()) == SymbolRef::ST_Debug);
2013 // Check for PLT entry registered with symbol name
2014 if (!SymbolAddress && (IsAArch64 || BC->isRISCV())) {
2015 const BinaryData *BD = BC->getPLTBinaryDataByName(SymbolName);
2016 SymbolAddress = BD ? BD->getAddress() : 0;
2019 // For PIE or dynamic libs, the linker may choose not to put the relocation
2020 // result at the address if it is a X86_64_64 one because it will emit a
2021 // dynamic relocation (X86_RELATIVE) for the dynamic linker and loader to
2022 // resolve it at run time. The static relocation result goes as the addend
2023 // of the dynamic relocation in this case. We can't verify these cases.
2024 // FIXME: perhaps we can try to find if it really emitted a corresponding
2025 // RELATIVE relocation at this offset with the correct value as the addend.
2026 if (!BC->HasFixedLoadAddress && RelSize == 8)
2027 SkipVerification = true;
2029 if (IsSectionRelocation && !IsAArch64) {
2030 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(SymbolAddress);
2031 assert(Section && "section expected for section relocation");
2032 SymbolName = "section " + std::string(Section->getName());
2033 // Convert section symbol relocations to regular relocations inside
2034 // non-section symbols.
2035 if (Section->containsAddress(ExtractedValue) && !IsPCRelative) {
2036 SymbolAddress = ExtractedValue;
2037 Addend = 0;
2038 } else {
2039 Addend = ExtractedValue - (SymbolAddress - PCRelOffset);
2043 // If no symbol has been found or if it is a relocation requiring the
2044 // creation of a GOT entry, do not link against the symbol but against
2045 // whatever address was extracted from the instruction itself. We are
2046 // not creating a GOT entry as this was already processed by the linker.
2047 // For GOT relocs, do not subtract addend as the addend does not refer
2048 // to this instruction's target, but it refers to the target in the GOT
2049 // entry.
2050 if (Relocation::isGOT(RType)) {
2051 Addend = 0;
2052 SymbolAddress = ExtractedValue + PCRelOffset;
2053 } else if (Relocation::isTLS(RType)) {
2054 SkipVerification = true;
2055 } else if (!SymbolAddress) {
2056 assert(!IsSectionRelocation);
2057 if (ExtractedValue || Addend == 0 || IsPCRelative) {
2058 SymbolAddress =
2059 truncateToSize(ExtractedValue - Addend + PCRelOffset, RelSize);
2060 } else {
2061 // This is weird case. The extracted value is zero but the addend is
2062 // non-zero and the relocation is not pc-rel. Using the previous logic,
2063 // the SymbolAddress would end up as a huge number. Seen in
2064 // exceptions_pic.test.
2065 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: relocation @ 0x"
2066 << Twine::utohexstr(Rel.getOffset())
2067 << " value does not match addend for "
2068 << "relocation to undefined symbol.\n");
2069 return true;
2073 auto verifyExtractedValue = [&]() {
2074 if (SkipVerification)
2075 return true;
2077 if (IsAArch64 || BC->isRISCV())
2078 return true;
2080 if (SymbolName == "__hot_start" || SymbolName == "__hot_end")
2081 return true;
2083 if (RType == ELF::R_X86_64_PLT32)
2084 return true;
2086 return truncateToSize(ExtractedValue, RelSize) ==
2087 truncateToSize(SymbolAddress + Addend - PCRelOffset, RelSize);
2090 (void)verifyExtractedValue;
2091 assert(verifyExtractedValue() && "mismatched extracted relocation value");
2093 return true;
2096 void RewriteInstance::processDynamicRelocations() {
2097 // Read .relr.dyn section containing compressed R_*_RELATIVE relocations.
2098 if (DynamicRelrSize > 0) {
2099 ErrorOr<BinarySection &> DynamicRelrSectionOrErr =
2100 BC->getSectionForAddress(*DynamicRelrAddress);
2101 if (!DynamicRelrSectionOrErr)
2102 report_error("unable to find section corresponding to DT_RELR",
2103 DynamicRelrSectionOrErr.getError());
2104 if (DynamicRelrSectionOrErr->getSize() != DynamicRelrSize)
2105 report_error("section size mismatch for DT_RELRSZ",
2106 errc::executable_format_error);
2107 readDynamicRelrRelocations(*DynamicRelrSectionOrErr);
2110 // Read relocations for PLT - DT_JMPREL.
2111 if (PLTRelocationsSize > 0) {
2112 ErrorOr<BinarySection &> PLTRelSectionOrErr =
2113 BC->getSectionForAddress(*PLTRelocationsAddress);
2114 if (!PLTRelSectionOrErr)
2115 report_error("unable to find section corresponding to DT_JMPREL",
2116 PLTRelSectionOrErr.getError());
2117 if (PLTRelSectionOrErr->getSize() != PLTRelocationsSize)
2118 report_error("section size mismatch for DT_PLTRELSZ",
2119 errc::executable_format_error);
2120 readDynamicRelocations(PLTRelSectionOrErr->getSectionRef(),
2121 /*IsJmpRel*/ true);
2124 // The rest of dynamic relocations - DT_RELA.
2125 if (DynamicRelocationsSize > 0) {
2126 ErrorOr<BinarySection &> DynamicRelSectionOrErr =
2127 BC->getSectionForAddress(*DynamicRelocationsAddress);
2128 if (!DynamicRelSectionOrErr)
2129 report_error("unable to find section corresponding to DT_RELA",
2130 DynamicRelSectionOrErr.getError());
2131 auto DynamicRelSectionSize = DynamicRelSectionOrErr->getSize();
2132 // On RISC-V DT_RELASZ seems to include both .rela.dyn and .rela.plt
2133 if (DynamicRelocationsSize == DynamicRelSectionSize + PLTRelocationsSize)
2134 DynamicRelocationsSize = DynamicRelSectionSize;
2135 if (DynamicRelSectionSize != DynamicRelocationsSize)
2136 report_error("section size mismatch for DT_RELASZ",
2137 errc::executable_format_error);
2138 readDynamicRelocations(DynamicRelSectionOrErr->getSectionRef(),
2139 /*IsJmpRel*/ false);
2143 void RewriteInstance::processRelocations() {
2144 if (!BC->HasRelocations)
2145 return;
2147 for (const SectionRef &Section : InputFile->sections()) {
2148 if (cantFail(Section.getRelocatedSection()) != InputFile->section_end() &&
2149 !BinarySection(*BC, Section).isAllocatable())
2150 readRelocations(Section);
2153 if (NumFailedRelocations)
2154 errs() << "BOLT-WARNING: Failed to analyze " << NumFailedRelocations
2155 << " relocations\n";
2158 void RewriteInstance::readDynamicRelocations(const SectionRef &Section,
2159 bool IsJmpRel) {
2160 assert(BinarySection(*BC, Section).isAllocatable() && "allocatable expected");
2162 LLVM_DEBUG({
2163 StringRef SectionName = cantFail(Section.getName());
2164 dbgs() << "BOLT-DEBUG: reading relocations for section " << SectionName
2165 << ":\n";
2168 for (const RelocationRef &Rel : Section.relocations()) {
2169 const uint64_t RType = Rel.getType();
2170 if (Relocation::isNone(RType))
2171 continue;
2173 StringRef SymbolName = "<none>";
2174 MCSymbol *Symbol = nullptr;
2175 uint64_t SymbolAddress = 0;
2176 const uint64_t Addend = getRelocationAddend(InputFile, Rel);
2178 symbol_iterator SymbolIter = Rel.getSymbol();
2179 if (SymbolIter != InputFile->symbol_end()) {
2180 SymbolName = cantFail(SymbolIter->getName());
2181 BinaryData *BD = BC->getBinaryDataByName(SymbolName);
2182 Symbol = BD ? BD->getSymbol()
2183 : BC->getOrCreateUndefinedGlobalSymbol(SymbolName);
2184 SymbolAddress = cantFail(SymbolIter->getAddress());
2185 (void)SymbolAddress;
2188 LLVM_DEBUG(
2189 SmallString<16> TypeName;
2190 Rel.getTypeName(TypeName);
2191 dbgs() << "BOLT-DEBUG: dynamic relocation at 0x"
2192 << Twine::utohexstr(Rel.getOffset()) << " : " << TypeName
2193 << " : " << SymbolName << " : " << Twine::utohexstr(SymbolAddress)
2194 << " : + 0x" << Twine::utohexstr(Addend) << '\n'
2197 if (IsJmpRel)
2198 IsJmpRelocation[RType] = true;
2200 if (Symbol)
2201 SymbolIndex[Symbol] = getRelocationSymbol(InputFile, Rel);
2203 BC->addDynamicRelocation(Rel.getOffset(), Symbol, RType, Addend);
2207 void RewriteInstance::readDynamicRelrRelocations(BinarySection &Section) {
2208 assert(Section.isAllocatable() && "allocatable expected");
2210 LLVM_DEBUG({
2211 StringRef SectionName = Section.getName();
2212 dbgs() << "BOLT-DEBUG: reading relocations in section " << SectionName
2213 << ":\n";
2216 const uint64_t RType = Relocation::getRelative();
2217 const uint8_t PSize = BC->AsmInfo->getCodePointerSize();
2218 const uint64_t MaxDelta = ((CHAR_BIT * DynamicRelrEntrySize) - 1) * PSize;
2220 auto ExtractAddendValue = [&](uint64_t Address) -> uint64_t {
2221 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(Address);
2222 assert(Section && "cannot get section for data address from RELR");
2223 DataExtractor DE = DataExtractor(Section->getContents(),
2224 BC->AsmInfo->isLittleEndian(), PSize);
2225 uint64_t Offset = Address - Section->getAddress();
2226 return DE.getUnsigned(&Offset, PSize);
2229 auto AddRelocation = [&](uint64_t Address) {
2230 uint64_t Addend = ExtractAddendValue(Address);
2231 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: R_*_RELATIVE relocation at 0x"
2232 << Twine::utohexstr(Address) << " to 0x"
2233 << Twine::utohexstr(Addend) << '\n';);
2234 BC->addDynamicRelocation(Address, nullptr, RType, Addend);
2237 DataExtractor DE = DataExtractor(Section.getContents(),
2238 BC->AsmInfo->isLittleEndian(), PSize);
2239 uint64_t Offset = 0, Address = 0;
2240 uint64_t RelrCount = DynamicRelrSize / DynamicRelrEntrySize;
2241 while (RelrCount--) {
2242 assert(DE.isValidOffset(Offset));
2243 uint64_t Entry = DE.getUnsigned(&Offset, DynamicRelrEntrySize);
2244 if ((Entry & 1) == 0) {
2245 AddRelocation(Entry);
2246 Address = Entry + PSize;
2247 } else {
2248 const uint64_t StartAddress = Address;
2249 while (Entry >>= 1) {
2250 if (Entry & 1)
2251 AddRelocation(Address);
2253 Address += PSize;
2256 Address = StartAddress + MaxDelta;
2261 void RewriteInstance::printRelocationInfo(const RelocationRef &Rel,
2262 StringRef SymbolName,
2263 uint64_t SymbolAddress,
2264 uint64_t Addend,
2265 uint64_t ExtractedValue) const {
2266 SmallString<16> TypeName;
2267 Rel.getTypeName(TypeName);
2268 const uint64_t Address = SymbolAddress + Addend;
2269 const uint64_t Offset = Rel.getOffset();
2270 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(SymbolAddress);
2271 BinaryFunction *Func =
2272 BC->getBinaryFunctionContainingAddress(Offset, false, BC->isAArch64());
2273 dbgs() << formatv("Relocation: offset = {0:x}; type = {1}; value = {2:x}; ",
2274 Offset, TypeName, ExtractedValue)
2275 << formatv("symbol = {0} ({1}); symbol address = {2:x}; ", SymbolName,
2276 Section ? Section->getName() : "", SymbolAddress)
2277 << formatv("addend = {0:x}; address = {1:x}; in = ", Addend, Address);
2278 if (Func)
2279 dbgs() << Func->getPrintName();
2280 else
2281 dbgs() << BC->getSectionForAddress(Rel.getOffset())->getName();
2282 dbgs() << '\n';
2285 void RewriteInstance::readRelocations(const SectionRef &Section) {
2286 LLVM_DEBUG({
2287 StringRef SectionName = cantFail(Section.getName());
2288 dbgs() << "BOLT-DEBUG: reading relocations for section " << SectionName
2289 << ":\n";
2291 if (BinarySection(*BC, Section).isAllocatable()) {
2292 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring runtime relocations\n");
2293 return;
2295 section_iterator SecIter = cantFail(Section.getRelocatedSection());
2296 assert(SecIter != InputFile->section_end() && "relocated section expected");
2297 SectionRef RelocatedSection = *SecIter;
2299 StringRef RelocatedSectionName = cantFail(RelocatedSection.getName());
2300 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: relocated section is "
2301 << RelocatedSectionName << '\n');
2303 if (!BinarySection(*BC, RelocatedSection).isAllocatable()) {
2304 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring relocations against "
2305 << "non-allocatable section\n");
2306 return;
2308 const bool SkipRelocs = StringSwitch<bool>(RelocatedSectionName)
2309 .Cases(".plt", ".rela.plt", ".got.plt",
2310 ".eh_frame", ".gcc_except_table", true)
2311 .Default(false);
2312 if (SkipRelocs) {
2313 LLVM_DEBUG(
2314 dbgs() << "BOLT-DEBUG: ignoring relocations against known section\n");
2315 return;
2318 for (const RelocationRef &Rel : Section.relocations())
2319 handleRelocation(RelocatedSection, Rel);
2322 void RewriteInstance::handleRelocation(const SectionRef &RelocatedSection,
2323 const RelocationRef &Rel) {
2324 const bool IsAArch64 = BC->isAArch64();
2325 const bool IsFromCode = RelocatedSection.isText();
2327 SmallString<16> TypeName;
2328 Rel.getTypeName(TypeName);
2329 uint64_t RType = Rel.getType();
2330 if (Relocation::skipRelocationType(RType))
2331 return;
2333 // Adjust the relocation type as the linker might have skewed it.
2334 if (BC->isX86() && (RType & ELF::R_X86_64_converted_reloc_bit)) {
2335 if (opts::Verbosity >= 1)
2336 dbgs() << "BOLT-WARNING: ignoring R_X86_64_converted_reloc_bit\n";
2337 RType &= ~ELF::R_X86_64_converted_reloc_bit;
2340 if (Relocation::isTLS(RType)) {
2341 // No special handling required for TLS relocations on X86.
2342 if (BC->isX86())
2343 return;
2345 // The non-got related TLS relocations on AArch64 and RISC-V also could be
2346 // skipped.
2347 if (!Relocation::isGOT(RType))
2348 return;
2351 if (!IsAArch64 && BC->getDynamicRelocationAt(Rel.getOffset())) {
2352 LLVM_DEBUG({
2353 dbgs() << formatv("BOLT-DEBUG: address {0:x} has a ", Rel.getOffset())
2354 << "dynamic relocation against it. Ignoring static relocation.\n";
2356 return;
2359 std::string SymbolName;
2360 uint64_t SymbolAddress;
2361 int64_t Addend;
2362 uint64_t ExtractedValue;
2363 bool IsSectionRelocation;
2364 bool Skip;
2365 if (!analyzeRelocation(Rel, RType, SymbolName, IsSectionRelocation,
2366 SymbolAddress, Addend, ExtractedValue, Skip)) {
2367 LLVM_DEBUG({
2368 dbgs() << "BOLT-WARNING: failed to analyze relocation @ offset = "
2369 << formatv("{0:x}; type name = {1}\n", Rel.getOffset(), TypeName);
2371 ++NumFailedRelocations;
2372 return;
2375 if (Skip) {
2376 LLVM_DEBUG({
2377 dbgs() << "BOLT-DEBUG: skipping relocation @ offset = "
2378 << formatv("{0:x}; type name = {1}\n", Rel.getOffset(), TypeName);
2380 return;
2383 const uint64_t Address = SymbolAddress + Addend;
2385 LLVM_DEBUG({
2386 dbgs() << "BOLT-DEBUG: ";
2387 printRelocationInfo(Rel, SymbolName, SymbolAddress, Addend, ExtractedValue);
2390 BinaryFunction *ContainingBF = nullptr;
2391 if (IsFromCode) {
2392 ContainingBF =
2393 BC->getBinaryFunctionContainingAddress(Rel.getOffset(),
2394 /*CheckPastEnd*/ false,
2395 /*UseMaxSize*/ true);
2396 assert(ContainingBF && "cannot find function for address in code");
2397 if (!IsAArch64 && !ContainingBF->containsAddress(Rel.getOffset())) {
2398 if (opts::Verbosity >= 1)
2399 outs() << formatv("BOLT-INFO: {0} has relocations in padding area\n",
2400 *ContainingBF);
2401 ContainingBF->setSize(ContainingBF->getMaxSize());
2402 ContainingBF->setSimple(false);
2403 return;
2407 MCSymbol *ReferencedSymbol = nullptr;
2408 if (!IsSectionRelocation) {
2409 if (BinaryData *BD = BC->getBinaryDataByName(SymbolName))
2410 ReferencedSymbol = BD->getSymbol();
2411 else if (BC->isGOTSymbol(SymbolName))
2412 if (BinaryData *BD = BC->getGOTSymbol())
2413 ReferencedSymbol = BD->getSymbol();
2416 ErrorOr<BinarySection &> ReferencedSection{std::errc::bad_address};
2417 symbol_iterator SymbolIter = Rel.getSymbol();
2418 if (SymbolIter != InputFile->symbol_end()) {
2419 SymbolRef Symbol = *SymbolIter;
2420 section_iterator Section =
2421 cantFail(Symbol.getSection(), "cannot get symbol section");
2422 if (Section != InputFile->section_end()) {
2423 Expected<StringRef> SectionName = Section->getName();
2424 if (SectionName && !SectionName->empty())
2425 ReferencedSection = BC->getUniqueSectionByName(*SectionName);
2426 } else if (ReferencedSymbol &&
2427 (cantFail(Symbol.getFlags()) & SymbolRef::SF_Absolute)) {
2428 // This might be a relocation for an ABS symbols like __global_pointer$ on
2429 // RISC-V
2430 ContainingBF->addRelocation(Rel.getOffset(), ReferencedSymbol,
2431 Rel.getType(), 0,
2432 cantFail(Symbol.getValue()));
2433 return;
2437 if (!ReferencedSection)
2438 ReferencedSection = BC->getSectionForAddress(SymbolAddress);
2440 const bool IsToCode = ReferencedSection && ReferencedSection->isText();
2442 // Special handling of PC-relative relocations.
2443 if (!IsAArch64 && !BC->isRISCV() && Relocation::isPCRelative(RType)) {
2444 if (!IsFromCode && IsToCode) {
2445 // PC-relative relocations from data to code are tricky since the
2446 // original information is typically lost after linking, even with
2447 // '--emit-relocs'. Such relocations are normally used by PIC-style
2448 // jump tables and they reference both the jump table and jump
2449 // targets by computing the difference between the two. If we blindly
2450 // apply the relocation, it will appear that it references an arbitrary
2451 // location in the code, possibly in a different function from the one
2452 // containing the jump table.
2454 // For that reason, we only register the fact that there is a
2455 // PC-relative relocation at a given address against the code.
2456 // The actual referenced label/address will be determined during jump
2457 // table analysis.
2458 BC->addPCRelativeDataRelocation(Rel.getOffset());
2459 } else if (ContainingBF && !IsSectionRelocation && ReferencedSymbol) {
2460 // If we know the referenced symbol, register the relocation from
2461 // the code. It's required to properly handle cases where
2462 // "symbol + addend" references an object different from "symbol".
2463 ContainingBF->addRelocation(Rel.getOffset(), ReferencedSymbol, RType,
2464 Addend, ExtractedValue);
2465 } else {
2466 LLVM_DEBUG({
2467 dbgs() << "BOLT-DEBUG: not creating PC-relative relocation at"
2468 << formatv("{0:x} for {1}\n", Rel.getOffset(), SymbolName);
2472 return;
2475 bool ForceRelocation = BC->forceSymbolRelocations(SymbolName);
2476 if ((BC->isAArch64() || BC->isRISCV()) && Relocation::isGOT(RType))
2477 ForceRelocation = true;
2479 if (!ReferencedSection && !ForceRelocation) {
2480 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: cannot determine referenced section.\n");
2481 return;
2484 // Occasionally we may see a reference past the last byte of the function
2485 // typically as a result of __builtin_unreachable(). Check it here.
2486 BinaryFunction *ReferencedBF = BC->getBinaryFunctionContainingAddress(
2487 Address, /*CheckPastEnd*/ true, /*UseMaxSize*/ IsAArch64);
2489 if (!IsSectionRelocation) {
2490 if (BinaryFunction *BF =
2491 BC->getBinaryFunctionContainingAddress(SymbolAddress)) {
2492 if (BF != ReferencedBF) {
2493 // It's possible we are referencing a function without referencing any
2494 // code, e.g. when taking a bitmask action on a function address.
2495 errs() << "BOLT-WARNING: non-standard function reference (e.g. bitmask)"
2496 << formatv(" detected against function {0} from ", *BF);
2497 if (IsFromCode)
2498 errs() << formatv("function {0}\n", *ContainingBF);
2499 else
2500 errs() << formatv("data section at {0:x}\n", Rel.getOffset());
2501 LLVM_DEBUG(printRelocationInfo(Rel, SymbolName, SymbolAddress, Addend,
2502 ExtractedValue));
2503 ReferencedBF = BF;
2506 } else if (ReferencedBF) {
2507 assert(ReferencedSection && "section expected for section relocation");
2508 if (*ReferencedBF->getOriginSection() != *ReferencedSection) {
2509 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring false function reference\n");
2510 ReferencedBF = nullptr;
2514 // Workaround for a member function pointer de-virtualization bug. We check
2515 // if a non-pc-relative relocation in the code is pointing to (fptr - 1).
2516 if (IsToCode && ContainingBF && !Relocation::isPCRelative(RType) &&
2517 (!ReferencedBF || (ReferencedBF->getAddress() != Address))) {
2518 if (const BinaryFunction *RogueBF =
2519 BC->getBinaryFunctionAtAddress(Address + 1)) {
2520 // Do an extra check that the function was referenced previously.
2521 // It's a linear search, but it should rarely happen.
2522 auto CheckReloc = [&](const Relocation &Rel) {
2523 return Rel.Symbol == RogueBF->getSymbol() &&
2524 !Relocation::isPCRelative(Rel.Type);
2526 bool Found = llvm::any_of(
2527 llvm::make_second_range(ContainingBF->Relocations), CheckReloc);
2529 if (Found) {
2530 errs() << "BOLT-WARNING: detected possible compiler de-virtualization "
2531 "bug: -1 addend used with non-pc-relative relocation against "
2532 << formatv("function {0} in function {1}\n", *RogueBF,
2533 *ContainingBF);
2534 return;
2539 if (ForceRelocation) {
2540 std::string Name =
2541 Relocation::isGOT(RType) ? "__BOLT_got_zero" : SymbolName;
2542 ReferencedSymbol = BC->registerNameAtAddress(Name, 0, 0, 0);
2543 SymbolAddress = 0;
2544 if (Relocation::isGOT(RType))
2545 Addend = Address;
2546 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: forcing relocation against symbol "
2547 << SymbolName << " with addend " << Addend << '\n');
2548 } else if (ReferencedBF) {
2549 ReferencedSymbol = ReferencedBF->getSymbol();
2550 uint64_t RefFunctionOffset = 0;
2552 // Adjust the point of reference to a code location inside a function.
2553 if (ReferencedBF->containsAddress(Address, /*UseMaxSize = */ true)) {
2554 RefFunctionOffset = Address - ReferencedBF->getAddress();
2555 if (Relocation::isInstructionReference(RType)) {
2556 // Instruction labels are created while disassembling so we just leave
2557 // the symbol empty for now. Since the extracted value is typically
2558 // unrelated to the referenced symbol (e.g., %pcrel_lo in RISC-V
2559 // references an instruction but the patched value references the low
2560 // bits of a data address), we set the extracted value to the symbol
2561 // address in order to be able to correctly reconstruct the reference
2562 // later.
2563 ReferencedSymbol = nullptr;
2564 ExtractedValue = Address;
2565 } else if (RefFunctionOffset) {
2566 if (ContainingBF && ContainingBF != ReferencedBF) {
2567 ReferencedSymbol =
2568 ReferencedBF->addEntryPointAtOffset(RefFunctionOffset);
2569 } else {
2570 ReferencedSymbol =
2571 ReferencedBF->getOrCreateLocalLabel(Address,
2572 /*CreatePastEnd =*/true);
2574 // If ContainingBF != nullptr, it equals ReferencedBF (see
2575 // if-condition above) so we're handling a relocation from a function
2576 // to itself. RISC-V uses such relocations for branches, for example.
2577 // These should not be registered as externally references offsets.
2578 if (!ContainingBF)
2579 ReferencedBF->registerReferencedOffset(RefFunctionOffset);
2581 if (opts::Verbosity > 1 &&
2582 BinarySection(*BC, RelocatedSection).isWritable())
2583 errs() << "BOLT-WARNING: writable reference into the middle of the "
2584 << formatv("function {0} detected at address {1:x}\n",
2585 *ReferencedBF, Rel.getOffset());
2587 SymbolAddress = Address;
2588 Addend = 0;
2590 LLVM_DEBUG({
2591 dbgs() << " referenced function " << *ReferencedBF;
2592 if (Address != ReferencedBF->getAddress())
2593 dbgs() << formatv(" at offset {0:x}", RefFunctionOffset);
2594 dbgs() << '\n';
2596 } else {
2597 if (IsToCode && SymbolAddress) {
2598 // This can happen e.g. with PIC-style jump tables.
2599 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: no corresponding function for "
2600 "relocation against code\n");
2603 // In AArch64 there are zero reasons to keep a reference to the
2604 // "original" symbol plus addend. The original symbol is probably just a
2605 // section symbol. If we are here, this means we are probably accessing
2606 // data, so it is imperative to keep the original address.
2607 if (IsAArch64) {
2608 SymbolName = formatv("SYMBOLat{0:x}", Address);
2609 SymbolAddress = Address;
2610 Addend = 0;
2613 if (BinaryData *BD = BC->getBinaryDataContainingAddress(SymbolAddress)) {
2614 // Note: this assertion is trying to check sanity of BinaryData objects
2615 // but AArch64 has inferred and incomplete object locations coming from
2616 // GOT/TLS or any other non-trivial relocation (that requires creation
2617 // of sections and whose symbol address is not really what should be
2618 // encoded in the instruction). So we essentially disabled this check
2619 // for AArch64 and live with bogus names for objects.
2620 assert((IsAArch64 || IsSectionRelocation ||
2621 BD->nameStartsWith(SymbolName) ||
2622 BD->nameStartsWith("PG" + SymbolName) ||
2623 (BD->nameStartsWith("ANONYMOUS") &&
2624 (BD->getSectionName().startswith(".plt") ||
2625 BD->getSectionName().endswith(".plt")))) &&
2626 "BOLT symbol names of all non-section relocations must match up "
2627 "with symbol names referenced in the relocation");
2629 if (IsSectionRelocation)
2630 BC->markAmbiguousRelocations(*BD, Address);
2632 ReferencedSymbol = BD->getSymbol();
2633 Addend += (SymbolAddress - BD->getAddress());
2634 SymbolAddress = BD->getAddress();
2635 assert(Address == SymbolAddress + Addend);
2636 } else {
2637 // These are mostly local data symbols but undefined symbols
2638 // in relocation sections can get through here too, from .plt.
2639 assert(
2640 (IsAArch64 || BC->isRISCV() || IsSectionRelocation ||
2641 BC->getSectionNameForAddress(SymbolAddress)->startswith(".plt")) &&
2642 "known symbols should not resolve to anonymous locals");
2644 if (IsSectionRelocation) {
2645 ReferencedSymbol =
2646 BC->getOrCreateGlobalSymbol(SymbolAddress, "SYMBOLat");
2647 } else {
2648 SymbolRef Symbol = *Rel.getSymbol();
2649 const uint64_t SymbolSize =
2650 IsAArch64 ? 0 : ELFSymbolRef(Symbol).getSize();
2651 const uint64_t SymbolAlignment = IsAArch64 ? 1 : Symbol.getAlignment();
2652 const uint32_t SymbolFlags = cantFail(Symbol.getFlags());
2653 std::string Name;
2654 if (SymbolFlags & SymbolRef::SF_Global) {
2655 Name = SymbolName;
2656 } else {
2657 if (StringRef(SymbolName)
2658 .startswith(BC->AsmInfo->getPrivateGlobalPrefix()))
2659 Name = NR.uniquify("PG" + SymbolName);
2660 else
2661 Name = NR.uniquify(SymbolName);
2663 ReferencedSymbol = BC->registerNameAtAddress(
2664 Name, SymbolAddress, SymbolSize, SymbolAlignment, SymbolFlags);
2667 if (IsSectionRelocation) {
2668 BinaryData *BD = BC->getBinaryDataByName(ReferencedSymbol->getName());
2669 BC->markAmbiguousRelocations(*BD, Address);
2674 auto checkMaxDataRelocations = [&]() {
2675 ++NumDataRelocations;
2676 LLVM_DEBUG(if (opts::MaxDataRelocations &&
2677 NumDataRelocations + 1 == opts::MaxDataRelocations) {
2678 dbgs() << "BOLT-DEBUG: processing ending on data relocation "
2679 << NumDataRelocations << ": ";
2680 printRelocationInfo(Rel, ReferencedSymbol->getName(), SymbolAddress,
2681 Addend, ExtractedValue);
2684 return (!opts::MaxDataRelocations ||
2685 NumDataRelocations < opts::MaxDataRelocations);
2688 if ((ReferencedSection && refersToReorderedSection(ReferencedSection)) ||
2689 (opts::ForceToDataRelocations && checkMaxDataRelocations()) ||
2690 // RISC-V has ADD/SUB data-to-data relocations
2691 BC->isRISCV())
2692 ForceRelocation = true;
2694 if (IsFromCode) {
2695 ContainingBF->addRelocation(Rel.getOffset(), ReferencedSymbol, RType,
2696 Addend, ExtractedValue);
2697 } else if (IsToCode || ForceRelocation) {
2698 BC->addRelocation(Rel.getOffset(), ReferencedSymbol, RType, Addend,
2699 ExtractedValue);
2700 } else {
2701 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring relocation from data to data\n");
2705 void RewriteInstance::selectFunctionsToProcess() {
2706 // Extend the list of functions to process or skip from a file.
2707 auto populateFunctionNames = [](cl::opt<std::string> &FunctionNamesFile,
2708 cl::list<std::string> &FunctionNames) {
2709 if (FunctionNamesFile.empty())
2710 return;
2711 std::ifstream FuncsFile(FunctionNamesFile, std::ios::in);
2712 std::string FuncName;
2713 while (std::getline(FuncsFile, FuncName))
2714 FunctionNames.push_back(FuncName);
2716 populateFunctionNames(opts::FunctionNamesFile, opts::ForceFunctionNames);
2717 populateFunctionNames(opts::SkipFunctionNamesFile, opts::SkipFunctionNames);
2718 populateFunctionNames(opts::FunctionNamesFileNR, opts::ForceFunctionNamesNR);
2720 // Make a set of functions to process to speed up lookups.
2721 std::unordered_set<std::string> ForceFunctionsNR(
2722 opts::ForceFunctionNamesNR.begin(), opts::ForceFunctionNamesNR.end());
2724 if ((!opts::ForceFunctionNames.empty() ||
2725 !opts::ForceFunctionNamesNR.empty()) &&
2726 !opts::SkipFunctionNames.empty()) {
2727 errs() << "BOLT-ERROR: cannot select functions to process and skip at the "
2728 "same time. Please use only one type of selection.\n";
2729 exit(1);
2732 uint64_t LiteThresholdExecCount = 0;
2733 if (opts::LiteThresholdPct) {
2734 if (opts::LiteThresholdPct > 100)
2735 opts::LiteThresholdPct = 100;
2737 std::vector<const BinaryFunction *> TopFunctions;
2738 for (auto &BFI : BC->getBinaryFunctions()) {
2739 const BinaryFunction &Function = BFI.second;
2740 if (ProfileReader->mayHaveProfileData(Function))
2741 TopFunctions.push_back(&Function);
2743 llvm::sort(
2744 TopFunctions, [](const BinaryFunction *A, const BinaryFunction *B) {
2745 return A->getKnownExecutionCount() < B->getKnownExecutionCount();
2748 size_t Index = TopFunctions.size() * opts::LiteThresholdPct / 100;
2749 if (Index)
2750 --Index;
2751 LiteThresholdExecCount = TopFunctions[Index]->getKnownExecutionCount();
2752 outs() << "BOLT-INFO: limiting processing to functions with at least "
2753 << LiteThresholdExecCount << " invocations\n";
2755 LiteThresholdExecCount = std::max(
2756 LiteThresholdExecCount, static_cast<uint64_t>(opts::LiteThresholdCount));
2758 StringSet<> ReorderFunctionsUserSet;
2759 StringSet<> ReorderFunctionsLTOCommonSet;
2760 if (opts::ReorderFunctions == ReorderFunctions::RT_USER) {
2761 for (const std::string &Function :
2762 ReorderFunctions::readFunctionOrderFile()) {
2763 ReorderFunctionsUserSet.insert(Function);
2764 if (std::optional<StringRef> LTOCommonName = getLTOCommonName(Function))
2765 ReorderFunctionsLTOCommonSet.insert(*LTOCommonName);
2769 uint64_t NumFunctionsToProcess = 0;
2770 auto mustSkip = [&](const BinaryFunction &Function) {
2771 if (opts::MaxFunctions.getNumOccurrences() &&
2772 NumFunctionsToProcess >= opts::MaxFunctions)
2773 return true;
2774 for (std::string &Name : opts::SkipFunctionNames)
2775 if (Function.hasNameRegex(Name))
2776 return true;
2778 return false;
2781 auto shouldProcess = [&](const BinaryFunction &Function) {
2782 if (mustSkip(Function))
2783 return false;
2785 // If the list is not empty, only process functions from the list.
2786 if (!opts::ForceFunctionNames.empty() || !ForceFunctionsNR.empty()) {
2787 // Regex check (-funcs and -funcs-file options).
2788 for (std::string &Name : opts::ForceFunctionNames)
2789 if (Function.hasNameRegex(Name))
2790 return true;
2792 // Non-regex check (-funcs-no-regex and -funcs-file-no-regex).
2793 for (const StringRef Name : Function.getNames())
2794 if (ForceFunctionsNR.count(Name.str()))
2795 return true;
2797 return false;
2800 if (opts::Lite) {
2801 // Forcibly include functions specified in the -function-order file.
2802 if (opts::ReorderFunctions == ReorderFunctions::RT_USER) {
2803 for (const StringRef Name : Function.getNames())
2804 if (ReorderFunctionsUserSet.contains(Name))
2805 return true;
2806 for (const StringRef Name : Function.getNames())
2807 if (std::optional<StringRef> LTOCommonName = getLTOCommonName(Name))
2808 if (ReorderFunctionsLTOCommonSet.contains(*LTOCommonName))
2809 return true;
2812 if (ProfileReader && !ProfileReader->mayHaveProfileData(Function))
2813 return false;
2815 if (Function.getKnownExecutionCount() < LiteThresholdExecCount)
2816 return false;
2819 return true;
2822 for (auto &BFI : BC->getBinaryFunctions()) {
2823 BinaryFunction &Function = BFI.second;
2825 // Pseudo functions are explicitly marked by us not to be processed.
2826 if (Function.isPseudo()) {
2827 Function.IsIgnored = true;
2828 Function.HasExternalRefRelocations = true;
2829 continue;
2832 // Decide what to do with fragments after parent functions are processed.
2833 if (Function.isFragment())
2834 continue;
2836 if (!shouldProcess(Function)) {
2837 if (opts::Verbosity >= 1) {
2838 outs() << "BOLT-INFO: skipping processing " << Function
2839 << " per user request\n";
2841 Function.setIgnored();
2842 } else {
2843 ++NumFunctionsToProcess;
2844 if (opts::MaxFunctions.getNumOccurrences() &&
2845 NumFunctionsToProcess == opts::MaxFunctions)
2846 outs() << "BOLT-INFO: processing ending on " << Function << '\n';
2850 if (!BC->HasSplitFunctions)
2851 return;
2853 // Fragment overrides:
2854 // - If the fragment must be skipped, then the parent must be skipped as well.
2855 // Otherwise, fragment should follow the parent function:
2856 // - if the parent is skipped, skip fragment,
2857 // - if the parent is processed, process the fragment(s) as well.
2858 for (auto &BFI : BC->getBinaryFunctions()) {
2859 BinaryFunction &Function = BFI.second;
2860 if (!Function.isFragment())
2861 continue;
2862 if (mustSkip(Function)) {
2863 for (BinaryFunction *Parent : Function.ParentFragments) {
2864 if (opts::Verbosity >= 1) {
2865 outs() << "BOLT-INFO: skipping processing " << *Parent
2866 << " together with fragment function\n";
2868 Parent->setIgnored();
2869 --NumFunctionsToProcess;
2871 Function.setIgnored();
2872 continue;
2875 bool IgnoredParent =
2876 llvm::any_of(Function.ParentFragments, [&](BinaryFunction *Parent) {
2877 return Parent->isIgnored();
2879 if (IgnoredParent) {
2880 if (opts::Verbosity >= 1) {
2881 outs() << "BOLT-INFO: skipping processing " << Function
2882 << " together with parent function\n";
2884 Function.setIgnored();
2885 } else {
2886 ++NumFunctionsToProcess;
2887 if (opts::Verbosity >= 1) {
2888 outs() << "BOLT-INFO: processing " << Function
2889 << " as a sibling of non-ignored function\n";
2891 if (opts::MaxFunctions && NumFunctionsToProcess == opts::MaxFunctions)
2892 outs() << "BOLT-INFO: processing ending on " << Function << '\n';
2897 void RewriteInstance::readDebugInfo() {
2898 NamedRegionTimer T("readDebugInfo", "read debug info", TimerGroupName,
2899 TimerGroupDesc, opts::TimeRewrite);
2900 if (!opts::UpdateDebugSections)
2901 return;
2903 BC->preprocessDebugInfo();
2906 void RewriteInstance::preprocessProfileData() {
2907 if (!ProfileReader)
2908 return;
2910 NamedRegionTimer T("preprocessprofile", "pre-process profile data",
2911 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
2913 outs() << "BOLT-INFO: pre-processing profile using "
2914 << ProfileReader->getReaderName() << '\n';
2916 if (BAT->enabledFor(InputFile)) {
2917 outs() << "BOLT-INFO: profile collection done on a binary already "
2918 "processed by BOLT\n";
2919 ProfileReader->setBAT(&*BAT);
2922 if (Error E = ProfileReader->preprocessProfile(*BC.get()))
2923 report_error("cannot pre-process profile", std::move(E));
2925 if (!BC->hasSymbolsWithFileName() && ProfileReader->hasLocalsWithFileName()) {
2926 errs() << "BOLT-ERROR: input binary does not have local file symbols "
2927 "but profile data includes function names with embedded file "
2928 "names. It appears that the input binary was stripped while a "
2929 "profiled binary was not\n";
2930 exit(1);
2934 void RewriteInstance::initializeMetadataManager() {
2935 if (opts::LinuxKernelMode)
2936 MetadataManager.registerRewriter(createLinuxKernelRewriter(*BC));
2938 MetadataManager.registerRewriter(createPseudoProbeRewriter(*BC));
2940 MetadataManager.registerRewriter(createSDTRewriter(*BC));
2943 void RewriteInstance::processMetadataPreCFG() {
2944 initializeMetadataManager();
2946 MetadataManager.runInitializersPreCFG();
2948 processProfileDataPreCFG();
2951 void RewriteInstance::processMetadataPostCFG() {
2952 MetadataManager.runInitializersPostCFG();
2955 void RewriteInstance::processProfileDataPreCFG() {
2956 if (!ProfileReader)
2957 return;
2959 NamedRegionTimer T("processprofile-precfg", "process profile data pre-CFG",
2960 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
2962 if (Error E = ProfileReader->readProfilePreCFG(*BC.get()))
2963 report_error("cannot read profile pre-CFG", std::move(E));
2966 void RewriteInstance::processProfileData() {
2967 if (!ProfileReader)
2968 return;
2970 NamedRegionTimer T("processprofile", "process profile data", TimerGroupName,
2971 TimerGroupDesc, opts::TimeRewrite);
2973 if (Error E = ProfileReader->readProfile(*BC.get()))
2974 report_error("cannot read profile", std::move(E));
2976 if (opts::PrintProfile || opts::PrintAll) {
2977 for (auto &BFI : BC->getBinaryFunctions()) {
2978 BinaryFunction &Function = BFI.second;
2979 if (Function.empty())
2980 continue;
2982 Function.print(outs(), "after attaching profile");
2986 if (!opts::SaveProfile.empty()) {
2987 YAMLProfileWriter PW(opts::SaveProfile);
2988 PW.writeProfile(*this);
2990 if (opts::AggregateOnly &&
2991 opts::ProfileFormat == opts::ProfileFormatKind::PF_YAML) {
2992 YAMLProfileWriter PW(opts::OutputFilename);
2993 PW.writeProfile(*this);
2996 // Release memory used by profile reader.
2997 ProfileReader.reset();
2999 if (opts::AggregateOnly)
3000 exit(0);
3003 void RewriteInstance::disassembleFunctions() {
3004 NamedRegionTimer T("disassembleFunctions", "disassemble functions",
3005 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3006 for (auto &BFI : BC->getBinaryFunctions()) {
3007 BinaryFunction &Function = BFI.second;
3009 ErrorOr<ArrayRef<uint8_t>> FunctionData = Function.getData();
3010 if (!FunctionData) {
3011 errs() << "BOLT-ERROR: corresponding section is non-executable or "
3012 << "empty for function " << Function << '\n';
3013 exit(1);
3016 // Treat zero-sized functions as non-simple ones.
3017 if (Function.getSize() == 0) {
3018 Function.setSimple(false);
3019 continue;
3022 // Offset of the function in the file.
3023 const auto *FileBegin =
3024 reinterpret_cast<const uint8_t *>(InputFile->getData().data());
3025 Function.setFileOffset(FunctionData->begin() - FileBegin);
3027 if (!shouldDisassemble(Function)) {
3028 NamedRegionTimer T("scan", "scan functions", "buildfuncs",
3029 "Scan Binary Functions", opts::TimeBuild);
3030 Function.scanExternalRefs();
3031 Function.setSimple(false);
3032 continue;
3035 if (!Function.disassemble()) {
3036 if (opts::processAllFunctions())
3037 BC->exitWithBugReport("function cannot be properly disassembled. "
3038 "Unable to continue in relocation mode.",
3039 Function);
3040 if (opts::Verbosity >= 1)
3041 outs() << "BOLT-INFO: could not disassemble function " << Function
3042 << ". Will ignore.\n";
3043 // Forcefully ignore the function.
3044 Function.setIgnored();
3045 continue;
3048 if (opts::PrintAll || opts::PrintDisasm)
3049 Function.print(outs(), "after disassembly");
3052 BC->processInterproceduralReferences();
3053 BC->populateJumpTables();
3055 for (auto &BFI : BC->getBinaryFunctions()) {
3056 BinaryFunction &Function = BFI.second;
3058 if (!shouldDisassemble(Function))
3059 continue;
3061 Function.postProcessEntryPoints();
3062 Function.postProcessJumpTables();
3065 BC->clearJumpTableTempData();
3066 BC->adjustCodePadding();
3068 for (auto &BFI : BC->getBinaryFunctions()) {
3069 BinaryFunction &Function = BFI.second;
3071 if (!shouldDisassemble(Function))
3072 continue;
3074 if (!Function.isSimple()) {
3075 assert((!BC->HasRelocations || Function.getSize() == 0 ||
3076 Function.hasIndirectTargetToSplitFragment()) &&
3077 "unexpected non-simple function in relocation mode");
3078 continue;
3081 // Fill in CFI information for this function
3082 if (!Function.trapsOnEntry() && !CFIRdWrt->fillCFIInfoFor(Function)) {
3083 if (BC->HasRelocations) {
3084 BC->exitWithBugReport("unable to fill CFI.", Function);
3085 } else {
3086 errs() << "BOLT-WARNING: unable to fill CFI for function " << Function
3087 << ". Skipping.\n";
3088 Function.setSimple(false);
3089 continue;
3093 // Parse LSDA.
3094 if (Function.getLSDAAddress() != 0 &&
3095 !BC->getFragmentsToSkip().count(&Function))
3096 Function.parseLSDA(getLSDAData(), getLSDAAddress());
3100 void RewriteInstance::buildFunctionsCFG() {
3101 NamedRegionTimer T("buildCFG", "buildCFG", "buildfuncs",
3102 "Build Binary Functions", opts::TimeBuild);
3104 // Create annotation indices to allow lock-free execution
3105 BC->MIB->getOrCreateAnnotationIndex("JTIndexReg");
3106 BC->MIB->getOrCreateAnnotationIndex("NOP");
3107 BC->MIB->getOrCreateAnnotationIndex("Size");
3109 ParallelUtilities::WorkFuncWithAllocTy WorkFun =
3110 [&](BinaryFunction &BF, MCPlusBuilder::AllocatorIdTy AllocId) {
3111 if (!BF.buildCFG(AllocId))
3112 return;
3114 if (opts::PrintAll) {
3115 auto L = BC->scopeLock();
3116 BF.print(outs(), "while building cfg");
3120 ParallelUtilities::PredicateTy SkipPredicate = [&](const BinaryFunction &BF) {
3121 return !shouldDisassemble(BF) || !BF.isSimple();
3124 ParallelUtilities::runOnEachFunctionWithUniqueAllocId(
3125 *BC, ParallelUtilities::SchedulingPolicy::SP_INST_LINEAR, WorkFun,
3126 SkipPredicate, "disassembleFunctions-buildCFG",
3127 /*ForceSequential*/ opts::SequentialDisassembly || opts::PrintAll);
3129 BC->postProcessSymbolTable();
3132 void RewriteInstance::postProcessFunctions() {
3133 // We mark fragments as non-simple here, not during disassembly,
3134 // So we can build their CFGs.
3135 BC->skipMarkedFragments();
3136 BC->clearFragmentsToSkip();
3138 BC->TotalScore = 0;
3139 BC->SumExecutionCount = 0;
3140 for (auto &BFI : BC->getBinaryFunctions()) {
3141 BinaryFunction &Function = BFI.second;
3143 // Set function as non-simple if it has dynamic relocations
3144 // in constant island, we don't want this function to be optimized
3145 // e.g. function splitting is unsupported.
3146 if (Function.hasDynamicRelocationAtIsland())
3147 Function.setSimple(false);
3149 if (Function.empty())
3150 continue;
3152 Function.postProcessCFG();
3154 if (opts::PrintAll || opts::PrintCFG)
3155 Function.print(outs(), "after building cfg");
3157 if (opts::DumpDotAll)
3158 Function.dumpGraphForPass("00_build-cfg");
3160 if (opts::PrintLoopInfo) {
3161 Function.calculateLoopInfo();
3162 Function.printLoopInfo(outs());
3165 BC->TotalScore += Function.getFunctionScore();
3166 BC->SumExecutionCount += Function.getKnownExecutionCount();
3169 if (opts::PrintGlobals) {
3170 outs() << "BOLT-INFO: Global symbols:\n";
3171 BC->printGlobalSymbols(outs());
3175 void RewriteInstance::runOptimizationPasses() {
3176 NamedRegionTimer T("runOptimizationPasses", "run optimization passes",
3177 TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3178 BinaryFunctionPassManager::runAllPasses(*BC);
3181 void RewriteInstance::preregisterSections() {
3182 // Preregister sections before emission to set their order in the output.
3183 const unsigned ROFlags = BinarySection::getFlags(/*IsReadOnly*/ true,
3184 /*IsText*/ false,
3185 /*IsAllocatable*/ true);
3186 if (BinarySection *EHFrameSection = getSection(getEHFrameSectionName())) {
3187 // New .eh_frame.
3188 BC->registerOrUpdateSection(getNewSecPrefix() + getEHFrameSectionName(),
3189 ELF::SHT_PROGBITS, ROFlags);
3190 // Fully register a relocatable copy of the original .eh_frame.
3191 BC->registerSection(".relocated.eh_frame", *EHFrameSection);
3193 BC->registerOrUpdateSection(getNewSecPrefix() + ".gcc_except_table",
3194 ELF::SHT_PROGBITS, ROFlags);
3195 BC->registerOrUpdateSection(getNewSecPrefix() + ".rodata", ELF::SHT_PROGBITS,
3196 ROFlags);
3197 BC->registerOrUpdateSection(getNewSecPrefix() + ".rodata.cold",
3198 ELF::SHT_PROGBITS, ROFlags);
3201 void RewriteInstance::emitAndLink() {
3202 NamedRegionTimer T("emitAndLink", "emit and link", TimerGroupName,
3203 TimerGroupDesc, opts::TimeRewrite);
3205 SmallString<0> ObjectBuffer;
3206 raw_svector_ostream OS(ObjectBuffer);
3208 // Implicitly MCObjectStreamer takes ownership of MCAsmBackend (MAB)
3209 // and MCCodeEmitter (MCE). ~MCObjectStreamer() will delete these
3210 // two instances.
3211 std::unique_ptr<MCStreamer> Streamer = BC->createStreamer(OS);
3213 if (EHFrameSection) {
3214 if (opts::UseOldText || opts::StrictMode) {
3215 // The section is going to be regenerated from scratch.
3216 // Empty the contents, but keep the section reference.
3217 EHFrameSection->clearContents();
3218 } else {
3219 // Make .eh_frame relocatable.
3220 relocateEHFrameSection();
3224 emitBinaryContext(*Streamer, *BC, getOrgSecPrefix());
3226 Streamer->finish();
3227 if (Streamer->getContext().hadError()) {
3228 errs() << "BOLT-ERROR: Emission failed.\n";
3229 exit(1);
3232 if (opts::KeepTmp) {
3233 SmallString<128> OutObjectPath;
3234 sys::fs::getPotentiallyUniqueTempFileName("output", "o", OutObjectPath);
3235 std::error_code EC;
3236 raw_fd_ostream FOS(OutObjectPath, EC);
3237 check_error(EC, "cannot create output object file");
3238 FOS << ObjectBuffer;
3239 outs() << "BOLT-INFO: intermediary output object file saved for debugging "
3240 "purposes: "
3241 << OutObjectPath << "\n";
3244 ErrorOr<BinarySection &> TextSection =
3245 BC->getUniqueSectionByName(BC->getMainCodeSectionName());
3246 if (BC->HasRelocations && TextSection)
3247 BC->renameSection(*TextSection, getOrgSecPrefix() + ".text");
3249 //////////////////////////////////////////////////////////////////////////////
3250 // Assign addresses to new sections.
3251 //////////////////////////////////////////////////////////////////////////////
3253 // Get output object as ObjectFile.
3254 std::unique_ptr<MemoryBuffer> ObjectMemBuffer =
3255 MemoryBuffer::getMemBuffer(ObjectBuffer, "in-memory object file", false);
3257 auto EFMM = std::make_unique<ExecutableFileMemoryManager>(*BC);
3258 EFMM->setNewSecPrefix(getNewSecPrefix());
3259 EFMM->setOrgSecPrefix(getOrgSecPrefix());
3261 Linker = std::make_unique<JITLinkLinker>(*BC, std::move(EFMM));
3262 Linker->loadObject(ObjectMemBuffer->getMemBufferRef(),
3263 [this](auto MapSection) { mapFileSections(MapSection); });
3265 // Update output addresses based on the new section map and
3266 // layout. Only do this for the object created by ourselves.
3267 updateOutputValues(*Linker);
3269 if (opts::UpdateDebugSections) {
3270 MCAsmLayout FinalLayout(
3271 static_cast<MCObjectStreamer *>(Streamer.get())->getAssembler());
3272 DebugInfoRewriter->updateLineTableOffsets(FinalLayout);
3275 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary())
3276 RtLibrary->link(*BC, ToolPath, *Linker, [this](auto MapSection) {
3277 // Map newly registered sections.
3278 this->mapAllocatableSections(MapSection);
3281 // Once the code is emitted, we can rename function sections to actual
3282 // output sections and de-register sections used for emission.
3283 for (BinaryFunction *Function : BC->getAllBinaryFunctions()) {
3284 ErrorOr<BinarySection &> Section = Function->getCodeSection();
3285 if (Section &&
3286 (Function->getImageAddress() == 0 || Function->getImageSize() == 0))
3287 continue;
3289 // Restore origin section for functions that were emitted or supposed to
3290 // be emitted to patch sections.
3291 if (Section)
3292 BC->deregisterSection(*Section);
3293 assert(Function->getOriginSectionName() && "expected origin section");
3294 Function->CodeSectionName = Function->getOriginSectionName()->str();
3295 for (const FunctionFragment &FF :
3296 Function->getLayout().getSplitFragments()) {
3297 if (ErrorOr<BinarySection &> ColdSection =
3298 Function->getCodeSection(FF.getFragmentNum()))
3299 BC->deregisterSection(*ColdSection);
3301 if (Function->getLayout().isSplit())
3302 Function->setColdCodeSectionName(getBOLTTextSectionName());
3305 if (opts::PrintCacheMetrics) {
3306 outs() << "BOLT-INFO: cache metrics after emitting functions:\n";
3307 CacheMetrics::printAll(BC->getSortedFunctions());
3311 void RewriteInstance::updateMetadata() {
3312 MetadataManager.runFinalizersAfterEmit();
3314 if (opts::UpdateDebugSections) {
3315 NamedRegionTimer T("updateDebugInfo", "update debug info", TimerGroupName,
3316 TimerGroupDesc, opts::TimeRewrite);
3317 DebugInfoRewriter->updateDebugInfo();
3320 if (opts::WriteBoltInfoSection)
3321 addBoltInfoSection();
3324 void RewriteInstance::mapFileSections(BOLTLinker::SectionMapper MapSection) {
3325 BC->deregisterUnusedSections();
3327 // If no new .eh_frame was written, remove relocated original .eh_frame.
3328 BinarySection *RelocatedEHFrameSection =
3329 getSection(".relocated" + getEHFrameSectionName());
3330 if (RelocatedEHFrameSection && RelocatedEHFrameSection->hasValidSectionID()) {
3331 BinarySection *NewEHFrameSection =
3332 getSection(getNewSecPrefix() + getEHFrameSectionName());
3333 if (!NewEHFrameSection || !NewEHFrameSection->isFinalized()) {
3334 // JITLink will still have to process relocations for the section, hence
3335 // we need to assign it the address that wouldn't result in relocation
3336 // processing failure.
3337 MapSection(*RelocatedEHFrameSection, NextAvailableAddress);
3338 BC->deregisterSection(*RelocatedEHFrameSection);
3342 mapCodeSections(MapSection);
3344 // Map the rest of the sections.
3345 mapAllocatableSections(MapSection);
3348 std::vector<BinarySection *> RewriteInstance::getCodeSections() {
3349 std::vector<BinarySection *> CodeSections;
3350 for (BinarySection &Section : BC->textSections())
3351 if (Section.hasValidSectionID())
3352 CodeSections.emplace_back(&Section);
3354 auto compareSections = [&](const BinarySection *A, const BinarySection *B) {
3355 // If both A and B have names starting with ".text.cold", then
3356 // - if opts::HotFunctionsAtEnd is true, we want order
3357 // ".text.cold.T", ".text.cold.T-1", ... ".text.cold.1", ".text.cold"
3358 // - if opts::HotFunctionsAtEnd is false, we want order
3359 // ".text.cold", ".text.cold.1", ... ".text.cold.T-1", ".text.cold.T"
3360 if (A->getName().startswith(BC->getColdCodeSectionName()) &&
3361 B->getName().startswith(BC->getColdCodeSectionName())) {
3362 if (A->getName().size() != B->getName().size())
3363 return (opts::HotFunctionsAtEnd)
3364 ? (A->getName().size() > B->getName().size())
3365 : (A->getName().size() < B->getName().size());
3366 return (opts::HotFunctionsAtEnd) ? (A->getName() > B->getName())
3367 : (A->getName() < B->getName());
3370 // Place movers before anything else.
3371 if (A->getName() == BC->getHotTextMoverSectionName())
3372 return true;
3373 if (B->getName() == BC->getHotTextMoverSectionName())
3374 return false;
3376 // Depending on the option, put main text at the beginning or at the end.
3377 if (opts::HotFunctionsAtEnd)
3378 return B->getName() == BC->getMainCodeSectionName();
3379 else
3380 return A->getName() == BC->getMainCodeSectionName();
3383 // Determine the order of sections.
3384 llvm::stable_sort(CodeSections, compareSections);
3386 return CodeSections;
3389 void RewriteInstance::mapCodeSections(BOLTLinker::SectionMapper MapSection) {
3390 if (BC->HasRelocations) {
3391 // Map sections for functions with pre-assigned addresses.
3392 for (BinaryFunction *InjectedFunction : BC->getInjectedBinaryFunctions()) {
3393 const uint64_t OutputAddress = InjectedFunction->getOutputAddress();
3394 if (!OutputAddress)
3395 continue;
3397 ErrorOr<BinarySection &> FunctionSection =
3398 InjectedFunction->getCodeSection();
3399 assert(FunctionSection && "function should have section");
3400 FunctionSection->setOutputAddress(OutputAddress);
3401 MapSection(*FunctionSection, OutputAddress);
3402 InjectedFunction->setImageAddress(FunctionSection->getAllocAddress());
3403 InjectedFunction->setImageSize(FunctionSection->getOutputSize());
3406 // Populate the list of sections to be allocated.
3407 std::vector<BinarySection *> CodeSections = getCodeSections();
3409 // Remove sections that were pre-allocated (patch sections).
3410 llvm::erase_if(CodeSections, [](BinarySection *Section) {
3411 return Section->getOutputAddress();
3413 LLVM_DEBUG(dbgs() << "Code sections in the order of output:\n";
3414 for (const BinarySection *Section : CodeSections)
3415 dbgs() << Section->getName() << '\n';
3418 uint64_t PaddingSize = 0; // size of padding required at the end
3420 // Allocate sections starting at a given Address.
3421 auto allocateAt = [&](uint64_t Address) {
3422 for (BinarySection *Section : CodeSections) {
3423 Address = alignTo(Address, Section->getAlignment());
3424 Section->setOutputAddress(Address);
3425 Address += Section->getOutputSize();
3427 // Hugify: Additional huge page from right side due to
3428 // weird ASLR mapping addresses (4KB aligned)
3429 if (opts::Hugify && !BC->HasFixedLoadAddress &&
3430 Section->getName() == BC->getMainCodeSectionName())
3431 Address = alignTo(Address, Section->getAlignment());
3434 // Make sure we allocate enough space for huge pages.
3435 ErrorOr<BinarySection &> TextSection =
3436 BC->getUniqueSectionByName(BC->getMainCodeSectionName());
3437 if (opts::HotText && TextSection && TextSection->hasValidSectionID()) {
3438 uint64_t HotTextEnd =
3439 TextSection->getOutputAddress() + TextSection->getOutputSize();
3440 HotTextEnd = alignTo(HotTextEnd, BC->PageAlign);
3441 if (HotTextEnd > Address) {
3442 PaddingSize = HotTextEnd - Address;
3443 Address = HotTextEnd;
3446 return Address;
3449 // Check if we can fit code in the original .text
3450 bool AllocationDone = false;
3451 if (opts::UseOldText) {
3452 const uint64_t CodeSize =
3453 allocateAt(BC->OldTextSectionAddress) - BC->OldTextSectionAddress;
3455 if (CodeSize <= BC->OldTextSectionSize) {
3456 outs() << "BOLT-INFO: using original .text for new code with 0x"
3457 << Twine::utohexstr(opts::AlignText) << " alignment\n";
3458 AllocationDone = true;
3459 } else {
3460 errs() << "BOLT-WARNING: original .text too small to fit the new code"
3461 << " using 0x" << Twine::utohexstr(opts::AlignText)
3462 << " alignment. " << CodeSize << " bytes needed, have "
3463 << BC->OldTextSectionSize << " bytes available.\n";
3464 opts::UseOldText = false;
3468 if (!AllocationDone)
3469 NextAvailableAddress = allocateAt(NextAvailableAddress);
3471 // Do the mapping for ORC layer based on the allocation.
3472 for (BinarySection *Section : CodeSections) {
3473 LLVM_DEBUG(
3474 dbgs() << "BOLT: mapping " << Section->getName() << " at 0x"
3475 << Twine::utohexstr(Section->getAllocAddress()) << " to 0x"
3476 << Twine::utohexstr(Section->getOutputAddress()) << '\n');
3477 MapSection(*Section, Section->getOutputAddress());
3478 Section->setOutputFileOffset(
3479 getFileOffsetForAddress(Section->getOutputAddress()));
3482 // Check if we need to insert a padding section for hot text.
3483 if (PaddingSize && !opts::UseOldText)
3484 outs() << "BOLT-INFO: padding code to 0x"
3485 << Twine::utohexstr(NextAvailableAddress)
3486 << " to accommodate hot text\n";
3488 return;
3491 // Processing in non-relocation mode.
3492 uint64_t NewTextSectionStartAddress = NextAvailableAddress;
3494 for (auto &BFI : BC->getBinaryFunctions()) {
3495 BinaryFunction &Function = BFI.second;
3496 if (!Function.isEmitted())
3497 continue;
3499 bool TooLarge = false;
3500 ErrorOr<BinarySection &> FuncSection = Function.getCodeSection();
3501 assert(FuncSection && "cannot find section for function");
3502 FuncSection->setOutputAddress(Function.getAddress());
3503 LLVM_DEBUG(dbgs() << "BOLT: mapping 0x"
3504 << Twine::utohexstr(FuncSection->getAllocAddress())
3505 << " to 0x" << Twine::utohexstr(Function.getAddress())
3506 << '\n');
3507 MapSection(*FuncSection, Function.getAddress());
3508 Function.setImageAddress(FuncSection->getAllocAddress());
3509 Function.setImageSize(FuncSection->getOutputSize());
3510 if (Function.getImageSize() > Function.getMaxSize()) {
3511 TooLarge = true;
3512 FailedAddresses.emplace_back(Function.getAddress());
3515 // Map jump tables if updating in-place.
3516 if (opts::JumpTables == JTS_BASIC) {
3517 for (auto &JTI : Function.JumpTables) {
3518 JumpTable *JT = JTI.second;
3519 BinarySection &Section = JT->getOutputSection();
3520 Section.setOutputAddress(JT->getAddress());
3521 Section.setOutputFileOffset(getFileOffsetForAddress(JT->getAddress()));
3522 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: mapping JT " << Section.getName()
3523 << " to 0x" << Twine::utohexstr(JT->getAddress())
3524 << '\n');
3525 MapSection(Section, JT->getAddress());
3529 if (!Function.isSplit())
3530 continue;
3532 assert(Function.getLayout().isHotColdSplit() &&
3533 "Cannot allocate more than two fragments per function in "
3534 "non-relocation mode.");
3536 FunctionFragment &FF =
3537 Function.getLayout().getFragment(FragmentNum::cold());
3538 ErrorOr<BinarySection &> ColdSection =
3539 Function.getCodeSection(FF.getFragmentNum());
3540 assert(ColdSection && "cannot find section for cold part");
3541 // Cold fragments are aligned at 16 bytes.
3542 NextAvailableAddress = alignTo(NextAvailableAddress, 16);
3543 if (TooLarge) {
3544 // The corresponding FDE will refer to address 0.
3545 FF.setAddress(0);
3546 FF.setImageAddress(0);
3547 FF.setImageSize(0);
3548 FF.setFileOffset(0);
3549 } else {
3550 FF.setAddress(NextAvailableAddress);
3551 FF.setImageAddress(ColdSection->getAllocAddress());
3552 FF.setImageSize(ColdSection->getOutputSize());
3553 FF.setFileOffset(getFileOffsetForAddress(NextAvailableAddress));
3554 ColdSection->setOutputAddress(FF.getAddress());
3557 LLVM_DEBUG(
3558 dbgs() << formatv(
3559 "BOLT: mapping cold fragment {0:x+} to {1:x+} with size {2:x+}\n",
3560 FF.getImageAddress(), FF.getAddress(), FF.getImageSize()));
3561 MapSection(*ColdSection, FF.getAddress());
3563 if (TooLarge)
3564 BC->deregisterSection(*ColdSection);
3566 NextAvailableAddress += FF.getImageSize();
3569 // Add the new text section aggregating all existing code sections.
3570 // This is pseudo-section that serves a purpose of creating a corresponding
3571 // entry in section header table.
3572 int64_t NewTextSectionSize =
3573 NextAvailableAddress - NewTextSectionStartAddress;
3574 if (NewTextSectionSize) {
3575 const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/true,
3576 /*IsText=*/true,
3577 /*IsAllocatable=*/true);
3578 BinarySection &Section =
3579 BC->registerOrUpdateSection(getBOLTTextSectionName(),
3580 ELF::SHT_PROGBITS,
3581 Flags,
3582 /*Data=*/nullptr,
3583 NewTextSectionSize,
3584 16);
3585 Section.setOutputAddress(NewTextSectionStartAddress);
3586 Section.setOutputFileOffset(
3587 getFileOffsetForAddress(NewTextSectionStartAddress));
3591 void RewriteInstance::mapAllocatableSections(
3592 BOLTLinker::SectionMapper MapSection) {
3593 // Allocate read-only sections first, then writable sections.
3594 enum : uint8_t { ST_READONLY, ST_READWRITE };
3595 for (uint8_t SType = ST_READONLY; SType <= ST_READWRITE; ++SType) {
3596 const uint64_t LastNextAvailableAddress = NextAvailableAddress;
3597 if (SType == ST_READWRITE) {
3598 // Align R+W segment to regular page size
3599 NextAvailableAddress = alignTo(NextAvailableAddress, BC->RegularPageSize);
3600 NewWritableSegmentAddress = NextAvailableAddress;
3603 for (BinarySection &Section : BC->allocatableSections()) {
3604 if (Section.isLinkOnly())
3605 continue;
3607 if (!Section.hasValidSectionID())
3608 continue;
3610 if (Section.isWritable() == (SType == ST_READONLY))
3611 continue;
3613 if (Section.getOutputAddress()) {
3614 LLVM_DEBUG({
3615 dbgs() << "BOLT-DEBUG: section " << Section.getName()
3616 << " is already mapped at 0x"
3617 << Twine::utohexstr(Section.getOutputAddress()) << '\n';
3619 continue;
3622 if (Section.hasSectionRef()) {
3623 LLVM_DEBUG({
3624 dbgs() << "BOLT-DEBUG: mapping original section " << Section.getName()
3625 << " to 0x" << Twine::utohexstr(Section.getAddress()) << '\n';
3627 Section.setOutputAddress(Section.getAddress());
3628 Section.setOutputFileOffset(Section.getInputFileOffset());
3629 MapSection(Section, Section.getAddress());
3630 } else {
3631 NextAvailableAddress =
3632 alignTo(NextAvailableAddress, Section.getAlignment());
3633 LLVM_DEBUG({
3634 dbgs() << "BOLT: mapping section " << Section.getName() << " (0x"
3635 << Twine::utohexstr(Section.getAllocAddress()) << ") to 0x"
3636 << Twine::utohexstr(NextAvailableAddress) << ":0x"
3637 << Twine::utohexstr(NextAvailableAddress +
3638 Section.getOutputSize())
3639 << '\n';
3642 MapSection(Section, NextAvailableAddress);
3643 Section.setOutputAddress(NextAvailableAddress);
3644 Section.setOutputFileOffset(
3645 getFileOffsetForAddress(NextAvailableAddress));
3647 NextAvailableAddress += Section.getOutputSize();
3651 if (SType == ST_READONLY) {
3652 if (PHDRTableAddress) {
3653 // Segment size includes the size of the PHDR area.
3654 NewTextSegmentSize = NextAvailableAddress - PHDRTableAddress;
3655 } else {
3656 // Existing PHDR table would be updated.
3657 NewTextSegmentSize = NextAvailableAddress - NewTextSegmentAddress;
3659 } else if (SType == ST_READWRITE) {
3660 NewWritableSegmentSize = NextAvailableAddress - NewWritableSegmentAddress;
3661 // Restore NextAvailableAddress if no new writable sections
3662 if (!NewWritableSegmentSize)
3663 NextAvailableAddress = LastNextAvailableAddress;
3668 void RewriteInstance::updateOutputValues(const BOLTLinker &Linker) {
3669 if (std::optional<AddressMap> Map = AddressMap::parse(*BC))
3670 BC->setIOAddressMap(std::move(*Map));
3672 for (BinaryFunction *Function : BC->getAllBinaryFunctions())
3673 Function->updateOutputValues(Linker);
3676 void RewriteInstance::patchELFPHDRTable() {
3677 auto ELF64LEFile = cast<ELF64LEObjectFile>(InputFile);
3678 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile();
3679 raw_fd_ostream &OS = Out->os();
3681 // Write/re-write program headers.
3682 Phnum = Obj.getHeader().e_phnum;
3683 if (PHDRTableOffset) {
3684 // Writing new pheader table and adding one new entry for R+X segment.
3685 Phnum += 1;
3686 if (NewWritableSegmentSize) {
3687 // Adding one more entry for R+W segment.
3688 Phnum += 1;
3690 } else {
3691 assert(!PHDRTableAddress && "unexpected address for program header table");
3692 PHDRTableOffset = Obj.getHeader().e_phoff;
3693 if (NewWritableSegmentSize) {
3694 errs() << "Unable to add writable segment with UseGnuStack option\n";
3695 exit(1);
3699 // NOTE Currently .eh_frame_hdr appends to the last segment, recalculate
3700 // last segments size based on the NextAvailableAddress variable.
3701 if (!NewWritableSegmentSize) {
3702 if (PHDRTableAddress)
3703 NewTextSegmentSize = NextAvailableAddress - PHDRTableAddress;
3704 else
3705 NewTextSegmentSize = NextAvailableAddress - NewTextSegmentAddress;
3706 } else {
3707 NewWritableSegmentSize = NextAvailableAddress - NewWritableSegmentAddress;
3710 OS.seek(PHDRTableOffset);
3712 bool ModdedGnuStack = false;
3713 (void)ModdedGnuStack;
3714 bool AddedSegment = false;
3715 (void)AddedSegment;
3717 auto createNewTextPhdr = [&]() {
3718 ELF64LEPhdrTy NewPhdr;
3719 NewPhdr.p_type = ELF::PT_LOAD;
3720 if (PHDRTableAddress) {
3721 NewPhdr.p_offset = PHDRTableOffset;
3722 NewPhdr.p_vaddr = PHDRTableAddress;
3723 NewPhdr.p_paddr = PHDRTableAddress;
3724 } else {
3725 NewPhdr.p_offset = NewTextSegmentOffset;
3726 NewPhdr.p_vaddr = NewTextSegmentAddress;
3727 NewPhdr.p_paddr = NewTextSegmentAddress;
3729 NewPhdr.p_filesz = NewTextSegmentSize;
3730 NewPhdr.p_memsz = NewTextSegmentSize;
3731 NewPhdr.p_flags = ELF::PF_X | ELF::PF_R;
3732 // FIXME: Currently instrumentation is experimental and the runtime data
3733 // is emitted with code, thus everything needs to be writable
3734 if (opts::Instrument)
3735 NewPhdr.p_flags |= ELF::PF_W;
3736 NewPhdr.p_align = BC->PageAlign;
3738 return NewPhdr;
3741 auto createNewWritableSectionsPhdr = [&]() {
3742 ELF64LEPhdrTy NewPhdr;
3743 NewPhdr.p_type = ELF::PT_LOAD;
3744 NewPhdr.p_offset = getFileOffsetForAddress(NewWritableSegmentAddress);
3745 NewPhdr.p_vaddr = NewWritableSegmentAddress;
3746 NewPhdr.p_paddr = NewWritableSegmentAddress;
3747 NewPhdr.p_filesz = NewWritableSegmentSize;
3748 NewPhdr.p_memsz = NewWritableSegmentSize;
3749 NewPhdr.p_align = BC->RegularPageSize;
3750 NewPhdr.p_flags = ELF::PF_R | ELF::PF_W;
3751 return NewPhdr;
3754 // Copy existing program headers with modifications.
3755 for (const ELF64LE::Phdr &Phdr : cantFail(Obj.program_headers())) {
3756 ELF64LE::Phdr NewPhdr = Phdr;
3757 if (PHDRTableAddress && Phdr.p_type == ELF::PT_PHDR) {
3758 NewPhdr.p_offset = PHDRTableOffset;
3759 NewPhdr.p_vaddr = PHDRTableAddress;
3760 NewPhdr.p_paddr = PHDRTableAddress;
3761 NewPhdr.p_filesz = sizeof(NewPhdr) * Phnum;
3762 NewPhdr.p_memsz = sizeof(NewPhdr) * Phnum;
3763 } else if (Phdr.p_type == ELF::PT_GNU_EH_FRAME) {
3764 ErrorOr<BinarySection &> EHFrameHdrSec =
3765 BC->getUniqueSectionByName(getNewSecPrefix() + ".eh_frame_hdr");
3766 if (EHFrameHdrSec && EHFrameHdrSec->isAllocatable() &&
3767 EHFrameHdrSec->isFinalized()) {
3768 NewPhdr.p_offset = EHFrameHdrSec->getOutputFileOffset();
3769 NewPhdr.p_vaddr = EHFrameHdrSec->getOutputAddress();
3770 NewPhdr.p_paddr = EHFrameHdrSec->getOutputAddress();
3771 NewPhdr.p_filesz = EHFrameHdrSec->getOutputSize();
3772 NewPhdr.p_memsz = EHFrameHdrSec->getOutputSize();
3774 } else if (opts::UseGnuStack && Phdr.p_type == ELF::PT_GNU_STACK) {
3775 NewPhdr = createNewTextPhdr();
3776 ModdedGnuStack = true;
3777 } else if (!opts::UseGnuStack && Phdr.p_type == ELF::PT_DYNAMIC) {
3778 // Insert the new header before DYNAMIC.
3779 ELF64LE::Phdr NewTextPhdr = createNewTextPhdr();
3780 OS.write(reinterpret_cast<const char *>(&NewTextPhdr),
3781 sizeof(NewTextPhdr));
3782 if (NewWritableSegmentSize) {
3783 ELF64LEPhdrTy NewWritablePhdr = createNewWritableSectionsPhdr();
3784 OS.write(reinterpret_cast<const char *>(&NewWritablePhdr),
3785 sizeof(NewWritablePhdr));
3787 AddedSegment = true;
3789 OS.write(reinterpret_cast<const char *>(&NewPhdr), sizeof(NewPhdr));
3792 if (!opts::UseGnuStack && !AddedSegment) {
3793 // Append the new header to the end of the table.
3794 ELF64LE::Phdr NewTextPhdr = createNewTextPhdr();
3795 OS.write(reinterpret_cast<const char *>(&NewTextPhdr), sizeof(NewTextPhdr));
3796 if (NewWritableSegmentSize) {
3797 ELF64LEPhdrTy NewWritablePhdr = createNewWritableSectionsPhdr();
3798 OS.write(reinterpret_cast<const char *>(&NewWritablePhdr),
3799 sizeof(NewWritablePhdr));
3803 assert((!opts::UseGnuStack || ModdedGnuStack) &&
3804 "could not find GNU_STACK program header to modify");
3807 namespace {
3809 /// Write padding to \p OS such that its current \p Offset becomes aligned
3810 /// at \p Alignment. Return new (aligned) offset.
3811 uint64_t appendPadding(raw_pwrite_stream &OS, uint64_t Offset,
3812 uint64_t Alignment) {
3813 if (!Alignment)
3814 return Offset;
3816 const uint64_t PaddingSize =
3817 offsetToAlignment(Offset, llvm::Align(Alignment));
3818 for (unsigned I = 0; I < PaddingSize; ++I)
3819 OS.write((unsigned char)0);
3820 return Offset + PaddingSize;
3825 void RewriteInstance::rewriteNoteSections() {
3826 auto ELF64LEFile = cast<ELF64LEObjectFile>(InputFile);
3827 const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile();
3828 raw_fd_ostream &OS = Out->os();
3830 uint64_t NextAvailableOffset = getFileOffsetForAddress(NextAvailableAddress);
3831 assert(NextAvailableOffset >= FirstNonAllocatableOffset &&
3832 "next available offset calculation failure");
3833 OS.seek(NextAvailableOffset);
3835 // Copy over non-allocatable section contents and update file offsets.
3836 for (const ELF64LE::Shdr &Section : cantFail(Obj.sections())) {
3837 if (Section.sh_type == ELF::SHT_NULL)
3838 continue;
3839 if (Section.sh_flags & ELF::SHF_ALLOC)
3840 continue;
3842 SectionRef SecRef = ELF64LEFile->toSectionRef(&Section);
3843 BinarySection *BSec = BC->getSectionForSectionRef(SecRef);
3844 assert(BSec && !BSec->isAllocatable() &&
3845 "Matching non-allocatable BinarySection should exist.");
3847 StringRef SectionName =
3848 cantFail(Obj.getSectionName(Section), "cannot get section name");
3849 if (shouldStrip(Section, SectionName))
3850 continue;
3852 // Insert padding as needed.
3853 NextAvailableOffset =
3854 appendPadding(OS, NextAvailableOffset, Section.sh_addralign);
3856 // New section size.
3857 uint64_t Size = 0;
3858 bool DataWritten = false;
3859 uint8_t *SectionData = nullptr;
3860 // Copy over section contents unless it's one of the sections we overwrite.
3861 if (!willOverwriteSection(SectionName)) {
3862 Size = Section.sh_size;
3863 StringRef Dataref = InputFile->getData().substr(Section.sh_offset, Size);
3864 std::string Data;
3865 if (BSec->getPatcher()) {
3866 Data = BSec->getPatcher()->patchBinary(Dataref);
3867 Dataref = StringRef(Data);
3870 // Section was expanded, so need to treat it as overwrite.
3871 if (Size != Dataref.size()) {
3872 BSec = &BC->registerOrUpdateNoteSection(
3873 SectionName, copyByteArray(Dataref), Dataref.size());
3874 Size = 0;
3875 } else {
3876 OS << Dataref;
3877 DataWritten = true;
3879 // Add padding as the section extension might rely on the alignment.
3880 Size = appendPadding(OS, Size, Section.sh_addralign);
3884 // Perform section post-processing.
3885 assert(BSec->getAlignment() <= Section.sh_addralign &&
3886 "alignment exceeds value in file");
3888 if (BSec->getAllocAddress()) {
3889 assert(!DataWritten && "Writing section twice.");
3890 (void)DataWritten;
3891 SectionData = BSec->getOutputData();
3893 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: " << (Size ? "appending" : "writing")
3894 << " contents to section " << SectionName << '\n');
3895 OS.write(reinterpret_cast<char *>(SectionData), BSec->getOutputSize());
3896 Size += BSec->getOutputSize();
3899 BSec->setOutputFileOffset(NextAvailableOffset);
3900 BSec->flushPendingRelocations(OS, [this](const MCSymbol *S) {
3901 return getNewValueForSymbol(S->getName());
3904 // Set/modify section info.
3905 BinarySection &NewSection = BC->registerOrUpdateNoteSection(
3906 SectionName, SectionData, Size, Section.sh_addralign,
3907 !BSec->isWritable(), BSec->getELFType());
3908 NewSection.setOutputAddress(0);
3909 NewSection.setOutputFileOffset(NextAvailableOffset);
3911 NextAvailableOffset += Size;
3914 // Write new note sections.
3915 for (BinarySection &Section : BC->nonAllocatableSections()) {
3916 if (Section.getOutputFileOffset() || !Section.getAllocAddress())
3917 continue;
3919 assert(!Section.hasPendingRelocations() && "cannot have pending relocs");
3921 NextAvailableOffset =
3922 appendPadding(OS, NextAvailableOffset, Section.getAlignment());
3923 Section.setOutputFileOffset(NextAvailableOffset);
3925 LLVM_DEBUG(
3926 dbgs() << "BOLT-DEBUG: writing out new section " << Section.getName()
3927 << " of size " << Section.getOutputSize() << " at offset 0x"
3928 << Twine::utohexstr(Section.getOutputFileOffset()) << '\n');
3930 OS.write(Section.getOutputContents().data(), Section.getOutputSize());
3931 NextAvailableOffset += Section.getOutputSize();
3935 template <typename ELFT>
3936 void RewriteInstance::finalizeSectionStringTable(ELFObjectFile<ELFT> *File) {
3937 // Pre-populate section header string table.
3938 for (const BinarySection &Section : BC->sections())
3939 if (!Section.isAnonymous())
3940 SHStrTab.add(Section.getOutputName());
3941 SHStrTab.finalize();
3943 const size_t SHStrTabSize = SHStrTab.getSize();
3944 uint8_t *DataCopy = new uint8_t[SHStrTabSize];
3945 memset(DataCopy, 0, SHStrTabSize);
3946 SHStrTab.write(DataCopy);
3947 BC->registerOrUpdateNoteSection(".shstrtab",
3948 DataCopy,
3949 SHStrTabSize,
3950 /*Alignment=*/1,
3951 /*IsReadOnly=*/true,
3952 ELF::SHT_STRTAB);
3955 void RewriteInstance::addBoltInfoSection() {
3956 std::string DescStr;
3957 raw_string_ostream DescOS(DescStr);
3959 DescOS << "BOLT revision: " << BoltRevision << ", "
3960 << "command line:";
3961 for (int I = 0; I < Argc; ++I)
3962 DescOS << " " << Argv[I];
3963 DescOS.flush();
3965 // Encode as GNU GOLD VERSION so it is easily printable by 'readelf -n'
3966 const std::string BoltInfo =
3967 BinarySection::encodeELFNote("GNU", DescStr, 4 /*NT_GNU_GOLD_VERSION*/);
3968 BC->registerOrUpdateNoteSection(".note.bolt_info", copyByteArray(BoltInfo),
3969 BoltInfo.size(),
3970 /*Alignment=*/1,
3971 /*IsReadOnly=*/true, ELF::SHT_NOTE);
3974 void RewriteInstance::addBATSection() {
3975 BC->registerOrUpdateNoteSection(BoltAddressTranslation::SECTION_NAME, nullptr,
3977 /*Alignment=*/1,
3978 /*IsReadOnly=*/true, ELF::SHT_NOTE);
3981 void RewriteInstance::encodeBATSection() {
3982 std::string DescStr;
3983 raw_string_ostream DescOS(DescStr);
3985 BAT->write(*BC, DescOS);
3986 DescOS.flush();
3988 const std::string BoltInfo =
3989 BinarySection::encodeELFNote("BOLT", DescStr, BinarySection::NT_BOLT_BAT);
3990 BC->registerOrUpdateNoteSection(BoltAddressTranslation::SECTION_NAME,
3991 copyByteArray(BoltInfo), BoltInfo.size(),
3992 /*Alignment=*/1,
3993 /*IsReadOnly=*/true, ELF::SHT_NOTE);
3996 template <typename ELFShdrTy>
3997 bool RewriteInstance::shouldStrip(const ELFShdrTy &Section,
3998 StringRef SectionName) {
3999 // Strip non-allocatable relocation sections.
4000 if (!(Section.sh_flags & ELF::SHF_ALLOC) && Section.sh_type == ELF::SHT_RELA)
4001 return true;
4003 // Strip debug sections if not updating them.
4004 if (isDebugSection(SectionName) && !opts::UpdateDebugSections)
4005 return true;
4007 // Strip symtab section if needed
4008 if (opts::RemoveSymtab && Section.sh_type == ELF::SHT_SYMTAB)
4009 return true;
4011 return false;
4014 template <typename ELFT>
4015 std::vector<typename object::ELFObjectFile<ELFT>::Elf_Shdr>
4016 RewriteInstance::getOutputSections(ELFObjectFile<ELFT> *File,
4017 std::vector<uint32_t> &NewSectionIndex) {
4018 using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr;
4019 const ELFFile<ELFT> &Obj = File->getELFFile();
4020 typename ELFT::ShdrRange Sections = cantFail(Obj.sections());
4022 // Keep track of section header entries attached to the corresponding section.
4023 std::vector<std::pair<BinarySection *, ELFShdrTy>> OutputSections;
4024 auto addSection = [&](const ELFShdrTy &Section, BinarySection *BinSec) {
4025 ELFShdrTy NewSection = Section;
4026 NewSection.sh_name = SHStrTab.getOffset(BinSec->getOutputName());
4027 OutputSections.emplace_back(BinSec, std::move(NewSection));
4030 // Copy over entries for original allocatable sections using modified name.
4031 for (const ELFShdrTy &Section : Sections) {
4032 // Always ignore this section.
4033 if (Section.sh_type == ELF::SHT_NULL) {
4034 OutputSections.emplace_back(nullptr, Section);
4035 continue;
4038 if (!(Section.sh_flags & ELF::SHF_ALLOC))
4039 continue;
4041 SectionRef SecRef = File->toSectionRef(&Section);
4042 BinarySection *BinSec = BC->getSectionForSectionRef(SecRef);
4043 assert(BinSec && "Matching BinarySection should exist.");
4045 addSection(Section, BinSec);
4048 for (BinarySection &Section : BC->allocatableSections()) {
4049 if (!Section.isFinalized())
4050 continue;
4052 if (Section.hasSectionRef() || Section.isAnonymous()) {
4053 if (opts::Verbosity)
4054 outs() << "BOLT-INFO: not writing section header for section "
4055 << Section.getOutputName() << '\n';
4056 continue;
4059 if (opts::Verbosity >= 1)
4060 outs() << "BOLT-INFO: writing section header for "
4061 << Section.getOutputName() << '\n';
4062 ELFShdrTy NewSection;
4063 NewSection.sh_type = ELF::SHT_PROGBITS;
4064 NewSection.sh_addr = Section.getOutputAddress();
4065 NewSection.sh_offset = Section.getOutputFileOffset();
4066 NewSection.sh_size = Section.getOutputSize();
4067 NewSection.sh_entsize = 0;
4068 NewSection.sh_flags = Section.getELFFlags();
4069 NewSection.sh_link = 0;
4070 NewSection.sh_info = 0;
4071 NewSection.sh_addralign = Section.getAlignment();
4072 addSection(NewSection, &Section);
4075 // Sort all allocatable sections by their offset.
4076 llvm::stable_sort(OutputSections, [](const auto &A, const auto &B) {
4077 return A.second.sh_offset < B.second.sh_offset;
4080 // Fix section sizes to prevent overlapping.
4081 ELFShdrTy *PrevSection = nullptr;
4082 BinarySection *PrevBinSec = nullptr;
4083 for (auto &SectionKV : OutputSections) {
4084 ELFShdrTy &Section = SectionKV.second;
4086 // TBSS section does not take file or memory space. Ignore it for layout
4087 // purposes.
4088 if (Section.sh_type == ELF::SHT_NOBITS && (Section.sh_flags & ELF::SHF_TLS))
4089 continue;
4091 if (PrevSection &&
4092 PrevSection->sh_addr + PrevSection->sh_size > Section.sh_addr) {
4093 if (opts::Verbosity > 1)
4094 outs() << "BOLT-INFO: adjusting size for section "
4095 << PrevBinSec->getOutputName() << '\n';
4096 PrevSection->sh_size = Section.sh_addr > PrevSection->sh_addr
4097 ? Section.sh_addr - PrevSection->sh_addr
4098 : 0;
4101 PrevSection = &Section;
4102 PrevBinSec = SectionKV.first;
4105 uint64_t LastFileOffset = 0;
4107 // Copy over entries for non-allocatable sections performing necessary
4108 // adjustments.
4109 for (const ELFShdrTy &Section : Sections) {
4110 if (Section.sh_type == ELF::SHT_NULL)
4111 continue;
4112 if (Section.sh_flags & ELF::SHF_ALLOC)
4113 continue;
4115 StringRef SectionName =
4116 cantFail(Obj.getSectionName(Section), "cannot get section name");
4118 if (shouldStrip(Section, SectionName))
4119 continue;
4121 SectionRef SecRef = File->toSectionRef(&Section);
4122 BinarySection *BinSec = BC->getSectionForSectionRef(SecRef);
4123 assert(BinSec && "Matching BinarySection should exist.");
4125 ELFShdrTy NewSection = Section;
4126 NewSection.sh_offset = BinSec->getOutputFileOffset();
4127 NewSection.sh_size = BinSec->getOutputSize();
4129 if (NewSection.sh_type == ELF::SHT_SYMTAB)
4130 NewSection.sh_info = NumLocalSymbols;
4132 addSection(NewSection, BinSec);
4134 LastFileOffset = BinSec->getOutputFileOffset();
4137 // Create entries for new non-allocatable sections.
4138 for (BinarySection &Section : BC->nonAllocatableSections()) {
4139 if (Section.getOutputFileOffset() <= LastFileOffset)
4140 continue;
4142 if (opts::Verbosity >= 1)
4143 outs() << "BOLT-INFO: writing section header for "
4144 << Section.getOutputName() << '\n';
4146 ELFShdrTy NewSection;
4147 NewSection.sh_type = Section.getELFType();
4148 NewSection.sh_addr = 0;
4149 NewSection.sh_offset = Section.getOutputFileOffset();
4150 NewSection.sh_size = Section.getOutputSize();
4151 NewSection.sh_entsize = 0;
4152 NewSection.sh_flags = Section.getELFFlags();
4153 NewSection.sh_link = 0;
4154 NewSection.sh_info = 0;
4155 NewSection.sh_addralign = Section.getAlignment();
4157 addSection(NewSection, &Section);
4160 // Assign indices to sections.
4161 std::unordered_map<std::string, uint64_t> NameToIndex;
4162 for (uint32_t Index = 1; Index < OutputSections.size(); ++Index)
4163 OutputSections[Index].first->setIndex(Index);
4165 // Update section index mapping
4166 NewSectionIndex.clear();
4167 NewSectionIndex.resize(Sections.size(), 0);
4168 for (const ELFShdrTy &Section : Sections) {
4169 if (Section.sh_type == ELF::SHT_NULL)
4170 continue;
4172 size_t OrgIndex = std::distance(Sections.begin(), &Section);
4174 SectionRef SecRef = File->toSectionRef(&Section);
4175 BinarySection *BinSec = BC->getSectionForSectionRef(SecRef);
4176 assert(BinSec && "BinarySection should exist for an input section.");
4178 // Some sections are stripped
4179 if (!BinSec->hasValidIndex())
4180 continue;
4182 NewSectionIndex[OrgIndex] = BinSec->getIndex();
4185 std::vector<ELFShdrTy> SectionsOnly(OutputSections.size());
4186 llvm::copy(llvm::make_second_range(OutputSections), SectionsOnly.begin());
4188 return SectionsOnly;
4191 // Rewrite section header table inserting new entries as needed. The sections
4192 // header table size itself may affect the offsets of other sections,
4193 // so we are placing it at the end of the binary.
4195 // As we rewrite entries we need to track how many sections were inserted
4196 // as it changes the sh_link value. We map old indices to new ones for
4197 // existing sections.
4198 template <typename ELFT>
4199 void RewriteInstance::patchELFSectionHeaderTable(ELFObjectFile<ELFT> *File) {
4200 using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr;
4201 using ELFEhdrTy = typename ELFObjectFile<ELFT>::Elf_Ehdr;
4202 raw_fd_ostream &OS = Out->os();
4203 const ELFFile<ELFT> &Obj = File->getELFFile();
4205 std::vector<uint32_t> NewSectionIndex;
4206 std::vector<ELFShdrTy> OutputSections =
4207 getOutputSections(File, NewSectionIndex);
4208 LLVM_DEBUG(
4209 dbgs() << "BOLT-DEBUG: old to new section index mapping:\n";
4210 for (uint64_t I = 0; I < NewSectionIndex.size(); ++I)
4211 dbgs() << " " << I << " -> " << NewSectionIndex[I] << '\n';
4214 // Align starting address for section header table. There's no architecutal
4215 // need to align this, it is just for pleasant human readability.
4216 uint64_t SHTOffset = OS.tell();
4217 SHTOffset = appendPadding(OS, SHTOffset, 16);
4219 // Write all section header entries while patching section references.
4220 for (ELFShdrTy &Section : OutputSections) {
4221 Section.sh_link = NewSectionIndex[Section.sh_link];
4222 if (Section.sh_type == ELF::SHT_REL || Section.sh_type == ELF::SHT_RELA) {
4223 if (Section.sh_info)
4224 Section.sh_info = NewSectionIndex[Section.sh_info];
4226 OS.write(reinterpret_cast<const char *>(&Section), sizeof(Section));
4229 // Fix ELF header.
4230 ELFEhdrTy NewEhdr = Obj.getHeader();
4232 if (BC->HasRelocations) {
4233 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary())
4234 NewEhdr.e_entry = RtLibrary->getRuntimeStartAddress();
4235 else
4236 NewEhdr.e_entry = getNewFunctionAddress(NewEhdr.e_entry);
4237 assert((NewEhdr.e_entry || !Obj.getHeader().e_entry) &&
4238 "cannot find new address for entry point");
4240 NewEhdr.e_phoff = PHDRTableOffset;
4241 NewEhdr.e_phnum = Phnum;
4242 NewEhdr.e_shoff = SHTOffset;
4243 NewEhdr.e_shnum = OutputSections.size();
4244 NewEhdr.e_shstrndx = NewSectionIndex[NewEhdr.e_shstrndx];
4245 OS.pwrite(reinterpret_cast<const char *>(&NewEhdr), sizeof(NewEhdr), 0);
4248 template <typename ELFT, typename WriteFuncTy, typename StrTabFuncTy>
4249 void RewriteInstance::updateELFSymbolTable(
4250 ELFObjectFile<ELFT> *File, bool IsDynSym,
4251 const typename object::ELFObjectFile<ELFT>::Elf_Shdr &SymTabSection,
4252 const std::vector<uint32_t> &NewSectionIndex, WriteFuncTy Write,
4253 StrTabFuncTy AddToStrTab) {
4254 const ELFFile<ELFT> &Obj = File->getELFFile();
4255 using ELFSymTy = typename ELFObjectFile<ELFT>::Elf_Sym;
4257 StringRef StringSection =
4258 cantFail(Obj.getStringTableForSymtab(SymTabSection));
4260 unsigned NumHotTextSymsUpdated = 0;
4261 unsigned NumHotDataSymsUpdated = 0;
4263 std::map<const BinaryFunction *, uint64_t> IslandSizes;
4264 auto getConstantIslandSize = [&IslandSizes](const BinaryFunction &BF) {
4265 auto Itr = IslandSizes.find(&BF);
4266 if (Itr != IslandSizes.end())
4267 return Itr->second;
4268 return IslandSizes[&BF] = BF.estimateConstantIslandSize();
4271 // Symbols for the new symbol table.
4272 std::vector<ELFSymTy> Symbols;
4274 auto getNewSectionIndex = [&](uint32_t OldIndex) {
4275 // For dynamic symbol table, the section index could be wrong on the input,
4276 // and its value is ignored by the runtime if it's different from
4277 // SHN_UNDEF and SHN_ABS.
4278 // However, we still need to update dynamic symbol table, so return a
4279 // section index, even though the index is broken.
4280 if (IsDynSym && OldIndex >= NewSectionIndex.size())
4281 return OldIndex;
4283 assert(OldIndex < NewSectionIndex.size() && "section index out of bounds");
4284 const uint32_t NewIndex = NewSectionIndex[OldIndex];
4286 // We may have stripped the section that dynsym was referencing due to
4287 // the linker bug. In that case return the old index avoiding marking
4288 // the symbol as undefined.
4289 if (IsDynSym && NewIndex != OldIndex && NewIndex == ELF::SHN_UNDEF)
4290 return OldIndex;
4291 return NewIndex;
4294 // Add extra symbols for the function.
4296 // Note that addExtraSymbols() could be called multiple times for the same
4297 // function with different FunctionSymbol matching the main function entry
4298 // point.
4299 auto addExtraSymbols = [&](const BinaryFunction &Function,
4300 const ELFSymTy &FunctionSymbol) {
4301 if (Function.isFolded()) {
4302 BinaryFunction *ICFParent = Function.getFoldedIntoFunction();
4303 while (ICFParent->isFolded())
4304 ICFParent = ICFParent->getFoldedIntoFunction();
4305 ELFSymTy ICFSymbol = FunctionSymbol;
4306 SmallVector<char, 256> Buf;
4307 ICFSymbol.st_name =
4308 AddToStrTab(Twine(cantFail(FunctionSymbol.getName(StringSection)))
4309 .concat(".icf.0")
4310 .toStringRef(Buf));
4311 ICFSymbol.st_value = ICFParent->getOutputAddress();
4312 ICFSymbol.st_size = ICFParent->getOutputSize();
4313 ICFSymbol.st_shndx = ICFParent->getCodeSection()->getIndex();
4314 Symbols.emplace_back(ICFSymbol);
4316 if (Function.isSplit()) {
4317 for (const FunctionFragment &FF :
4318 Function.getLayout().getSplitFragments()) {
4319 if (FF.getAddress()) {
4320 ELFSymTy NewColdSym = FunctionSymbol;
4321 const SmallString<256> SymbolName = formatv(
4322 "{0}.cold.{1}", cantFail(FunctionSymbol.getName(StringSection)),
4323 FF.getFragmentNum().get() - 1);
4324 NewColdSym.st_name = AddToStrTab(SymbolName);
4325 NewColdSym.st_shndx =
4326 Function.getCodeSection(FF.getFragmentNum())->getIndex();
4327 NewColdSym.st_value = FF.getAddress();
4328 NewColdSym.st_size = FF.getImageSize();
4329 NewColdSym.setBindingAndType(ELF::STB_LOCAL, ELF::STT_FUNC);
4330 Symbols.emplace_back(NewColdSym);
4334 if (Function.hasConstantIsland()) {
4335 uint64_t DataMark = Function.getOutputDataAddress();
4336 uint64_t CISize = getConstantIslandSize(Function);
4337 uint64_t CodeMark = DataMark + CISize;
4338 ELFSymTy DataMarkSym = FunctionSymbol;
4339 DataMarkSym.st_name = AddToStrTab("$d");
4340 DataMarkSym.st_value = DataMark;
4341 DataMarkSym.st_size = 0;
4342 DataMarkSym.setType(ELF::STT_NOTYPE);
4343 DataMarkSym.setBinding(ELF::STB_LOCAL);
4344 ELFSymTy CodeMarkSym = DataMarkSym;
4345 CodeMarkSym.st_name = AddToStrTab("$x");
4346 CodeMarkSym.st_value = CodeMark;
4347 Symbols.emplace_back(DataMarkSym);
4348 Symbols.emplace_back(CodeMarkSym);
4350 if (Function.hasConstantIsland() && Function.isSplit()) {
4351 uint64_t DataMark = Function.getOutputColdDataAddress();
4352 uint64_t CISize = getConstantIslandSize(Function);
4353 uint64_t CodeMark = DataMark + CISize;
4354 ELFSymTy DataMarkSym = FunctionSymbol;
4355 DataMarkSym.st_name = AddToStrTab("$d");
4356 DataMarkSym.st_value = DataMark;
4357 DataMarkSym.st_size = 0;
4358 DataMarkSym.setType(ELF::STT_NOTYPE);
4359 DataMarkSym.setBinding(ELF::STB_LOCAL);
4360 ELFSymTy CodeMarkSym = DataMarkSym;
4361 CodeMarkSym.st_name = AddToStrTab("$x");
4362 CodeMarkSym.st_value = CodeMark;
4363 Symbols.emplace_back(DataMarkSym);
4364 Symbols.emplace_back(CodeMarkSym);
4368 // For regular (non-dynamic) symbol table, exclude symbols referring
4369 // to non-allocatable sections.
4370 auto shouldStrip = [&](const ELFSymTy &Symbol) {
4371 if (Symbol.isAbsolute() || !Symbol.isDefined())
4372 return false;
4374 // If we cannot link the symbol to a section, leave it as is.
4375 Expected<const typename ELFT::Shdr *> Section =
4376 Obj.getSection(Symbol.st_shndx);
4377 if (!Section)
4378 return false;
4380 // Remove the section symbol iif the corresponding section was stripped.
4381 if (Symbol.getType() == ELF::STT_SECTION) {
4382 if (!getNewSectionIndex(Symbol.st_shndx))
4383 return true;
4384 return false;
4387 // Symbols in non-allocatable sections are typically remnants of relocations
4388 // emitted under "-emit-relocs" linker option. Delete those as we delete
4389 // relocations against non-allocatable sections.
4390 if (!((*Section)->sh_flags & ELF::SHF_ALLOC))
4391 return true;
4393 return false;
4396 for (const ELFSymTy &Symbol : cantFail(Obj.symbols(&SymTabSection))) {
4397 // For regular (non-dynamic) symbol table strip unneeded symbols.
4398 if (!IsDynSym && shouldStrip(Symbol))
4399 continue;
4401 const BinaryFunction *Function =
4402 BC->getBinaryFunctionAtAddress(Symbol.st_value);
4403 // Ignore false function references, e.g. when the section address matches
4404 // the address of the function.
4405 if (Function && Symbol.getType() == ELF::STT_SECTION)
4406 Function = nullptr;
4408 // For non-dynamic symtab, make sure the symbol section matches that of
4409 // the function. It can mismatch e.g. if the symbol is a section marker
4410 // in which case we treat the symbol separately from the function.
4411 // For dynamic symbol table, the section index could be wrong on the input,
4412 // and its value is ignored by the runtime if it's different from
4413 // SHN_UNDEF and SHN_ABS.
4414 if (!IsDynSym && Function &&
4415 Symbol.st_shndx !=
4416 Function->getOriginSection()->getSectionRef().getIndex())
4417 Function = nullptr;
4419 // Create a new symbol based on the existing symbol.
4420 ELFSymTy NewSymbol = Symbol;
4422 if (Function) {
4423 // If the symbol matched a function that was not emitted, update the
4424 // corresponding section index but otherwise leave it unchanged.
4425 if (Function->isEmitted()) {
4426 NewSymbol.st_value = Function->getOutputAddress();
4427 NewSymbol.st_size = Function->getOutputSize();
4428 NewSymbol.st_shndx = Function->getCodeSection()->getIndex();
4429 } else if (Symbol.st_shndx < ELF::SHN_LORESERVE) {
4430 NewSymbol.st_shndx = getNewSectionIndex(Symbol.st_shndx);
4433 // Add new symbols to the symbol table if necessary.
4434 if (!IsDynSym)
4435 addExtraSymbols(*Function, NewSymbol);
4436 } else {
4437 // Check if the function symbol matches address inside a function, i.e.
4438 // it marks a secondary entry point.
4439 Function =
4440 (Symbol.getType() == ELF::STT_FUNC)
4441 ? BC->getBinaryFunctionContainingAddress(Symbol.st_value,
4442 /*CheckPastEnd=*/false,
4443 /*UseMaxSize=*/true)
4444 : nullptr;
4446 if (Function && Function->isEmitted()) {
4447 assert(Function->getLayout().isHotColdSplit() &&
4448 "Adding symbols based on cold fragment when there are more than "
4449 "2 fragments");
4450 const uint64_t OutputAddress =
4451 Function->translateInputToOutputAddress(Symbol.st_value);
4453 NewSymbol.st_value = OutputAddress;
4454 // Force secondary entry points to have zero size.
4455 NewSymbol.st_size = 0;
4457 // Find fragment containing entrypoint
4458 FunctionLayout::fragment_const_iterator FF = llvm::find_if(
4459 Function->getLayout().fragments(), [&](const FunctionFragment &FF) {
4460 uint64_t Lo = FF.getAddress();
4461 uint64_t Hi = Lo + FF.getImageSize();
4462 return Lo <= OutputAddress && OutputAddress < Hi;
4465 if (FF == Function->getLayout().fragment_end()) {
4466 assert(
4467 OutputAddress >= Function->getCodeSection()->getOutputAddress() &&
4468 OutputAddress < (Function->getCodeSection()->getOutputAddress() +
4469 Function->getCodeSection()->getOutputSize()) &&
4470 "Cannot locate fragment containg secondary entrypoint");
4471 FF = Function->getLayout().fragment_begin();
4474 NewSymbol.st_shndx =
4475 Function->getCodeSection(FF->getFragmentNum())->getIndex();
4476 } else {
4477 // Check if the symbol belongs to moved data object and update it.
4478 BinaryData *BD = opts::ReorderData.empty()
4479 ? nullptr
4480 : BC->getBinaryDataAtAddress(Symbol.st_value);
4481 if (BD && BD->isMoved() && !BD->isJumpTable()) {
4482 assert((!BD->getSize() || !Symbol.st_size ||
4483 Symbol.st_size == BD->getSize()) &&
4484 "sizes must match");
4486 BinarySection &OutputSection = BD->getOutputSection();
4487 assert(OutputSection.getIndex());
4488 LLVM_DEBUG(dbgs()
4489 << "BOLT-DEBUG: moving " << BD->getName() << " from "
4490 << *BC->getSectionNameForAddress(Symbol.st_value) << " ("
4491 << Symbol.st_shndx << ") to " << OutputSection.getName()
4492 << " (" << OutputSection.getIndex() << ")\n");
4493 NewSymbol.st_shndx = OutputSection.getIndex();
4494 NewSymbol.st_value = BD->getOutputAddress();
4495 } else {
4496 // Otherwise just update the section for the symbol.
4497 if (Symbol.st_shndx < ELF::SHN_LORESERVE)
4498 NewSymbol.st_shndx = getNewSectionIndex(Symbol.st_shndx);
4501 // Detect local syms in the text section that we didn't update
4502 // and that were preserved by the linker to support relocations against
4503 // .text. Remove them from the symtab.
4504 if (Symbol.getType() == ELF::STT_NOTYPE &&
4505 Symbol.getBinding() == ELF::STB_LOCAL && Symbol.st_size == 0) {
4506 if (BC->getBinaryFunctionContainingAddress(Symbol.st_value,
4507 /*CheckPastEnd=*/false,
4508 /*UseMaxSize=*/true)) {
4509 // Can only delete the symbol if not patching. Such symbols should
4510 // not exist in the dynamic symbol table.
4511 assert(!IsDynSym && "cannot delete symbol");
4512 continue;
4518 // Handle special symbols based on their name.
4519 Expected<StringRef> SymbolName = Symbol.getName(StringSection);
4520 assert(SymbolName && "cannot get symbol name");
4522 auto updateSymbolValue = [&](const StringRef Name,
4523 std::optional<uint64_t> Value = std::nullopt) {
4524 NewSymbol.st_value = Value ? *Value : getNewValueForSymbol(Name);
4525 NewSymbol.st_shndx = ELF::SHN_ABS;
4526 outs() << "BOLT-INFO: setting " << Name << " to 0x"
4527 << Twine::utohexstr(NewSymbol.st_value) << '\n';
4530 if (opts::HotText &&
4531 (*SymbolName == "__hot_start" || *SymbolName == "__hot_end")) {
4532 updateSymbolValue(*SymbolName);
4533 ++NumHotTextSymsUpdated;
4536 if (opts::HotData && (*SymbolName == "__hot_data_start" ||
4537 *SymbolName == "__hot_data_end")) {
4538 updateSymbolValue(*SymbolName);
4539 ++NumHotDataSymsUpdated;
4542 if (*SymbolName == "_end")
4543 updateSymbolValue(*SymbolName, NextAvailableAddress);
4545 if (IsDynSym)
4546 Write((&Symbol - cantFail(Obj.symbols(&SymTabSection)).begin()) *
4547 sizeof(ELFSymTy),
4548 NewSymbol);
4549 else
4550 Symbols.emplace_back(NewSymbol);
4553 if (IsDynSym) {
4554 assert(Symbols.empty());
4555 return;
4558 // Add symbols of injected functions
4559 for (BinaryFunction *Function : BC->getInjectedBinaryFunctions()) {
4560 ELFSymTy NewSymbol;
4561 BinarySection *OriginSection = Function->getOriginSection();
4562 NewSymbol.st_shndx =
4563 OriginSection
4564 ? getNewSectionIndex(OriginSection->getSectionRef().getIndex())
4565 : Function->getCodeSection()->getIndex();
4566 NewSymbol.st_value = Function->getOutputAddress();
4567 NewSymbol.st_name = AddToStrTab(Function->getOneName());
4568 NewSymbol.st_size = Function->getOutputSize();
4569 NewSymbol.st_other = 0;
4570 NewSymbol.setBindingAndType(ELF::STB_LOCAL, ELF::STT_FUNC);
4571 Symbols.emplace_back(NewSymbol);
4573 if (Function->isSplit()) {
4574 assert(Function->getLayout().isHotColdSplit() &&
4575 "Adding symbols based on cold fragment when there are more than "
4576 "2 fragments");
4577 ELFSymTy NewColdSym = NewSymbol;
4578 NewColdSym.setType(ELF::STT_NOTYPE);
4579 SmallVector<char, 256> Buf;
4580 NewColdSym.st_name = AddToStrTab(
4581 Twine(Function->getPrintName()).concat(".cold.0").toStringRef(Buf));
4582 const FunctionFragment &ColdFF =
4583 Function->getLayout().getFragment(FragmentNum::cold());
4584 NewColdSym.st_value = ColdFF.getAddress();
4585 NewColdSym.st_size = ColdFF.getImageSize();
4586 Symbols.emplace_back(NewColdSym);
4590 auto AddSymbol = [&](const StringRef &Name, uint64_t Address) {
4591 if (!Address)
4592 return;
4594 ELFSymTy Symbol;
4595 Symbol.st_value = Address;
4596 Symbol.st_shndx = ELF::SHN_ABS;
4597 Symbol.st_name = AddToStrTab(Name);
4598 Symbol.st_size = 0;
4599 Symbol.st_other = 0;
4600 Symbol.setBindingAndType(ELF::STB_WEAK, ELF::STT_NOTYPE);
4602 outs() << "BOLT-INFO: setting " << Name << " to 0x"
4603 << Twine::utohexstr(Symbol.st_value) << '\n';
4605 Symbols.emplace_back(Symbol);
4608 // Add runtime library start and fini address symbols
4609 if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary()) {
4610 AddSymbol("__bolt_runtime_start", RtLibrary->getRuntimeStartAddress());
4611 AddSymbol("__bolt_runtime_fini", RtLibrary->getRuntimeFiniAddress());
4614 assert((!NumHotTextSymsUpdated || NumHotTextSymsUpdated == 2) &&
4615 "either none or both __hot_start/__hot_end symbols were expected");
4616 assert((!NumHotDataSymsUpdated || NumHotDataSymsUpdated == 2) &&
4617 "either none or both __hot_data_start/__hot_data_end symbols were "
4618 "expected");
4620 auto AddEmittedSymbol = [&](const StringRef &Name) {
4621 AddSymbol(Name, getNewValueForSymbol(Name));
4624 if (opts::HotText && !NumHotTextSymsUpdated) {
4625 AddEmittedSymbol("__hot_start");
4626 AddEmittedSymbol("__hot_end");
4629 if (opts::HotData && !NumHotDataSymsUpdated) {
4630 AddEmittedSymbol("__hot_data_start");
4631 AddEmittedSymbol("__hot_data_end");
4634 // Put local symbols at the beginning.
4635 llvm::stable_sort(Symbols, [](const ELFSymTy &A, const ELFSymTy &B) {
4636 if (A.getBinding() == ELF::STB_LOCAL && B.getBinding() != ELF::STB_LOCAL)
4637 return true;
4638 return false;
4641 for (const ELFSymTy &Symbol : Symbols)
4642 Write(0, Symbol);
4645 template <typename ELFT>
4646 void RewriteInstance::patchELFSymTabs(ELFObjectFile<ELFT> *File) {
4647 const ELFFile<ELFT> &Obj = File->getELFFile();
4648 using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr;
4649 using ELFSymTy = typename ELFObjectFile<ELFT>::Elf_Sym;
4651 // Compute a preview of how section indices will change after rewriting, so
4652 // we can properly update the symbol table based on new section indices.
4653 std::vector<uint32_t> NewSectionIndex;
4654 getOutputSections(File, NewSectionIndex);
4656 // Set pointer at the end of the output file, so we can pwrite old symbol
4657 // tables if we need to.
4658 uint64_t NextAvailableOffset = getFileOffsetForAddress(NextAvailableAddress);
4659 assert(NextAvailableOffset >= FirstNonAllocatableOffset &&
4660 "next available offset calculation failure");
4661 Out->os().seek(NextAvailableOffset);
4663 // Update dynamic symbol table.
4664 const ELFShdrTy *DynSymSection = nullptr;
4665 for (const ELFShdrTy &Section : cantFail(Obj.sections())) {
4666 if (Section.sh_type == ELF::SHT_DYNSYM) {
4667 DynSymSection = &Section;
4668 break;
4671 assert((DynSymSection || BC->IsStaticExecutable) &&
4672 "dynamic symbol table expected");
4673 if (DynSymSection) {
4674 updateELFSymbolTable(
4675 File,
4676 /*IsDynSym=*/true,
4677 *DynSymSection,
4678 NewSectionIndex,
4679 [&](size_t Offset, const ELFSymTy &Sym) {
4680 Out->os().pwrite(reinterpret_cast<const char *>(&Sym),
4681 sizeof(ELFSymTy),
4682 DynSymSection->sh_offset + Offset);
4684 [](StringRef) -> size_t { return 0; });
4687 if (opts::RemoveSymtab)
4688 return;
4690 // (re)create regular symbol table.
4691 const ELFShdrTy *SymTabSection = nullptr;
4692 for (const ELFShdrTy &Section : cantFail(Obj.sections())) {
4693 if (Section.sh_type == ELF::SHT_SYMTAB) {
4694 SymTabSection = &Section;
4695 break;
4698 if (!SymTabSection) {
4699 errs() << "BOLT-WARNING: no symbol table found\n";
4700 return;
4703 const ELFShdrTy *StrTabSection =
4704 cantFail(Obj.getSection(SymTabSection->sh_link));
4705 std::string NewContents;
4706 std::string NewStrTab = std::string(
4707 File->getData().substr(StrTabSection->sh_offset, StrTabSection->sh_size));
4708 StringRef SecName = cantFail(Obj.getSectionName(*SymTabSection));
4709 StringRef StrSecName = cantFail(Obj.getSectionName(*StrTabSection));
4711 NumLocalSymbols = 0;
4712 updateELFSymbolTable(
4713 File,
4714 /*IsDynSym=*/false,
4715 *SymTabSection,
4716 NewSectionIndex,
4717 [&](size_t Offset, const ELFSymTy &Sym) {
4718 if (Sym.getBinding() == ELF::STB_LOCAL)
4719 ++NumLocalSymbols;
4720 NewContents.append(reinterpret_cast<const char *>(&Sym),
4721 sizeof(ELFSymTy));
4723 [&](StringRef Str) {
4724 size_t Idx = NewStrTab.size();
4725 NewStrTab.append(NameResolver::restore(Str).str());
4726 NewStrTab.append(1, '\0');
4727 return Idx;
4730 BC->registerOrUpdateNoteSection(SecName,
4731 copyByteArray(NewContents),
4732 NewContents.size(),
4733 /*Alignment=*/1,
4734 /*IsReadOnly=*/true,
4735 ELF::SHT_SYMTAB);
4737 BC->registerOrUpdateNoteSection(StrSecName,
4738 copyByteArray(NewStrTab),
4739 NewStrTab.size(),
4740 /*Alignment=*/1,
4741 /*IsReadOnly=*/true,
4742 ELF::SHT_STRTAB);
4745 template <typename ELFT>
4746 void RewriteInstance::patchELFAllocatableRelrSection(
4747 ELFObjectFile<ELFT> *File) {
4748 if (!DynamicRelrAddress)
4749 return;
4751 raw_fd_ostream &OS = Out->os();
4752 const uint8_t PSize = BC->AsmInfo->getCodePointerSize();
4753 const uint64_t MaxDelta = ((CHAR_BIT * DynamicRelrEntrySize) - 1) * PSize;
4755 auto FixAddend = [&](const BinarySection &Section, const Relocation &Rel,
4756 uint64_t FileOffset) {
4757 // Fix relocation symbol value in place if no static relocation found
4758 // on the same address. We won't check the BF relocations here since it
4759 // is rare case and no optimization is required.
4760 if (Section.getRelocationAt(Rel.Offset))
4761 return;
4763 // No fixup needed if symbol address was not changed
4764 const uint64_t Addend = getNewFunctionOrDataAddress(Rel.Addend);
4765 if (!Addend)
4766 return;
4768 OS.pwrite(reinterpret_cast<const char *>(&Addend), PSize, FileOffset);
4771 // Fill new relative relocation offsets set
4772 std::set<uint64_t> RelOffsets;
4773 for (const BinarySection &Section : BC->allocatableSections()) {
4774 const uint64_t SectionInputAddress = Section.getAddress();
4775 uint64_t SectionAddress = Section.getOutputAddress();
4776 if (!SectionAddress)
4777 SectionAddress = SectionInputAddress;
4779 for (const Relocation &Rel : Section.dynamicRelocations()) {
4780 if (!Rel.isRelative())
4781 continue;
4783 uint64_t RelOffset =
4784 getNewFunctionOrDataAddress(SectionInputAddress + Rel.Offset);
4786 RelOffset = RelOffset == 0 ? SectionAddress + Rel.Offset : RelOffset;
4787 assert((RelOffset & 1) == 0 && "Wrong relocation offset");
4788 RelOffsets.emplace(RelOffset);
4789 FixAddend(Section, Rel, RelOffset);
4793 ErrorOr<BinarySection &> Section =
4794 BC->getSectionForAddress(*DynamicRelrAddress);
4795 assert(Section && "cannot get .relr.dyn section");
4796 assert(Section->isRelr() && "Expected section to be SHT_RELR type");
4797 uint64_t RelrDynOffset = Section->getInputFileOffset();
4798 const uint64_t RelrDynEndOffset = RelrDynOffset + Section->getSize();
4800 auto WriteRelr = [&](uint64_t Value) {
4801 if (RelrDynOffset + DynamicRelrEntrySize > RelrDynEndOffset) {
4802 errs() << "BOLT-ERROR: Offset overflow for relr.dyn section\n";
4803 exit(1);
4806 OS.pwrite(reinterpret_cast<const char *>(&Value), DynamicRelrEntrySize,
4807 RelrDynOffset);
4808 RelrDynOffset += DynamicRelrEntrySize;
4811 for (auto RelIt = RelOffsets.begin(); RelIt != RelOffsets.end();) {
4812 WriteRelr(*RelIt);
4813 uint64_t Base = *RelIt++ + PSize;
4814 while (1) {
4815 uint64_t Bitmap = 0;
4816 for (; RelIt != RelOffsets.end(); ++RelIt) {
4817 const uint64_t Delta = *RelIt - Base;
4818 if (Delta >= MaxDelta || Delta % PSize)
4819 break;
4821 Bitmap |= (1ULL << (Delta / PSize));
4824 if (!Bitmap)
4825 break;
4827 WriteRelr((Bitmap << 1) | 1);
4828 Base += MaxDelta;
4832 // Fill the rest of the section with empty bitmap value
4833 while (RelrDynOffset != RelrDynEndOffset)
4834 WriteRelr(1);
4837 template <typename ELFT>
4838 void
4839 RewriteInstance::patchELFAllocatableRelaSections(ELFObjectFile<ELFT> *File) {
4840 using Elf_Rela = typename ELFT::Rela;
4841 raw_fd_ostream &OS = Out->os();
4842 const ELFFile<ELFT> &EF = File->getELFFile();
4844 uint64_t RelDynOffset = 0, RelDynEndOffset = 0;
4845 uint64_t RelPltOffset = 0, RelPltEndOffset = 0;
4847 auto setSectionFileOffsets = [&](uint64_t Address, uint64_t &Start,
4848 uint64_t &End) {
4849 ErrorOr<BinarySection &> Section = BC->getSectionForAddress(Address);
4850 assert(Section && "cannot get relocation section");
4851 Start = Section->getInputFileOffset();
4852 End = Start + Section->getSize();
4855 if (!DynamicRelocationsAddress && !PLTRelocationsAddress)
4856 return;
4858 if (DynamicRelocationsAddress)
4859 setSectionFileOffsets(*DynamicRelocationsAddress, RelDynOffset,
4860 RelDynEndOffset);
4862 if (PLTRelocationsAddress)
4863 setSectionFileOffsets(*PLTRelocationsAddress, RelPltOffset,
4864 RelPltEndOffset);
4866 DynamicRelativeRelocationsCount = 0;
4868 auto writeRela = [&OS](const Elf_Rela *RelA, uint64_t &Offset) {
4869 OS.pwrite(reinterpret_cast<const char *>(RelA), sizeof(*RelA), Offset);
4870 Offset += sizeof(*RelA);
4873 auto writeRelocations = [&](bool PatchRelative) {
4874 for (BinarySection &Section : BC->allocatableSections()) {
4875 const uint64_t SectionInputAddress = Section.getAddress();
4876 uint64_t SectionAddress = Section.getOutputAddress();
4877 if (!SectionAddress)
4878 SectionAddress = SectionInputAddress;
4880 for (const Relocation &Rel : Section.dynamicRelocations()) {
4881 const bool IsRelative = Rel.isRelative();
4882 if (PatchRelative != IsRelative)
4883 continue;
4885 if (IsRelative)
4886 ++DynamicRelativeRelocationsCount;
4888 Elf_Rela NewRelA;
4889 MCSymbol *Symbol = Rel.Symbol;
4890 uint32_t SymbolIdx = 0;
4891 uint64_t Addend = Rel.Addend;
4892 uint64_t RelOffset =
4893 getNewFunctionOrDataAddress(SectionInputAddress + Rel.Offset);
4895 RelOffset = RelOffset == 0 ? SectionAddress + Rel.Offset : RelOffset;
4896 if (Rel.Symbol) {
4897 SymbolIdx = getOutputDynamicSymbolIndex(Symbol);
4898 } else {
4899 // Usually this case is used for R_*_(I)RELATIVE relocations
4900 const uint64_t Address = getNewFunctionOrDataAddress(Addend);
4901 if (Address)
4902 Addend = Address;
4905 NewRelA.setSymbolAndType(SymbolIdx, Rel.Type, EF.isMips64EL());
4906 NewRelA.r_offset = RelOffset;
4907 NewRelA.r_addend = Addend;
4909 const bool IsJmpRel = IsJmpRelocation.contains(Rel.Type);
4910 uint64_t &Offset = IsJmpRel ? RelPltOffset : RelDynOffset;
4911 const uint64_t &EndOffset =
4912 IsJmpRel ? RelPltEndOffset : RelDynEndOffset;
4913 if (!Offset || !EndOffset) {
4914 errs() << "BOLT-ERROR: Invalid offsets for dynamic relocation\n";
4915 exit(1);
4918 if (Offset + sizeof(NewRelA) > EndOffset) {
4919 errs() << "BOLT-ERROR: Offset overflow for dynamic relocation\n";
4920 exit(1);
4923 writeRela(&NewRelA, Offset);
4928 // Place R_*_RELATIVE relocations in RELA section if RELR is not presented.
4929 // The dynamic linker expects all R_*_RELATIVE relocations in RELA
4930 // to be emitted first.
4931 if (!DynamicRelrAddress)
4932 writeRelocations(/* PatchRelative */ true);
4933 writeRelocations(/* PatchRelative */ false);
4935 auto fillNone = [&](uint64_t &Offset, uint64_t EndOffset) {
4936 if (!Offset)
4937 return;
4939 typename ELFObjectFile<ELFT>::Elf_Rela RelA;
4940 RelA.setSymbolAndType(0, Relocation::getNone(), EF.isMips64EL());
4941 RelA.r_offset = 0;
4942 RelA.r_addend = 0;
4943 while (Offset < EndOffset)
4944 writeRela(&RelA, Offset);
4946 assert(Offset == EndOffset && "Unexpected section overflow");
4949 // Fill the rest of the sections with R_*_NONE relocations
4950 fillNone(RelDynOffset, RelDynEndOffset);
4951 fillNone(RelPltOffset, RelPltEndOffset);
4954 template <typename ELFT>
4955 void RewriteInstance::patchELFGOT(ELFObjectFile<ELFT> *File) {
4956 raw_fd_ostream &OS = Out->os();
4958 SectionRef GOTSection;
4959 for (const SectionRef &Section : File->sections()) {
4960 StringRef SectionName = cantFail(Section.getName());
4961 if (SectionName == ".got") {
4962 GOTSection = Section;
4963 break;
4966 if (!GOTSection.getObject()) {
4967 if (!BC->IsStaticExecutable)
4968 errs() << "BOLT-INFO: no .got section found\n";
4969 return;
4972 StringRef GOTContents = cantFail(GOTSection.getContents());
4973 for (const uint64_t *GOTEntry =
4974 reinterpret_cast<const uint64_t *>(GOTContents.data());
4975 GOTEntry < reinterpret_cast<const uint64_t *>(GOTContents.data() +
4976 GOTContents.size());
4977 ++GOTEntry) {
4978 if (uint64_t NewAddress = getNewFunctionAddress(*GOTEntry)) {
4979 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: patching GOT entry 0x"
4980 << Twine::utohexstr(*GOTEntry) << " with 0x"
4981 << Twine::utohexstr(NewAddress) << '\n');
4982 OS.pwrite(reinterpret_cast<const char *>(&NewAddress), sizeof(NewAddress),
4983 reinterpret_cast<const char *>(GOTEntry) -
4984 File->getData().data());
4989 template <typename ELFT>
4990 void RewriteInstance::patchELFDynamic(ELFObjectFile<ELFT> *File) {
4991 if (BC->IsStaticExecutable)
4992 return;
4994 const ELFFile<ELFT> &Obj = File->getELFFile();
4995 raw_fd_ostream &OS = Out->os();
4997 using Elf_Phdr = typename ELFFile<ELFT>::Elf_Phdr;
4998 using Elf_Dyn = typename ELFFile<ELFT>::Elf_Dyn;
5000 // Locate DYNAMIC by looking through program headers.
5001 uint64_t DynamicOffset = 0;
5002 const Elf_Phdr *DynamicPhdr = nullptr;
5003 for (const Elf_Phdr &Phdr : cantFail(Obj.program_headers())) {
5004 if (Phdr.p_type == ELF::PT_DYNAMIC) {
5005 DynamicOffset = Phdr.p_offset;
5006 DynamicPhdr = &Phdr;
5007 assert(Phdr.p_memsz == Phdr.p_filesz && "dynamic sizes should match");
5008 break;
5011 assert(DynamicPhdr && "missing dynamic in ELF binary");
5013 bool ZNowSet = false;
5015 // Go through all dynamic entries and patch functions addresses with
5016 // new ones.
5017 typename ELFT::DynRange DynamicEntries =
5018 cantFail(Obj.dynamicEntries(), "error accessing dynamic table");
5019 auto DTB = DynamicEntries.begin();
5020 for (const Elf_Dyn &Dyn : DynamicEntries) {
5021 Elf_Dyn NewDE = Dyn;
5022 bool ShouldPatch = true;
5023 switch (Dyn.d_tag) {
5024 default:
5025 ShouldPatch = false;
5026 break;
5027 case ELF::DT_RELACOUNT:
5028 NewDE.d_un.d_val = DynamicRelativeRelocationsCount;
5029 break;
5030 case ELF::DT_INIT:
5031 case ELF::DT_FINI: {
5032 if (BC->HasRelocations) {
5033 if (uint64_t NewAddress = getNewFunctionAddress(Dyn.getPtr())) {
5034 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: patching dynamic entry of type "
5035 << Dyn.getTag() << '\n');
5036 NewDE.d_un.d_ptr = NewAddress;
5039 RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary();
5040 if (RtLibrary && Dyn.getTag() == ELF::DT_FINI) {
5041 if (uint64_t Addr = RtLibrary->getRuntimeFiniAddress())
5042 NewDE.d_un.d_ptr = Addr;
5044 if (RtLibrary && Dyn.getTag() == ELF::DT_INIT && !BC->HasInterpHeader) {
5045 if (auto Addr = RtLibrary->getRuntimeStartAddress()) {
5046 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Set DT_INIT to 0x"
5047 << Twine::utohexstr(Addr) << '\n');
5048 NewDE.d_un.d_ptr = Addr;
5051 break;
5053 case ELF::DT_FLAGS:
5054 if (BC->RequiresZNow) {
5055 NewDE.d_un.d_val |= ELF::DF_BIND_NOW;
5056 ZNowSet = true;
5058 break;
5059 case ELF::DT_FLAGS_1:
5060 if (BC->RequiresZNow) {
5061 NewDE.d_un.d_val |= ELF::DF_1_NOW;
5062 ZNowSet = true;
5064 break;
5066 if (ShouldPatch)
5067 OS.pwrite(reinterpret_cast<const char *>(&NewDE), sizeof(NewDE),
5068 DynamicOffset + (&Dyn - DTB) * sizeof(Dyn));
5071 if (BC->RequiresZNow && !ZNowSet) {
5072 errs() << "BOLT-ERROR: output binary requires immediate relocation "
5073 "processing which depends on DT_FLAGS or DT_FLAGS_1 presence in "
5074 ".dynamic. Please re-link the binary with -znow.\n";
5075 exit(1);
5079 template <typename ELFT>
5080 Error RewriteInstance::readELFDynamic(ELFObjectFile<ELFT> *File) {
5081 const ELFFile<ELFT> &Obj = File->getELFFile();
5083 using Elf_Phdr = typename ELFFile<ELFT>::Elf_Phdr;
5084 using Elf_Dyn = typename ELFFile<ELFT>::Elf_Dyn;
5086 // Locate DYNAMIC by looking through program headers.
5087 const Elf_Phdr *DynamicPhdr = nullptr;
5088 for (const Elf_Phdr &Phdr : cantFail(Obj.program_headers())) {
5089 if (Phdr.p_type == ELF::PT_DYNAMIC) {
5090 DynamicPhdr = &Phdr;
5091 break;
5095 if (!DynamicPhdr) {
5096 outs() << "BOLT-INFO: static input executable detected\n";
5097 // TODO: static PIE executable might have dynamic header
5098 BC->IsStaticExecutable = true;
5099 return Error::success();
5102 if (DynamicPhdr->p_memsz != DynamicPhdr->p_filesz)
5103 return createStringError(errc::executable_format_error,
5104 "dynamic section sizes should match");
5106 // Go through all dynamic entries to locate entries of interest.
5107 auto DynamicEntriesOrErr = Obj.dynamicEntries();
5108 if (!DynamicEntriesOrErr)
5109 return DynamicEntriesOrErr.takeError();
5110 typename ELFT::DynRange DynamicEntries = DynamicEntriesOrErr.get();
5112 for (const Elf_Dyn &Dyn : DynamicEntries) {
5113 switch (Dyn.d_tag) {
5114 case ELF::DT_INIT:
5115 if (!BC->HasInterpHeader) {
5116 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Set start function address\n");
5117 BC->StartFunctionAddress = Dyn.getPtr();
5119 break;
5120 case ELF::DT_FINI:
5121 BC->FiniFunctionAddress = Dyn.getPtr();
5122 break;
5123 case ELF::DT_RELA:
5124 DynamicRelocationsAddress = Dyn.getPtr();
5125 break;
5126 case ELF::DT_RELASZ:
5127 DynamicRelocationsSize = Dyn.getVal();
5128 break;
5129 case ELF::DT_JMPREL:
5130 PLTRelocationsAddress = Dyn.getPtr();
5131 break;
5132 case ELF::DT_PLTRELSZ:
5133 PLTRelocationsSize = Dyn.getVal();
5134 break;
5135 case ELF::DT_RELACOUNT:
5136 DynamicRelativeRelocationsCount = Dyn.getVal();
5137 break;
5138 case ELF::DT_RELR:
5139 DynamicRelrAddress = Dyn.getPtr();
5140 break;
5141 case ELF::DT_RELRSZ:
5142 DynamicRelrSize = Dyn.getVal();
5143 break;
5144 case ELF::DT_RELRENT:
5145 DynamicRelrEntrySize = Dyn.getVal();
5146 break;
5150 if (!DynamicRelocationsAddress || !DynamicRelocationsSize) {
5151 DynamicRelocationsAddress.reset();
5152 DynamicRelocationsSize = 0;
5155 if (!PLTRelocationsAddress || !PLTRelocationsSize) {
5156 PLTRelocationsAddress.reset();
5157 PLTRelocationsSize = 0;
5160 if (!DynamicRelrAddress || !DynamicRelrSize) {
5161 DynamicRelrAddress.reset();
5162 DynamicRelrSize = 0;
5163 } else if (!DynamicRelrEntrySize) {
5164 errs() << "BOLT-ERROR: expected DT_RELRENT to be presented "
5165 << "in DYNAMIC section\n";
5166 exit(1);
5167 } else if (DynamicRelrSize % DynamicRelrEntrySize) {
5168 errs() << "BOLT-ERROR: expected RELR table size to be divisible "
5169 << "by RELR entry size\n";
5170 exit(1);
5173 return Error::success();
5176 uint64_t RewriteInstance::getNewFunctionAddress(uint64_t OldAddress) {
5177 const BinaryFunction *Function = BC->getBinaryFunctionAtAddress(OldAddress);
5178 if (!Function)
5179 return 0;
5181 return Function->getOutputAddress();
5184 uint64_t RewriteInstance::getNewFunctionOrDataAddress(uint64_t OldAddress) {
5185 if (uint64_t Function = getNewFunctionAddress(OldAddress))
5186 return Function;
5188 const BinaryData *BD = BC->getBinaryDataAtAddress(OldAddress);
5189 if (BD && BD->isMoved())
5190 return BD->getOutputAddress();
5192 return 0;
5195 void RewriteInstance::rewriteFile() {
5196 std::error_code EC;
5197 Out = std::make_unique<ToolOutputFile>(opts::OutputFilename, EC,
5198 sys::fs::OF_None);
5199 check_error(EC, "cannot create output executable file");
5201 raw_fd_ostream &OS = Out->os();
5203 // Copy allocatable part of the input.
5204 OS << InputFile->getData().substr(0, FirstNonAllocatableOffset);
5206 auto Streamer = BC->createStreamer(OS);
5207 // Make sure output stream has enough reserved space, otherwise
5208 // pwrite() will fail.
5209 uint64_t Offset = OS.seek(getFileOffsetForAddress(NextAvailableAddress));
5210 (void)Offset;
5211 assert(Offset == getFileOffsetForAddress(NextAvailableAddress) &&
5212 "error resizing output file");
5214 // Overwrite functions with fixed output address. This is mostly used by
5215 // non-relocation mode, with one exception: injected functions are covered
5216 // here in both modes.
5217 uint64_t CountOverwrittenFunctions = 0;
5218 uint64_t OverwrittenScore = 0;
5219 for (BinaryFunction *Function : BC->getAllBinaryFunctions()) {
5220 if (Function->getImageAddress() == 0 || Function->getImageSize() == 0)
5221 continue;
5223 if (Function->getImageSize() > Function->getMaxSize()) {
5224 if (opts::Verbosity >= 1)
5225 errs() << "BOLT-WARNING: new function size (0x"
5226 << Twine::utohexstr(Function->getImageSize())
5227 << ") is larger than maximum allowed size (0x"
5228 << Twine::utohexstr(Function->getMaxSize()) << ") for function "
5229 << *Function << '\n';
5231 // Remove jump table sections that this function owns in non-reloc mode
5232 // because we don't want to write them anymore.
5233 if (!BC->HasRelocations && opts::JumpTables == JTS_BASIC) {
5234 for (auto &JTI : Function->JumpTables) {
5235 JumpTable *JT = JTI.second;
5236 BinarySection &Section = JT->getOutputSection();
5237 BC->deregisterSection(Section);
5240 continue;
5243 const auto HasAddress = [](const FunctionFragment &FF) {
5244 return FF.empty() ||
5245 (FF.getImageAddress() != 0 && FF.getImageSize() != 0);
5247 const bool SplitFragmentsHaveAddress =
5248 llvm::all_of(Function->getLayout().getSplitFragments(), HasAddress);
5249 if (Function->isSplit() && !SplitFragmentsHaveAddress) {
5250 const auto HasNoAddress = [](const FunctionFragment &FF) {
5251 return FF.getImageAddress() == 0 && FF.getImageSize() == 0;
5253 assert(llvm::all_of(Function->getLayout().getSplitFragments(),
5254 HasNoAddress) &&
5255 "Some split fragments have an address while others do not");
5256 (void)HasNoAddress;
5257 continue;
5260 OverwrittenScore += Function->getFunctionScore();
5261 ++CountOverwrittenFunctions;
5263 // Overwrite function in the output file.
5264 if (opts::Verbosity >= 2)
5265 outs() << "BOLT: rewriting function \"" << *Function << "\"\n";
5267 OS.pwrite(reinterpret_cast<char *>(Function->getImageAddress()),
5268 Function->getImageSize(), Function->getFileOffset());
5270 // Write nops at the end of the function.
5271 if (Function->getMaxSize() != std::numeric_limits<uint64_t>::max()) {
5272 uint64_t Pos = OS.tell();
5273 OS.seek(Function->getFileOffset() + Function->getImageSize());
5274 BC->MAB->writeNopData(
5275 OS, Function->getMaxSize() - Function->getImageSize(), &*BC->STI);
5277 OS.seek(Pos);
5280 if (!Function->isSplit())
5281 continue;
5283 // Write cold part
5284 if (opts::Verbosity >= 2) {
5285 outs() << formatv("BOLT: rewriting function \"{0}\" (split parts)\n",
5286 *Function);
5289 for (const FunctionFragment &FF :
5290 Function->getLayout().getSplitFragments()) {
5291 OS.pwrite(reinterpret_cast<char *>(FF.getImageAddress()),
5292 FF.getImageSize(), FF.getFileOffset());
5296 // Print function statistics for non-relocation mode.
5297 if (!BC->HasRelocations) {
5298 outs() << "BOLT: " << CountOverwrittenFunctions << " out of "
5299 << BC->getBinaryFunctions().size()
5300 << " functions were overwritten.\n";
5301 if (BC->TotalScore != 0) {
5302 double Coverage = OverwrittenScore / (double)BC->TotalScore * 100.0;
5303 outs() << format("BOLT-INFO: rewritten functions cover %.2lf", Coverage)
5304 << "% of the execution count of simple functions of "
5305 "this binary\n";
5309 if (BC->HasRelocations && opts::TrapOldCode) {
5310 uint64_t SavedPos = OS.tell();
5311 // Overwrite function body to make sure we never execute these instructions.
5312 for (auto &BFI : BC->getBinaryFunctions()) {
5313 BinaryFunction &BF = BFI.second;
5314 if (!BF.getFileOffset() || !BF.isEmitted())
5315 continue;
5316 OS.seek(BF.getFileOffset());
5317 StringRef TrapInstr = BC->MIB->getTrapFillValue();
5318 unsigned NInstr = BF.getMaxSize() / TrapInstr.size();
5319 for (unsigned I = 0; I < NInstr; ++I)
5320 OS.write(TrapInstr.data(), TrapInstr.size());
5322 OS.seek(SavedPos);
5325 // Write all allocatable sections - reloc-mode text is written here as well
5326 for (BinarySection &Section : BC->allocatableSections()) {
5327 if (!Section.isFinalized() || !Section.getOutputData())
5328 continue;
5329 if (Section.isLinkOnly())
5330 continue;
5332 if (opts::Verbosity >= 1)
5333 outs() << "BOLT: writing new section " << Section.getName()
5334 << "\n data at 0x" << Twine::utohexstr(Section.getAllocAddress())
5335 << "\n of size " << Section.getOutputSize() << "\n at offset "
5336 << Section.getOutputFileOffset() << '\n';
5337 OS.pwrite(reinterpret_cast<const char *>(Section.getOutputData()),
5338 Section.getOutputSize(), Section.getOutputFileOffset());
5341 for (BinarySection &Section : BC->allocatableSections())
5342 Section.flushPendingRelocations(OS, [this](const MCSymbol *S) {
5343 return getNewValueForSymbol(S->getName());
5346 // If .eh_frame is present create .eh_frame_hdr.
5347 if (EHFrameSection)
5348 writeEHFrameHeader();
5350 // Add BOLT Addresses Translation maps to allow profile collection to
5351 // happen in the output binary
5352 if (opts::EnableBAT)
5353 addBATSection();
5355 // Patch program header table.
5356 patchELFPHDRTable();
5358 // Finalize memory image of section string table.
5359 finalizeSectionStringTable();
5361 // Update symbol tables.
5362 patchELFSymTabs();
5364 patchBuildID();
5366 if (opts::EnableBAT)
5367 encodeBATSection();
5369 // Copy non-allocatable sections once allocatable part is finished.
5370 rewriteNoteSections();
5372 if (BC->HasRelocations) {
5373 patchELFAllocatableRelaSections();
5374 patchELFAllocatableRelrSection();
5375 patchELFGOT();
5378 // Patch dynamic section/segment.
5379 patchELFDynamic();
5381 // Update ELF book-keeping info.
5382 patchELFSectionHeaderTable();
5384 if (opts::PrintSections) {
5385 outs() << "BOLT-INFO: Sections after processing:\n";
5386 BC->printSections(outs());
5389 Out->keep();
5390 EC = sys::fs::setPermissions(
5391 opts::OutputFilename,
5392 static_cast<sys::fs::perms>(sys::fs::perms::all_all &
5393 ~sys::fs::getUmask()));
5394 check_error(EC, "cannot set permissions of output file");
5397 void RewriteInstance::writeEHFrameHeader() {
5398 BinarySection *NewEHFrameSection =
5399 getSection(getNewSecPrefix() + getEHFrameSectionName());
5401 // No need to update the header if no new .eh_frame was created.
5402 if (!NewEHFrameSection)
5403 return;
5405 DWARFDebugFrame NewEHFrame(BC->TheTriple->getArch(), true,
5406 NewEHFrameSection->getOutputAddress());
5407 Error E = NewEHFrame.parse(DWARFDataExtractor(
5408 NewEHFrameSection->getOutputContents(), BC->AsmInfo->isLittleEndian(),
5409 BC->AsmInfo->getCodePointerSize()));
5410 check_error(std::move(E), "failed to parse EH frame");
5412 uint64_t RelocatedEHFrameAddress = 0;
5413 StringRef RelocatedEHFrameContents;
5414 BinarySection *RelocatedEHFrameSection =
5415 getSection(".relocated" + getEHFrameSectionName());
5416 if (RelocatedEHFrameSection) {
5417 RelocatedEHFrameAddress = RelocatedEHFrameSection->getOutputAddress();
5418 RelocatedEHFrameContents = RelocatedEHFrameSection->getOutputContents();
5420 DWARFDebugFrame RelocatedEHFrame(BC->TheTriple->getArch(), true,
5421 RelocatedEHFrameAddress);
5422 Error Er = RelocatedEHFrame.parse(DWARFDataExtractor(
5423 RelocatedEHFrameContents, BC->AsmInfo->isLittleEndian(),
5424 BC->AsmInfo->getCodePointerSize()));
5425 check_error(std::move(Er), "failed to parse EH frame");
5427 LLVM_DEBUG(dbgs() << "BOLT: writing a new .eh_frame_hdr\n");
5429 NextAvailableAddress =
5430 appendPadding(Out->os(), NextAvailableAddress, EHFrameHdrAlign);
5432 const uint64_t EHFrameHdrOutputAddress = NextAvailableAddress;
5433 const uint64_t EHFrameHdrFileOffset =
5434 getFileOffsetForAddress(NextAvailableAddress);
5436 std::vector<char> NewEHFrameHdr = CFIRdWrt->generateEHFrameHeader(
5437 RelocatedEHFrame, NewEHFrame, EHFrameHdrOutputAddress, FailedAddresses);
5439 assert(Out->os().tell() == EHFrameHdrFileOffset && "offset mismatch");
5440 Out->os().write(NewEHFrameHdr.data(), NewEHFrameHdr.size());
5442 const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/true,
5443 /*IsText=*/false,
5444 /*IsAllocatable=*/true);
5445 BinarySection *OldEHFrameHdrSection = getSection(".eh_frame_hdr");
5446 if (OldEHFrameHdrSection)
5447 OldEHFrameHdrSection->setOutputName(getOrgSecPrefix() + ".eh_frame_hdr");
5449 BinarySection &EHFrameHdrSec = BC->registerOrUpdateSection(
5450 getNewSecPrefix() + ".eh_frame_hdr", ELF::SHT_PROGBITS, Flags, nullptr,
5451 NewEHFrameHdr.size(), /*Alignment=*/1);
5452 EHFrameHdrSec.setOutputFileOffset(EHFrameHdrFileOffset);
5453 EHFrameHdrSec.setOutputAddress(EHFrameHdrOutputAddress);
5454 EHFrameHdrSec.setOutputName(".eh_frame_hdr");
5456 NextAvailableAddress += EHFrameHdrSec.getOutputSize();
5458 // Merge new .eh_frame with the relocated original so that gdb can locate all
5459 // FDEs.
5460 if (RelocatedEHFrameSection) {
5461 const uint64_t NewEHFrameSectionSize =
5462 RelocatedEHFrameSection->getOutputAddress() +
5463 RelocatedEHFrameSection->getOutputSize() -
5464 NewEHFrameSection->getOutputAddress();
5465 NewEHFrameSection->updateContents(NewEHFrameSection->getOutputData(),
5466 NewEHFrameSectionSize);
5467 BC->deregisterSection(*RelocatedEHFrameSection);
5470 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: size of .eh_frame after merge is "
5471 << NewEHFrameSection->getOutputSize() << '\n');
5474 uint64_t RewriteInstance::getNewValueForSymbol(const StringRef Name) {
5475 auto Value = Linker->lookupSymbol(Name);
5476 if (Value)
5477 return *Value;
5479 // Return the original value if we haven't emitted the symbol.
5480 BinaryData *BD = BC->getBinaryDataByName(Name);
5481 if (!BD)
5482 return 0;
5484 return BD->getAddress();
5487 uint64_t RewriteInstance::getFileOffsetForAddress(uint64_t Address) const {
5488 // Check if it's possibly part of the new segment.
5489 if (Address >= NewTextSegmentAddress)
5490 return Address - NewTextSegmentAddress + NewTextSegmentOffset;
5492 // Find an existing segment that matches the address.
5493 const auto SegmentInfoI = BC->SegmentMapInfo.upper_bound(Address);
5494 if (SegmentInfoI == BC->SegmentMapInfo.begin())
5495 return 0;
5497 const SegmentInfo &SegmentInfo = std::prev(SegmentInfoI)->second;
5498 if (Address < SegmentInfo.Address ||
5499 Address >= SegmentInfo.Address + SegmentInfo.FileSize)
5500 return 0;
5502 return SegmentInfo.FileOffset + Address - SegmentInfo.Address;
5505 bool RewriteInstance::willOverwriteSection(StringRef SectionName) {
5506 if (llvm::is_contained(SectionsToOverwrite, SectionName))
5507 return true;
5508 if (llvm::is_contained(DebugSectionsToOverwrite, SectionName))
5509 return true;
5511 ErrorOr<BinarySection &> Section = BC->getUniqueSectionByName(SectionName);
5512 return Section && Section->isAllocatable() && Section->isFinalized();
5515 bool RewriteInstance::isDebugSection(StringRef SectionName) {
5516 if (SectionName.startswith(".debug_") || SectionName.startswith(".zdebug_") ||
5517 SectionName == ".gdb_index" || SectionName == ".stab" ||
5518 SectionName == ".stabstr")
5519 return true;
5521 return false;
5524 bool RewriteInstance::isKSymtabSection(StringRef SectionName) {
5525 if (SectionName.startswith("__ksymtab"))
5526 return true;
5528 return false;