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