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