xref: /llvm-project/bolt/lib/Rewrite/RewriteInstance.cpp (revision 3fe50b6dde174c76b3380927d7dd43ac19527d64)
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 &[ParentName, BF] : AmbiguousFragments) {
1436     const uint64_t Address = BF->getAddress();
1437 
1438     // Get fragment's own symbol
1439     const auto SymIt = llvm::find_if(
1440         llvm::make_range(FileSymRefs.equal_range(Address)), [&](auto SI) {
1441           StringRef Name = cantFail(SI.second.getName());
1442           return Name.contains(ParentName);
1443         });
1444     if (SymIt == FileSymRefs.end()) {
1445       BC->errs()
1446           << "BOLT-ERROR: symbol lookup failed for function at address 0x"
1447           << Twine::utohexstr(Address) << '\n';
1448       exit(1);
1449     }
1450 
1451     // Find containing FILE symbol
1452     ELFSymbolRef Symbol = SymIt->second;
1453     auto FSI = llvm::upper_bound(FileSymbols, Symbol);
1454     if (FSI == FileSymbols.begin()) {
1455       BC->errs() << "BOLT-ERROR: owning FILE symbol not found for symbol "
1456                  << cantFail(Symbol.getName()) << '\n';
1457       exit(1);
1458     }
1459 
1460     ELFSymbolRef StopSymbol = LocalSymEnd;
1461     if (FSI != FileSymbols.end())
1462       StopSymbol = *FSI;
1463 
1464     uint64_t ParentAddress{0};
1465 
1466     // BOLT split fragment symbols are emitted just before the main function
1467     // symbol.
1468     for (ELFSymbolRef NextSymbol = Symbol; NextSymbol < StopSymbol;
1469          NextSymbol.moveNext()) {
1470       StringRef Name = cantFail(NextSymbol.getName());
1471       if (Name == ParentName) {
1472         ParentAddress = cantFail(NextSymbol.getValue());
1473         goto registerParent;
1474       }
1475       if (Name.starts_with(ParentName))
1476         // With multi-way splitting, there are multiple fragments with different
1477         // suffixes. Parent follows the last fragment.
1478         continue;
1479       break;
1480     }
1481 
1482     // Iterate over local file symbols and check symbol names to match parent.
1483     for (ELFSymbolRef Symbol(FSI[-1]); Symbol < StopSymbol; Symbol.moveNext()) {
1484       if (cantFail(Symbol.getName()) == ParentName) {
1485         ParentAddress = cantFail(Symbol.getAddress());
1486         break;
1487       }
1488     }
1489 
1490 registerParent:
1491     // No local parent is found, use global parent function.
1492     if (!ParentAddress)
1493       if (BinaryData *ParentBD = BC->getBinaryDataByName(ParentName))
1494         ParentAddress = ParentBD->getAddress();
1495 
1496     if (BinaryFunction *ParentBF =
1497             BC->getBinaryFunctionAtAddress(ParentAddress)) {
1498       BC->registerFragment(*BF, *ParentBF);
1499       continue;
1500     }
1501     BC->errs() << "BOLT-ERROR: parent function not found for " << *BF << '\n';
1502     exit(1);
1503   }
1504 }
1505 
1506 void RewriteInstance::createPLTBinaryFunction(uint64_t TargetAddress,
1507                                               uint64_t EntryAddress,
1508                                               uint64_t EntrySize) {
1509   if (!TargetAddress)
1510     return;
1511 
1512   auto setPLTSymbol = [&](BinaryFunction *BF, StringRef Name) {
1513     const unsigned PtrSize = BC->AsmInfo->getCodePointerSize();
1514     MCSymbol *TargetSymbol = BC->registerNameAtAddress(
1515         Name.str() + "@GOT", TargetAddress, PtrSize, PtrSize);
1516     BF->setPLTSymbol(TargetSymbol);
1517   };
1518 
1519   BinaryFunction *BF = BC->getBinaryFunctionAtAddress(EntryAddress);
1520   if (BF && BC->isAArch64()) {
1521     // Handle IFUNC trampoline with symbol
1522     setPLTSymbol(BF, BF->getOneName());
1523     return;
1524   }
1525 
1526   const Relocation *Rel = BC->getDynamicRelocationAt(TargetAddress);
1527   if (!Rel)
1528     return;
1529 
1530   MCSymbol *Symbol = Rel->Symbol;
1531   if (!Symbol) {
1532     if (!BC->isAArch64() || !Rel->Addend || !Rel->isIRelative())
1533       return;
1534 
1535     // IFUNC trampoline without symbol
1536     BinaryFunction *TargetBF = BC->getBinaryFunctionAtAddress(Rel->Addend);
1537     if (!TargetBF) {
1538       BC->errs()
1539           << "BOLT-WARNING: Expected BF to be presented as IFUNC resolver at "
1540           << Twine::utohexstr(Rel->Addend) << ", skipping\n";
1541       return;
1542     }
1543 
1544     Symbol = TargetBF->getSymbol();
1545   }
1546 
1547   ErrorOr<BinarySection &> Section = BC->getSectionForAddress(EntryAddress);
1548   assert(Section && "cannot get section for address");
1549   if (!BF)
1550     BF = BC->createBinaryFunction(Symbol->getName().str() + "@PLT", *Section,
1551                                   EntryAddress, 0, EntrySize,
1552                                   Section->getAlignment());
1553   else
1554     BF->addAlternativeName(Symbol->getName().str() + "@PLT");
1555   setPLTSymbol(BF, Symbol->getName());
1556 }
1557 
1558 void RewriteInstance::disassemblePLTInstruction(const BinarySection &Section,
1559                                                 uint64_t InstrOffset,
1560                                                 MCInst &Instruction,
1561                                                 uint64_t &InstrSize) {
1562   const uint64_t SectionAddress = Section.getAddress();
1563   const uint64_t SectionSize = Section.getSize();
1564   StringRef PLTContents = Section.getContents();
1565   ArrayRef<uint8_t> PLTData(
1566       reinterpret_cast<const uint8_t *>(PLTContents.data()), SectionSize);
1567 
1568   const uint64_t InstrAddr = SectionAddress + InstrOffset;
1569   if (!BC->DisAsm->getInstruction(Instruction, InstrSize,
1570                                   PLTData.slice(InstrOffset), InstrAddr,
1571                                   nulls())) {
1572     BC->errs()
1573         << "BOLT-ERROR: unable to disassemble instruction in PLT section "
1574         << Section.getName() << formatv(" at offset {0:x}\n", InstrOffset);
1575     exit(1);
1576   }
1577 }
1578 
1579 void RewriteInstance::disassemblePLTSectionAArch64(BinarySection &Section) {
1580   const uint64_t SectionAddress = Section.getAddress();
1581   const uint64_t SectionSize = Section.getSize();
1582 
1583   uint64_t InstrOffset = 0;
1584   // Locate new plt entry
1585   while (InstrOffset < SectionSize) {
1586     InstructionListType Instructions;
1587     MCInst Instruction;
1588     uint64_t EntryOffset = InstrOffset;
1589     uint64_t EntrySize = 0;
1590     uint64_t InstrSize;
1591     // Loop through entry instructions
1592     while (InstrOffset < SectionSize) {
1593       disassemblePLTInstruction(Section, InstrOffset, Instruction, InstrSize);
1594       EntrySize += InstrSize;
1595       if (!BC->MIB->isIndirectBranch(Instruction)) {
1596         Instructions.emplace_back(Instruction);
1597         InstrOffset += InstrSize;
1598         continue;
1599       }
1600 
1601       const uint64_t EntryAddress = SectionAddress + EntryOffset;
1602       const uint64_t TargetAddress = BC->MIB->analyzePLTEntry(
1603           Instruction, Instructions.begin(), Instructions.end(), EntryAddress);
1604 
1605       createPLTBinaryFunction(TargetAddress, EntryAddress, EntrySize);
1606       break;
1607     }
1608 
1609     // Branch instruction
1610     InstrOffset += InstrSize;
1611 
1612     // Skip nops if any
1613     while (InstrOffset < SectionSize) {
1614       disassemblePLTInstruction(Section, InstrOffset, Instruction, InstrSize);
1615       if (!BC->MIB->isNoop(Instruction))
1616         break;
1617 
1618       InstrOffset += InstrSize;
1619     }
1620   }
1621 }
1622 
1623 void RewriteInstance::disassemblePLTSectionRISCV(BinarySection &Section) {
1624   const uint64_t SectionAddress = Section.getAddress();
1625   const uint64_t SectionSize = Section.getSize();
1626   StringRef PLTContents = Section.getContents();
1627   ArrayRef<uint8_t> PLTData(
1628       reinterpret_cast<const uint8_t *>(PLTContents.data()), SectionSize);
1629 
1630   auto disassembleInstruction = [&](uint64_t InstrOffset, MCInst &Instruction,
1631                                     uint64_t &InstrSize) {
1632     const uint64_t InstrAddr = SectionAddress + InstrOffset;
1633     if (!BC->DisAsm->getInstruction(Instruction, InstrSize,
1634                                     PLTData.slice(InstrOffset), InstrAddr,
1635                                     nulls())) {
1636       BC->errs()
1637           << "BOLT-ERROR: unable to disassemble instruction in PLT section "
1638           << Section.getName() << " at offset 0x"
1639           << Twine::utohexstr(InstrOffset) << '\n';
1640       exit(1);
1641     }
1642   };
1643 
1644   // Skip the first special entry since no relocation points to it.
1645   uint64_t InstrOffset = 32;
1646 
1647   while (InstrOffset < SectionSize) {
1648     InstructionListType Instructions;
1649     MCInst Instruction;
1650     const uint64_t EntryOffset = InstrOffset;
1651     const uint64_t EntrySize = 16;
1652     uint64_t InstrSize;
1653 
1654     while (InstrOffset < EntryOffset + EntrySize) {
1655       disassembleInstruction(InstrOffset, Instruction, InstrSize);
1656       Instructions.emplace_back(Instruction);
1657       InstrOffset += InstrSize;
1658     }
1659 
1660     const uint64_t EntryAddress = SectionAddress + EntryOffset;
1661     const uint64_t TargetAddress = BC->MIB->analyzePLTEntry(
1662         Instruction, Instructions.begin(), Instructions.end(), EntryAddress);
1663 
1664     createPLTBinaryFunction(TargetAddress, EntryAddress, EntrySize);
1665   }
1666 }
1667 
1668 void RewriteInstance::disassemblePLTSectionX86(BinarySection &Section,
1669                                                uint64_t EntrySize) {
1670   const uint64_t SectionAddress = Section.getAddress();
1671   const uint64_t SectionSize = Section.getSize();
1672 
1673   for (uint64_t EntryOffset = 0; EntryOffset + EntrySize <= SectionSize;
1674        EntryOffset += EntrySize) {
1675     MCInst Instruction;
1676     uint64_t InstrSize, InstrOffset = EntryOffset;
1677     while (InstrOffset < EntryOffset + EntrySize) {
1678       disassemblePLTInstruction(Section, InstrOffset, Instruction, InstrSize);
1679       // Check if the entry size needs adjustment.
1680       if (EntryOffset == 0 && BC->MIB->isTerminateBranch(Instruction) &&
1681           EntrySize == 8)
1682         EntrySize = 16;
1683 
1684       if (BC->MIB->isIndirectBranch(Instruction))
1685         break;
1686 
1687       InstrOffset += InstrSize;
1688     }
1689 
1690     if (InstrOffset + InstrSize > EntryOffset + EntrySize)
1691       continue;
1692 
1693     uint64_t TargetAddress;
1694     if (!BC->MIB->evaluateMemOperandTarget(Instruction, TargetAddress,
1695                                            SectionAddress + InstrOffset,
1696                                            InstrSize)) {
1697       BC->errs() << "BOLT-ERROR: error evaluating PLT instruction at offset 0x"
1698                  << Twine::utohexstr(SectionAddress + InstrOffset) << '\n';
1699       exit(1);
1700     }
1701 
1702     createPLTBinaryFunction(TargetAddress, SectionAddress + EntryOffset,
1703                             EntrySize);
1704   }
1705 }
1706 
1707 void RewriteInstance::disassemblePLT() {
1708   auto analyzeOnePLTSection = [&](BinarySection &Section, uint64_t EntrySize) {
1709     if (BC->isAArch64())
1710       return disassemblePLTSectionAArch64(Section);
1711     if (BC->isRISCV())
1712       return disassemblePLTSectionRISCV(Section);
1713     if (BC->isX86())
1714       return disassemblePLTSectionX86(Section, EntrySize);
1715     llvm_unreachable("Unmplemented PLT");
1716   };
1717 
1718   for (BinarySection &Section : BC->allocatableSections()) {
1719     const PLTSectionInfo *PLTSI = getPLTSectionInfo(Section.getName());
1720     if (!PLTSI)
1721       continue;
1722 
1723     analyzeOnePLTSection(Section, PLTSI->EntrySize);
1724 
1725     BinaryFunction *PltBF;
1726     auto BFIter = BC->getBinaryFunctions().find(Section.getAddress());
1727     if (BFIter != BC->getBinaryFunctions().end()) {
1728       PltBF = &BFIter->second;
1729     } else {
1730       // If we did not register any function at the start of the section,
1731       // then it must be a general PLT entry. Add a function at the location.
1732       PltBF = BC->createBinaryFunction(
1733           "__BOLT_PSEUDO_" + Section.getName().str(), Section,
1734           Section.getAddress(), 0, PLTSI->EntrySize, Section.getAlignment());
1735     }
1736     PltBF->setPseudo(true);
1737   }
1738 }
1739 
1740 void RewriteInstance::adjustFunctionBoundaries() {
1741   for (auto BFI = BC->getBinaryFunctions().begin(),
1742             BFE = BC->getBinaryFunctions().end();
1743        BFI != BFE; ++BFI) {
1744     BinaryFunction &Function = BFI->second;
1745     const BinaryFunction *NextFunction = nullptr;
1746     if (std::next(BFI) != BFE)
1747       NextFunction = &std::next(BFI)->second;
1748 
1749     // Check if there's a symbol or a function with a larger address in the
1750     // same section. If there is - it determines the maximum size for the
1751     // current function. Otherwise, it is the size of a containing section
1752     // the defines it.
1753     //
1754     // NOTE: ignore some symbols that could be tolerated inside the body
1755     //       of a function.
1756     auto NextSymRefI = FileSymRefs.upper_bound(Function.getAddress());
1757     while (NextSymRefI != FileSymRefs.end()) {
1758       SymbolRef &Symbol = NextSymRefI->second;
1759       const uint64_t SymbolAddress = NextSymRefI->first;
1760       const uint64_t SymbolSize = ELFSymbolRef(Symbol).getSize();
1761 
1762       if (NextFunction && SymbolAddress >= NextFunction->getAddress())
1763         break;
1764 
1765       if (!Function.isSymbolValidInScope(Symbol, SymbolSize))
1766         break;
1767 
1768       // Skip basic block labels. This happens on RISC-V with linker relaxation
1769       // enabled because every branch needs a relocation and corresponding
1770       // symbol. We don't want to add such symbols as entry points.
1771       const auto PrivateLabelPrefix = BC->AsmInfo->getPrivateLabelPrefix();
1772       if (!PrivateLabelPrefix.empty() &&
1773           cantFail(Symbol.getName()).starts_with(PrivateLabelPrefix)) {
1774         ++NextSymRefI;
1775         continue;
1776       }
1777 
1778       // This is potentially another entry point into the function.
1779       uint64_t EntryOffset = NextSymRefI->first - Function.getAddress();
1780       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding entry point to function "
1781                         << Function << " at offset 0x"
1782                         << Twine::utohexstr(EntryOffset) << '\n');
1783       Function.addEntryPointAtOffset(EntryOffset);
1784 
1785       ++NextSymRefI;
1786     }
1787 
1788     // Function runs at most till the end of the containing section.
1789     uint64_t NextObjectAddress = Function.getOriginSection()->getEndAddress();
1790     // Or till the next object marked by a symbol.
1791     if (NextSymRefI != FileSymRefs.end())
1792       NextObjectAddress = std::min(NextSymRefI->first, NextObjectAddress);
1793 
1794     // Or till the next function not marked by a symbol.
1795     if (NextFunction)
1796       NextObjectAddress =
1797           std::min(NextFunction->getAddress(), NextObjectAddress);
1798 
1799     const uint64_t MaxSize = NextObjectAddress - Function.getAddress();
1800     if (MaxSize < Function.getSize()) {
1801       BC->errs() << "BOLT-ERROR: symbol seen in the middle of the function "
1802                  << Function << ". Skipping.\n";
1803       Function.setSimple(false);
1804       Function.setMaxSize(Function.getSize());
1805       continue;
1806     }
1807     Function.setMaxSize(MaxSize);
1808     if (!Function.getSize() && Function.isSimple()) {
1809       // Some assembly functions have their size set to 0, use the max
1810       // size as their real size.
1811       if (opts::Verbosity >= 1)
1812         BC->outs() << "BOLT-INFO: setting size of function " << Function
1813                    << " to " << Function.getMaxSize() << " (was 0)\n";
1814       Function.setSize(Function.getMaxSize());
1815     }
1816   }
1817 }
1818 
1819 void RewriteInstance::relocateEHFrameSection() {
1820   assert(EHFrameSection && "Non-empty .eh_frame section expected.");
1821 
1822   BinarySection *RelocatedEHFrameSection =
1823       getSection(".relocated" + getEHFrameSectionName());
1824   assert(RelocatedEHFrameSection &&
1825          "Relocated eh_frame section should be preregistered.");
1826   DWARFDataExtractor DE(EHFrameSection->getContents(),
1827                         BC->AsmInfo->isLittleEndian(),
1828                         BC->AsmInfo->getCodePointerSize());
1829   auto createReloc = [&](uint64_t Value, uint64_t Offset, uint64_t DwarfType) {
1830     if (DwarfType == dwarf::DW_EH_PE_omit)
1831       return;
1832 
1833     // Only fix references that are relative to other locations.
1834     if (!(DwarfType & dwarf::DW_EH_PE_pcrel) &&
1835         !(DwarfType & dwarf::DW_EH_PE_textrel) &&
1836         !(DwarfType & dwarf::DW_EH_PE_funcrel) &&
1837         !(DwarfType & dwarf::DW_EH_PE_datarel))
1838       return;
1839 
1840     if (!(DwarfType & dwarf::DW_EH_PE_sdata4))
1841       return;
1842 
1843     uint64_t RelType;
1844     switch (DwarfType & 0x0f) {
1845     default:
1846       llvm_unreachable("unsupported DWARF encoding type");
1847     case dwarf::DW_EH_PE_sdata4:
1848     case dwarf::DW_EH_PE_udata4:
1849       RelType = Relocation::getPC32();
1850       Offset -= 4;
1851       break;
1852     case dwarf::DW_EH_PE_sdata8:
1853     case dwarf::DW_EH_PE_udata8:
1854       RelType = Relocation::getPC64();
1855       Offset -= 8;
1856       break;
1857     }
1858 
1859     // Create a relocation against an absolute value since the goal is to
1860     // preserve the contents of the section independent of the new values
1861     // of referenced symbols.
1862     RelocatedEHFrameSection->addRelocation(Offset, nullptr, RelType, Value);
1863   };
1864 
1865   Error E = EHFrameParser::parse(DE, EHFrameSection->getAddress(), createReloc);
1866   check_error(std::move(E), "failed to patch EH frame");
1867 }
1868 
1869 Error RewriteInstance::readSpecialSections() {
1870   NamedRegionTimer T("readSpecialSections", "read special sections",
1871                      TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
1872 
1873   bool HasTextRelocations = false;
1874   bool HasSymbolTable = false;
1875   bool HasDebugInfo = false;
1876 
1877   // Process special sections.
1878   for (const SectionRef &Section : InputFile->sections()) {
1879     Expected<StringRef> SectionNameOrErr = Section.getName();
1880     check_error(SectionNameOrErr.takeError(), "cannot get section name");
1881     StringRef SectionName = *SectionNameOrErr;
1882 
1883     if (Error E = Section.getContents().takeError())
1884       return E;
1885     BC->registerSection(Section);
1886     LLVM_DEBUG(
1887         dbgs() << "BOLT-DEBUG: registering section " << SectionName << " @ 0x"
1888                << Twine::utohexstr(Section.getAddress()) << ":0x"
1889                << Twine::utohexstr(Section.getAddress() + Section.getSize())
1890                << "\n");
1891     if (isDebugSection(SectionName))
1892       HasDebugInfo = true;
1893   }
1894 
1895   // Set IsRelro section attribute based on PT_GNU_RELRO segment.
1896   markGnuRelroSections();
1897 
1898   if (HasDebugInfo && !opts::UpdateDebugSections && !opts::AggregateOnly) {
1899     BC->errs() << "BOLT-WARNING: debug info will be stripped from the binary. "
1900                   "Use -update-debug-sections to keep it.\n";
1901   }
1902 
1903   HasTextRelocations = (bool)BC->getUniqueSectionByName(
1904       ".rela" + std::string(BC->getMainCodeSectionName()));
1905   HasSymbolTable = (bool)BC->getUniqueSectionByName(".symtab");
1906   EHFrameSection = BC->getUniqueSectionByName(".eh_frame");
1907 
1908   if (ErrorOr<BinarySection &> BATSec =
1909           BC->getUniqueSectionByName(BoltAddressTranslation::SECTION_NAME)) {
1910     BC->HasBATSection = true;
1911     // Do not read BAT when plotting a heatmap
1912     if (!opts::HeatmapMode) {
1913       if (std::error_code EC = BAT->parse(BC->outs(), BATSec->getContents())) {
1914         BC->errs() << "BOLT-ERROR: failed to parse BOLT address translation "
1915                       "table.\n";
1916         exit(1);
1917       }
1918     }
1919   }
1920 
1921   if (opts::PrintSections) {
1922     BC->outs() << "BOLT-INFO: Sections from original binary:\n";
1923     BC->printSections(BC->outs());
1924   }
1925 
1926   if (opts::RelocationMode == cl::BOU_TRUE && !HasTextRelocations) {
1927     BC->errs()
1928         << "BOLT-ERROR: relocations against code are missing from the input "
1929            "file. Cannot proceed in relocations mode (-relocs).\n";
1930     exit(1);
1931   }
1932 
1933   BC->HasRelocations =
1934       HasTextRelocations && (opts::RelocationMode != cl::BOU_FALSE);
1935 
1936   if (BC->IsLinuxKernel && BC->HasRelocations) {
1937     BC->outs() << "BOLT-INFO: disabling relocation mode for Linux kernel\n";
1938     BC->HasRelocations = false;
1939   }
1940 
1941   BC->IsStripped = !HasSymbolTable;
1942 
1943   if (BC->IsStripped && !opts::AllowStripped) {
1944     BC->errs()
1945         << "BOLT-ERROR: stripped binaries are not supported. If you know "
1946            "what you're doing, use --allow-stripped to proceed";
1947     exit(1);
1948   }
1949 
1950   // Force non-relocation mode for heatmap generation
1951   if (opts::HeatmapMode)
1952     BC->HasRelocations = false;
1953 
1954   if (BC->HasRelocations)
1955     BC->outs() << "BOLT-INFO: enabling " << (opts::StrictMode ? "strict " : "")
1956                << "relocation mode\n";
1957 
1958   // Read EH frame for function boundaries info.
1959   Expected<const DWARFDebugFrame *> EHFrameOrError = BC->DwCtx->getEHFrame();
1960   if (!EHFrameOrError)
1961     report_error("expected valid eh_frame section", EHFrameOrError.takeError());
1962   CFIRdWrt.reset(new CFIReaderWriter(*BC, *EHFrameOrError.get()));
1963 
1964   processSectionMetadata();
1965 
1966   // Read .dynamic/PT_DYNAMIC.
1967   return readELFDynamic();
1968 }
1969 
1970 void RewriteInstance::adjustCommandLineOptions() {
1971   if (BC->isAArch64() && !BC->HasRelocations)
1972     BC->errs() << "BOLT-WARNING: non-relocation mode for AArch64 is not fully "
1973                   "supported\n";
1974 
1975   if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary())
1976     RtLibrary->adjustCommandLineOptions(*BC);
1977 
1978   if (BC->isX86() && BC->MAB->allowAutoPadding()) {
1979     if (!BC->HasRelocations) {
1980       BC->errs()
1981           << "BOLT-ERROR: cannot apply mitigations for Intel JCC erratum in "
1982              "non-relocation mode\n";
1983       exit(1);
1984     }
1985     BC->outs()
1986         << "BOLT-WARNING: using mitigation for Intel JCC erratum, layout "
1987            "may take several minutes\n";
1988   }
1989 
1990   if (opts::SplitEH && !BC->HasRelocations) {
1991     BC->errs() << "BOLT-WARNING: disabling -split-eh in non-relocation mode\n";
1992     opts::SplitEH = false;
1993   }
1994 
1995   if (opts::StrictMode && !BC->HasRelocations) {
1996     BC->errs()
1997         << "BOLT-WARNING: disabling strict mode (-strict) in non-relocation "
1998            "mode\n";
1999     opts::StrictMode = false;
2000   }
2001 
2002   if (BC->HasRelocations && opts::AggregateOnly &&
2003       !opts::StrictMode.getNumOccurrences()) {
2004     BC->outs() << "BOLT-INFO: enabling strict relocation mode for aggregation "
2005                   "purposes\n";
2006     opts::StrictMode = true;
2007   }
2008 
2009   if (!BC->HasRelocations &&
2010       opts::ReorderFunctions != ReorderFunctions::RT_NONE) {
2011     BC->errs() << "BOLT-ERROR: function reordering only works when "
2012                << "relocations are enabled\n";
2013     exit(1);
2014   }
2015 
2016   if (opts::Instrument ||
2017       (opts::ReorderFunctions != ReorderFunctions::RT_NONE &&
2018        !opts::HotText.getNumOccurrences())) {
2019     opts::HotText = true;
2020   } else if (opts::HotText && !BC->HasRelocations) {
2021     BC->errs() << "BOLT-WARNING: hot text is disabled in non-relocation mode\n";
2022     opts::HotText = false;
2023   }
2024 
2025   if (opts::HotText && opts::HotTextMoveSections.getNumOccurrences() == 0) {
2026     opts::HotTextMoveSections.addValue(".stub");
2027     opts::HotTextMoveSections.addValue(".mover");
2028     opts::HotTextMoveSections.addValue(".never_hugify");
2029   }
2030 
2031   if (opts::UseOldText && !BC->OldTextSectionAddress) {
2032     BC->errs()
2033         << "BOLT-WARNING: cannot use old .text as the section was not found"
2034            "\n";
2035     opts::UseOldText = false;
2036   }
2037   if (opts::UseOldText && !BC->HasRelocations) {
2038     BC->errs() << "BOLT-WARNING: cannot use old .text in non-relocation mode\n";
2039     opts::UseOldText = false;
2040   }
2041 
2042   if (!opts::AlignText.getNumOccurrences())
2043     opts::AlignText = BC->PageAlign;
2044 
2045   if (opts::AlignText < opts::AlignFunctions)
2046     opts::AlignText = (unsigned)opts::AlignFunctions;
2047 
2048   if (BC->isX86() && opts::Lite.getNumOccurrences() == 0 && !opts::StrictMode &&
2049       !opts::UseOldText)
2050     opts::Lite = true;
2051 
2052   if (opts::Lite && opts::UseOldText) {
2053     BC->errs() << "BOLT-WARNING: cannot combine -lite with -use-old-text. "
2054                   "Disabling -use-old-text.\n";
2055     opts::UseOldText = false;
2056   }
2057 
2058   if (opts::Lite && opts::StrictMode) {
2059     BC->errs()
2060         << "BOLT-ERROR: -strict and -lite cannot be used at the same time\n";
2061     exit(1);
2062   }
2063 
2064   if (opts::Lite)
2065     BC->outs() << "BOLT-INFO: enabling lite mode\n";
2066 
2067   if (BC->IsLinuxKernel) {
2068     if (!opts::KeepNops.getNumOccurrences())
2069       opts::KeepNops = true;
2070 
2071     // Linux kernel may resume execution after a trap instruction in some cases.
2072     if (!opts::TerminalTrap.getNumOccurrences())
2073       opts::TerminalTrap = false;
2074   }
2075 }
2076 
2077 namespace {
2078 template <typename ELFT>
2079 int64_t getRelocationAddend(const ELFObjectFile<ELFT> *Obj,
2080                             const RelocationRef &RelRef) {
2081   using ELFShdrTy = typename ELFT::Shdr;
2082   using Elf_Rela = typename ELFT::Rela;
2083   int64_t Addend = 0;
2084   const ELFFile<ELFT> &EF = Obj->getELFFile();
2085   DataRefImpl Rel = RelRef.getRawDataRefImpl();
2086   const ELFShdrTy *RelocationSection = cantFail(EF.getSection(Rel.d.a));
2087   switch (RelocationSection->sh_type) {
2088   default:
2089     llvm_unreachable("unexpected relocation section type");
2090   case ELF::SHT_REL:
2091     break;
2092   case ELF::SHT_RELA: {
2093     const Elf_Rela *RelA = Obj->getRela(Rel);
2094     Addend = RelA->r_addend;
2095     break;
2096   }
2097   }
2098 
2099   return Addend;
2100 }
2101 
2102 int64_t getRelocationAddend(const ELFObjectFileBase *Obj,
2103                             const RelocationRef &Rel) {
2104   return getRelocationAddend(cast<ELF64LEObjectFile>(Obj), Rel);
2105 }
2106 
2107 template <typename ELFT>
2108 uint32_t getRelocationSymbol(const ELFObjectFile<ELFT> *Obj,
2109                              const RelocationRef &RelRef) {
2110   using ELFShdrTy = typename ELFT::Shdr;
2111   uint32_t Symbol = 0;
2112   const ELFFile<ELFT> &EF = Obj->getELFFile();
2113   DataRefImpl Rel = RelRef.getRawDataRefImpl();
2114   const ELFShdrTy *RelocationSection = cantFail(EF.getSection(Rel.d.a));
2115   switch (RelocationSection->sh_type) {
2116   default:
2117     llvm_unreachable("unexpected relocation section type");
2118   case ELF::SHT_REL:
2119     Symbol = Obj->getRel(Rel)->getSymbol(EF.isMips64EL());
2120     break;
2121   case ELF::SHT_RELA:
2122     Symbol = Obj->getRela(Rel)->getSymbol(EF.isMips64EL());
2123     break;
2124   }
2125 
2126   return Symbol;
2127 }
2128 
2129 uint32_t getRelocationSymbol(const ELFObjectFileBase *Obj,
2130                              const RelocationRef &Rel) {
2131   return getRelocationSymbol(cast<ELF64LEObjectFile>(Obj), Rel);
2132 }
2133 } // anonymous namespace
2134 
2135 bool RewriteInstance::analyzeRelocation(
2136     const RelocationRef &Rel, uint64_t &RType, std::string &SymbolName,
2137     bool &IsSectionRelocation, uint64_t &SymbolAddress, int64_t &Addend,
2138     uint64_t &ExtractedValue, bool &Skip) const {
2139   Skip = false;
2140   if (!Relocation::isSupported(RType))
2141     return false;
2142 
2143   const bool IsAArch64 = BC->isAArch64();
2144 
2145   const size_t RelSize = Relocation::getSizeForType(RType);
2146 
2147   ErrorOr<uint64_t> Value =
2148       BC->getUnsignedValueAtAddress(Rel.getOffset(), RelSize);
2149   assert(Value && "failed to extract relocated value");
2150   if ((Skip = Relocation::skipRelocationProcess(RType, *Value)))
2151     return true;
2152 
2153   ExtractedValue = Relocation::extractValue(RType, *Value, Rel.getOffset());
2154   Addend = getRelocationAddend(InputFile, Rel);
2155 
2156   const bool IsPCRelative = Relocation::isPCRelative(RType);
2157   const uint64_t PCRelOffset = IsPCRelative && !IsAArch64 ? Rel.getOffset() : 0;
2158   bool SkipVerification = false;
2159   auto SymbolIter = Rel.getSymbol();
2160   if (SymbolIter == InputFile->symbol_end()) {
2161     SymbolAddress = ExtractedValue - Addend + PCRelOffset;
2162     MCSymbol *RelSymbol =
2163         BC->getOrCreateGlobalSymbol(SymbolAddress, "RELSYMat");
2164     SymbolName = std::string(RelSymbol->getName());
2165     IsSectionRelocation = false;
2166   } else {
2167     const SymbolRef &Symbol = *SymbolIter;
2168     SymbolName = std::string(cantFail(Symbol.getName()));
2169     SymbolAddress = cantFail(Symbol.getAddress());
2170     SkipVerification = (cantFail(Symbol.getType()) == SymbolRef::ST_Other);
2171     // Section symbols are marked as ST_Debug.
2172     IsSectionRelocation = (cantFail(Symbol.getType()) == SymbolRef::ST_Debug);
2173     // Check for PLT entry registered with symbol name
2174     if (!SymbolAddress && (IsAArch64 || BC->isRISCV())) {
2175       const BinaryData *BD = BC->getPLTBinaryDataByName(SymbolName);
2176       SymbolAddress = BD ? BD->getAddress() : 0;
2177     }
2178   }
2179   // For PIE or dynamic libs, the linker may choose not to put the relocation
2180   // result at the address if it is a X86_64_64 one because it will emit a
2181   // dynamic relocation (X86_RELATIVE) for the dynamic linker and loader to
2182   // resolve it at run time. The static relocation result goes as the addend
2183   // of the dynamic relocation in this case. We can't verify these cases.
2184   // FIXME: perhaps we can try to find if it really emitted a corresponding
2185   // RELATIVE relocation at this offset with the correct value as the addend.
2186   if (!BC->HasFixedLoadAddress && RelSize == 8)
2187     SkipVerification = true;
2188 
2189   if (IsSectionRelocation && !IsAArch64) {
2190     ErrorOr<BinarySection &> Section = BC->getSectionForAddress(SymbolAddress);
2191     assert(Section && "section expected for section relocation");
2192     SymbolName = "section " + std::string(Section->getName());
2193     // Convert section symbol relocations to regular relocations inside
2194     // non-section symbols.
2195     if (Section->containsAddress(ExtractedValue) && !IsPCRelative) {
2196       SymbolAddress = ExtractedValue;
2197       Addend = 0;
2198     } else {
2199       Addend = ExtractedValue - (SymbolAddress - PCRelOffset);
2200     }
2201   }
2202 
2203   // If no symbol has been found or if it is a relocation requiring the
2204   // creation of a GOT entry, do not link against the symbol but against
2205   // whatever address was extracted from the instruction itself. We are
2206   // not creating a GOT entry as this was already processed by the linker.
2207   // For GOT relocs, do not subtract addend as the addend does not refer
2208   // to this instruction's target, but it refers to the target in the GOT
2209   // entry.
2210   if (Relocation::isGOT(RType)) {
2211     Addend = 0;
2212     SymbolAddress = ExtractedValue + PCRelOffset;
2213   } else if (Relocation::isTLS(RType)) {
2214     SkipVerification = true;
2215   } else if (!SymbolAddress) {
2216     assert(!IsSectionRelocation);
2217     if (ExtractedValue || Addend == 0 || IsPCRelative) {
2218       SymbolAddress =
2219           truncateToSize(ExtractedValue - Addend + PCRelOffset, RelSize);
2220     } else {
2221       // This is weird case.  The extracted value is zero but the addend is
2222       // non-zero and the relocation is not pc-rel.  Using the previous logic,
2223       // the SymbolAddress would end up as a huge number.  Seen in
2224       // exceptions_pic.test.
2225       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: relocation @ 0x"
2226                         << Twine::utohexstr(Rel.getOffset())
2227                         << " value does not match addend for "
2228                         << "relocation to undefined symbol.\n");
2229       return true;
2230     }
2231   }
2232 
2233   auto verifyExtractedValue = [&]() {
2234     if (SkipVerification)
2235       return true;
2236 
2237     if (IsAArch64 || BC->isRISCV())
2238       return true;
2239 
2240     if (SymbolName == "__hot_start" || SymbolName == "__hot_end")
2241       return true;
2242 
2243     if (RType == ELF::R_X86_64_PLT32)
2244       return true;
2245 
2246     return truncateToSize(ExtractedValue, RelSize) ==
2247            truncateToSize(SymbolAddress + Addend - PCRelOffset, RelSize);
2248   };
2249 
2250   (void)verifyExtractedValue;
2251   assert(verifyExtractedValue() && "mismatched extracted relocation value");
2252 
2253   return true;
2254 }
2255 
2256 void RewriteInstance::processDynamicRelocations() {
2257   // Read .relr.dyn section containing compressed R_*_RELATIVE relocations.
2258   if (DynamicRelrSize > 0) {
2259     ErrorOr<BinarySection &> DynamicRelrSectionOrErr =
2260         BC->getSectionForAddress(*DynamicRelrAddress);
2261     if (!DynamicRelrSectionOrErr)
2262       report_error("unable to find section corresponding to DT_RELR",
2263                    DynamicRelrSectionOrErr.getError());
2264     if (DynamicRelrSectionOrErr->getSize() != DynamicRelrSize)
2265       report_error("section size mismatch for DT_RELRSZ",
2266                    errc::executable_format_error);
2267     readDynamicRelrRelocations(*DynamicRelrSectionOrErr);
2268   }
2269 
2270   // Read relocations for PLT - DT_JMPREL.
2271   if (PLTRelocationsSize > 0) {
2272     ErrorOr<BinarySection &> PLTRelSectionOrErr =
2273         BC->getSectionForAddress(*PLTRelocationsAddress);
2274     if (!PLTRelSectionOrErr)
2275       report_error("unable to find section corresponding to DT_JMPREL",
2276                    PLTRelSectionOrErr.getError());
2277     if (PLTRelSectionOrErr->getSize() != PLTRelocationsSize)
2278       report_error("section size mismatch for DT_PLTRELSZ",
2279                    errc::executable_format_error);
2280     readDynamicRelocations(PLTRelSectionOrErr->getSectionRef(),
2281                            /*IsJmpRel*/ true);
2282   }
2283 
2284   // The rest of dynamic relocations - DT_RELA.
2285   // The static executable might have .rela.dyn secion and not have PT_DYNAMIC
2286   if (!DynamicRelocationsSize && BC->IsStaticExecutable) {
2287     ErrorOr<BinarySection &> DynamicRelSectionOrErr =
2288         BC->getUniqueSectionByName(getRelaDynSectionName());
2289     if (DynamicRelSectionOrErr) {
2290       DynamicRelocationsAddress = DynamicRelSectionOrErr->getAddress();
2291       DynamicRelocationsSize = DynamicRelSectionOrErr->getSize();
2292       const SectionRef &SectionRef = DynamicRelSectionOrErr->getSectionRef();
2293       DynamicRelativeRelocationsCount = std::distance(
2294           SectionRef.relocation_begin(), SectionRef.relocation_end());
2295     }
2296   }
2297 
2298   if (DynamicRelocationsSize > 0) {
2299     ErrorOr<BinarySection &> DynamicRelSectionOrErr =
2300         BC->getSectionForAddress(*DynamicRelocationsAddress);
2301     if (!DynamicRelSectionOrErr)
2302       report_error("unable to find section corresponding to DT_RELA",
2303                    DynamicRelSectionOrErr.getError());
2304     auto DynamicRelSectionSize = DynamicRelSectionOrErr->getSize();
2305     // On RISC-V DT_RELASZ seems to include both .rela.dyn and .rela.plt
2306     if (DynamicRelocationsSize == DynamicRelSectionSize + PLTRelocationsSize)
2307       DynamicRelocationsSize = DynamicRelSectionSize;
2308     if (DynamicRelSectionSize != DynamicRelocationsSize)
2309       report_error("section size mismatch for DT_RELASZ",
2310                    errc::executable_format_error);
2311     readDynamicRelocations(DynamicRelSectionOrErr->getSectionRef(),
2312                            /*IsJmpRel*/ false);
2313   }
2314 }
2315 
2316 void RewriteInstance::processRelocations() {
2317   if (!BC->HasRelocations)
2318     return;
2319 
2320   for (const SectionRef &Section : InputFile->sections()) {
2321     section_iterator SecIter = cantFail(Section.getRelocatedSection());
2322     if (SecIter == InputFile->section_end())
2323       continue;
2324     if (BinarySection(*BC, Section).isAllocatable())
2325       continue;
2326 
2327     readRelocations(Section);
2328   }
2329 
2330   if (NumFailedRelocations)
2331     BC->errs() << "BOLT-WARNING: Failed to analyze " << NumFailedRelocations
2332                << " relocations\n";
2333 }
2334 
2335 void RewriteInstance::readDynamicRelocations(const SectionRef &Section,
2336                                              bool IsJmpRel) {
2337   assert(BinarySection(*BC, Section).isAllocatable() && "allocatable expected");
2338 
2339   LLVM_DEBUG({
2340     StringRef SectionName = cantFail(Section.getName());
2341     dbgs() << "BOLT-DEBUG: reading relocations for section " << SectionName
2342            << ":\n";
2343   });
2344 
2345   for (const RelocationRef &Rel : Section.relocations()) {
2346     const uint64_t RType = Rel.getType();
2347     if (Relocation::isNone(RType))
2348       continue;
2349 
2350     StringRef SymbolName = "<none>";
2351     MCSymbol *Symbol = nullptr;
2352     uint64_t SymbolAddress = 0;
2353     const uint64_t Addend = getRelocationAddend(InputFile, Rel);
2354 
2355     symbol_iterator SymbolIter = Rel.getSymbol();
2356     if (SymbolIter != InputFile->symbol_end()) {
2357       SymbolName = cantFail(SymbolIter->getName());
2358       BinaryData *BD = BC->getBinaryDataByName(SymbolName);
2359       Symbol = BD ? BD->getSymbol()
2360                   : BC->getOrCreateUndefinedGlobalSymbol(SymbolName);
2361       SymbolAddress = cantFail(SymbolIter->getAddress());
2362       (void)SymbolAddress;
2363     }
2364 
2365     LLVM_DEBUG(
2366       SmallString<16> TypeName;
2367       Rel.getTypeName(TypeName);
2368       dbgs() << "BOLT-DEBUG: dynamic relocation at 0x"
2369              << Twine::utohexstr(Rel.getOffset()) << " : " << TypeName
2370              << " : " << SymbolName << " : " <<  Twine::utohexstr(SymbolAddress)
2371              << " : + 0x" << Twine::utohexstr(Addend) << '\n'
2372     );
2373 
2374     if (IsJmpRel)
2375       IsJmpRelocation[RType] = true;
2376 
2377     if (Symbol)
2378       SymbolIndex[Symbol] = getRelocationSymbol(InputFile, Rel);
2379 
2380     BC->addDynamicRelocation(Rel.getOffset(), Symbol, RType, Addend);
2381   }
2382 }
2383 
2384 void RewriteInstance::readDynamicRelrRelocations(BinarySection &Section) {
2385   assert(Section.isAllocatable() && "allocatable expected");
2386 
2387   LLVM_DEBUG({
2388     StringRef SectionName = Section.getName();
2389     dbgs() << "BOLT-DEBUG: reading relocations in section " << SectionName
2390            << ":\n";
2391   });
2392 
2393   const uint64_t RType = Relocation::getRelative();
2394   const uint8_t PSize = BC->AsmInfo->getCodePointerSize();
2395   const uint64_t MaxDelta = ((CHAR_BIT * DynamicRelrEntrySize) - 1) * PSize;
2396 
2397   auto ExtractAddendValue = [&](uint64_t Address) -> uint64_t {
2398     ErrorOr<BinarySection &> Section = BC->getSectionForAddress(Address);
2399     assert(Section && "cannot get section for data address from RELR");
2400     DataExtractor DE = DataExtractor(Section->getContents(),
2401                                      BC->AsmInfo->isLittleEndian(), PSize);
2402     uint64_t Offset = Address - Section->getAddress();
2403     return DE.getUnsigned(&Offset, PSize);
2404   };
2405 
2406   auto AddRelocation = [&](uint64_t Address) {
2407     uint64_t Addend = ExtractAddendValue(Address);
2408     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: R_*_RELATIVE relocation at 0x"
2409                       << Twine::utohexstr(Address) << " to 0x"
2410                       << Twine::utohexstr(Addend) << '\n';);
2411     BC->addDynamicRelocation(Address, nullptr, RType, Addend);
2412   };
2413 
2414   DataExtractor DE = DataExtractor(Section.getContents(),
2415                                    BC->AsmInfo->isLittleEndian(), PSize);
2416   uint64_t Offset = 0, Address = 0;
2417   uint64_t RelrCount = DynamicRelrSize / DynamicRelrEntrySize;
2418   while (RelrCount--) {
2419     assert(DE.isValidOffset(Offset));
2420     uint64_t Entry = DE.getUnsigned(&Offset, DynamicRelrEntrySize);
2421     if ((Entry & 1) == 0) {
2422       AddRelocation(Entry);
2423       Address = Entry + PSize;
2424     } else {
2425       const uint64_t StartAddress = Address;
2426       while (Entry >>= 1) {
2427         if (Entry & 1)
2428           AddRelocation(Address);
2429 
2430         Address += PSize;
2431       }
2432 
2433       Address = StartAddress + MaxDelta;
2434     }
2435   }
2436 }
2437 
2438 void RewriteInstance::printRelocationInfo(const RelocationRef &Rel,
2439                                           StringRef SymbolName,
2440                                           uint64_t SymbolAddress,
2441                                           uint64_t Addend,
2442                                           uint64_t ExtractedValue) const {
2443   SmallString<16> TypeName;
2444   Rel.getTypeName(TypeName);
2445   const uint64_t Address = SymbolAddress + Addend;
2446   const uint64_t Offset = Rel.getOffset();
2447   ErrorOr<BinarySection &> Section = BC->getSectionForAddress(SymbolAddress);
2448   BinaryFunction *Func =
2449       BC->getBinaryFunctionContainingAddress(Offset, false, BC->isAArch64());
2450   dbgs() << formatv("Relocation: offset = {0:x}; type = {1}; value = {2:x}; ",
2451                     Offset, TypeName, ExtractedValue)
2452          << formatv("symbol = {0} ({1}); symbol address = {2:x}; ", SymbolName,
2453                     Section ? Section->getName() : "", SymbolAddress)
2454          << formatv("addend = {0:x}; address = {1:x}; in = ", Addend, Address);
2455   if (Func)
2456     dbgs() << Func->getPrintName();
2457   else
2458     dbgs() << BC->getSectionForAddress(Rel.getOffset())->getName();
2459   dbgs() << '\n';
2460 }
2461 
2462 void RewriteInstance::readRelocations(const SectionRef &Section) {
2463   LLVM_DEBUG({
2464     StringRef SectionName = cantFail(Section.getName());
2465     dbgs() << "BOLT-DEBUG: reading relocations for section " << SectionName
2466            << ":\n";
2467   });
2468   if (BinarySection(*BC, Section).isAllocatable()) {
2469     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring runtime relocations\n");
2470     return;
2471   }
2472   section_iterator SecIter = cantFail(Section.getRelocatedSection());
2473   assert(SecIter != InputFile->section_end() && "relocated section expected");
2474   SectionRef RelocatedSection = *SecIter;
2475 
2476   StringRef RelocatedSectionName = cantFail(RelocatedSection.getName());
2477   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: relocated section is "
2478                     << RelocatedSectionName << '\n');
2479 
2480   if (!BinarySection(*BC, RelocatedSection).isAllocatable()) {
2481     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring relocations against "
2482                       << "non-allocatable section\n");
2483     return;
2484   }
2485   const bool SkipRelocs = StringSwitch<bool>(RelocatedSectionName)
2486                               .Cases(".plt", ".rela.plt", ".got.plt",
2487                                      ".eh_frame", ".gcc_except_table", true)
2488                               .Default(false);
2489   if (SkipRelocs) {
2490     LLVM_DEBUG(
2491         dbgs() << "BOLT-DEBUG: ignoring relocations against known section\n");
2492     return;
2493   }
2494 
2495   for (const RelocationRef &Rel : Section.relocations())
2496     handleRelocation(RelocatedSection, Rel);
2497 }
2498 
2499 void RewriteInstance::handleRelocation(const SectionRef &RelocatedSection,
2500                                        const RelocationRef &Rel) {
2501   const bool IsAArch64 = BC->isAArch64();
2502   const bool IsFromCode = RelocatedSection.isText();
2503 
2504   SmallString<16> TypeName;
2505   Rel.getTypeName(TypeName);
2506   uint64_t RType = Rel.getType();
2507   if (Relocation::skipRelocationType(RType))
2508     return;
2509 
2510   // Adjust the relocation type as the linker might have skewed it.
2511   if (BC->isX86() && (RType & ELF::R_X86_64_converted_reloc_bit)) {
2512     if (opts::Verbosity >= 1)
2513       dbgs() << "BOLT-WARNING: ignoring R_X86_64_converted_reloc_bit\n";
2514     RType &= ~ELF::R_X86_64_converted_reloc_bit;
2515   }
2516 
2517   if (Relocation::isTLS(RType)) {
2518     // No special handling required for TLS relocations on X86.
2519     if (BC->isX86())
2520       return;
2521 
2522     // The non-got related TLS relocations on AArch64 and RISC-V also could be
2523     // skipped.
2524     if (!Relocation::isGOT(RType))
2525       return;
2526   }
2527 
2528   if (!IsAArch64 && BC->getDynamicRelocationAt(Rel.getOffset())) {
2529     LLVM_DEBUG({
2530       dbgs() << formatv("BOLT-DEBUG: address {0:x} has a ", Rel.getOffset())
2531              << "dynamic relocation against it. Ignoring static relocation.\n";
2532     });
2533     return;
2534   }
2535 
2536   std::string SymbolName;
2537   uint64_t SymbolAddress;
2538   int64_t Addend;
2539   uint64_t ExtractedValue;
2540   bool IsSectionRelocation;
2541   bool Skip;
2542   if (!analyzeRelocation(Rel, RType, SymbolName, IsSectionRelocation,
2543                          SymbolAddress, Addend, ExtractedValue, Skip)) {
2544     LLVM_DEBUG({
2545       dbgs() << "BOLT-WARNING: failed to analyze relocation @ offset = "
2546              << formatv("{0:x}; type name = {1}\n", Rel.getOffset(), TypeName);
2547     });
2548     ++NumFailedRelocations;
2549     return;
2550   }
2551 
2552   if (Skip) {
2553     LLVM_DEBUG({
2554       dbgs() << "BOLT-DEBUG: skipping relocation @ offset = "
2555              << formatv("{0:x}; type name = {1}\n", Rel.getOffset(), TypeName);
2556     });
2557     return;
2558   }
2559 
2560   const uint64_t Address = SymbolAddress + Addend;
2561 
2562   LLVM_DEBUG({
2563     dbgs() << "BOLT-DEBUG: ";
2564     printRelocationInfo(Rel, SymbolName, SymbolAddress, Addend, ExtractedValue);
2565   });
2566 
2567   BinaryFunction *ContainingBF = nullptr;
2568   if (IsFromCode) {
2569     ContainingBF =
2570         BC->getBinaryFunctionContainingAddress(Rel.getOffset(),
2571                                                /*CheckPastEnd*/ false,
2572                                                /*UseMaxSize*/ true);
2573     assert(ContainingBF && "cannot find function for address in code");
2574     if (!IsAArch64 && !ContainingBF->containsAddress(Rel.getOffset())) {
2575       if (opts::Verbosity >= 1)
2576         BC->outs() << formatv(
2577             "BOLT-INFO: {0} has relocations in padding area\n", *ContainingBF);
2578       ContainingBF->setSize(ContainingBF->getMaxSize());
2579       ContainingBF->setSimple(false);
2580       return;
2581     }
2582   }
2583 
2584   MCSymbol *ReferencedSymbol = nullptr;
2585   if (!IsSectionRelocation) {
2586     if (BinaryData *BD = BC->getBinaryDataByName(SymbolName))
2587       ReferencedSymbol = BD->getSymbol();
2588     else if (BC->isGOTSymbol(SymbolName))
2589       if (BinaryData *BD = BC->getGOTSymbol())
2590         ReferencedSymbol = BD->getSymbol();
2591   }
2592 
2593   ErrorOr<BinarySection &> ReferencedSection{std::errc::bad_address};
2594   symbol_iterator SymbolIter = Rel.getSymbol();
2595   if (SymbolIter != InputFile->symbol_end()) {
2596     SymbolRef Symbol = *SymbolIter;
2597     section_iterator Section =
2598         cantFail(Symbol.getSection(), "cannot get symbol section");
2599     if (Section != InputFile->section_end()) {
2600       Expected<StringRef> SectionName = Section->getName();
2601       if (SectionName && !SectionName->empty())
2602         ReferencedSection = BC->getUniqueSectionByName(*SectionName);
2603     } else if (ReferencedSymbol && ContainingBF &&
2604                (cantFail(Symbol.getFlags()) & SymbolRef::SF_Absolute)) {
2605       // This might be a relocation for an ABS symbols like __global_pointer$ on
2606       // RISC-V
2607       ContainingBF->addRelocation(Rel.getOffset(), ReferencedSymbol,
2608                                   Rel.getType(), 0,
2609                                   cantFail(Symbol.getValue()));
2610       return;
2611     }
2612   }
2613 
2614   if (!ReferencedSection)
2615     ReferencedSection = BC->getSectionForAddress(SymbolAddress);
2616 
2617   const bool IsToCode = ReferencedSection && ReferencedSection->isText();
2618 
2619   // Special handling of PC-relative relocations.
2620   if (BC->isX86() && Relocation::isPCRelative(RType)) {
2621     if (!IsFromCode && IsToCode) {
2622       // PC-relative relocations from data to code are tricky since the
2623       // original information is typically lost after linking, even with
2624       // '--emit-relocs'. Such relocations are normally used by PIC-style
2625       // jump tables and they reference both the jump table and jump
2626       // targets by computing the difference between the two. If we blindly
2627       // apply the relocation, it will appear that it references an arbitrary
2628       // location in the code, possibly in a different function from the one
2629       // containing the jump table.
2630       //
2631       // For that reason, we only register the fact that there is a
2632       // PC-relative relocation at a given address against the code.
2633       // The actual referenced label/address will be determined during jump
2634       // table analysis.
2635       BC->addPCRelativeDataRelocation(Rel.getOffset());
2636     } else if (ContainingBF && !IsSectionRelocation && ReferencedSymbol) {
2637       // If we know the referenced symbol, register the relocation from
2638       // the code. It's required  to properly handle cases where
2639       // "symbol + addend" references an object different from "symbol".
2640       ContainingBF->addRelocation(Rel.getOffset(), ReferencedSymbol, RType,
2641                                   Addend, ExtractedValue);
2642     } else {
2643       LLVM_DEBUG({
2644         dbgs() << "BOLT-DEBUG: not creating PC-relative relocation at"
2645                << formatv("{0:x} for {1}\n", Rel.getOffset(), SymbolName);
2646       });
2647     }
2648 
2649     return;
2650   }
2651 
2652   bool ForceRelocation = BC->forceSymbolRelocations(SymbolName);
2653   if ((BC->isAArch64() || BC->isRISCV()) && Relocation::isGOT(RType))
2654     ForceRelocation = true;
2655 
2656   if (!ReferencedSection && !ForceRelocation) {
2657     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: cannot determine referenced section.\n");
2658     return;
2659   }
2660 
2661   // Occasionally we may see a reference past the last byte of the function
2662   // typically as a result of __builtin_unreachable(). Check it here.
2663   BinaryFunction *ReferencedBF = BC->getBinaryFunctionContainingAddress(
2664       Address, /*CheckPastEnd*/ true, /*UseMaxSize*/ IsAArch64);
2665 
2666   if (!IsSectionRelocation) {
2667     if (BinaryFunction *BF =
2668             BC->getBinaryFunctionContainingAddress(SymbolAddress)) {
2669       if (BF != ReferencedBF) {
2670         // It's possible we are referencing a function without referencing any
2671         // code, e.g. when taking a bitmask action on a function address.
2672         BC->errs()
2673             << "BOLT-WARNING: non-standard function reference (e.g. bitmask)"
2674             << formatv(" detected against function {0} from ", *BF);
2675         if (IsFromCode)
2676           BC->errs() << formatv("function {0}\n", *ContainingBF);
2677         else
2678           BC->errs() << formatv("data section at {0:x}\n", Rel.getOffset());
2679         LLVM_DEBUG(printRelocationInfo(Rel, SymbolName, SymbolAddress, Addend,
2680                                        ExtractedValue));
2681         ReferencedBF = BF;
2682       }
2683     }
2684   } else if (ReferencedBF) {
2685     assert(ReferencedSection && "section expected for section relocation");
2686     if (*ReferencedBF->getOriginSection() != *ReferencedSection) {
2687       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring false function reference\n");
2688       ReferencedBF = nullptr;
2689     }
2690   }
2691 
2692   // Workaround for a member function pointer de-virtualization bug. We check
2693   // if a non-pc-relative relocation in the code is pointing to (fptr - 1).
2694   if (IsToCode && ContainingBF && !Relocation::isPCRelative(RType) &&
2695       (!ReferencedBF || (ReferencedBF->getAddress() != Address))) {
2696     if (const BinaryFunction *RogueBF =
2697             BC->getBinaryFunctionAtAddress(Address + 1)) {
2698       // Do an extra check that the function was referenced previously.
2699       // It's a linear search, but it should rarely happen.
2700       auto CheckReloc = [&](const Relocation &Rel) {
2701         return Rel.Symbol == RogueBF->getSymbol() &&
2702                !Relocation::isPCRelative(Rel.Type);
2703       };
2704       bool Found = llvm::any_of(
2705           llvm::make_second_range(ContainingBF->Relocations), CheckReloc);
2706 
2707       if (Found) {
2708         BC->errs()
2709             << "BOLT-WARNING: detected possible compiler de-virtualization "
2710                "bug: -1 addend used with non-pc-relative relocation against "
2711             << formatv("function {0} in function {1}\n", *RogueBF,
2712                        *ContainingBF);
2713         return;
2714       }
2715     }
2716   }
2717 
2718   if (ForceRelocation) {
2719     std::string Name =
2720         Relocation::isGOT(RType) ? "__BOLT_got_zero" : SymbolName;
2721     ReferencedSymbol = BC->registerNameAtAddress(Name, 0, 0, 0);
2722     SymbolAddress = 0;
2723     if (Relocation::isGOT(RType))
2724       Addend = Address;
2725     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: forcing relocation against symbol "
2726                       << SymbolName << " with addend " << Addend << '\n');
2727   } else if (ReferencedBF) {
2728     ReferencedSymbol = ReferencedBF->getSymbol();
2729     uint64_t RefFunctionOffset = 0;
2730 
2731     // Adjust the point of reference to a code location inside a function.
2732     if (ReferencedBF->containsAddress(Address, /*UseMaxSize = */ true)) {
2733       RefFunctionOffset = Address - ReferencedBF->getAddress();
2734       if (Relocation::isInstructionReference(RType)) {
2735         // Instruction labels are created while disassembling so we just leave
2736         // the symbol empty for now. Since the extracted value is typically
2737         // unrelated to the referenced symbol (e.g., %pcrel_lo in RISC-V
2738         // references an instruction but the patched value references the low
2739         // bits of a data address), we set the extracted value to the symbol
2740         // address in order to be able to correctly reconstruct the reference
2741         // later.
2742         ReferencedSymbol = nullptr;
2743         ExtractedValue = Address;
2744       } else if (RefFunctionOffset) {
2745         if (ContainingBF && ContainingBF != ReferencedBF) {
2746           ReferencedSymbol =
2747               ReferencedBF->addEntryPointAtOffset(RefFunctionOffset);
2748         } else {
2749           ReferencedSymbol =
2750               ReferencedBF->getOrCreateLocalLabel(Address,
2751                                                   /*CreatePastEnd =*/true);
2752 
2753           // If ContainingBF != nullptr, it equals ReferencedBF (see
2754           // if-condition above) so we're handling a relocation from a function
2755           // to itself. RISC-V uses such relocations for branches, for example.
2756           // These should not be registered as externally references offsets.
2757           if (!ContainingBF)
2758             ReferencedBF->registerReferencedOffset(RefFunctionOffset);
2759         }
2760         if (opts::Verbosity > 1 &&
2761             BinarySection(*BC, RelocatedSection).isWritable())
2762           BC->errs()
2763               << "BOLT-WARNING: writable reference into the middle of the "
2764               << formatv("function {0} detected at address {1:x}\n",
2765                          *ReferencedBF, Rel.getOffset());
2766       }
2767       SymbolAddress = Address;
2768       Addend = 0;
2769     }
2770     LLVM_DEBUG({
2771       dbgs() << "  referenced function " << *ReferencedBF;
2772       if (Address != ReferencedBF->getAddress())
2773         dbgs() << formatv(" at offset {0:x}", RefFunctionOffset);
2774       dbgs() << '\n';
2775     });
2776   } else {
2777     if (IsToCode && SymbolAddress) {
2778       // This can happen e.g. with PIC-style jump tables.
2779       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: no corresponding function for "
2780                            "relocation against code\n");
2781     }
2782 
2783     // In AArch64 there are zero reasons to keep a reference to the
2784     // "original" symbol plus addend. The original symbol is probably just a
2785     // section symbol. If we are here, this means we are probably accessing
2786     // data, so it is imperative to keep the original address.
2787     if (IsAArch64) {
2788       SymbolName = formatv("SYMBOLat{0:x}", Address);
2789       SymbolAddress = Address;
2790       Addend = 0;
2791     }
2792 
2793     if (BinaryData *BD = BC->getBinaryDataContainingAddress(SymbolAddress)) {
2794       // Note: this assertion is trying to check sanity of BinaryData objects
2795       // but AArch64 has inferred and incomplete object locations coming from
2796       // GOT/TLS or any other non-trivial relocation (that requires creation
2797       // of sections and whose symbol address is not really what should be
2798       // encoded in the instruction). So we essentially disabled this check
2799       // for AArch64 and live with bogus names for objects.
2800       assert((IsAArch64 || IsSectionRelocation ||
2801               BD->nameStartsWith(SymbolName) ||
2802               BD->nameStartsWith("PG" + SymbolName) ||
2803               (BD->nameStartsWith("ANONYMOUS") &&
2804                (BD->getSectionName().starts_with(".plt") ||
2805                 BD->getSectionName().ends_with(".plt")))) &&
2806              "BOLT symbol names of all non-section relocations must match up "
2807              "with symbol names referenced in the relocation");
2808 
2809       if (IsSectionRelocation)
2810         BC->markAmbiguousRelocations(*BD, Address);
2811 
2812       ReferencedSymbol = BD->getSymbol();
2813       Addend += (SymbolAddress - BD->getAddress());
2814       SymbolAddress = BD->getAddress();
2815       assert(Address == SymbolAddress + Addend);
2816     } else {
2817       // These are mostly local data symbols but undefined symbols
2818       // in relocation sections can get through here too, from .plt.
2819       assert(
2820           (IsAArch64 || BC->isRISCV() || IsSectionRelocation ||
2821            BC->getSectionNameForAddress(SymbolAddress)->starts_with(".plt")) &&
2822           "known symbols should not resolve to anonymous locals");
2823 
2824       if (IsSectionRelocation) {
2825         ReferencedSymbol =
2826             BC->getOrCreateGlobalSymbol(SymbolAddress, "SYMBOLat");
2827       } else {
2828         SymbolRef Symbol = *Rel.getSymbol();
2829         const uint64_t SymbolSize =
2830             IsAArch64 ? 0 : ELFSymbolRef(Symbol).getSize();
2831         const uint64_t SymbolAlignment = IsAArch64 ? 1 : Symbol.getAlignment();
2832         const uint32_t SymbolFlags = cantFail(Symbol.getFlags());
2833         std::string Name;
2834         if (SymbolFlags & SymbolRef::SF_Global) {
2835           Name = SymbolName;
2836         } else {
2837           if (StringRef(SymbolName)
2838                   .starts_with(BC->AsmInfo->getPrivateGlobalPrefix()))
2839             Name = NR.uniquify("PG" + SymbolName);
2840           else
2841             Name = NR.uniquify(SymbolName);
2842         }
2843         ReferencedSymbol = BC->registerNameAtAddress(
2844             Name, SymbolAddress, SymbolSize, SymbolAlignment, SymbolFlags);
2845       }
2846 
2847       if (IsSectionRelocation) {
2848         BinaryData *BD = BC->getBinaryDataByName(ReferencedSymbol->getName());
2849         BC->markAmbiguousRelocations(*BD, Address);
2850       }
2851     }
2852   }
2853 
2854   auto checkMaxDataRelocations = [&]() {
2855     ++NumDataRelocations;
2856     LLVM_DEBUG(if (opts::MaxDataRelocations &&
2857                    NumDataRelocations + 1 == opts::MaxDataRelocations) {
2858       dbgs() << "BOLT-DEBUG: processing ending on data relocation "
2859              << NumDataRelocations << ": ";
2860       printRelocationInfo(Rel, ReferencedSymbol->getName(), SymbolAddress,
2861                           Addend, ExtractedValue);
2862     });
2863 
2864     return (!opts::MaxDataRelocations ||
2865             NumDataRelocations < opts::MaxDataRelocations);
2866   };
2867 
2868   if ((ReferencedSection && refersToReorderedSection(ReferencedSection)) ||
2869       (opts::ForceToDataRelocations && checkMaxDataRelocations()) ||
2870       // RISC-V has ADD/SUB data-to-data relocations
2871       BC->isRISCV())
2872     ForceRelocation = true;
2873 
2874   if (IsFromCode)
2875     ContainingBF->addRelocation(Rel.getOffset(), ReferencedSymbol, RType,
2876                                 Addend, ExtractedValue);
2877   else if (IsToCode || ForceRelocation)
2878     BC->addRelocation(Rel.getOffset(), ReferencedSymbol, RType, Addend,
2879                       ExtractedValue);
2880   else
2881     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: ignoring relocation from data to data\n");
2882 }
2883 
2884 void RewriteInstance::selectFunctionsToProcess() {
2885   // Extend the list of functions to process or skip from a file.
2886   auto populateFunctionNames = [](cl::opt<std::string> &FunctionNamesFile,
2887                                   cl::list<std::string> &FunctionNames) {
2888     if (FunctionNamesFile.empty())
2889       return;
2890     std::ifstream FuncsFile(FunctionNamesFile, std::ios::in);
2891     std::string FuncName;
2892     while (std::getline(FuncsFile, FuncName))
2893       FunctionNames.push_back(FuncName);
2894   };
2895   populateFunctionNames(opts::FunctionNamesFile, opts::ForceFunctionNames);
2896   populateFunctionNames(opts::SkipFunctionNamesFile, opts::SkipFunctionNames);
2897   populateFunctionNames(opts::FunctionNamesFileNR, opts::ForceFunctionNamesNR);
2898 
2899   // Make a set of functions to process to speed up lookups.
2900   std::unordered_set<std::string> ForceFunctionsNR(
2901       opts::ForceFunctionNamesNR.begin(), opts::ForceFunctionNamesNR.end());
2902 
2903   if ((!opts::ForceFunctionNames.empty() ||
2904        !opts::ForceFunctionNamesNR.empty()) &&
2905       !opts::SkipFunctionNames.empty()) {
2906     BC->errs()
2907         << "BOLT-ERROR: cannot select functions to process and skip at the "
2908            "same time. Please use only one type of selection.\n";
2909     exit(1);
2910   }
2911 
2912   uint64_t LiteThresholdExecCount = 0;
2913   if (opts::LiteThresholdPct) {
2914     if (opts::LiteThresholdPct > 100)
2915       opts::LiteThresholdPct = 100;
2916 
2917     std::vector<const BinaryFunction *> TopFunctions;
2918     for (auto &BFI : BC->getBinaryFunctions()) {
2919       const BinaryFunction &Function = BFI.second;
2920       if (ProfileReader->mayHaveProfileData(Function))
2921         TopFunctions.push_back(&Function);
2922     }
2923     llvm::sort(
2924         TopFunctions, [](const BinaryFunction *A, const BinaryFunction *B) {
2925           return A->getKnownExecutionCount() < B->getKnownExecutionCount();
2926         });
2927 
2928     size_t Index = TopFunctions.size() * opts::LiteThresholdPct / 100;
2929     if (Index)
2930       --Index;
2931     LiteThresholdExecCount = TopFunctions[Index]->getKnownExecutionCount();
2932     BC->outs() << "BOLT-INFO: limiting processing to functions with at least "
2933                << LiteThresholdExecCount << " invocations\n";
2934   }
2935   LiteThresholdExecCount = std::max(
2936       LiteThresholdExecCount, static_cast<uint64_t>(opts::LiteThresholdCount));
2937 
2938   StringSet<> ReorderFunctionsUserSet;
2939   StringSet<> ReorderFunctionsLTOCommonSet;
2940   if (opts::ReorderFunctions == ReorderFunctions::RT_USER) {
2941     std::vector<std::string> FunctionNames;
2942     BC->logBOLTErrorsAndQuitOnFatal(
2943         ReorderFunctions::readFunctionOrderFile(FunctionNames));
2944     for (const std::string &Function : FunctionNames) {
2945       ReorderFunctionsUserSet.insert(Function);
2946       if (std::optional<StringRef> LTOCommonName = getLTOCommonName(Function))
2947         ReorderFunctionsLTOCommonSet.insert(*LTOCommonName);
2948     }
2949   }
2950 
2951   uint64_t NumFunctionsToProcess = 0;
2952   auto mustSkip = [&](const BinaryFunction &Function) {
2953     if (opts::MaxFunctions.getNumOccurrences() &&
2954         NumFunctionsToProcess >= opts::MaxFunctions)
2955       return true;
2956     for (std::string &Name : opts::SkipFunctionNames)
2957       if (Function.hasNameRegex(Name))
2958         return true;
2959 
2960     return false;
2961   };
2962 
2963   auto shouldProcess = [&](const BinaryFunction &Function) {
2964     if (mustSkip(Function))
2965       return false;
2966 
2967     // If the list is not empty, only process functions from the list.
2968     if (!opts::ForceFunctionNames.empty() || !ForceFunctionsNR.empty()) {
2969       // Regex check (-funcs and -funcs-file options).
2970       for (std::string &Name : opts::ForceFunctionNames)
2971         if (Function.hasNameRegex(Name))
2972           return true;
2973 
2974       // Non-regex check (-funcs-no-regex and -funcs-file-no-regex).
2975       for (const StringRef Name : Function.getNames())
2976         if (ForceFunctionsNR.count(Name.str()))
2977           return true;
2978 
2979       return false;
2980     }
2981 
2982     if (opts::Lite) {
2983       // Forcibly include functions specified in the -function-order file.
2984       if (opts::ReorderFunctions == ReorderFunctions::RT_USER) {
2985         for (const StringRef Name : Function.getNames())
2986           if (ReorderFunctionsUserSet.contains(Name))
2987             return true;
2988         for (const StringRef Name : Function.getNames())
2989           if (std::optional<StringRef> LTOCommonName = getLTOCommonName(Name))
2990             if (ReorderFunctionsLTOCommonSet.contains(*LTOCommonName))
2991               return true;
2992       }
2993 
2994       if (ProfileReader && !ProfileReader->mayHaveProfileData(Function))
2995         return false;
2996 
2997       if (Function.getKnownExecutionCount() < LiteThresholdExecCount)
2998         return false;
2999     }
3000 
3001     return true;
3002   };
3003 
3004   for (auto &BFI : BC->getBinaryFunctions()) {
3005     BinaryFunction &Function = BFI.second;
3006 
3007     // Pseudo functions are explicitly marked by us not to be processed.
3008     if (Function.isPseudo()) {
3009       Function.IsIgnored = true;
3010       Function.HasExternalRefRelocations = true;
3011       continue;
3012     }
3013 
3014     // Decide what to do with fragments after parent functions are processed.
3015     if (Function.isFragment())
3016       continue;
3017 
3018     if (!shouldProcess(Function)) {
3019       if (opts::Verbosity >= 1) {
3020         BC->outs() << "BOLT-INFO: skipping processing " << Function
3021                    << " per user request\n";
3022       }
3023       Function.setIgnored();
3024     } else {
3025       ++NumFunctionsToProcess;
3026       if (opts::MaxFunctions.getNumOccurrences() &&
3027           NumFunctionsToProcess == opts::MaxFunctions)
3028         BC->outs() << "BOLT-INFO: processing ending on " << Function << '\n';
3029     }
3030   }
3031 
3032   if (!BC->HasSplitFunctions)
3033     return;
3034 
3035   // Fragment overrides:
3036   // - If the fragment must be skipped, then the parent must be skipped as well.
3037   // Otherwise, fragment should follow the parent function:
3038   // - if the parent is skipped, skip fragment,
3039   // - if the parent is processed, process the fragment(s) as well.
3040   for (auto &BFI : BC->getBinaryFunctions()) {
3041     BinaryFunction &Function = BFI.second;
3042     if (!Function.isFragment())
3043       continue;
3044     if (mustSkip(Function)) {
3045       for (BinaryFunction *Parent : Function.ParentFragments) {
3046         if (opts::Verbosity >= 1) {
3047           BC->outs() << "BOLT-INFO: skipping processing " << *Parent
3048                      << " together with fragment function\n";
3049         }
3050         Parent->setIgnored();
3051         --NumFunctionsToProcess;
3052       }
3053       Function.setIgnored();
3054       continue;
3055     }
3056 
3057     bool IgnoredParent =
3058         llvm::any_of(Function.ParentFragments, [&](BinaryFunction *Parent) {
3059           return Parent->isIgnored();
3060         });
3061     if (IgnoredParent) {
3062       if (opts::Verbosity >= 1) {
3063         BC->outs() << "BOLT-INFO: skipping processing " << Function
3064                    << " together with parent function\n";
3065       }
3066       Function.setIgnored();
3067     } else {
3068       ++NumFunctionsToProcess;
3069       if (opts::Verbosity >= 1) {
3070         BC->outs() << "BOLT-INFO: processing " << Function
3071                    << " as a sibling of non-ignored function\n";
3072       }
3073       if (opts::MaxFunctions && NumFunctionsToProcess == opts::MaxFunctions)
3074         BC->outs() << "BOLT-INFO: processing ending on " << Function << '\n';
3075     }
3076   }
3077 }
3078 
3079 void RewriteInstance::readDebugInfo() {
3080   NamedRegionTimer T("readDebugInfo", "read debug info", TimerGroupName,
3081                      TimerGroupDesc, opts::TimeRewrite);
3082   if (!opts::UpdateDebugSections)
3083     return;
3084 
3085   BC->preprocessDebugInfo();
3086 }
3087 
3088 void RewriteInstance::preprocessProfileData() {
3089   if (!ProfileReader)
3090     return;
3091 
3092   NamedRegionTimer T("preprocessprofile", "pre-process profile data",
3093                      TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3094 
3095   BC->outs() << "BOLT-INFO: pre-processing profile using "
3096              << ProfileReader->getReaderName() << '\n';
3097 
3098   if (BAT->enabledFor(InputFile)) {
3099     BC->outs() << "BOLT-INFO: profile collection done on a binary already "
3100                   "processed by BOLT\n";
3101     ProfileReader->setBAT(&*BAT);
3102   }
3103 
3104   if (Error E = ProfileReader->preprocessProfile(*BC.get()))
3105     report_error("cannot pre-process profile", std::move(E));
3106 
3107   if (!BC->hasSymbolsWithFileName() && ProfileReader->hasLocalsWithFileName() &&
3108       !opts::AllowStripped) {
3109     BC->errs()
3110         << "BOLT-ERROR: input binary does not have local file symbols "
3111            "but profile data includes function names with embedded file "
3112            "names. It appears that the input binary was stripped while a "
3113            "profiled binary was not. If you know what you are doing and "
3114            "wish to proceed, use -allow-stripped option.\n";
3115     exit(1);
3116   }
3117 }
3118 
3119 void RewriteInstance::initializeMetadataManager() {
3120   if (BC->IsLinuxKernel)
3121     MetadataManager.registerRewriter(createLinuxKernelRewriter(*BC));
3122 
3123   MetadataManager.registerRewriter(createBuildIDRewriter(*BC));
3124 
3125   MetadataManager.registerRewriter(createPseudoProbeRewriter(*BC));
3126 
3127   MetadataManager.registerRewriter(createSDTRewriter(*BC));
3128 }
3129 
3130 void RewriteInstance::processSectionMetadata() {
3131   initializeMetadataManager();
3132 
3133   MetadataManager.runSectionInitializers();
3134 }
3135 
3136 void RewriteInstance::processMetadataPreCFG() {
3137   MetadataManager.runInitializersPreCFG();
3138 
3139   processProfileDataPreCFG();
3140 }
3141 
3142 void RewriteInstance::processMetadataPostCFG() {
3143   MetadataManager.runInitializersPostCFG();
3144 }
3145 
3146 void RewriteInstance::processProfileDataPreCFG() {
3147   if (!ProfileReader)
3148     return;
3149 
3150   NamedRegionTimer T("processprofile-precfg", "process profile data pre-CFG",
3151                      TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3152 
3153   if (Error E = ProfileReader->readProfilePreCFG(*BC.get()))
3154     report_error("cannot read profile pre-CFG", std::move(E));
3155 }
3156 
3157 void RewriteInstance::processProfileData() {
3158   if (!ProfileReader)
3159     return;
3160 
3161   NamedRegionTimer T("processprofile", "process profile data", TimerGroupName,
3162                      TimerGroupDesc, opts::TimeRewrite);
3163 
3164   if (Error E = ProfileReader->readProfile(*BC.get()))
3165     report_error("cannot read profile", std::move(E));
3166 
3167   if (opts::PrintProfile || opts::PrintAll) {
3168     for (auto &BFI : BC->getBinaryFunctions()) {
3169       BinaryFunction &Function = BFI.second;
3170       if (Function.empty())
3171         continue;
3172 
3173       Function.print(BC->outs(), "after attaching profile");
3174     }
3175   }
3176 
3177   if (!opts::SaveProfile.empty() && !BAT->enabledFor(InputFile)) {
3178     YAMLProfileWriter PW(opts::SaveProfile);
3179     PW.writeProfile(*this);
3180   }
3181   if (opts::AggregateOnly &&
3182       opts::ProfileFormat == opts::ProfileFormatKind::PF_YAML &&
3183       !BAT->enabledFor(InputFile)) {
3184     YAMLProfileWriter PW(opts::OutputFilename);
3185     PW.writeProfile(*this);
3186   }
3187 
3188   // Release memory used by profile reader.
3189   ProfileReader.reset();
3190 
3191   if (opts::AggregateOnly) {
3192     PrintProgramStats PPS(&*BAT);
3193     BC->logBOLTErrorsAndQuitOnFatal(PPS.runOnFunctions(*BC));
3194     exit(0);
3195   }
3196 }
3197 
3198 void RewriteInstance::disassembleFunctions() {
3199   NamedRegionTimer T("disassembleFunctions", "disassemble functions",
3200                      TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3201   for (auto &BFI : BC->getBinaryFunctions()) {
3202     BinaryFunction &Function = BFI.second;
3203 
3204     ErrorOr<ArrayRef<uint8_t>> FunctionData = Function.getData();
3205     if (!FunctionData) {
3206       BC->errs() << "BOLT-ERROR: corresponding section is non-executable or "
3207                  << "empty for function " << Function << '\n';
3208       exit(1);
3209     }
3210 
3211     // Treat zero-sized functions as non-simple ones.
3212     if (Function.getSize() == 0) {
3213       Function.setSimple(false);
3214       continue;
3215     }
3216 
3217     // Offset of the function in the file.
3218     const auto *FileBegin =
3219         reinterpret_cast<const uint8_t *>(InputFile->getData().data());
3220     Function.setFileOffset(FunctionData->begin() - FileBegin);
3221 
3222     if (!shouldDisassemble(Function)) {
3223       NamedRegionTimer T("scan", "scan functions", "buildfuncs",
3224                          "Scan Binary Functions", opts::TimeBuild);
3225       Function.scanExternalRefs();
3226       Function.setSimple(false);
3227       continue;
3228     }
3229 
3230     bool DisasmFailed{false};
3231     handleAllErrors(Function.disassemble(), [&](const BOLTError &E) {
3232       DisasmFailed = true;
3233       if (E.isFatal()) {
3234         E.log(BC->errs());
3235         exit(1);
3236       }
3237       if (opts::processAllFunctions()) {
3238         BC->errs() << BC->generateBugReportMessage(
3239             "function cannot be properly disassembled. "
3240             "Unable to continue in relocation mode.",
3241             Function);
3242         exit(1);
3243       }
3244       if (opts::Verbosity >= 1)
3245         BC->outs() << "BOLT-INFO: could not disassemble function " << Function
3246                    << ". Will ignore.\n";
3247       // Forcefully ignore the function.
3248       Function.setIgnored();
3249     });
3250 
3251     if (DisasmFailed)
3252       continue;
3253 
3254     if (opts::PrintAll || opts::PrintDisasm)
3255       Function.print(BC->outs(), "after disassembly");
3256   }
3257 
3258   BC->processInterproceduralReferences();
3259   BC->populateJumpTables();
3260 
3261   for (auto &BFI : BC->getBinaryFunctions()) {
3262     BinaryFunction &Function = BFI.second;
3263 
3264     if (!shouldDisassemble(Function))
3265       continue;
3266 
3267     Function.postProcessEntryPoints();
3268     Function.postProcessJumpTables();
3269   }
3270 
3271   BC->clearJumpTableTempData();
3272   BC->adjustCodePadding();
3273 
3274   for (auto &BFI : BC->getBinaryFunctions()) {
3275     BinaryFunction &Function = BFI.second;
3276 
3277     if (!shouldDisassemble(Function))
3278       continue;
3279 
3280     if (!Function.isSimple()) {
3281       assert((!BC->HasRelocations || Function.getSize() == 0 ||
3282               Function.hasIndirectTargetToSplitFragment()) &&
3283              "unexpected non-simple function in relocation mode");
3284       continue;
3285     }
3286 
3287     // Fill in CFI information for this function
3288     if (!Function.trapsOnEntry() && !CFIRdWrt->fillCFIInfoFor(Function)) {
3289       if (BC->HasRelocations) {
3290         BC->errs() << BC->generateBugReportMessage("unable to fill CFI.",
3291                                                    Function);
3292         exit(1);
3293       } else {
3294         BC->errs() << "BOLT-WARNING: unable to fill CFI for function "
3295                    << Function << ". Skipping.\n";
3296         Function.setSimple(false);
3297         continue;
3298       }
3299     }
3300 
3301     // Parse LSDA.
3302     if (Function.getLSDAAddress() != 0 &&
3303         !BC->getFragmentsToSkip().count(&Function)) {
3304       ErrorOr<BinarySection &> LSDASection =
3305           BC->getSectionForAddress(Function.getLSDAAddress());
3306       check_error(LSDASection.getError(), "failed to get LSDA section");
3307       ArrayRef<uint8_t> LSDAData = ArrayRef<uint8_t>(
3308           LSDASection->getData(), LSDASection->getContents().size());
3309       BC->logBOLTErrorsAndQuitOnFatal(
3310           Function.parseLSDA(LSDAData, LSDASection->getAddress()));
3311     }
3312   }
3313 }
3314 
3315 void RewriteInstance::buildFunctionsCFG() {
3316   NamedRegionTimer T("buildCFG", "buildCFG", "buildfuncs",
3317                      "Build Binary Functions", opts::TimeBuild);
3318 
3319   // Create annotation indices to allow lock-free execution
3320   BC->MIB->getOrCreateAnnotationIndex("JTIndexReg");
3321   BC->MIB->getOrCreateAnnotationIndex("NOP");
3322 
3323   ParallelUtilities::WorkFuncWithAllocTy WorkFun =
3324       [&](BinaryFunction &BF, MCPlusBuilder::AllocatorIdTy AllocId) {
3325         bool HadErrors{false};
3326         handleAllErrors(BF.buildCFG(AllocId), [&](const BOLTError &E) {
3327           if (!E.getMessage().empty())
3328             E.log(BC->errs());
3329           if (E.isFatal())
3330             exit(1);
3331           HadErrors = true;
3332         });
3333 
3334         if (HadErrors)
3335           return;
3336 
3337         if (opts::PrintAll) {
3338           auto L = BC->scopeLock();
3339           BF.print(BC->outs(), "while building cfg");
3340         }
3341       };
3342 
3343   ParallelUtilities::PredicateTy SkipPredicate = [&](const BinaryFunction &BF) {
3344     return !shouldDisassemble(BF) || !BF.isSimple();
3345   };
3346 
3347   ParallelUtilities::runOnEachFunctionWithUniqueAllocId(
3348       *BC, ParallelUtilities::SchedulingPolicy::SP_INST_LINEAR, WorkFun,
3349       SkipPredicate, "disassembleFunctions-buildCFG",
3350       /*ForceSequential*/ opts::SequentialDisassembly || opts::PrintAll);
3351 
3352   BC->postProcessSymbolTable();
3353 }
3354 
3355 void RewriteInstance::postProcessFunctions() {
3356   // We mark fragments as non-simple here, not during disassembly,
3357   // So we can build their CFGs.
3358   BC->skipMarkedFragments();
3359   BC->clearFragmentsToSkip();
3360 
3361   BC->TotalScore = 0;
3362   BC->SumExecutionCount = 0;
3363   for (auto &BFI : BC->getBinaryFunctions()) {
3364     BinaryFunction &Function = BFI.second;
3365 
3366     // Set function as non-simple if it has dynamic relocations
3367     // in constant island, we don't want this function to be optimized
3368     // e.g. function splitting is unsupported.
3369     if (Function.hasDynamicRelocationAtIsland())
3370       Function.setSimple(false);
3371 
3372     if (Function.empty())
3373       continue;
3374 
3375     Function.postProcessCFG();
3376 
3377     if (opts::PrintAll || opts::PrintCFG)
3378       Function.print(BC->outs(), "after building cfg");
3379 
3380     if (opts::DumpDotAll)
3381       Function.dumpGraphForPass("00_build-cfg");
3382 
3383     if (opts::PrintLoopInfo) {
3384       Function.calculateLoopInfo();
3385       Function.printLoopInfo(BC->outs());
3386     }
3387 
3388     BC->TotalScore += Function.getFunctionScore();
3389     BC->SumExecutionCount += Function.getKnownExecutionCount();
3390   }
3391 
3392   if (opts::PrintGlobals) {
3393     BC->outs() << "BOLT-INFO: Global symbols:\n";
3394     BC->printGlobalSymbols(BC->outs());
3395   }
3396 }
3397 
3398 void RewriteInstance::runOptimizationPasses() {
3399   NamedRegionTimer T("runOptimizationPasses", "run optimization passes",
3400                      TimerGroupName, TimerGroupDesc, opts::TimeRewrite);
3401   BC->logBOLTErrorsAndQuitOnFatal(BinaryFunctionPassManager::runAllPasses(*BC));
3402 }
3403 
3404 void RewriteInstance::preregisterSections() {
3405   // Preregister sections before emission to set their order in the output.
3406   const unsigned ROFlags = BinarySection::getFlags(/*IsReadOnly*/ true,
3407                                                    /*IsText*/ false,
3408                                                    /*IsAllocatable*/ true);
3409   if (BinarySection *EHFrameSection = getSection(getEHFrameSectionName())) {
3410     // New .eh_frame.
3411     BC->registerOrUpdateSection(getNewSecPrefix() + getEHFrameSectionName(),
3412                                 ELF::SHT_PROGBITS, ROFlags);
3413     // Fully register a relocatable copy of the original .eh_frame.
3414     BC->registerSection(".relocated.eh_frame", *EHFrameSection);
3415   }
3416   BC->registerOrUpdateSection(getNewSecPrefix() + ".gcc_except_table",
3417                               ELF::SHT_PROGBITS, ROFlags);
3418   BC->registerOrUpdateSection(getNewSecPrefix() + ".rodata", ELF::SHT_PROGBITS,
3419                               ROFlags);
3420   BC->registerOrUpdateSection(getNewSecPrefix() + ".rodata.cold",
3421                               ELF::SHT_PROGBITS, ROFlags);
3422 }
3423 
3424 void RewriteInstance::emitAndLink() {
3425   NamedRegionTimer T("emitAndLink", "emit and link", TimerGroupName,
3426                      TimerGroupDesc, opts::TimeRewrite);
3427 
3428   SmallString<0> ObjectBuffer;
3429   raw_svector_ostream OS(ObjectBuffer);
3430 
3431   // Implicitly MCObjectStreamer takes ownership of MCAsmBackend (MAB)
3432   // and MCCodeEmitter (MCE). ~MCObjectStreamer() will delete these
3433   // two instances.
3434   std::unique_ptr<MCStreamer> Streamer = BC->createStreamer(OS);
3435 
3436   if (EHFrameSection) {
3437     if (opts::UseOldText || opts::StrictMode) {
3438       // The section is going to be regenerated from scratch.
3439       // Empty the contents, but keep the section reference.
3440       EHFrameSection->clearContents();
3441     } else {
3442       // Make .eh_frame relocatable.
3443       relocateEHFrameSection();
3444     }
3445   }
3446 
3447   emitBinaryContext(*Streamer, *BC, getOrgSecPrefix());
3448 
3449   Streamer->finish();
3450   if (Streamer->getContext().hadError()) {
3451     BC->errs() << "BOLT-ERROR: Emission failed.\n";
3452     exit(1);
3453   }
3454 
3455   if (opts::KeepTmp) {
3456     SmallString<128> OutObjectPath;
3457     sys::fs::getPotentiallyUniqueTempFileName("output", "o", OutObjectPath);
3458     std::error_code EC;
3459     raw_fd_ostream FOS(OutObjectPath, EC);
3460     check_error(EC, "cannot create output object file");
3461     FOS << ObjectBuffer;
3462     BC->outs()
3463         << "BOLT-INFO: intermediary output object file saved for debugging "
3464            "purposes: "
3465         << OutObjectPath << "\n";
3466   }
3467 
3468   ErrorOr<BinarySection &> TextSection =
3469       BC->getUniqueSectionByName(BC->getMainCodeSectionName());
3470   if (BC->HasRelocations && TextSection)
3471     BC->renameSection(*TextSection,
3472                       getOrgSecPrefix() + BC->getMainCodeSectionName());
3473 
3474   //////////////////////////////////////////////////////////////////////////////
3475   // Assign addresses to new sections.
3476   //////////////////////////////////////////////////////////////////////////////
3477 
3478   // Get output object as ObjectFile.
3479   std::unique_ptr<MemoryBuffer> ObjectMemBuffer =
3480       MemoryBuffer::getMemBuffer(ObjectBuffer, "in-memory object file", false);
3481 
3482   auto EFMM = std::make_unique<ExecutableFileMemoryManager>(*BC);
3483   EFMM->setNewSecPrefix(getNewSecPrefix());
3484   EFMM->setOrgSecPrefix(getOrgSecPrefix());
3485 
3486   Linker = std::make_unique<JITLinkLinker>(*BC, std::move(EFMM));
3487   Linker->loadObject(ObjectMemBuffer->getMemBufferRef(),
3488                      [this](auto MapSection) { mapFileSections(MapSection); });
3489 
3490   // Update output addresses based on the new section map and
3491   // layout. Only do this for the object created by ourselves.
3492   updateOutputValues(*Linker);
3493 
3494   if (opts::UpdateDebugSections) {
3495     DebugInfoRewriter->updateLineTableOffsets(
3496         static_cast<MCObjectStreamer &>(*Streamer).getAssembler());
3497   }
3498 
3499   if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary())
3500     RtLibrary->link(*BC, ToolPath, *Linker, [this](auto MapSection) {
3501       // Map newly registered sections.
3502       this->mapAllocatableSections(MapSection);
3503     });
3504 
3505   // Once the code is emitted, we can rename function sections to actual
3506   // output sections and de-register sections used for emission.
3507   for (BinaryFunction *Function : BC->getAllBinaryFunctions()) {
3508     ErrorOr<BinarySection &> Section = Function->getCodeSection();
3509     if (Section &&
3510         (Function->getImageAddress() == 0 || Function->getImageSize() == 0))
3511       continue;
3512 
3513     // Restore origin section for functions that were emitted or supposed to
3514     // be emitted to patch sections.
3515     if (Section)
3516       BC->deregisterSection(*Section);
3517     assert(Function->getOriginSectionName() && "expected origin section");
3518     Function->CodeSectionName = Function->getOriginSectionName()->str();
3519     for (const FunctionFragment &FF :
3520          Function->getLayout().getSplitFragments()) {
3521       if (ErrorOr<BinarySection &> ColdSection =
3522               Function->getCodeSection(FF.getFragmentNum()))
3523         BC->deregisterSection(*ColdSection);
3524     }
3525     if (Function->getLayout().isSplit())
3526       Function->setColdCodeSectionName(getBOLTTextSectionName());
3527   }
3528 
3529   if (opts::PrintCacheMetrics) {
3530     BC->outs() << "BOLT-INFO: cache metrics after emitting functions:\n";
3531     CacheMetrics::printAll(BC->outs(), BC->getSortedFunctions());
3532   }
3533 }
3534 
3535 void RewriteInstance::finalizeMetadataPreEmit() {
3536   MetadataManager.runFinalizersPreEmit();
3537 }
3538 
3539 void RewriteInstance::updateMetadata() {
3540   MetadataManager.runFinalizersAfterEmit();
3541 
3542   if (opts::UpdateDebugSections) {
3543     NamedRegionTimer T("updateDebugInfo", "update debug info", TimerGroupName,
3544                        TimerGroupDesc, opts::TimeRewrite);
3545     DebugInfoRewriter->updateDebugInfo();
3546   }
3547 
3548   if (opts::WriteBoltInfoSection)
3549     addBoltInfoSection();
3550 }
3551 
3552 void RewriteInstance::mapFileSections(BOLTLinker::SectionMapper MapSection) {
3553   BC->deregisterUnusedSections();
3554 
3555   // If no new .eh_frame was written, remove relocated original .eh_frame.
3556   BinarySection *RelocatedEHFrameSection =
3557       getSection(".relocated" + getEHFrameSectionName());
3558   if (RelocatedEHFrameSection && RelocatedEHFrameSection->hasValidSectionID()) {
3559     BinarySection *NewEHFrameSection =
3560         getSection(getNewSecPrefix() + getEHFrameSectionName());
3561     if (!NewEHFrameSection || !NewEHFrameSection->isFinalized()) {
3562       // JITLink will still have to process relocations for the section, hence
3563       // we need to assign it the address that wouldn't result in relocation
3564       // processing failure.
3565       MapSection(*RelocatedEHFrameSection, NextAvailableAddress);
3566       BC->deregisterSection(*RelocatedEHFrameSection);
3567     }
3568   }
3569 
3570   mapCodeSections(MapSection);
3571 
3572   // Map the rest of the sections.
3573   mapAllocatableSections(MapSection);
3574 
3575   if (!BC->BOLTReserved.empty()) {
3576     const uint64_t AllocatedSize =
3577         NextAvailableAddress - BC->BOLTReserved.start();
3578     if (BC->BOLTReserved.size() < AllocatedSize) {
3579       BC->errs() << "BOLT-ERROR: reserved space (" << BC->BOLTReserved.size()
3580                  << " byte" << (BC->BOLTReserved.size() == 1 ? "" : "s")
3581                  << ") is smaller than required for new allocations ("
3582                  << AllocatedSize << " bytes)\n";
3583       exit(1);
3584     }
3585   }
3586 }
3587 
3588 std::vector<BinarySection *> RewriteInstance::getCodeSections() {
3589   std::vector<BinarySection *> CodeSections;
3590   for (BinarySection &Section : BC->textSections())
3591     if (Section.hasValidSectionID())
3592       CodeSections.emplace_back(&Section);
3593 
3594   auto compareSections = [&](const BinarySection *A, const BinarySection *B) {
3595     // If both A and B have names starting with ".text.cold", then
3596     // - if opts::HotFunctionsAtEnd is true, we want order
3597     //   ".text.cold.T", ".text.cold.T-1", ... ".text.cold.1", ".text.cold"
3598     // - if opts::HotFunctionsAtEnd is false, we want order
3599     //   ".text.cold", ".text.cold.1", ... ".text.cold.T-1", ".text.cold.T"
3600     if (A->getName().starts_with(BC->getColdCodeSectionName()) &&
3601         B->getName().starts_with(BC->getColdCodeSectionName())) {
3602       if (A->getName().size() != B->getName().size())
3603         return (opts::HotFunctionsAtEnd)
3604                    ? (A->getName().size() > B->getName().size())
3605                    : (A->getName().size() < B->getName().size());
3606       return (opts::HotFunctionsAtEnd) ? (A->getName() > B->getName())
3607                                        : (A->getName() < B->getName());
3608     }
3609 
3610     // Place movers before anything else.
3611     if (A->getName() == BC->getHotTextMoverSectionName())
3612       return true;
3613     if (B->getName() == BC->getHotTextMoverSectionName())
3614       return false;
3615 
3616     // Depending on opts::HotFunctionsAtEnd, place main and warm sections in
3617     // order.
3618     if (opts::HotFunctionsAtEnd) {
3619       if (B->getName() == BC->getMainCodeSectionName())
3620         return true;
3621       if (A->getName() == BC->getMainCodeSectionName())
3622         return false;
3623       return (B->getName() == BC->getWarmCodeSectionName());
3624     } else {
3625       if (A->getName() == BC->getMainCodeSectionName())
3626         return true;
3627       if (B->getName() == BC->getMainCodeSectionName())
3628         return false;
3629       return (A->getName() == BC->getWarmCodeSectionName());
3630     }
3631   };
3632 
3633   // Determine the order of sections.
3634   llvm::stable_sort(CodeSections, compareSections);
3635 
3636   return CodeSections;
3637 }
3638 
3639 void RewriteInstance::mapCodeSections(BOLTLinker::SectionMapper MapSection) {
3640   if (BC->HasRelocations) {
3641     // Map sections for functions with pre-assigned addresses.
3642     for (BinaryFunction *InjectedFunction : BC->getInjectedBinaryFunctions()) {
3643       const uint64_t OutputAddress = InjectedFunction->getOutputAddress();
3644       if (!OutputAddress)
3645         continue;
3646 
3647       ErrorOr<BinarySection &> FunctionSection =
3648           InjectedFunction->getCodeSection();
3649       assert(FunctionSection && "function should have section");
3650       FunctionSection->setOutputAddress(OutputAddress);
3651       MapSection(*FunctionSection, OutputAddress);
3652       InjectedFunction->setImageAddress(FunctionSection->getAllocAddress());
3653       InjectedFunction->setImageSize(FunctionSection->getOutputSize());
3654     }
3655 
3656     // Populate the list of sections to be allocated.
3657     std::vector<BinarySection *> CodeSections = getCodeSections();
3658 
3659     // Remove sections that were pre-allocated (patch sections).
3660     llvm::erase_if(CodeSections, [](BinarySection *Section) {
3661       return Section->getOutputAddress();
3662     });
3663     LLVM_DEBUG(dbgs() << "Code sections in the order of output:\n";
3664       for (const BinarySection *Section : CodeSections)
3665         dbgs() << Section->getName() << '\n';
3666     );
3667 
3668     uint64_t PaddingSize = 0; // size of padding required at the end
3669 
3670     // Allocate sections starting at a given Address.
3671     auto allocateAt = [&](uint64_t Address) {
3672       const char *LastNonColdSectionName = BC->HasWarmSection
3673                                                ? BC->getWarmCodeSectionName()
3674                                                : BC->getMainCodeSectionName();
3675       for (BinarySection *Section : CodeSections) {
3676         Address = alignTo(Address, Section->getAlignment());
3677         Section->setOutputAddress(Address);
3678         Address += Section->getOutputSize();
3679 
3680         // Hugify: Additional huge page from right side due to
3681         // weird ASLR mapping addresses (4KB aligned)
3682         if (opts::Hugify && !BC->HasFixedLoadAddress &&
3683             Section->getName() == LastNonColdSectionName)
3684           Address = alignTo(Address, Section->getAlignment());
3685       }
3686 
3687       // Make sure we allocate enough space for huge pages.
3688       ErrorOr<BinarySection &> TextSection =
3689           BC->getUniqueSectionByName(LastNonColdSectionName);
3690       if (opts::HotText && TextSection && TextSection->hasValidSectionID()) {
3691         uint64_t HotTextEnd =
3692             TextSection->getOutputAddress() + TextSection->getOutputSize();
3693         HotTextEnd = alignTo(HotTextEnd, BC->PageAlign);
3694         if (HotTextEnd > Address) {
3695           PaddingSize = HotTextEnd - Address;
3696           Address = HotTextEnd;
3697         }
3698       }
3699       return Address;
3700     };
3701 
3702     // Check if we can fit code in the original .text
3703     bool AllocationDone = false;
3704     if (opts::UseOldText) {
3705       const uint64_t CodeSize =
3706           allocateAt(BC->OldTextSectionAddress) - BC->OldTextSectionAddress;
3707 
3708       if (CodeSize <= BC->OldTextSectionSize) {
3709         BC->outs() << "BOLT-INFO: using original .text for new code with 0x"
3710                    << Twine::utohexstr(opts::AlignText) << " alignment\n";
3711         AllocationDone = true;
3712       } else {
3713         BC->errs()
3714             << "BOLT-WARNING: original .text too small to fit the new code"
3715             << " using 0x" << Twine::utohexstr(opts::AlignText)
3716             << " alignment. " << CodeSize << " bytes needed, have "
3717             << BC->OldTextSectionSize << " bytes available.\n";
3718         opts::UseOldText = false;
3719       }
3720     }
3721 
3722     if (!AllocationDone)
3723       NextAvailableAddress = allocateAt(NextAvailableAddress);
3724 
3725     // Do the mapping for ORC layer based on the allocation.
3726     for (BinarySection *Section : CodeSections) {
3727       LLVM_DEBUG(
3728           dbgs() << "BOLT: mapping " << Section->getName() << " at 0x"
3729                  << Twine::utohexstr(Section->getAllocAddress()) << " to 0x"
3730                  << Twine::utohexstr(Section->getOutputAddress()) << '\n');
3731       MapSection(*Section, Section->getOutputAddress());
3732       Section->setOutputFileOffset(
3733           getFileOffsetForAddress(Section->getOutputAddress()));
3734     }
3735 
3736     // Check if we need to insert a padding section for hot text.
3737     if (PaddingSize && !opts::UseOldText)
3738       BC->outs() << "BOLT-INFO: padding code to 0x"
3739                  << Twine::utohexstr(NextAvailableAddress)
3740                  << " to accommodate hot text\n";
3741 
3742     return;
3743   }
3744 
3745   // Processing in non-relocation mode.
3746   uint64_t NewTextSectionStartAddress = NextAvailableAddress;
3747 
3748   for (auto &BFI : BC->getBinaryFunctions()) {
3749     BinaryFunction &Function = BFI.second;
3750     if (!Function.isEmitted())
3751       continue;
3752 
3753     bool TooLarge = false;
3754     ErrorOr<BinarySection &> FuncSection = Function.getCodeSection();
3755     assert(FuncSection && "cannot find section for function");
3756     FuncSection->setOutputAddress(Function.getAddress());
3757     LLVM_DEBUG(dbgs() << "BOLT: mapping 0x"
3758                       << Twine::utohexstr(FuncSection->getAllocAddress())
3759                       << " to 0x" << Twine::utohexstr(Function.getAddress())
3760                       << '\n');
3761     MapSection(*FuncSection, Function.getAddress());
3762     Function.setImageAddress(FuncSection->getAllocAddress());
3763     Function.setImageSize(FuncSection->getOutputSize());
3764     if (Function.getImageSize() > Function.getMaxSize()) {
3765       assert(!BC->isX86() && "Unexpected large function.");
3766       TooLarge = true;
3767       FailedAddresses.emplace_back(Function.getAddress());
3768     }
3769 
3770     // Map jump tables if updating in-place.
3771     if (opts::JumpTables == JTS_BASIC) {
3772       for (auto &JTI : Function.JumpTables) {
3773         JumpTable *JT = JTI.second;
3774         BinarySection &Section = JT->getOutputSection();
3775         Section.setOutputAddress(JT->getAddress());
3776         Section.setOutputFileOffset(getFileOffsetForAddress(JT->getAddress()));
3777         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: mapping JT " << Section.getName()
3778                           << " to 0x" << Twine::utohexstr(JT->getAddress())
3779                           << '\n');
3780         MapSection(Section, JT->getAddress());
3781       }
3782     }
3783 
3784     if (!Function.isSplit())
3785       continue;
3786 
3787     assert(Function.getLayout().isHotColdSplit() &&
3788            "Cannot allocate more than two fragments per function in "
3789            "non-relocation mode.");
3790 
3791     FunctionFragment &FF =
3792         Function.getLayout().getFragment(FragmentNum::cold());
3793     ErrorOr<BinarySection &> ColdSection =
3794         Function.getCodeSection(FF.getFragmentNum());
3795     assert(ColdSection && "cannot find section for cold part");
3796     // Cold fragments are aligned at 16 bytes.
3797     NextAvailableAddress = alignTo(NextAvailableAddress, 16);
3798     if (TooLarge) {
3799       // The corresponding FDE will refer to address 0.
3800       FF.setAddress(0);
3801       FF.setImageAddress(0);
3802       FF.setImageSize(0);
3803       FF.setFileOffset(0);
3804     } else {
3805       FF.setAddress(NextAvailableAddress);
3806       FF.setImageAddress(ColdSection->getAllocAddress());
3807       FF.setImageSize(ColdSection->getOutputSize());
3808       FF.setFileOffset(getFileOffsetForAddress(NextAvailableAddress));
3809       ColdSection->setOutputAddress(FF.getAddress());
3810     }
3811 
3812     LLVM_DEBUG(
3813         dbgs() << formatv(
3814             "BOLT: mapping cold fragment {0:x+} to {1:x+} with size {2:x+}\n",
3815             FF.getImageAddress(), FF.getAddress(), FF.getImageSize()));
3816     MapSection(*ColdSection, FF.getAddress());
3817 
3818     if (TooLarge)
3819       BC->deregisterSection(*ColdSection);
3820 
3821     NextAvailableAddress += FF.getImageSize();
3822   }
3823 
3824   // Add the new text section aggregating all existing code sections.
3825   // This is pseudo-section that serves a purpose of creating a corresponding
3826   // entry in section header table.
3827   const uint64_t NewTextSectionSize =
3828       NextAvailableAddress - NewTextSectionStartAddress;
3829   if (NewTextSectionSize) {
3830     const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/true,
3831                                                    /*IsText=*/true,
3832                                                    /*IsAllocatable=*/true);
3833     BinarySection &Section =
3834       BC->registerOrUpdateSection(getBOLTTextSectionName(),
3835                                   ELF::SHT_PROGBITS,
3836                                   Flags,
3837                                   /*Data=*/nullptr,
3838                                   NewTextSectionSize,
3839                                   16);
3840     Section.setOutputAddress(NewTextSectionStartAddress);
3841     Section.setOutputFileOffset(
3842         getFileOffsetForAddress(NewTextSectionStartAddress));
3843   }
3844 }
3845 
3846 void RewriteInstance::mapAllocatableSections(
3847     BOLTLinker::SectionMapper MapSection) {
3848   // Allocate read-only sections first, then writable sections.
3849   enum : uint8_t { ST_READONLY, ST_READWRITE };
3850   for (uint8_t SType = ST_READONLY; SType <= ST_READWRITE; ++SType) {
3851     const uint64_t LastNextAvailableAddress = NextAvailableAddress;
3852     if (SType == ST_READWRITE) {
3853       // Align R+W segment to regular page size
3854       NextAvailableAddress = alignTo(NextAvailableAddress, BC->RegularPageSize);
3855       NewWritableSegmentAddress = NextAvailableAddress;
3856     }
3857 
3858     for (BinarySection &Section : BC->allocatableSections()) {
3859       if (Section.isLinkOnly())
3860         continue;
3861 
3862       if (!Section.hasValidSectionID())
3863         continue;
3864 
3865       if (Section.isWritable() == (SType == ST_READONLY))
3866         continue;
3867 
3868       if (Section.getOutputAddress()) {
3869         LLVM_DEBUG({
3870           dbgs() << "BOLT-DEBUG: section " << Section.getName()
3871                  << " is already mapped at 0x"
3872                  << Twine::utohexstr(Section.getOutputAddress()) << '\n';
3873         });
3874         continue;
3875       }
3876 
3877       if (Section.hasSectionRef()) {
3878         LLVM_DEBUG({
3879           dbgs() << "BOLT-DEBUG: mapping original section " << Section.getName()
3880                  << " to 0x" << Twine::utohexstr(Section.getAddress()) << '\n';
3881         });
3882         Section.setOutputAddress(Section.getAddress());
3883         Section.setOutputFileOffset(Section.getInputFileOffset());
3884         MapSection(Section, Section.getAddress());
3885       } else {
3886         NextAvailableAddress =
3887             alignTo(NextAvailableAddress, Section.getAlignment());
3888         LLVM_DEBUG({
3889           dbgs() << "BOLT: mapping section " << Section.getName() << " (0x"
3890                  << Twine::utohexstr(Section.getAllocAddress()) << ") to 0x"
3891                  << Twine::utohexstr(NextAvailableAddress) << ":0x"
3892                  << Twine::utohexstr(NextAvailableAddress +
3893                                      Section.getOutputSize())
3894                  << '\n';
3895         });
3896 
3897         MapSection(Section, NextAvailableAddress);
3898         Section.setOutputAddress(NextAvailableAddress);
3899         Section.setOutputFileOffset(
3900             getFileOffsetForAddress(NextAvailableAddress));
3901 
3902         NextAvailableAddress += Section.getOutputSize();
3903       }
3904     }
3905 
3906     if (SType == ST_READONLY) {
3907       if (PHDRTableAddress) {
3908         // Segment size includes the size of the PHDR area.
3909         NewTextSegmentSize = NextAvailableAddress - PHDRTableAddress;
3910       } else if (NewTextSegmentAddress) {
3911         // Existing PHDR table would be updated.
3912         NewTextSegmentSize = NextAvailableAddress - NewTextSegmentAddress;
3913       }
3914     } else if (SType == ST_READWRITE) {
3915       NewWritableSegmentSize = NextAvailableAddress - NewWritableSegmentAddress;
3916       // Restore NextAvailableAddress if no new writable sections
3917       if (!NewWritableSegmentSize)
3918         NextAvailableAddress = LastNextAvailableAddress;
3919     }
3920   }
3921 }
3922 
3923 void RewriteInstance::updateOutputValues(const BOLTLinker &Linker) {
3924   if (std::optional<AddressMap> Map = AddressMap::parse(*BC))
3925     BC->setIOAddressMap(std::move(*Map));
3926 
3927   for (BinaryFunction *Function : BC->getAllBinaryFunctions())
3928     Function->updateOutputValues(Linker);
3929 }
3930 
3931 void RewriteInstance::patchELFPHDRTable() {
3932   auto ELF64LEFile = cast<ELF64LEObjectFile>(InputFile);
3933   const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile();
3934   raw_fd_ostream &OS = Out->os();
3935 
3936   // Write/re-write program headers.
3937   Phnum = Obj.getHeader().e_phnum;
3938   if (PHDRTableOffset) {
3939     // Writing new pheader table and adding one new entry for R+X segment.
3940     Phnum += 1;
3941     if (NewWritableSegmentSize) {
3942       // Adding one more entry for R+W segment.
3943       Phnum += 1;
3944     }
3945   } else {
3946     assert(!PHDRTableAddress && "unexpected address for program header table");
3947     PHDRTableOffset = Obj.getHeader().e_phoff;
3948     if (NewWritableSegmentSize) {
3949       BC->errs() << "BOLT-ERROR: unable to add writable segment\n";
3950       exit(1);
3951     }
3952   }
3953 
3954   // NOTE Currently .eh_frame_hdr appends to the last segment, recalculate
3955   // last segments size based on the NextAvailableAddress variable.
3956   if (!NewWritableSegmentSize) {
3957     if (PHDRTableAddress)
3958       NewTextSegmentSize = NextAvailableAddress - PHDRTableAddress;
3959     else if (NewTextSegmentAddress)
3960       NewTextSegmentSize = NextAvailableAddress - NewTextSegmentAddress;
3961   } else {
3962     NewWritableSegmentSize = NextAvailableAddress - NewWritableSegmentAddress;
3963   }
3964 
3965   const uint64_t SavedPos = OS.tell();
3966   OS.seek(PHDRTableOffset);
3967 
3968   auto createNewTextPhdr = [&]() {
3969     ELF64LEPhdrTy NewPhdr;
3970     NewPhdr.p_type = ELF::PT_LOAD;
3971     if (PHDRTableAddress) {
3972       NewPhdr.p_offset = PHDRTableOffset;
3973       NewPhdr.p_vaddr = PHDRTableAddress;
3974       NewPhdr.p_paddr = PHDRTableAddress;
3975     } else {
3976       NewPhdr.p_offset = NewTextSegmentOffset;
3977       NewPhdr.p_vaddr = NewTextSegmentAddress;
3978       NewPhdr.p_paddr = NewTextSegmentAddress;
3979     }
3980     NewPhdr.p_filesz = NewTextSegmentSize;
3981     NewPhdr.p_memsz = NewTextSegmentSize;
3982     NewPhdr.p_flags = ELF::PF_X | ELF::PF_R;
3983     if (opts::Instrument) {
3984       // FIXME: Currently instrumentation is experimental and the runtime data
3985       // is emitted with code, thus everything needs to be writable.
3986       NewPhdr.p_flags |= ELF::PF_W;
3987     }
3988     NewPhdr.p_align = BC->PageAlign;
3989 
3990     return NewPhdr;
3991   };
3992 
3993   auto writeNewSegmentPhdrs = [&]() {
3994     if (PHDRTableAddress || NewTextSegmentSize) {
3995       ELF64LE::Phdr NewPhdr = createNewTextPhdr();
3996       OS.write(reinterpret_cast<const char *>(&NewPhdr), sizeof(NewPhdr));
3997     }
3998 
3999     if (NewWritableSegmentSize) {
4000       ELF64LEPhdrTy NewPhdr;
4001       NewPhdr.p_type = ELF::PT_LOAD;
4002       NewPhdr.p_offset = getFileOffsetForAddress(NewWritableSegmentAddress);
4003       NewPhdr.p_vaddr = NewWritableSegmentAddress;
4004       NewPhdr.p_paddr = NewWritableSegmentAddress;
4005       NewPhdr.p_filesz = NewWritableSegmentSize;
4006       NewPhdr.p_memsz = NewWritableSegmentSize;
4007       NewPhdr.p_align = BC->RegularPageSize;
4008       NewPhdr.p_flags = ELF::PF_R | ELF::PF_W;
4009       OS.write(reinterpret_cast<const char *>(&NewPhdr), sizeof(NewPhdr));
4010     }
4011   };
4012 
4013   bool ModdedGnuStack = false;
4014   bool AddedSegment = false;
4015 
4016   // Copy existing program headers with modifications.
4017   for (const ELF64LE::Phdr &Phdr : cantFail(Obj.program_headers())) {
4018     ELF64LE::Phdr NewPhdr = Phdr;
4019     switch (Phdr.p_type) {
4020     case ELF::PT_PHDR:
4021       if (PHDRTableAddress) {
4022         NewPhdr.p_offset = PHDRTableOffset;
4023         NewPhdr.p_vaddr = PHDRTableAddress;
4024         NewPhdr.p_paddr = PHDRTableAddress;
4025         NewPhdr.p_filesz = sizeof(NewPhdr) * Phnum;
4026         NewPhdr.p_memsz = sizeof(NewPhdr) * Phnum;
4027       }
4028       break;
4029     case ELF::PT_GNU_EH_FRAME: {
4030       ErrorOr<BinarySection &> EHFrameHdrSec = BC->getUniqueSectionByName(
4031           getNewSecPrefix() + getEHFrameHdrSectionName());
4032       if (EHFrameHdrSec && EHFrameHdrSec->isAllocatable() &&
4033           EHFrameHdrSec->isFinalized()) {
4034         NewPhdr.p_offset = EHFrameHdrSec->getOutputFileOffset();
4035         NewPhdr.p_vaddr = EHFrameHdrSec->getOutputAddress();
4036         NewPhdr.p_paddr = EHFrameHdrSec->getOutputAddress();
4037         NewPhdr.p_filesz = EHFrameHdrSec->getOutputSize();
4038         NewPhdr.p_memsz = EHFrameHdrSec->getOutputSize();
4039       }
4040       break;
4041     }
4042     case ELF::PT_GNU_STACK:
4043       if (opts::UseGnuStack) {
4044         // Overwrite the header with the new text segment header.
4045         NewPhdr = createNewTextPhdr();
4046         ModdedGnuStack = true;
4047       }
4048       break;
4049     case ELF::PT_DYNAMIC:
4050       if (!opts::UseGnuStack) {
4051         // Insert new headers before DYNAMIC.
4052         writeNewSegmentPhdrs();
4053         AddedSegment = true;
4054       }
4055       break;
4056     }
4057     OS.write(reinterpret_cast<const char *>(&NewPhdr), sizeof(NewPhdr));
4058   }
4059 
4060   if (!opts::UseGnuStack && !AddedSegment) {
4061     // Append new headers to the end of the table.
4062     writeNewSegmentPhdrs();
4063   }
4064 
4065   if (opts::UseGnuStack && !ModdedGnuStack) {
4066     BC->errs()
4067         << "BOLT-ERROR: could not find PT_GNU_STACK program header to modify\n";
4068     exit(1);
4069   }
4070 
4071   OS.seek(SavedPos);
4072 }
4073 
4074 namespace {
4075 
4076 /// Write padding to \p OS such that its current \p Offset becomes aligned
4077 /// at \p Alignment. Return new (aligned) offset.
4078 uint64_t appendPadding(raw_pwrite_stream &OS, uint64_t Offset,
4079                        uint64_t Alignment) {
4080   if (!Alignment)
4081     return Offset;
4082 
4083   const uint64_t PaddingSize =
4084       offsetToAlignment(Offset, llvm::Align(Alignment));
4085   for (unsigned I = 0; I < PaddingSize; ++I)
4086     OS.write((unsigned char)0);
4087   return Offset + PaddingSize;
4088 }
4089 
4090 }
4091 
4092 void RewriteInstance::rewriteNoteSections() {
4093   auto ELF64LEFile = cast<ELF64LEObjectFile>(InputFile);
4094   const ELFFile<ELF64LE> &Obj = ELF64LEFile->getELFFile();
4095   raw_fd_ostream &OS = Out->os();
4096 
4097   uint64_t NextAvailableOffset = std::max(
4098       getFileOffsetForAddress(NextAvailableAddress), FirstNonAllocatableOffset);
4099   OS.seek(NextAvailableOffset);
4100 
4101   // Copy over non-allocatable section contents and update file offsets.
4102   for (const ELF64LE::Shdr &Section : cantFail(Obj.sections())) {
4103     if (Section.sh_type == ELF::SHT_NULL)
4104       continue;
4105     if (Section.sh_flags & ELF::SHF_ALLOC)
4106       continue;
4107 
4108     SectionRef SecRef = ELF64LEFile->toSectionRef(&Section);
4109     BinarySection *BSec = BC->getSectionForSectionRef(SecRef);
4110     assert(BSec && !BSec->isAllocatable() &&
4111            "Matching non-allocatable BinarySection should exist.");
4112 
4113     StringRef SectionName =
4114         cantFail(Obj.getSectionName(Section), "cannot get section name");
4115     if (shouldStrip(Section, SectionName))
4116       continue;
4117 
4118     // Insert padding as needed.
4119     NextAvailableOffset =
4120         appendPadding(OS, NextAvailableOffset, Section.sh_addralign);
4121 
4122     // New section size.
4123     uint64_t Size = 0;
4124     bool DataWritten = false;
4125     uint8_t *SectionData = nullptr;
4126     // Copy over section contents unless it's one of the sections we overwrite.
4127     if (!willOverwriteSection(SectionName)) {
4128       Size = Section.sh_size;
4129       StringRef Dataref = InputFile->getData().substr(Section.sh_offset, Size);
4130       std::string Data;
4131       if (BSec->getPatcher()) {
4132         Data = BSec->getPatcher()->patchBinary(Dataref);
4133         Dataref = StringRef(Data);
4134       }
4135 
4136       // Section was expanded, so need to treat it as overwrite.
4137       if (Size != Dataref.size()) {
4138         BSec = &BC->registerOrUpdateNoteSection(
4139             SectionName, copyByteArray(Dataref), Dataref.size());
4140         Size = 0;
4141       } else {
4142         OS << Dataref;
4143         DataWritten = true;
4144 
4145         // Add padding as the section extension might rely on the alignment.
4146         Size = appendPadding(OS, Size, Section.sh_addralign);
4147       }
4148     }
4149 
4150     // Perform section post-processing.
4151     assert(BSec->getAlignment() <= Section.sh_addralign &&
4152            "alignment exceeds value in file");
4153 
4154     if (BSec->getAllocAddress()) {
4155       assert(!DataWritten && "Writing section twice.");
4156       (void)DataWritten;
4157       SectionData = BSec->getOutputData();
4158 
4159       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: " << (Size ? "appending" : "writing")
4160                         << " contents to section " << SectionName << '\n');
4161       OS.write(reinterpret_cast<char *>(SectionData), BSec->getOutputSize());
4162       Size += BSec->getOutputSize();
4163     }
4164 
4165     BSec->setOutputFileOffset(NextAvailableOffset);
4166     BSec->flushPendingRelocations(OS, [this](const MCSymbol *S) {
4167       return getNewValueForSymbol(S->getName());
4168     });
4169 
4170     // Section contents are no longer needed, but we need to update the size so
4171     // that it will be reflected in the section header table.
4172     BSec->updateContents(nullptr, Size);
4173 
4174     NextAvailableOffset += Size;
4175   }
4176 
4177   // Write new note sections.
4178   for (BinarySection &Section : BC->nonAllocatableSections()) {
4179     if (Section.getOutputFileOffset() || !Section.getAllocAddress())
4180       continue;
4181 
4182     assert(!Section.hasPendingRelocations() && "cannot have pending relocs");
4183 
4184     NextAvailableOffset =
4185         appendPadding(OS, NextAvailableOffset, Section.getAlignment());
4186     Section.setOutputFileOffset(NextAvailableOffset);
4187 
4188     LLVM_DEBUG(
4189         dbgs() << "BOLT-DEBUG: writing out new section " << Section.getName()
4190                << " of size " << Section.getOutputSize() << " at offset 0x"
4191                << Twine::utohexstr(Section.getOutputFileOffset()) << '\n');
4192 
4193     OS.write(Section.getOutputContents().data(), Section.getOutputSize());
4194     NextAvailableOffset += Section.getOutputSize();
4195   }
4196 }
4197 
4198 template <typename ELFT>
4199 void RewriteInstance::finalizeSectionStringTable(ELFObjectFile<ELFT> *File) {
4200   // Pre-populate section header string table.
4201   for (const BinarySection &Section : BC->sections())
4202     if (!Section.isAnonymous())
4203       SHStrTab.add(Section.getOutputName());
4204   SHStrTab.finalize();
4205 
4206   const size_t SHStrTabSize = SHStrTab.getSize();
4207   uint8_t *DataCopy = new uint8_t[SHStrTabSize];
4208   memset(DataCopy, 0, SHStrTabSize);
4209   SHStrTab.write(DataCopy);
4210   BC->registerOrUpdateNoteSection(".shstrtab",
4211                                   DataCopy,
4212                                   SHStrTabSize,
4213                                   /*Alignment=*/1,
4214                                   /*IsReadOnly=*/true,
4215                                   ELF::SHT_STRTAB);
4216 }
4217 
4218 void RewriteInstance::addBoltInfoSection() {
4219   std::string DescStr;
4220   raw_string_ostream DescOS(DescStr);
4221 
4222   DescOS << "BOLT revision: " << BoltRevision << ", "
4223          << "command line:";
4224   for (int I = 0; I < Argc; ++I)
4225     DescOS << " " << Argv[I];
4226   DescOS.flush();
4227 
4228   // Encode as GNU GOLD VERSION so it is easily printable by 'readelf -n'
4229   const std::string BoltInfo =
4230       BinarySection::encodeELFNote("GNU", DescStr, 4 /*NT_GNU_GOLD_VERSION*/);
4231   BC->registerOrUpdateNoteSection(".note.bolt_info", copyByteArray(BoltInfo),
4232                                   BoltInfo.size(),
4233                                   /*Alignment=*/1,
4234                                   /*IsReadOnly=*/true, ELF::SHT_NOTE);
4235 }
4236 
4237 void RewriteInstance::addBATSection() {
4238   BC->registerOrUpdateNoteSection(BoltAddressTranslation::SECTION_NAME, nullptr,
4239                                   0,
4240                                   /*Alignment=*/1,
4241                                   /*IsReadOnly=*/true, ELF::SHT_NOTE);
4242 }
4243 
4244 void RewriteInstance::encodeBATSection() {
4245   std::string DescStr;
4246   raw_string_ostream DescOS(DescStr);
4247 
4248   BAT->write(*BC, DescOS);
4249   DescOS.flush();
4250 
4251   const std::string BoltInfo =
4252       BinarySection::encodeELFNote("BOLT", DescStr, BinarySection::NT_BOLT_BAT);
4253   BC->registerOrUpdateNoteSection(BoltAddressTranslation::SECTION_NAME,
4254                                   copyByteArray(BoltInfo), BoltInfo.size(),
4255                                   /*Alignment=*/1,
4256                                   /*IsReadOnly=*/true, ELF::SHT_NOTE);
4257   BC->outs() << "BOLT-INFO: BAT section size (bytes): " << BoltInfo.size()
4258              << '\n';
4259 }
4260 
4261 template <typename ELFShdrTy>
4262 bool RewriteInstance::shouldStrip(const ELFShdrTy &Section,
4263                                   StringRef SectionName) {
4264   // Strip non-allocatable relocation sections.
4265   if (!(Section.sh_flags & ELF::SHF_ALLOC) && Section.sh_type == ELF::SHT_RELA)
4266     return true;
4267 
4268   // Strip debug sections if not updating them.
4269   if (isDebugSection(SectionName) && !opts::UpdateDebugSections)
4270     return true;
4271 
4272   // Strip symtab section if needed
4273   if (opts::RemoveSymtab && Section.sh_type == ELF::SHT_SYMTAB)
4274     return true;
4275 
4276   return false;
4277 }
4278 
4279 template <typename ELFT>
4280 std::vector<typename object::ELFObjectFile<ELFT>::Elf_Shdr>
4281 RewriteInstance::getOutputSections(ELFObjectFile<ELFT> *File,
4282                                    std::vector<uint32_t> &NewSectionIndex) {
4283   using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr;
4284   const ELFFile<ELFT> &Obj = File->getELFFile();
4285   typename ELFT::ShdrRange Sections = cantFail(Obj.sections());
4286 
4287   // Keep track of section header entries attached to the corresponding section.
4288   std::vector<std::pair<BinarySection *, ELFShdrTy>> OutputSections;
4289   auto addSection = [&](const ELFShdrTy &Section, BinarySection &BinSec) {
4290     ELFShdrTy NewSection = Section;
4291     NewSection.sh_name = SHStrTab.getOffset(BinSec.getOutputName());
4292     OutputSections.emplace_back(&BinSec, std::move(NewSection));
4293   };
4294 
4295   // Copy over entries for original allocatable sections using modified name.
4296   for (const ELFShdrTy &Section : Sections) {
4297     // Always ignore this section.
4298     if (Section.sh_type == ELF::SHT_NULL) {
4299       OutputSections.emplace_back(nullptr, Section);
4300       continue;
4301     }
4302 
4303     if (!(Section.sh_flags & ELF::SHF_ALLOC))
4304       continue;
4305 
4306     SectionRef SecRef = File->toSectionRef(&Section);
4307     BinarySection *BinSec = BC->getSectionForSectionRef(SecRef);
4308     assert(BinSec && "Matching BinarySection should exist.");
4309 
4310     addSection(Section, *BinSec);
4311   }
4312 
4313   for (BinarySection &Section : BC->allocatableSections()) {
4314     if (!Section.isFinalized())
4315       continue;
4316 
4317     if (Section.hasSectionRef() || Section.isAnonymous()) {
4318       if (opts::Verbosity)
4319         BC->outs() << "BOLT-INFO: not writing section header for section "
4320                    << Section.getOutputName() << '\n';
4321       continue;
4322     }
4323 
4324     if (opts::Verbosity >= 1)
4325       BC->outs() << "BOLT-INFO: writing section header for "
4326                  << Section.getOutputName() << '\n';
4327     ELFShdrTy NewSection;
4328     NewSection.sh_type = ELF::SHT_PROGBITS;
4329     NewSection.sh_addr = Section.getOutputAddress();
4330     NewSection.sh_offset = Section.getOutputFileOffset();
4331     NewSection.sh_size = Section.getOutputSize();
4332     NewSection.sh_entsize = 0;
4333     NewSection.sh_flags = Section.getELFFlags();
4334     NewSection.sh_link = 0;
4335     NewSection.sh_info = 0;
4336     NewSection.sh_addralign = Section.getAlignment();
4337     addSection(NewSection, Section);
4338   }
4339 
4340   // Sort all allocatable sections by their offset.
4341   llvm::stable_sort(OutputSections, [](const auto &A, const auto &B) {
4342     return A.second.sh_offset < B.second.sh_offset;
4343   });
4344 
4345   // Fix section sizes to prevent overlapping.
4346   ELFShdrTy *PrevSection = nullptr;
4347   BinarySection *PrevBinSec = nullptr;
4348   for (auto &SectionKV : OutputSections) {
4349     ELFShdrTy &Section = SectionKV.second;
4350 
4351     // Ignore NOBITS sections as they don't take any space in the file.
4352     if (Section.sh_type == ELF::SHT_NOBITS)
4353       continue;
4354 
4355     // Note that address continuity is not guaranteed as sections could be
4356     // placed in different loadable segments.
4357     if (PrevSection &&
4358         PrevSection->sh_offset + PrevSection->sh_size > Section.sh_offset) {
4359       if (opts::Verbosity > 1)
4360         BC->outs() << "BOLT-INFO: adjusting size for section "
4361                    << PrevBinSec->getOutputName() << '\n';
4362       PrevSection->sh_size = Section.sh_offset - PrevSection->sh_offset;
4363     }
4364 
4365     PrevSection = &Section;
4366     PrevBinSec = SectionKV.first;
4367   }
4368 
4369   uint64_t LastFileOffset = 0;
4370 
4371   // Copy over entries for non-allocatable sections performing necessary
4372   // adjustments.
4373   for (const ELFShdrTy &Section : Sections) {
4374     if (Section.sh_type == ELF::SHT_NULL)
4375       continue;
4376     if (Section.sh_flags & ELF::SHF_ALLOC)
4377       continue;
4378 
4379     StringRef SectionName =
4380         cantFail(Obj.getSectionName(Section), "cannot get section name");
4381 
4382     if (shouldStrip(Section, SectionName))
4383       continue;
4384 
4385     SectionRef SecRef = File->toSectionRef(&Section);
4386     BinarySection *BinSec = BC->getSectionForSectionRef(SecRef);
4387     assert(BinSec && "Matching BinarySection should exist.");
4388 
4389     ELFShdrTy NewSection = Section;
4390     NewSection.sh_offset = BinSec->getOutputFileOffset();
4391     NewSection.sh_size = BinSec->getOutputSize();
4392 
4393     if (NewSection.sh_type == ELF::SHT_SYMTAB)
4394       NewSection.sh_info = NumLocalSymbols;
4395 
4396     addSection(NewSection, *BinSec);
4397 
4398     LastFileOffset = BinSec->getOutputFileOffset();
4399   }
4400 
4401   // Create entries for new non-allocatable sections.
4402   for (BinarySection &Section : BC->nonAllocatableSections()) {
4403     if (Section.getOutputFileOffset() <= LastFileOffset)
4404       continue;
4405 
4406     if (opts::Verbosity >= 1)
4407       BC->outs() << "BOLT-INFO: writing section header for "
4408                  << Section.getOutputName() << '\n';
4409 
4410     ELFShdrTy NewSection;
4411     NewSection.sh_type = Section.getELFType();
4412     NewSection.sh_addr = 0;
4413     NewSection.sh_offset = Section.getOutputFileOffset();
4414     NewSection.sh_size = Section.getOutputSize();
4415     NewSection.sh_entsize = 0;
4416     NewSection.sh_flags = Section.getELFFlags();
4417     NewSection.sh_link = 0;
4418     NewSection.sh_info = 0;
4419     NewSection.sh_addralign = Section.getAlignment();
4420 
4421     addSection(NewSection, Section);
4422   }
4423 
4424   // Assign indices to sections.
4425   std::unordered_map<std::string, uint64_t> NameToIndex;
4426   for (uint32_t Index = 1; Index < OutputSections.size(); ++Index)
4427     OutputSections[Index].first->setIndex(Index);
4428 
4429   // Update section index mapping
4430   NewSectionIndex.clear();
4431   NewSectionIndex.resize(Sections.size(), 0);
4432   for (const ELFShdrTy &Section : Sections) {
4433     if (Section.sh_type == ELF::SHT_NULL)
4434       continue;
4435 
4436     size_t OrgIndex = std::distance(Sections.begin(), &Section);
4437 
4438     SectionRef SecRef = File->toSectionRef(&Section);
4439     BinarySection *BinSec = BC->getSectionForSectionRef(SecRef);
4440     assert(BinSec && "BinarySection should exist for an input section.");
4441 
4442     // Some sections are stripped
4443     if (!BinSec->hasValidIndex())
4444       continue;
4445 
4446     NewSectionIndex[OrgIndex] = BinSec->getIndex();
4447   }
4448 
4449   std::vector<ELFShdrTy> SectionsOnly(OutputSections.size());
4450   llvm::copy(llvm::make_second_range(OutputSections), SectionsOnly.begin());
4451 
4452   return SectionsOnly;
4453 }
4454 
4455 // Rewrite section header table inserting new entries as needed. The sections
4456 // header table size itself may affect the offsets of other sections,
4457 // so we are placing it at the end of the binary.
4458 //
4459 // As we rewrite entries we need to track how many sections were inserted
4460 // as it changes the sh_link value. We map old indices to new ones for
4461 // existing sections.
4462 template <typename ELFT>
4463 void RewriteInstance::patchELFSectionHeaderTable(ELFObjectFile<ELFT> *File) {
4464   using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr;
4465   using ELFEhdrTy = typename ELFObjectFile<ELFT>::Elf_Ehdr;
4466   raw_fd_ostream &OS = Out->os();
4467   const ELFFile<ELFT> &Obj = File->getELFFile();
4468 
4469   // Mapping from old section indices to new ones
4470   std::vector<uint32_t> NewSectionIndex;
4471   std::vector<ELFShdrTy> OutputSections =
4472       getOutputSections(File, NewSectionIndex);
4473   LLVM_DEBUG(
4474     dbgs() << "BOLT-DEBUG: old to new section index mapping:\n";
4475     for (uint64_t I = 0; I < NewSectionIndex.size(); ++I)
4476       dbgs() << "  " << I << " -> " << NewSectionIndex[I] << '\n';
4477   );
4478 
4479   // Align starting address for section header table. There's no architecutal
4480   // need to align this, it is just for pleasant human readability.
4481   uint64_t SHTOffset = OS.tell();
4482   SHTOffset = appendPadding(OS, SHTOffset, 16);
4483 
4484   // Write all section header entries while patching section references.
4485   for (ELFShdrTy &Section : OutputSections) {
4486     Section.sh_link = NewSectionIndex[Section.sh_link];
4487     if (Section.sh_type == ELF::SHT_REL || Section.sh_type == ELF::SHT_RELA)
4488       Section.sh_info = NewSectionIndex[Section.sh_info];
4489     OS.write(reinterpret_cast<const char *>(&Section), sizeof(Section));
4490   }
4491 
4492   // Fix ELF header.
4493   ELFEhdrTy NewEhdr = Obj.getHeader();
4494 
4495   if (BC->HasRelocations) {
4496     if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary())
4497       NewEhdr.e_entry = RtLibrary->getRuntimeStartAddress();
4498     else
4499       NewEhdr.e_entry = getNewFunctionAddress(NewEhdr.e_entry);
4500     assert((NewEhdr.e_entry || !Obj.getHeader().e_entry) &&
4501            "cannot find new address for entry point");
4502   }
4503   if (PHDRTableOffset) {
4504     NewEhdr.e_phoff = PHDRTableOffset;
4505     NewEhdr.e_phnum = Phnum;
4506   }
4507   NewEhdr.e_shoff = SHTOffset;
4508   NewEhdr.e_shnum = OutputSections.size();
4509   NewEhdr.e_shstrndx = NewSectionIndex[NewEhdr.e_shstrndx];
4510   OS.pwrite(reinterpret_cast<const char *>(&NewEhdr), sizeof(NewEhdr), 0);
4511 }
4512 
4513 template <typename ELFT, typename WriteFuncTy, typename StrTabFuncTy>
4514 void RewriteInstance::updateELFSymbolTable(
4515     ELFObjectFile<ELFT> *File, bool IsDynSym,
4516     const typename object::ELFObjectFile<ELFT>::Elf_Shdr &SymTabSection,
4517     const std::vector<uint32_t> &NewSectionIndex, WriteFuncTy Write,
4518     StrTabFuncTy AddToStrTab) {
4519   const ELFFile<ELFT> &Obj = File->getELFFile();
4520   using ELFSymTy = typename ELFObjectFile<ELFT>::Elf_Sym;
4521 
4522   StringRef StringSection =
4523       cantFail(Obj.getStringTableForSymtab(SymTabSection));
4524 
4525   unsigned NumHotTextSymsUpdated = 0;
4526   unsigned NumHotDataSymsUpdated = 0;
4527 
4528   std::map<const BinaryFunction *, uint64_t> IslandSizes;
4529   auto getConstantIslandSize = [&IslandSizes](const BinaryFunction &BF) {
4530     auto Itr = IslandSizes.find(&BF);
4531     if (Itr != IslandSizes.end())
4532       return Itr->second;
4533     return IslandSizes[&BF] = BF.estimateConstantIslandSize();
4534   };
4535 
4536   // Symbols for the new symbol table.
4537   std::vector<ELFSymTy> Symbols;
4538 
4539   bool EmittedColdFileSymbol = false;
4540 
4541   auto getNewSectionIndex = [&](uint32_t OldIndex) {
4542     // For dynamic symbol table, the section index could be wrong on the input,
4543     // and its value is ignored by the runtime if it's different from
4544     // SHN_UNDEF and SHN_ABS.
4545     // However, we still need to update dynamic symbol table, so return a
4546     // section index, even though the index is broken.
4547     if (IsDynSym && OldIndex >= NewSectionIndex.size())
4548       return OldIndex;
4549 
4550     assert(OldIndex < NewSectionIndex.size() && "section index out of bounds");
4551     const uint32_t NewIndex = NewSectionIndex[OldIndex];
4552 
4553     // We may have stripped the section that dynsym was referencing due to
4554     // the linker bug. In that case return the old index avoiding marking
4555     // the symbol as undefined.
4556     if (IsDynSym && NewIndex != OldIndex && NewIndex == ELF::SHN_UNDEF)
4557       return OldIndex;
4558     return NewIndex;
4559   };
4560 
4561   // Get the extra symbol name of a split fragment; used in addExtraSymbols.
4562   auto getSplitSymbolName = [&](const FunctionFragment &FF,
4563                                 const ELFSymTy &FunctionSymbol) {
4564     SmallString<256> SymbolName;
4565     if (BC->HasWarmSection)
4566       SymbolName =
4567           formatv("{0}.{1}", cantFail(FunctionSymbol.getName(StringSection)),
4568                   FF.getFragmentNum() == FragmentNum::warm() ? "warm" : "cold");
4569     else
4570       SymbolName = formatv("{0}.cold.{1}",
4571                            cantFail(FunctionSymbol.getName(StringSection)),
4572                            FF.getFragmentNum().get() - 1);
4573     return SymbolName;
4574   };
4575 
4576   // Add extra symbols for the function.
4577   //
4578   // Note that addExtraSymbols() could be called multiple times for the same
4579   // function with different FunctionSymbol matching the main function entry
4580   // point.
4581   auto addExtraSymbols = [&](const BinaryFunction &Function,
4582                              const ELFSymTy &FunctionSymbol) {
4583     if (Function.isFolded()) {
4584       BinaryFunction *ICFParent = Function.getFoldedIntoFunction();
4585       while (ICFParent->isFolded())
4586         ICFParent = ICFParent->getFoldedIntoFunction();
4587       ELFSymTy ICFSymbol = FunctionSymbol;
4588       SmallVector<char, 256> Buf;
4589       ICFSymbol.st_name =
4590           AddToStrTab(Twine(cantFail(FunctionSymbol.getName(StringSection)))
4591                           .concat(".icf.0")
4592                           .toStringRef(Buf));
4593       ICFSymbol.st_value = ICFParent->getOutputAddress();
4594       ICFSymbol.st_size = ICFParent->getOutputSize();
4595       ICFSymbol.st_shndx = ICFParent->getCodeSection()->getIndex();
4596       Symbols.emplace_back(ICFSymbol);
4597     }
4598     if (Function.isSplit()) {
4599       // Prepend synthetic FILE symbol to prevent local cold fragments from
4600       // colliding with existing symbols with the same name.
4601       if (!EmittedColdFileSymbol &&
4602           FunctionSymbol.getBinding() == ELF::STB_GLOBAL) {
4603         ELFSymTy FileSymbol;
4604         FileSymbol.st_shndx = ELF::SHN_ABS;
4605         FileSymbol.st_name = AddToStrTab(getBOLTFileSymbolName());
4606         FileSymbol.st_value = 0;
4607         FileSymbol.st_size = 0;
4608         FileSymbol.st_other = 0;
4609         FileSymbol.setBindingAndType(ELF::STB_LOCAL, ELF::STT_FILE);
4610         Symbols.emplace_back(FileSymbol);
4611         EmittedColdFileSymbol = true;
4612       }
4613       for (const FunctionFragment &FF :
4614            Function.getLayout().getSplitFragments()) {
4615         if (FF.getAddress()) {
4616           ELFSymTy NewColdSym = FunctionSymbol;
4617           const SmallString<256> SymbolName =
4618               getSplitSymbolName(FF, FunctionSymbol);
4619           NewColdSym.st_name = AddToStrTab(SymbolName);
4620           NewColdSym.st_shndx =
4621               Function.getCodeSection(FF.getFragmentNum())->getIndex();
4622           NewColdSym.st_value = FF.getAddress();
4623           NewColdSym.st_size = FF.getImageSize();
4624           NewColdSym.setBindingAndType(ELF::STB_LOCAL, ELF::STT_FUNC);
4625           Symbols.emplace_back(NewColdSym);
4626         }
4627       }
4628     }
4629     if (Function.hasConstantIsland()) {
4630       uint64_t DataMark = Function.getOutputDataAddress();
4631       uint64_t CISize = getConstantIslandSize(Function);
4632       uint64_t CodeMark = DataMark + CISize;
4633       ELFSymTy DataMarkSym = FunctionSymbol;
4634       DataMarkSym.st_name = AddToStrTab("$d");
4635       DataMarkSym.st_value = DataMark;
4636       DataMarkSym.st_size = 0;
4637       DataMarkSym.setType(ELF::STT_NOTYPE);
4638       DataMarkSym.setBinding(ELF::STB_LOCAL);
4639       ELFSymTy CodeMarkSym = DataMarkSym;
4640       CodeMarkSym.st_name = AddToStrTab("$x");
4641       CodeMarkSym.st_value = CodeMark;
4642       Symbols.emplace_back(DataMarkSym);
4643       Symbols.emplace_back(CodeMarkSym);
4644     }
4645     if (Function.hasConstantIsland() && Function.isSplit()) {
4646       uint64_t DataMark = Function.getOutputColdDataAddress();
4647       uint64_t CISize = getConstantIslandSize(Function);
4648       uint64_t CodeMark = DataMark + CISize;
4649       ELFSymTy DataMarkSym = FunctionSymbol;
4650       DataMarkSym.st_name = AddToStrTab("$d");
4651       DataMarkSym.st_value = DataMark;
4652       DataMarkSym.st_size = 0;
4653       DataMarkSym.setType(ELF::STT_NOTYPE);
4654       DataMarkSym.setBinding(ELF::STB_LOCAL);
4655       ELFSymTy CodeMarkSym = DataMarkSym;
4656       CodeMarkSym.st_name = AddToStrTab("$x");
4657       CodeMarkSym.st_value = CodeMark;
4658       Symbols.emplace_back(DataMarkSym);
4659       Symbols.emplace_back(CodeMarkSym);
4660     }
4661   };
4662 
4663   // For regular (non-dynamic) symbol table, exclude symbols referring
4664   // to non-allocatable sections.
4665   auto shouldStrip = [&](const ELFSymTy &Symbol) {
4666     if (Symbol.isAbsolute() || !Symbol.isDefined())
4667       return false;
4668 
4669     // If we cannot link the symbol to a section, leave it as is.
4670     Expected<const typename ELFT::Shdr *> Section =
4671         Obj.getSection(Symbol.st_shndx);
4672     if (!Section)
4673       return false;
4674 
4675     // Remove the section symbol iif the corresponding section was stripped.
4676     if (Symbol.getType() == ELF::STT_SECTION) {
4677       if (!getNewSectionIndex(Symbol.st_shndx))
4678         return true;
4679       return false;
4680     }
4681 
4682     // Symbols in non-allocatable sections are typically remnants of relocations
4683     // emitted under "-emit-relocs" linker option. Delete those as we delete
4684     // relocations against non-allocatable sections.
4685     if (!((*Section)->sh_flags & ELF::SHF_ALLOC))
4686       return true;
4687 
4688     return false;
4689   };
4690 
4691   for (const ELFSymTy &Symbol : cantFail(Obj.symbols(&SymTabSection))) {
4692     // For regular (non-dynamic) symbol table strip unneeded symbols.
4693     if (!IsDynSym && shouldStrip(Symbol))
4694       continue;
4695 
4696     const BinaryFunction *Function =
4697         BC->getBinaryFunctionAtAddress(Symbol.st_value);
4698     // Ignore false function references, e.g. when the section address matches
4699     // the address of the function.
4700     if (Function && Symbol.getType() == ELF::STT_SECTION)
4701       Function = nullptr;
4702 
4703     // For non-dynamic symtab, make sure the symbol section matches that of
4704     // the function. It can mismatch e.g. if the symbol is a section marker
4705     // in which case we treat the symbol separately from the function.
4706     // For dynamic symbol table, the section index could be wrong on the input,
4707     // and its value is ignored by the runtime if it's different from
4708     // SHN_UNDEF and SHN_ABS.
4709     if (!IsDynSym && Function &&
4710         Symbol.st_shndx !=
4711             Function->getOriginSection()->getSectionRef().getIndex())
4712       Function = nullptr;
4713 
4714     // Create a new symbol based on the existing symbol.
4715     ELFSymTy NewSymbol = Symbol;
4716 
4717     // Handle special symbols based on their name.
4718     Expected<StringRef> SymbolName = Symbol.getName(StringSection);
4719     assert(SymbolName && "cannot get symbol name");
4720 
4721     auto updateSymbolValue = [&](const StringRef Name,
4722                                  std::optional<uint64_t> Value = std::nullopt) {
4723       NewSymbol.st_value = Value ? *Value : getNewValueForSymbol(Name);
4724       NewSymbol.st_shndx = ELF::SHN_ABS;
4725       BC->outs() << "BOLT-INFO: setting " << Name << " to 0x"
4726                  << Twine::utohexstr(NewSymbol.st_value) << '\n';
4727     };
4728 
4729     if (*SymbolName == "__hot_start" || *SymbolName == "__hot_end") {
4730       if (opts::HotText) {
4731         updateSymbolValue(*SymbolName);
4732         ++NumHotTextSymsUpdated;
4733       }
4734       goto registerSymbol;
4735     }
4736 
4737     if (*SymbolName == "__hot_data_start" || *SymbolName == "__hot_data_end") {
4738       if (opts::HotData) {
4739         updateSymbolValue(*SymbolName);
4740         ++NumHotDataSymsUpdated;
4741       }
4742       goto registerSymbol;
4743     }
4744 
4745     if (*SymbolName == "_end") {
4746       if (NextAvailableAddress > Symbol.st_value)
4747         updateSymbolValue(*SymbolName, NextAvailableAddress);
4748       goto registerSymbol;
4749     }
4750 
4751     if (Function) {
4752       // If the symbol matched a function that was not emitted, update the
4753       // corresponding section index but otherwise leave it unchanged.
4754       if (Function->isEmitted()) {
4755         NewSymbol.st_value = Function->getOutputAddress();
4756         NewSymbol.st_size = Function->getOutputSize();
4757         NewSymbol.st_shndx = Function->getCodeSection()->getIndex();
4758       } else if (Symbol.st_shndx < ELF::SHN_LORESERVE) {
4759         NewSymbol.st_shndx = getNewSectionIndex(Symbol.st_shndx);
4760       }
4761 
4762       // Add new symbols to the symbol table if necessary.
4763       if (!IsDynSym)
4764         addExtraSymbols(*Function, NewSymbol);
4765     } else {
4766       // Check if the function symbol matches address inside a function, i.e.
4767       // it marks a secondary entry point.
4768       Function =
4769           (Symbol.getType() == ELF::STT_FUNC)
4770               ? BC->getBinaryFunctionContainingAddress(Symbol.st_value,
4771                                                        /*CheckPastEnd=*/false,
4772                                                        /*UseMaxSize=*/true)
4773               : nullptr;
4774 
4775       if (Function && Function->isEmitted()) {
4776         assert(Function->getLayout().isHotColdSplit() &&
4777                "Adding symbols based on cold fragment when there are more than "
4778                "2 fragments");
4779         const uint64_t OutputAddress =
4780             Function->translateInputToOutputAddress(Symbol.st_value);
4781 
4782         NewSymbol.st_value = OutputAddress;
4783         // Force secondary entry points to have zero size.
4784         NewSymbol.st_size = 0;
4785 
4786         // Find fragment containing entrypoint
4787         FunctionLayout::fragment_const_iterator FF = llvm::find_if(
4788             Function->getLayout().fragments(), [&](const FunctionFragment &FF) {
4789               uint64_t Lo = FF.getAddress();
4790               uint64_t Hi = Lo + FF.getImageSize();
4791               return Lo <= OutputAddress && OutputAddress < Hi;
4792             });
4793 
4794         if (FF == Function->getLayout().fragment_end()) {
4795           assert(
4796               OutputAddress >= Function->getCodeSection()->getOutputAddress() &&
4797               OutputAddress < (Function->getCodeSection()->getOutputAddress() +
4798                                Function->getCodeSection()->getOutputSize()) &&
4799               "Cannot locate fragment containing secondary entrypoint");
4800           FF = Function->getLayout().fragment_begin();
4801         }
4802 
4803         NewSymbol.st_shndx =
4804             Function->getCodeSection(FF->getFragmentNum())->getIndex();
4805       } else {
4806         // Check if the symbol belongs to moved data object and update it.
4807         BinaryData *BD = opts::ReorderData.empty()
4808                              ? nullptr
4809                              : BC->getBinaryDataAtAddress(Symbol.st_value);
4810         if (BD && BD->isMoved() && !BD->isJumpTable()) {
4811           assert((!BD->getSize() || !Symbol.st_size ||
4812                   Symbol.st_size == BD->getSize()) &&
4813                  "sizes must match");
4814 
4815           BinarySection &OutputSection = BD->getOutputSection();
4816           assert(OutputSection.getIndex());
4817           LLVM_DEBUG(dbgs()
4818                      << "BOLT-DEBUG: moving " << BD->getName() << " from "
4819                      << *BC->getSectionNameForAddress(Symbol.st_value) << " ("
4820                      << Symbol.st_shndx << ") to " << OutputSection.getName()
4821                      << " (" << OutputSection.getIndex() << ")\n");
4822           NewSymbol.st_shndx = OutputSection.getIndex();
4823           NewSymbol.st_value = BD->getOutputAddress();
4824         } else {
4825           // Otherwise just update the section for the symbol.
4826           if (Symbol.st_shndx < ELF::SHN_LORESERVE)
4827             NewSymbol.st_shndx = getNewSectionIndex(Symbol.st_shndx);
4828         }
4829 
4830         // Detect local syms in the text section that we didn't update
4831         // and that were preserved by the linker to support relocations against
4832         // .text. Remove them from the symtab.
4833         if (Symbol.getType() == ELF::STT_NOTYPE &&
4834             Symbol.getBinding() == ELF::STB_LOCAL && Symbol.st_size == 0) {
4835           if (BC->getBinaryFunctionContainingAddress(Symbol.st_value,
4836                                                      /*CheckPastEnd=*/false,
4837                                                      /*UseMaxSize=*/true)) {
4838             // Can only delete the symbol if not patching. Such symbols should
4839             // not exist in the dynamic symbol table.
4840             assert(!IsDynSym && "cannot delete symbol");
4841             continue;
4842           }
4843         }
4844       }
4845     }
4846 
4847   registerSymbol:
4848     if (IsDynSym)
4849       Write((&Symbol - cantFail(Obj.symbols(&SymTabSection)).begin()) *
4850                 sizeof(ELFSymTy),
4851             NewSymbol);
4852     else
4853       Symbols.emplace_back(NewSymbol);
4854   }
4855 
4856   if (IsDynSym) {
4857     assert(Symbols.empty());
4858     return;
4859   }
4860 
4861   // Add symbols of injected functions
4862   for (BinaryFunction *Function : BC->getInjectedBinaryFunctions()) {
4863     ELFSymTy NewSymbol;
4864     BinarySection *OriginSection = Function->getOriginSection();
4865     NewSymbol.st_shndx =
4866         OriginSection
4867             ? getNewSectionIndex(OriginSection->getSectionRef().getIndex())
4868             : Function->getCodeSection()->getIndex();
4869     NewSymbol.st_value = Function->getOutputAddress();
4870     NewSymbol.st_name = AddToStrTab(Function->getOneName());
4871     NewSymbol.st_size = Function->getOutputSize();
4872     NewSymbol.st_other = 0;
4873     NewSymbol.setBindingAndType(ELF::STB_LOCAL, ELF::STT_FUNC);
4874     Symbols.emplace_back(NewSymbol);
4875 
4876     if (Function->isSplit()) {
4877       assert(Function->getLayout().isHotColdSplit() &&
4878              "Adding symbols based on cold fragment when there are more than "
4879              "2 fragments");
4880       ELFSymTy NewColdSym = NewSymbol;
4881       NewColdSym.setType(ELF::STT_NOTYPE);
4882       SmallVector<char, 256> Buf;
4883       NewColdSym.st_name = AddToStrTab(
4884           Twine(Function->getPrintName()).concat(".cold.0").toStringRef(Buf));
4885       const FunctionFragment &ColdFF =
4886           Function->getLayout().getFragment(FragmentNum::cold());
4887       NewColdSym.st_value = ColdFF.getAddress();
4888       NewColdSym.st_size = ColdFF.getImageSize();
4889       Symbols.emplace_back(NewColdSym);
4890     }
4891   }
4892 
4893   auto AddSymbol = [&](const StringRef &Name, uint64_t Address) {
4894     if (!Address)
4895       return;
4896 
4897     ELFSymTy Symbol;
4898     Symbol.st_value = Address;
4899     Symbol.st_shndx = ELF::SHN_ABS;
4900     Symbol.st_name = AddToStrTab(Name);
4901     Symbol.st_size = 0;
4902     Symbol.st_other = 0;
4903     Symbol.setBindingAndType(ELF::STB_WEAK, ELF::STT_NOTYPE);
4904 
4905     BC->outs() << "BOLT-INFO: setting " << Name << " to 0x"
4906                << Twine::utohexstr(Symbol.st_value) << '\n';
4907 
4908     Symbols.emplace_back(Symbol);
4909   };
4910 
4911   // Add runtime library start and fini address symbols
4912   if (RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary()) {
4913     AddSymbol("__bolt_runtime_start", RtLibrary->getRuntimeStartAddress());
4914     AddSymbol("__bolt_runtime_fini", RtLibrary->getRuntimeFiniAddress());
4915   }
4916 
4917   assert((!NumHotTextSymsUpdated || NumHotTextSymsUpdated == 2) &&
4918          "either none or both __hot_start/__hot_end symbols were expected");
4919   assert((!NumHotDataSymsUpdated || NumHotDataSymsUpdated == 2) &&
4920          "either none or both __hot_data_start/__hot_data_end symbols were "
4921          "expected");
4922 
4923   auto AddEmittedSymbol = [&](const StringRef &Name) {
4924     AddSymbol(Name, getNewValueForSymbol(Name));
4925   };
4926 
4927   if (opts::HotText && !NumHotTextSymsUpdated) {
4928     AddEmittedSymbol("__hot_start");
4929     AddEmittedSymbol("__hot_end");
4930   }
4931 
4932   if (opts::HotData && !NumHotDataSymsUpdated) {
4933     AddEmittedSymbol("__hot_data_start");
4934     AddEmittedSymbol("__hot_data_end");
4935   }
4936 
4937   // Put local symbols at the beginning.
4938   llvm::stable_sort(Symbols, [](const ELFSymTy &A, const ELFSymTy &B) {
4939     if (A.getBinding() == ELF::STB_LOCAL && B.getBinding() != ELF::STB_LOCAL)
4940       return true;
4941     return false;
4942   });
4943 
4944   for (const ELFSymTy &Symbol : Symbols)
4945     Write(0, Symbol);
4946 }
4947 
4948 template <typename ELFT>
4949 void RewriteInstance::patchELFSymTabs(ELFObjectFile<ELFT> *File) {
4950   const ELFFile<ELFT> &Obj = File->getELFFile();
4951   using ELFShdrTy = typename ELFObjectFile<ELFT>::Elf_Shdr;
4952   using ELFSymTy = typename ELFObjectFile<ELFT>::Elf_Sym;
4953 
4954   // Compute a preview of how section indices will change after rewriting, so
4955   // we can properly update the symbol table based on new section indices.
4956   std::vector<uint32_t> NewSectionIndex;
4957   getOutputSections(File, NewSectionIndex);
4958 
4959   // Update dynamic symbol table.
4960   const ELFShdrTy *DynSymSection = nullptr;
4961   for (const ELFShdrTy &Section : cantFail(Obj.sections())) {
4962     if (Section.sh_type == ELF::SHT_DYNSYM) {
4963       DynSymSection = &Section;
4964       break;
4965     }
4966   }
4967   assert((DynSymSection || BC->IsStaticExecutable) &&
4968          "dynamic symbol table expected");
4969   if (DynSymSection) {
4970     updateELFSymbolTable(
4971         File,
4972         /*IsDynSym=*/true,
4973         *DynSymSection,
4974         NewSectionIndex,
4975         [&](size_t Offset, const ELFSymTy &Sym) {
4976           Out->os().pwrite(reinterpret_cast<const char *>(&Sym),
4977                            sizeof(ELFSymTy),
4978                            DynSymSection->sh_offset + Offset);
4979         },
4980         [](StringRef) -> size_t { return 0; });
4981   }
4982 
4983   if (opts::RemoveSymtab)
4984     return;
4985 
4986   // (re)create regular symbol table.
4987   const ELFShdrTy *SymTabSection = nullptr;
4988   for (const ELFShdrTy &Section : cantFail(Obj.sections())) {
4989     if (Section.sh_type == ELF::SHT_SYMTAB) {
4990       SymTabSection = &Section;
4991       break;
4992     }
4993   }
4994   if (!SymTabSection) {
4995     BC->errs() << "BOLT-WARNING: no symbol table found\n";
4996     return;
4997   }
4998 
4999   const ELFShdrTy *StrTabSection =
5000       cantFail(Obj.getSection(SymTabSection->sh_link));
5001   std::string NewContents;
5002   std::string NewStrTab = std::string(
5003       File->getData().substr(StrTabSection->sh_offset, StrTabSection->sh_size));
5004   StringRef SecName = cantFail(Obj.getSectionName(*SymTabSection));
5005   StringRef StrSecName = cantFail(Obj.getSectionName(*StrTabSection));
5006 
5007   NumLocalSymbols = 0;
5008   updateELFSymbolTable(
5009       File,
5010       /*IsDynSym=*/false,
5011       *SymTabSection,
5012       NewSectionIndex,
5013       [&](size_t Offset, const ELFSymTy &Sym) {
5014         if (Sym.getBinding() == ELF::STB_LOCAL)
5015           ++NumLocalSymbols;
5016         NewContents.append(reinterpret_cast<const char *>(&Sym),
5017                            sizeof(ELFSymTy));
5018       },
5019       [&](StringRef Str) {
5020         size_t Idx = NewStrTab.size();
5021         NewStrTab.append(NameResolver::restore(Str).str());
5022         NewStrTab.append(1, '\0');
5023         return Idx;
5024       });
5025 
5026   BC->registerOrUpdateNoteSection(SecName,
5027                                   copyByteArray(NewContents),
5028                                   NewContents.size(),
5029                                   /*Alignment=*/1,
5030                                   /*IsReadOnly=*/true,
5031                                   ELF::SHT_SYMTAB);
5032 
5033   BC->registerOrUpdateNoteSection(StrSecName,
5034                                   copyByteArray(NewStrTab),
5035                                   NewStrTab.size(),
5036                                   /*Alignment=*/1,
5037                                   /*IsReadOnly=*/true,
5038                                   ELF::SHT_STRTAB);
5039 }
5040 
5041 template <typename ELFT>
5042 void RewriteInstance::patchELFAllocatableRelrSection(
5043     ELFObjectFile<ELFT> *File) {
5044   if (!DynamicRelrAddress)
5045     return;
5046 
5047   raw_fd_ostream &OS = Out->os();
5048   const uint8_t PSize = BC->AsmInfo->getCodePointerSize();
5049   const uint64_t MaxDelta = ((CHAR_BIT * DynamicRelrEntrySize) - 1) * PSize;
5050 
5051   auto FixAddend = [&](const BinarySection &Section, const Relocation &Rel,
5052                        uint64_t FileOffset) {
5053     // Fix relocation symbol value in place if no static relocation found
5054     // on the same address. We won't check the BF relocations here since it
5055     // is rare case and no optimization is required.
5056     if (Section.getRelocationAt(Rel.Offset))
5057       return;
5058 
5059     // No fixup needed if symbol address was not changed
5060     const uint64_t Addend = getNewFunctionOrDataAddress(Rel.Addend);
5061     if (!Addend)
5062       return;
5063 
5064     OS.pwrite(reinterpret_cast<const char *>(&Addend), PSize, FileOffset);
5065   };
5066 
5067   // Fill new relative relocation offsets set
5068   std::set<uint64_t> RelOffsets;
5069   for (const BinarySection &Section : BC->allocatableSections()) {
5070     const uint64_t SectionInputAddress = Section.getAddress();
5071     uint64_t SectionAddress = Section.getOutputAddress();
5072     if (!SectionAddress)
5073       SectionAddress = SectionInputAddress;
5074 
5075     for (const Relocation &Rel : Section.dynamicRelocations()) {
5076       if (!Rel.isRelative())
5077         continue;
5078 
5079       uint64_t RelOffset =
5080           getNewFunctionOrDataAddress(SectionInputAddress + Rel.Offset);
5081 
5082       RelOffset = RelOffset == 0 ? SectionAddress + Rel.Offset : RelOffset;
5083       assert((RelOffset & 1) == 0 && "Wrong relocation offset");
5084       RelOffsets.emplace(RelOffset);
5085       FixAddend(Section, Rel, RelOffset);
5086     }
5087   }
5088 
5089   ErrorOr<BinarySection &> Section =
5090       BC->getSectionForAddress(*DynamicRelrAddress);
5091   assert(Section && "cannot get .relr.dyn section");
5092   assert(Section->isRelr() && "Expected section to be SHT_RELR type");
5093   uint64_t RelrDynOffset = Section->getInputFileOffset();
5094   const uint64_t RelrDynEndOffset = RelrDynOffset + Section->getSize();
5095 
5096   auto WriteRelr = [&](uint64_t Value) {
5097     if (RelrDynOffset + DynamicRelrEntrySize > RelrDynEndOffset) {
5098       BC->errs() << "BOLT-ERROR: Offset overflow for relr.dyn section\n";
5099       exit(1);
5100     }
5101 
5102     OS.pwrite(reinterpret_cast<const char *>(&Value), DynamicRelrEntrySize,
5103               RelrDynOffset);
5104     RelrDynOffset += DynamicRelrEntrySize;
5105   };
5106 
5107   for (auto RelIt = RelOffsets.begin(); RelIt != RelOffsets.end();) {
5108     WriteRelr(*RelIt);
5109     uint64_t Base = *RelIt++ + PSize;
5110     while (1) {
5111       uint64_t Bitmap = 0;
5112       for (; RelIt != RelOffsets.end(); ++RelIt) {
5113         const uint64_t Delta = *RelIt - Base;
5114         if (Delta >= MaxDelta || Delta % PSize)
5115           break;
5116 
5117         Bitmap |= (1ULL << (Delta / PSize));
5118       }
5119 
5120       if (!Bitmap)
5121         break;
5122 
5123       WriteRelr((Bitmap << 1) | 1);
5124       Base += MaxDelta;
5125     }
5126   }
5127 
5128   // Fill the rest of the section with empty bitmap value
5129   while (RelrDynOffset != RelrDynEndOffset)
5130     WriteRelr(1);
5131 }
5132 
5133 template <typename ELFT>
5134 void
5135 RewriteInstance::patchELFAllocatableRelaSections(ELFObjectFile<ELFT> *File) {
5136   using Elf_Rela = typename ELFT::Rela;
5137   raw_fd_ostream &OS = Out->os();
5138   const ELFFile<ELFT> &EF = File->getELFFile();
5139 
5140   uint64_t RelDynOffset = 0, RelDynEndOffset = 0;
5141   uint64_t RelPltOffset = 0, RelPltEndOffset = 0;
5142 
5143   auto setSectionFileOffsets = [&](uint64_t Address, uint64_t &Start,
5144                                    uint64_t &End) {
5145     ErrorOr<BinarySection &> Section = BC->getSectionForAddress(Address);
5146     assert(Section && "cannot get relocation section");
5147     Start = Section->getInputFileOffset();
5148     End = Start + Section->getSize();
5149   };
5150 
5151   if (!DynamicRelocationsAddress && !PLTRelocationsAddress)
5152     return;
5153 
5154   if (DynamicRelocationsAddress)
5155     setSectionFileOffsets(*DynamicRelocationsAddress, RelDynOffset,
5156                           RelDynEndOffset);
5157 
5158   if (PLTRelocationsAddress)
5159     setSectionFileOffsets(*PLTRelocationsAddress, RelPltOffset,
5160                           RelPltEndOffset);
5161 
5162   DynamicRelativeRelocationsCount = 0;
5163 
5164   auto writeRela = [&OS](const Elf_Rela *RelA, uint64_t &Offset) {
5165     OS.pwrite(reinterpret_cast<const char *>(RelA), sizeof(*RelA), Offset);
5166     Offset += sizeof(*RelA);
5167   };
5168 
5169   auto writeRelocations = [&](bool PatchRelative) {
5170     for (BinarySection &Section : BC->allocatableSections()) {
5171       const uint64_t SectionInputAddress = Section.getAddress();
5172       uint64_t SectionAddress = Section.getOutputAddress();
5173       if (!SectionAddress)
5174         SectionAddress = SectionInputAddress;
5175 
5176       for (const Relocation &Rel : Section.dynamicRelocations()) {
5177         const bool IsRelative = Rel.isRelative();
5178         if (PatchRelative != IsRelative)
5179           continue;
5180 
5181         if (IsRelative)
5182           ++DynamicRelativeRelocationsCount;
5183 
5184         Elf_Rela NewRelA;
5185         MCSymbol *Symbol = Rel.Symbol;
5186         uint32_t SymbolIdx = 0;
5187         uint64_t Addend = Rel.Addend;
5188         uint64_t RelOffset =
5189             getNewFunctionOrDataAddress(SectionInputAddress + Rel.Offset);
5190 
5191         RelOffset = RelOffset == 0 ? SectionAddress + Rel.Offset : RelOffset;
5192         if (Rel.Symbol) {
5193           SymbolIdx = getOutputDynamicSymbolIndex(Symbol);
5194         } else {
5195           // Usually this case is used for R_*_(I)RELATIVE relocations
5196           const uint64_t Address = getNewFunctionOrDataAddress(Addend);
5197           if (Address)
5198             Addend = Address;
5199         }
5200 
5201         NewRelA.setSymbolAndType(SymbolIdx, Rel.Type, EF.isMips64EL());
5202         NewRelA.r_offset = RelOffset;
5203         NewRelA.r_addend = Addend;
5204 
5205         const bool IsJmpRel = IsJmpRelocation.contains(Rel.Type);
5206         uint64_t &Offset = IsJmpRel ? RelPltOffset : RelDynOffset;
5207         const uint64_t &EndOffset =
5208             IsJmpRel ? RelPltEndOffset : RelDynEndOffset;
5209         if (!Offset || !EndOffset) {
5210           BC->errs() << "BOLT-ERROR: Invalid offsets for dynamic relocation\n";
5211           exit(1);
5212         }
5213 
5214         if (Offset + sizeof(NewRelA) > EndOffset) {
5215           BC->errs() << "BOLT-ERROR: Offset overflow for dynamic relocation\n";
5216           exit(1);
5217         }
5218 
5219         writeRela(&NewRelA, Offset);
5220       }
5221     }
5222   };
5223 
5224   // Place R_*_RELATIVE relocations in RELA section if RELR is not presented.
5225   // The dynamic linker expects all R_*_RELATIVE relocations in RELA
5226   // to be emitted first.
5227   if (!DynamicRelrAddress)
5228     writeRelocations(/* PatchRelative */ true);
5229   writeRelocations(/* PatchRelative */ false);
5230 
5231   auto fillNone = [&](uint64_t &Offset, uint64_t EndOffset) {
5232     if (!Offset)
5233       return;
5234 
5235     typename ELFObjectFile<ELFT>::Elf_Rela RelA;
5236     RelA.setSymbolAndType(0, Relocation::getNone(), EF.isMips64EL());
5237     RelA.r_offset = 0;
5238     RelA.r_addend = 0;
5239     while (Offset < EndOffset)
5240       writeRela(&RelA, Offset);
5241 
5242     assert(Offset == EndOffset && "Unexpected section overflow");
5243   };
5244 
5245   // Fill the rest of the sections with R_*_NONE relocations
5246   fillNone(RelDynOffset, RelDynEndOffset);
5247   fillNone(RelPltOffset, RelPltEndOffset);
5248 }
5249 
5250 template <typename ELFT>
5251 void RewriteInstance::patchELFGOT(ELFObjectFile<ELFT> *File) {
5252   raw_fd_ostream &OS = Out->os();
5253 
5254   SectionRef GOTSection;
5255   for (const SectionRef &Section : File->sections()) {
5256     StringRef SectionName = cantFail(Section.getName());
5257     if (SectionName == ".got") {
5258       GOTSection = Section;
5259       break;
5260     }
5261   }
5262   if (!GOTSection.getObject()) {
5263     if (!BC->IsStaticExecutable)
5264       BC->errs() << "BOLT-INFO: no .got section found\n";
5265     return;
5266   }
5267 
5268   StringRef GOTContents = cantFail(GOTSection.getContents());
5269   for (const uint64_t *GOTEntry =
5270            reinterpret_cast<const uint64_t *>(GOTContents.data());
5271        GOTEntry < reinterpret_cast<const uint64_t *>(GOTContents.data() +
5272                                                      GOTContents.size());
5273        ++GOTEntry) {
5274     if (uint64_t NewAddress = getNewFunctionAddress(*GOTEntry)) {
5275       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: patching GOT entry 0x"
5276                         << Twine::utohexstr(*GOTEntry) << " with 0x"
5277                         << Twine::utohexstr(NewAddress) << '\n');
5278       OS.pwrite(reinterpret_cast<const char *>(&NewAddress), sizeof(NewAddress),
5279                 reinterpret_cast<const char *>(GOTEntry) -
5280                     File->getData().data());
5281     }
5282   }
5283 }
5284 
5285 template <typename ELFT>
5286 void RewriteInstance::patchELFDynamic(ELFObjectFile<ELFT> *File) {
5287   if (BC->IsStaticExecutable)
5288     return;
5289 
5290   const ELFFile<ELFT> &Obj = File->getELFFile();
5291   raw_fd_ostream &OS = Out->os();
5292 
5293   using Elf_Phdr = typename ELFFile<ELFT>::Elf_Phdr;
5294   using Elf_Dyn = typename ELFFile<ELFT>::Elf_Dyn;
5295 
5296   // Locate DYNAMIC by looking through program headers.
5297   uint64_t DynamicOffset = 0;
5298   const Elf_Phdr *DynamicPhdr = nullptr;
5299   for (const Elf_Phdr &Phdr : cantFail(Obj.program_headers())) {
5300     if (Phdr.p_type == ELF::PT_DYNAMIC) {
5301       DynamicOffset = Phdr.p_offset;
5302       DynamicPhdr = &Phdr;
5303       assert(Phdr.p_memsz == Phdr.p_filesz && "dynamic sizes should match");
5304       break;
5305     }
5306   }
5307   assert(DynamicPhdr && "missing dynamic in ELF binary");
5308 
5309   bool ZNowSet = false;
5310 
5311   // Go through all dynamic entries and patch functions addresses with
5312   // new ones.
5313   typename ELFT::DynRange DynamicEntries =
5314       cantFail(Obj.dynamicEntries(), "error accessing dynamic table");
5315   auto DTB = DynamicEntries.begin();
5316   for (const Elf_Dyn &Dyn : DynamicEntries) {
5317     Elf_Dyn NewDE = Dyn;
5318     bool ShouldPatch = true;
5319     switch (Dyn.d_tag) {
5320     default:
5321       ShouldPatch = false;
5322       break;
5323     case ELF::DT_RELACOUNT:
5324       NewDE.d_un.d_val = DynamicRelativeRelocationsCount;
5325       break;
5326     case ELF::DT_INIT:
5327     case ELF::DT_FINI: {
5328       if (BC->HasRelocations) {
5329         if (uint64_t NewAddress = getNewFunctionAddress(Dyn.getPtr())) {
5330           LLVM_DEBUG(dbgs() << "BOLT-DEBUG: patching dynamic entry of type "
5331                             << Dyn.getTag() << '\n');
5332           NewDE.d_un.d_ptr = NewAddress;
5333         }
5334       }
5335       RuntimeLibrary *RtLibrary = BC->getRuntimeLibrary();
5336       if (RtLibrary && Dyn.getTag() == ELF::DT_FINI) {
5337         if (uint64_t Addr = RtLibrary->getRuntimeFiniAddress())
5338           NewDE.d_un.d_ptr = Addr;
5339       }
5340       if (RtLibrary && Dyn.getTag() == ELF::DT_INIT && !BC->HasInterpHeader) {
5341         if (auto Addr = RtLibrary->getRuntimeStartAddress()) {
5342           LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Set DT_INIT to 0x"
5343                             << Twine::utohexstr(Addr) << '\n');
5344           NewDE.d_un.d_ptr = Addr;
5345         }
5346       }
5347       break;
5348     }
5349     case ELF::DT_FLAGS:
5350       if (BC->RequiresZNow) {
5351         NewDE.d_un.d_val |= ELF::DF_BIND_NOW;
5352         ZNowSet = true;
5353       }
5354       break;
5355     case ELF::DT_FLAGS_1:
5356       if (BC->RequiresZNow) {
5357         NewDE.d_un.d_val |= ELF::DF_1_NOW;
5358         ZNowSet = true;
5359       }
5360       break;
5361     }
5362     if (ShouldPatch)
5363       OS.pwrite(reinterpret_cast<const char *>(&NewDE), sizeof(NewDE),
5364                 DynamicOffset + (&Dyn - DTB) * sizeof(Dyn));
5365   }
5366 
5367   if (BC->RequiresZNow && !ZNowSet) {
5368     BC->errs()
5369         << "BOLT-ERROR: output binary requires immediate relocation "
5370            "processing which depends on DT_FLAGS or DT_FLAGS_1 presence in "
5371            ".dynamic. Please re-link the binary with -znow.\n";
5372     exit(1);
5373   }
5374 }
5375 
5376 template <typename ELFT>
5377 Error RewriteInstance::readELFDynamic(ELFObjectFile<ELFT> *File) {
5378   const ELFFile<ELFT> &Obj = File->getELFFile();
5379 
5380   using Elf_Phdr = typename ELFFile<ELFT>::Elf_Phdr;
5381   using Elf_Dyn = typename ELFFile<ELFT>::Elf_Dyn;
5382 
5383   // Locate DYNAMIC by looking through program headers.
5384   const Elf_Phdr *DynamicPhdr = nullptr;
5385   for (const Elf_Phdr &Phdr : cantFail(Obj.program_headers())) {
5386     if (Phdr.p_type == ELF::PT_DYNAMIC) {
5387       DynamicPhdr = &Phdr;
5388       break;
5389     }
5390   }
5391 
5392   if (!DynamicPhdr) {
5393     BC->outs() << "BOLT-INFO: static input executable detected\n";
5394     // TODO: static PIE executable might have dynamic header
5395     BC->IsStaticExecutable = true;
5396     return Error::success();
5397   }
5398 
5399   if (DynamicPhdr->p_memsz != DynamicPhdr->p_filesz)
5400     return createStringError(errc::executable_format_error,
5401                              "dynamic section sizes should match");
5402 
5403   // Go through all dynamic entries to locate entries of interest.
5404   auto DynamicEntriesOrErr = Obj.dynamicEntries();
5405   if (!DynamicEntriesOrErr)
5406     return DynamicEntriesOrErr.takeError();
5407   typename ELFT::DynRange DynamicEntries = DynamicEntriesOrErr.get();
5408 
5409   for (const Elf_Dyn &Dyn : DynamicEntries) {
5410     switch (Dyn.d_tag) {
5411     case ELF::DT_INIT:
5412       if (!BC->HasInterpHeader) {
5413         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Set start function address\n");
5414         BC->StartFunctionAddress = Dyn.getPtr();
5415       }
5416       break;
5417     case ELF::DT_FINI:
5418       BC->FiniAddress = Dyn.getPtr();
5419       break;
5420     case ELF::DT_FINI_ARRAY:
5421       BC->FiniArrayAddress = Dyn.getPtr();
5422       break;
5423     case ELF::DT_FINI_ARRAYSZ:
5424       BC->FiniArraySize = Dyn.getPtr();
5425       break;
5426     case ELF::DT_RELA:
5427       DynamicRelocationsAddress = Dyn.getPtr();
5428       break;
5429     case ELF::DT_RELASZ:
5430       DynamicRelocationsSize = Dyn.getVal();
5431       break;
5432     case ELF::DT_JMPREL:
5433       PLTRelocationsAddress = Dyn.getPtr();
5434       break;
5435     case ELF::DT_PLTRELSZ:
5436       PLTRelocationsSize = Dyn.getVal();
5437       break;
5438     case ELF::DT_RELACOUNT:
5439       DynamicRelativeRelocationsCount = Dyn.getVal();
5440       break;
5441     case ELF::DT_RELR:
5442       DynamicRelrAddress = Dyn.getPtr();
5443       break;
5444     case ELF::DT_RELRSZ:
5445       DynamicRelrSize = Dyn.getVal();
5446       break;
5447     case ELF::DT_RELRENT:
5448       DynamicRelrEntrySize = Dyn.getVal();
5449       break;
5450     }
5451   }
5452 
5453   if (!DynamicRelocationsAddress || !DynamicRelocationsSize) {
5454     DynamicRelocationsAddress.reset();
5455     DynamicRelocationsSize = 0;
5456   }
5457 
5458   if (!PLTRelocationsAddress || !PLTRelocationsSize) {
5459     PLTRelocationsAddress.reset();
5460     PLTRelocationsSize = 0;
5461   }
5462 
5463   if (!DynamicRelrAddress || !DynamicRelrSize) {
5464     DynamicRelrAddress.reset();
5465     DynamicRelrSize = 0;
5466   } else if (!DynamicRelrEntrySize) {
5467     BC->errs() << "BOLT-ERROR: expected DT_RELRENT to be presented "
5468                << "in DYNAMIC section\n";
5469     exit(1);
5470   } else if (DynamicRelrSize % DynamicRelrEntrySize) {
5471     BC->errs() << "BOLT-ERROR: expected RELR table size to be divisible "
5472                << "by RELR entry size\n";
5473     exit(1);
5474   }
5475 
5476   return Error::success();
5477 }
5478 
5479 uint64_t RewriteInstance::getNewFunctionAddress(uint64_t OldAddress) {
5480   const BinaryFunction *Function = BC->getBinaryFunctionAtAddress(OldAddress);
5481   if (!Function)
5482     return 0;
5483 
5484   return Function->getOutputAddress();
5485 }
5486 
5487 uint64_t RewriteInstance::getNewFunctionOrDataAddress(uint64_t OldAddress) {
5488   if (uint64_t Function = getNewFunctionAddress(OldAddress))
5489     return Function;
5490 
5491   const BinaryData *BD = BC->getBinaryDataAtAddress(OldAddress);
5492   if (BD && BD->isMoved())
5493     return BD->getOutputAddress();
5494 
5495   if (const BinaryFunction *BF =
5496           BC->getBinaryFunctionContainingAddress(OldAddress)) {
5497     if (BF->isEmitted()) {
5498       BC->errs() << "BOLT-ERROR: unable to get new address corresponding to "
5499                     "input address 0x"
5500                  << Twine::utohexstr(OldAddress) << " in function " << *BF
5501                  << ". Consider adding this function to --skip-funcs=...\n";
5502       exit(1);
5503     }
5504   }
5505 
5506   return 0;
5507 }
5508 
5509 void RewriteInstance::rewriteFile() {
5510   std::error_code EC;
5511   Out = std::make_unique<ToolOutputFile>(opts::OutputFilename, EC,
5512                                          sys::fs::OF_None);
5513   check_error(EC, "cannot create output executable file");
5514 
5515   raw_fd_ostream &OS = Out->os();
5516 
5517   // Copy allocatable part of the input.
5518   OS << InputFile->getData().substr(0, FirstNonAllocatableOffset);
5519 
5520   auto Streamer = BC->createStreamer(OS);
5521   // Make sure output stream has enough reserved space, otherwise
5522   // pwrite() will fail.
5523   uint64_t Offset = std::max(getFileOffsetForAddress(NextAvailableAddress),
5524                              FirstNonAllocatableOffset);
5525   Offset = OS.seek(Offset);
5526   assert((Offset != (uint64_t)-1) && "Error resizing output file");
5527 
5528   // Overwrite functions with fixed output address. This is mostly used by
5529   // non-relocation mode, with one exception: injected functions are covered
5530   // here in both modes.
5531   uint64_t CountOverwrittenFunctions = 0;
5532   uint64_t OverwrittenScore = 0;
5533   for (BinaryFunction *Function : BC->getAllBinaryFunctions()) {
5534     if (Function->getImageAddress() == 0 || Function->getImageSize() == 0)
5535       continue;
5536 
5537     if (Function->getImageSize() > Function->getMaxSize()) {
5538       assert(!BC->isX86() && "Unexpected large function.");
5539       if (opts::Verbosity >= 1)
5540         BC->errs() << "BOLT-WARNING: new function size (0x"
5541                    << Twine::utohexstr(Function->getImageSize())
5542                    << ") is larger than maximum allowed size (0x"
5543                    << Twine::utohexstr(Function->getMaxSize())
5544                    << ") for function " << *Function << '\n';
5545 
5546       // Remove jump table sections that this function owns in non-reloc mode
5547       // because we don't want to write them anymore.
5548       if (!BC->HasRelocations && opts::JumpTables == JTS_BASIC) {
5549         for (auto &JTI : Function->JumpTables) {
5550           JumpTable *JT = JTI.second;
5551           BinarySection &Section = JT->getOutputSection();
5552           BC->deregisterSection(Section);
5553         }
5554       }
5555       continue;
5556     }
5557 
5558     const auto HasAddress = [](const FunctionFragment &FF) {
5559       return FF.empty() ||
5560              (FF.getImageAddress() != 0 && FF.getImageSize() != 0);
5561     };
5562     const bool SplitFragmentsHaveAddress =
5563         llvm::all_of(Function->getLayout().getSplitFragments(), HasAddress);
5564     if (Function->isSplit() && !SplitFragmentsHaveAddress) {
5565       const auto HasNoAddress = [](const FunctionFragment &FF) {
5566         return FF.getImageAddress() == 0 && FF.getImageSize() == 0;
5567       };
5568       assert(llvm::all_of(Function->getLayout().getSplitFragments(),
5569                           HasNoAddress) &&
5570              "Some split fragments have an address while others do not");
5571       (void)HasNoAddress;
5572       continue;
5573     }
5574 
5575     OverwrittenScore += Function->getFunctionScore();
5576     ++CountOverwrittenFunctions;
5577 
5578     // Overwrite function in the output file.
5579     if (opts::Verbosity >= 2)
5580       BC->outs() << "BOLT: rewriting function \"" << *Function << "\"\n";
5581 
5582     OS.pwrite(reinterpret_cast<char *>(Function->getImageAddress()),
5583               Function->getImageSize(), Function->getFileOffset());
5584 
5585     // Write nops at the end of the function.
5586     if (Function->getMaxSize() != std::numeric_limits<uint64_t>::max()) {
5587       uint64_t Pos = OS.tell();
5588       OS.seek(Function->getFileOffset() + Function->getImageSize());
5589       BC->MAB->writeNopData(
5590           OS, Function->getMaxSize() - Function->getImageSize(), &*BC->STI);
5591 
5592       OS.seek(Pos);
5593     }
5594 
5595     if (!Function->isSplit())
5596       continue;
5597 
5598     // Write cold part
5599     if (opts::Verbosity >= 2) {
5600       BC->outs() << formatv("BOLT: rewriting function \"{0}\" (split parts)\n",
5601                             *Function);
5602     }
5603 
5604     for (const FunctionFragment &FF :
5605          Function->getLayout().getSplitFragments()) {
5606       OS.pwrite(reinterpret_cast<char *>(FF.getImageAddress()),
5607                 FF.getImageSize(), FF.getFileOffset());
5608     }
5609   }
5610 
5611   // Print function statistics for non-relocation mode.
5612   if (!BC->HasRelocations) {
5613     BC->outs() << "BOLT: " << CountOverwrittenFunctions << " out of "
5614                << BC->getBinaryFunctions().size()
5615                << " functions were overwritten.\n";
5616     if (BC->TotalScore != 0) {
5617       double Coverage = OverwrittenScore / (double)BC->TotalScore * 100.0;
5618       BC->outs() << format("BOLT-INFO: rewritten functions cover %.2lf",
5619                            Coverage)
5620                  << "% of the execution count of simple functions of "
5621                     "this binary\n";
5622     }
5623   }
5624 
5625   if (BC->HasRelocations && opts::TrapOldCode) {
5626     uint64_t SavedPos = OS.tell();
5627     // Overwrite function body to make sure we never execute these instructions.
5628     for (auto &BFI : BC->getBinaryFunctions()) {
5629       BinaryFunction &BF = BFI.second;
5630       if (!BF.getFileOffset() || !BF.isEmitted())
5631         continue;
5632       OS.seek(BF.getFileOffset());
5633       StringRef TrapInstr = BC->MIB->getTrapFillValue();
5634       unsigned NInstr = BF.getMaxSize() / TrapInstr.size();
5635       for (unsigned I = 0; I < NInstr; ++I)
5636         OS.write(TrapInstr.data(), TrapInstr.size());
5637     }
5638     OS.seek(SavedPos);
5639   }
5640 
5641   // Write all allocatable sections - reloc-mode text is written here as well
5642   for (BinarySection &Section : BC->allocatableSections()) {
5643     if (!Section.isFinalized() || !Section.getOutputData())
5644       continue;
5645     if (Section.isLinkOnly())
5646       continue;
5647 
5648     if (opts::Verbosity >= 1)
5649       BC->outs() << "BOLT: writing new section " << Section.getName()
5650                  << "\n data at 0x"
5651                  << Twine::utohexstr(Section.getAllocAddress()) << "\n of size "
5652                  << Section.getOutputSize() << "\n at offset "
5653                  << Section.getOutputFileOffset() << '\n';
5654     OS.pwrite(reinterpret_cast<const char *>(Section.getOutputData()),
5655               Section.getOutputSize(), Section.getOutputFileOffset());
5656   }
5657 
5658   for (BinarySection &Section : BC->allocatableSections())
5659     Section.flushPendingRelocations(OS, [this](const MCSymbol *S) {
5660       return getNewValueForSymbol(S->getName());
5661     });
5662 
5663   // If .eh_frame is present create .eh_frame_hdr.
5664   if (EHFrameSection)
5665     writeEHFrameHeader();
5666 
5667   // Add BOLT Addresses Translation maps to allow profile collection to
5668   // happen in the output binary
5669   if (opts::EnableBAT)
5670     addBATSection();
5671 
5672   // Patch program header table.
5673   if (!BC->IsLinuxKernel)
5674     patchELFPHDRTable();
5675 
5676   // Finalize memory image of section string table.
5677   finalizeSectionStringTable();
5678 
5679   // Update symbol tables.
5680   patchELFSymTabs();
5681 
5682   if (opts::EnableBAT)
5683     encodeBATSection();
5684 
5685   // Copy non-allocatable sections once allocatable part is finished.
5686   rewriteNoteSections();
5687 
5688   if (BC->HasRelocations) {
5689     patchELFAllocatableRelaSections();
5690     patchELFAllocatableRelrSection();
5691     patchELFGOT();
5692   }
5693 
5694   // Patch dynamic section/segment.
5695   patchELFDynamic();
5696 
5697   // Update ELF book-keeping info.
5698   patchELFSectionHeaderTable();
5699 
5700   if (opts::PrintSections) {
5701     BC->outs() << "BOLT-INFO: Sections after processing:\n";
5702     BC->printSections(BC->outs());
5703   }
5704 
5705   Out->keep();
5706   EC = sys::fs::setPermissions(
5707       opts::OutputFilename,
5708       static_cast<sys::fs::perms>(sys::fs::perms::all_all &
5709                                   ~sys::fs::getUmask()));
5710   check_error(EC, "cannot set permissions of output file");
5711 }
5712 
5713 void RewriteInstance::writeEHFrameHeader() {
5714   BinarySection *NewEHFrameSection =
5715       getSection(getNewSecPrefix() + getEHFrameSectionName());
5716 
5717   // No need to update the header if no new .eh_frame was created.
5718   if (!NewEHFrameSection)
5719     return;
5720 
5721   DWARFDebugFrame NewEHFrame(BC->TheTriple->getArch(), true,
5722                              NewEHFrameSection->getOutputAddress());
5723   Error E = NewEHFrame.parse(DWARFDataExtractor(
5724       NewEHFrameSection->getOutputContents(), BC->AsmInfo->isLittleEndian(),
5725       BC->AsmInfo->getCodePointerSize()));
5726   check_error(std::move(E), "failed to parse EH frame");
5727 
5728   uint64_t RelocatedEHFrameAddress = 0;
5729   StringRef RelocatedEHFrameContents;
5730   BinarySection *RelocatedEHFrameSection =
5731       getSection(".relocated" + getEHFrameSectionName());
5732   if (RelocatedEHFrameSection) {
5733     RelocatedEHFrameAddress = RelocatedEHFrameSection->getOutputAddress();
5734     RelocatedEHFrameContents = RelocatedEHFrameSection->getOutputContents();
5735   }
5736   DWARFDebugFrame RelocatedEHFrame(BC->TheTriple->getArch(), true,
5737                                    RelocatedEHFrameAddress);
5738   Error Er = RelocatedEHFrame.parse(DWARFDataExtractor(
5739       RelocatedEHFrameContents, BC->AsmInfo->isLittleEndian(),
5740       BC->AsmInfo->getCodePointerSize()));
5741   check_error(std::move(Er), "failed to parse EH frame");
5742 
5743   LLVM_DEBUG(dbgs() << "BOLT: writing a new " << getEHFrameHdrSectionName()
5744                     << '\n');
5745 
5746   NextAvailableAddress =
5747       appendPadding(Out->os(), NextAvailableAddress, EHFrameHdrAlign);
5748 
5749   const uint64_t EHFrameHdrOutputAddress = NextAvailableAddress;
5750   const uint64_t EHFrameHdrFileOffset =
5751       getFileOffsetForAddress(NextAvailableAddress);
5752 
5753   std::vector<char> NewEHFrameHdr = CFIRdWrt->generateEHFrameHeader(
5754       RelocatedEHFrame, NewEHFrame, EHFrameHdrOutputAddress, FailedAddresses);
5755 
5756   Out->os().seek(EHFrameHdrFileOffset);
5757   Out->os().write(NewEHFrameHdr.data(), NewEHFrameHdr.size());
5758 
5759   const unsigned Flags = BinarySection::getFlags(/*IsReadOnly=*/true,
5760                                                  /*IsText=*/false,
5761                                                  /*IsAllocatable=*/true);
5762   BinarySection *OldEHFrameHdrSection = getSection(getEHFrameHdrSectionName());
5763   if (OldEHFrameHdrSection)
5764     OldEHFrameHdrSection->setOutputName(getOrgSecPrefix() +
5765                                         getEHFrameHdrSectionName());
5766 
5767   BinarySection &EHFrameHdrSec = BC->registerOrUpdateSection(
5768       getNewSecPrefix() + getEHFrameHdrSectionName(), ELF::SHT_PROGBITS, Flags,
5769       nullptr, NewEHFrameHdr.size(), /*Alignment=*/1);
5770   EHFrameHdrSec.setOutputFileOffset(EHFrameHdrFileOffset);
5771   EHFrameHdrSec.setOutputAddress(EHFrameHdrOutputAddress);
5772   EHFrameHdrSec.setOutputName(getEHFrameHdrSectionName());
5773 
5774   NextAvailableAddress += EHFrameHdrSec.getOutputSize();
5775 
5776   if (!BC->BOLTReserved.empty() &&
5777       (NextAvailableAddress > BC->BOLTReserved.end())) {
5778     BC->errs() << "BOLT-ERROR: unable to fit " << getEHFrameHdrSectionName()
5779                << " into reserved space\n";
5780     exit(1);
5781   }
5782 
5783   // Merge new .eh_frame with the relocated original so that gdb can locate all
5784   // FDEs.
5785   if (RelocatedEHFrameSection) {
5786     const uint64_t NewEHFrameSectionSize =
5787         RelocatedEHFrameSection->getOutputAddress() +
5788         RelocatedEHFrameSection->getOutputSize() -
5789         NewEHFrameSection->getOutputAddress();
5790     NewEHFrameSection->updateContents(NewEHFrameSection->getOutputData(),
5791                                       NewEHFrameSectionSize);
5792     BC->deregisterSection(*RelocatedEHFrameSection);
5793   }
5794 
5795   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: size of .eh_frame after merge is "
5796                     << NewEHFrameSection->getOutputSize() << '\n');
5797 }
5798 
5799 uint64_t RewriteInstance::getNewValueForSymbol(const StringRef Name) {
5800   auto Value = Linker->lookupSymbol(Name);
5801   if (Value)
5802     return *Value;
5803 
5804   // Return the original value if we haven't emitted the symbol.
5805   BinaryData *BD = BC->getBinaryDataByName(Name);
5806   if (!BD)
5807     return 0;
5808 
5809   return BD->getAddress();
5810 }
5811 
5812 uint64_t RewriteInstance::getFileOffsetForAddress(uint64_t Address) const {
5813   // Check if it's possibly part of the new segment.
5814   if (NewTextSegmentAddress && Address >= NewTextSegmentAddress)
5815     return Address - NewTextSegmentAddress + NewTextSegmentOffset;
5816 
5817   // Find an existing segment that matches the address.
5818   const auto SegmentInfoI = BC->SegmentMapInfo.upper_bound(Address);
5819   if (SegmentInfoI == BC->SegmentMapInfo.begin())
5820     return 0;
5821 
5822   const SegmentInfo &SegmentInfo = std::prev(SegmentInfoI)->second;
5823   if (Address < SegmentInfo.Address ||
5824       Address >= SegmentInfo.Address + SegmentInfo.FileSize)
5825     return 0;
5826 
5827   return SegmentInfo.FileOffset + Address - SegmentInfo.Address;
5828 }
5829 
5830 bool RewriteInstance::willOverwriteSection(StringRef SectionName) {
5831   if (llvm::is_contained(SectionsToOverwrite, SectionName))
5832     return true;
5833   if (llvm::is_contained(DebugSectionsToOverwrite, SectionName))
5834     return true;
5835 
5836   ErrorOr<BinarySection &> Section = BC->getUniqueSectionByName(SectionName);
5837   return Section && Section->isAllocatable() && Section->isFinalized();
5838 }
5839 
5840 bool RewriteInstance::isDebugSection(StringRef SectionName) {
5841   if (SectionName.starts_with(".debug_") ||
5842       SectionName.starts_with(".zdebug_") || SectionName == ".gdb_index" ||
5843       SectionName == ".stab" || SectionName == ".stabstr")
5844     return true;
5845 
5846   return false;
5847 }
5848