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