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