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