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