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