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