LLVM 20.0.0git
ELF_i386.cpp
Go to the documentation of this file.
1//===----- ELF_i386.cpp - JIT linker implementation for ELF/i386 ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// ELF/i386 jit-link implementation.
10//
11//===----------------------------------------------------------------------===//
12
15#include "ELFLinkGraphBuilder.h"
16#include "JITLinkGeneric.h"
20
21#define DEBUG_TYPE "jitlink"
22
23using namespace llvm;
24using namespace llvm::jitlink;
25
26namespace {
27constexpr StringRef ELFGOTSymbolName = "_GLOBAL_OFFSET_TABLE_";
28
29Error buildTables_ELF_i386(LinkGraph &G) {
30 LLVM_DEBUG(dbgs() << "Visiting edges in graph:\n");
31
33 i386::PLTTableManager PLT(GOT);
34 visitExistingEdges(G, GOT, PLT);
35 return Error::success();
36}
37} // namespace
38
39namespace llvm::jitlink {
40
41class ELFJITLinker_i386 : public JITLinker<ELFJITLinker_i386> {
42 friend class JITLinker<ELFJITLinker_i386>;
43
44public:
45 ELFJITLinker_i386(std::unique_ptr<JITLinkContext> Ctx,
46 std::unique_ptr<LinkGraph> G, PassConfiguration PassConfig)
47 : JITLinker(std::move(Ctx), std::move(G), std::move(PassConfig)) {
49 [this](LinkGraph &G) { return getOrCreateGOTSymbol(G); });
50 }
51
52private:
53 Symbol *GOTSymbol = nullptr;
54
55 Error getOrCreateGOTSymbol(LinkGraph &G) {
56 auto DefineExternalGOTSymbolIfPresent =
59 if (Sym.getName() == ELFGOTSymbolName)
60 if (auto *GOTSection = G.findSectionByName(
62 GOTSymbol = &Sym;
63 return {*GOTSection, true};
64 }
65 return {};
66 });
67
68 // Try to attach _GLOBAL_OFFSET_TABLE_ to the GOT if it's defined as an
69 // external.
70 if (auto Err = DefineExternalGOTSymbolIfPresent(G))
71 return Err;
72
73 // If we succeeded then we're done.
74 if (GOTSymbol)
75 return Error::success();
76
77 // Otherwise look for a GOT section: If it already has a start symbol we'll
78 // record it, otherwise we'll create our own.
79 // If there's a GOT section but we didn't find an external GOT symbol...
80 if (auto *GOTSection =
81 G.findSectionByName(i386::GOTTableManager::getSectionName())) {
82
83 // Check for an existing defined symbol.
84 for (auto *Sym : GOTSection->symbols())
85 if (Sym->getName() == ELFGOTSymbolName) {
86 GOTSymbol = Sym;
87 return Error::success();
88 }
89
90 // If there's no defined symbol then create one.
91 SectionRange SR(*GOTSection);
92
93 if (SR.empty()) {
94 GOTSymbol =
95 &G.addAbsoluteSymbol(ELFGOTSymbolName, orc::ExecutorAddr(), 0,
97 } else {
98 GOTSymbol =
99 &G.addDefinedSymbol(*SR.getFirstBlock(), 0, ELFGOTSymbolName, 0,
100 Linkage::Strong, Scope::Local, false, true);
101 }
102 }
103
104 return Error::success();
105 }
106
107 Error applyFixup(LinkGraph &G, Block &B, const Edge &E) const {
108 return i386::applyFixup(G, B, E, GOTSymbol);
109 }
110};
111
112template <typename ELFT>
114private:
115 static Expected<i386::EdgeKind_i386> getRelocationKind(const uint32_t Type) {
116 using namespace i386;
117 switch (Type) {
118 case ELF::R_386_NONE:
119 return EdgeKind_i386::None;
120 case ELF::R_386_32:
121 return EdgeKind_i386::Pointer32;
122 case ELF::R_386_PC32:
123 return EdgeKind_i386::PCRel32;
124 case ELF::R_386_16:
125 return EdgeKind_i386::Pointer16;
126 case ELF::R_386_PC16:
127 return EdgeKind_i386::PCRel16;
128 case ELF::R_386_GOT32:
129 return EdgeKind_i386::RequestGOTAndTransformToDelta32FromGOT;
130 case ELF::R_386_GOTPC:
131 return EdgeKind_i386::Delta32;
132 case ELF::R_386_GOTOFF:
133 return EdgeKind_i386::Delta32FromGOT;
134 case ELF::R_386_PLT32:
135 return EdgeKind_i386::BranchPCRel32;
136 }
137
138 return make_error<JITLinkError>("Unsupported i386 relocation:" +
139 formatv("{0:d}", Type));
140 }
141
142 Error addRelocations() override {
143 LLVM_DEBUG(dbgs() << "Adding relocations\n");
145 using Self = ELFLinkGraphBuilder_i386;
146
147 for (const auto &RelSect : Base::Sections) {
148 // Validate the section to read relocation entries from.
149 if (RelSect.sh_type == ELF::SHT_RELA)
150 return make_error<StringError>(
151 "No SHT_RELA in valid i386 ELF object files",
153
154 if (Error Err = Base::forEachRelRelocation(RelSect, this,
155 &Self::addSingleRelocation))
156 return Err;
157 }
158
159 return Error::success();
160 }
161
162 Error addSingleRelocation(const typename ELFT::Rel &Rel,
163 const typename ELFT::Shdr &FixupSection,
164 Block &BlockToFix) {
166
167 uint32_t SymbolIndex = Rel.getSymbol(false);
168 auto ObjSymbol = Base::Obj.getRelocationSymbol(Rel, Base::SymTabSec);
169 if (!ObjSymbol)
170 return ObjSymbol.takeError();
171
172 Symbol *GraphSymbol = Base::getGraphSymbol(SymbolIndex);
173 if (!GraphSymbol)
174 return make_error<StringError>(
175 formatv("Could not find symbol at given index, did you add it to "
176 "JITSymbolTable? index: {0}, shndx: {1} Size of table: {2}",
177 SymbolIndex, (*ObjSymbol)->st_shndx,
178 Base::GraphSymbols.size()),
180
181 Expected<i386::EdgeKind_i386> Kind = getRelocationKind(Rel.getType(false));
182 if (!Kind)
183 return Kind.takeError();
184
185 auto FixupAddress = orc::ExecutorAddr(FixupSection.sh_addr) + Rel.r_offset;
186 int64_t Addend = 0;
187
188 switch (*Kind) {
190 const char *FixupContent = BlockToFix.getContent().data() +
191 (FixupAddress - BlockToFix.getAddress());
192 Addend = *(const support::ulittle32_t *)FixupContent;
193 break;
194 }
195 default:
196 break;
197 }
198
199 Edge::OffsetT Offset = FixupAddress - BlockToFix.getAddress();
200 Edge GE(*Kind, Offset, *GraphSymbol, Addend);
201 LLVM_DEBUG({
202 dbgs() << " ";
203 printEdge(dbgs(), BlockToFix, GE, i386::getEdgeKindName(*Kind));
204 dbgs() << "\n";
205 });
206
207 BlockToFix.addEdge(std::move(GE));
208 return Error::success();
209 }
210
211public:
213 Triple TT, SubtargetFeatures Features)
214 : ELFLinkGraphBuilder<ELFT>(Obj, std::move(TT), std::move(Features),
215 FileName, i386::getEdgeKindName) {}
216};
217
220 LLVM_DEBUG({
221 dbgs() << "Building jitlink graph for new input "
222 << ObjectBuffer.getBufferIdentifier() << "...\n";
223 });
224
225 auto ELFObj = object::ObjectFile::createELFObjectFile(ObjectBuffer);
226 if (!ELFObj)
227 return ELFObj.takeError();
228
229 auto Features = (*ELFObj)->getFeatures();
230 if (!Features)
231 return Features.takeError();
232
233 assert((*ELFObj)->getArch() == Triple::x86 &&
234 "Only i386 (little endian) is supported for now");
235
236 auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF32LE>>(**ELFObj);
238 (*ELFObj)->getFileName(), ELFObjFile.getELFFile(),
239 (*ELFObj)->makeTriple(), std::move(*Features))
240 .buildGraph();
241}
242
243void link_ELF_i386(std::unique_ptr<LinkGraph> G,
244 std::unique_ptr<JITLinkContext> Ctx) {
246 const Triple &TT = G->getTargetTriple();
247 if (Ctx->shouldAddDefaultTargetPasses(TT)) {
248 if (auto MarkLive = Ctx->getMarkLivePass(TT))
249 Config.PrePrunePasses.push_back(std::move(MarkLive));
250 else
251 Config.PrePrunePasses.push_back(markAllSymbolsLive);
252
253 // Add an in-place GOT and PLT build pass.
254 Config.PostPrunePasses.push_back(buildTables_ELF_i386);
255
256 // Add GOT/Stubs optimizer pass.
257 Config.PreFixupPasses.push_back(i386::optimizeGOTAndStubAccesses);
258 }
259 if (auto Err = Ctx->modifyPassConfig(*G, Config))
260 return Ctx->notifyFailed(std::move(Err));
261
262 ELFJITLinker_i386::link(std::move(Ctx), std::move(G), std::move(Config));
263}
264
265} // namespace llvm::jitlink
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
RelaxConfig Config
Definition: ELF_riscv.cpp:506
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define G(x, y, z)
Definition: MD5.cpp:56
if(PassOpts->AAPipeline)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const T * data() const
Definition: ArrayRef.h:162
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
StringRef getBufferIdentifier() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Manages the enabling and disabling of subtarget specific features.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Expected< std::unique_ptr< ObjectFile > > createELFObjectFile(MemoryBufferRef Object, bool InitContent=true)
Represents an address in the executor process.
@ SHT_RELA
Definition: ELF.h:1092
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
auto formatv(const char *Fmt, Ts &&...Vals) -> formatv_object< decltype(std::make_tuple(support::detail::build_format_adapter(std::forward< Ts >(Vals))...))>
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1849
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858