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