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