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