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