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 
13 #include "llvm/ExecutionEngine/JITLink/ELF_i386.h"
14 #include "DefineExternalSectionStartAndEndSymbols.h"
15 #include "ELFLinkGraphBuilder.h"
16 #include "JITLinkGeneric.h"
17 #include "llvm/BinaryFormat/ELF.h"
18 #include "llvm/ExecutionEngine/JITLink/i386.h"
19 #include "llvm/Object/ELFObjectFile.h"
20 
21 #define DEBUG_TYPE "jitlink"
22 
23 using namespace llvm;
24 using namespace llvm::jitlink;
25 
26 namespace {
27 constexpr StringRef ELFGOTSymbolName = "_GLOBAL_OFFSET_TABLE_";
28 
29 Error buildTables_ELF_i386(LinkGraph &G) {
30   LLVM_DEBUG(dbgs() << "Visiting edges in graph:\n");
31 
32   i386::GOTTableManager GOT;
33   visitExistingEdges(G, GOT);
34   return Error::success();
35 }
36 } // namespace
37 
38 namespace llvm::jitlink {
39 
40 class ELFJITLinker_i386 : public JITLinker<ELFJITLinker_i386> {
41   friend class JITLinker<ELFJITLinker_i386>;
42 
43 public:
44   ELFJITLinker_i386(std::unique_ptr<JITLinkContext> Ctx,
45                     std::unique_ptr<LinkGraph> G, PassConfiguration PassConfig)
46       : JITLinker(std::move(Ctx), std::move(G), std::move(PassConfig)) {
47     getPassConfig().PostAllocationPasses.push_back(
48         [this](LinkGraph &G) { return getOrCreateGOTSymbol(G); });
49   }
50 
51 private:
52   Symbol *GOTSymbol = nullptr;
53 
54   Error getOrCreateGOTSymbol(LinkGraph &G) {
55     auto DefineExternalGOTSymbolIfPresent =
56         createDefineExternalSectionStartAndEndSymbolsPass(
57             [&](LinkGraph &LG, Symbol &Sym) -> SectionRangeSymbolDesc {
58               if (Sym.getName() == ELFGOTSymbolName)
59                 if (auto *GOTSection = G.findSectionByName(
60                         i386::GOTTableManager::getSectionName())) {
61                   GOTSymbol = &Sym;
62                   return {*GOTSection, true};
63                 }
64               return {};
65             });
66 
67     // Try to attach _GLOBAL_OFFSET_TABLE_ to the GOT if it's defined as an
68     // external.
69     if (auto Err = DefineExternalGOTSymbolIfPresent(G))
70       return Err;
71 
72     // If we succeeded then we're done.
73     if (GOTSymbol)
74       return Error::success();
75 
76     // Otherwise look for a GOT section: If it already has a start symbol we'll
77     // record it, otherwise we'll create our own.
78     // If there's a GOT section but we didn't find an external GOT symbol...
79     if (auto *GOTSection =
80             G.findSectionByName(i386::GOTTableManager::getSectionName())) {
81 
82       // Check for an existing defined symbol.
83       for (auto *Sym : GOTSection->symbols())
84         if (Sym->getName() == ELFGOTSymbolName) {
85           GOTSymbol = Sym;
86           return Error::success();
87         }
88 
89       // If there's no defined symbol then create one.
90       SectionRange SR(*GOTSection);
91 
92       if (SR.empty()) {
93         GOTSymbol =
94             &G.addAbsoluteSymbol(ELFGOTSymbolName, orc::ExecutorAddr(), 0,
95                                  Linkage::Strong, Scope::Local, true);
96       } else {
97         GOTSymbol =
98             &G.addDefinedSymbol(*SR.getFirstBlock(), 0, ELFGOTSymbolName, 0,
99                                 Linkage::Strong, Scope::Local, false, true);
100       }
101     }
102 
103     return Error::success();
104   }
105 
106   Error applyFixup(LinkGraph &G, Block &B, const Edge &E) const {
107     return i386::applyFixup(G, B, E, GOTSymbol);
108   }
109 };
110 
111 template <typename ELFT>
112 class ELFLinkGraphBuilder_i386 : public ELFLinkGraphBuilder<ELFT> {
113 private:
114   static Expected<i386::EdgeKind_i386> getRelocationKind(const uint32_t Type) {
115     using namespace i386;
116     switch (Type) {
117     case ELF::R_386_NONE:
118       return EdgeKind_i386::None;
119     case ELF::R_386_32:
120       return EdgeKind_i386::Pointer32;
121     case ELF::R_386_PC32:
122       return EdgeKind_i386::PCRel32;
123     case ELF::R_386_16:
124       return EdgeKind_i386::Pointer16;
125     case ELF::R_386_PC16:
126       return EdgeKind_i386::PCRel16;
127     case ELF::R_386_GOT32:
128       return EdgeKind_i386::RequestGOTAndTransformToDelta32FromGOT;
129     case ELF::R_386_GOTPC:
130       return EdgeKind_i386::Delta32;
131     case ELF::R_386_GOTOFF:
132       return EdgeKind_i386::Delta32FromGOT;
133     }
134 
135     return make_error<JITLinkError>("Unsupported i386 relocation:" +
136                                     formatv("{0:d}", Type));
137   }
138 
139   Error addRelocations() override {
140     LLVM_DEBUG(dbgs() << "Adding relocations\n");
141     using Base = ELFLinkGraphBuilder<ELFT>;
142     using Self = ELFLinkGraphBuilder_i386;
143 
144     for (const auto &RelSect : Base::Sections) {
145       // Validate the section to read relocation entries from.
146       if (RelSect.sh_type == ELF::SHT_RELA)
147         return make_error<StringError>(
148             "No SHT_RELA in valid i386 ELF object files",
149             inconvertibleErrorCode());
150 
151       if (Error Err = Base::forEachRelRelocation(RelSect, this,
152                                                  &Self::addSingleRelocation))
153         return Err;
154     }
155 
156     return Error::success();
157   }
158 
159   Error addSingleRelocation(const typename ELFT::Rel &Rel,
160                             const typename ELFT::Shdr &FixupSection,
161                             Block &BlockToFix) {
162     using Base = ELFLinkGraphBuilder<ELFT>;
163 
164     uint32_t SymbolIndex = Rel.getSymbol(false);
165     auto ObjSymbol = Base::Obj.getRelocationSymbol(Rel, Base::SymTabSec);
166     if (!ObjSymbol)
167       return ObjSymbol.takeError();
168 
169     Symbol *GraphSymbol = Base::getGraphSymbol(SymbolIndex);
170     if (!GraphSymbol)
171       return make_error<StringError>(
172           formatv("Could not find symbol at given index, did you add it to "
173                   "JITSymbolTable? index: {0}, shndx: {1} Size of table: {2}",
174                   SymbolIndex, (*ObjSymbol)->st_shndx,
175                   Base::GraphSymbols.size()),
176           inconvertibleErrorCode());
177 
178     Expected<i386::EdgeKind_i386> Kind = getRelocationKind(Rel.getType(false));
179     if (!Kind)
180       return Kind.takeError();
181 
182     auto FixupAddress = orc::ExecutorAddr(FixupSection.sh_addr) + Rel.r_offset;
183     int64_t Addend = 0;
184 
185     switch (*Kind) {
186     case i386::EdgeKind_i386::Delta32: {
187       const char *FixupContent = BlockToFix.getContent().data() +
188                                  (FixupAddress - BlockToFix.getAddress());
189       Addend = *(const support::ulittle32_t *)FixupContent;
190       break;
191     }
192     default:
193       break;
194     }
195 
196     Edge::OffsetT Offset = FixupAddress - BlockToFix.getAddress();
197     Edge GE(*Kind, Offset, *GraphSymbol, Addend);
198     LLVM_DEBUG({
199       dbgs() << "    ";
200       printEdge(dbgs(), BlockToFix, GE, i386::getEdgeKindName(*Kind));
201       dbgs() << "\n";
202     });
203 
204     BlockToFix.addEdge(std::move(GE));
205     return Error::success();
206   }
207 
208 public:
209   ELFLinkGraphBuilder_i386(StringRef FileName, const object::ELFFile<ELFT> &Obj,
210                            const Triple T)
211       : ELFLinkGraphBuilder<ELFT>(Obj, std::move(T), FileName,
212                                   i386::getEdgeKindName) {}
213 };
214 
215 Expected<std::unique_ptr<LinkGraph>>
216 createLinkGraphFromELFObject_i386(MemoryBufferRef ObjectBuffer) {
217   LLVM_DEBUG({
218     dbgs() << "Building jitlink graph for new input "
219            << ObjectBuffer.getBufferIdentifier() << "...\n";
220   });
221 
222   auto ELFObj = object::ObjectFile::createELFObjectFile(ObjectBuffer);
223   if (!ELFObj)
224     return ELFObj.takeError();
225 
226   assert((*ELFObj)->getArch() == Triple::x86 &&
227          "Only i386 (little endian) is supported for now");
228 
229   auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF32LE>>(**ELFObj);
230   return ELFLinkGraphBuilder_i386<object::ELF32LE>((*ELFObj)->getFileName(),
231                                                    ELFObjFile.getELFFile(),
232                                                    (*ELFObj)->makeTriple())
233       .buildGraph();
234 }
235 
236 void link_ELF_i386(std::unique_ptr<LinkGraph> G,
237                    std::unique_ptr<JITLinkContext> Ctx) {
238   PassConfiguration Config;
239   const Triple &TT = G->getTargetTriple();
240   if (Ctx->shouldAddDefaultTargetPasses(TT)) {
241     if (auto MarkLive = Ctx->getMarkLivePass(TT))
242       Config.PrePrunePasses.push_back(std::move(MarkLive));
243     else
244       Config.PrePrunePasses.push_back(markAllSymbolsLive);
245 
246     // Add an in-place GOT build pass.
247     Config.PostPrunePasses.push_back(buildTables_ELF_i386);
248   }
249   if (auto Err = Ctx->modifyPassConfig(*G, Config))
250     return Ctx->notifyFailed(std::move(Err));
251 
252   ELFJITLinker_i386::link(std::move(Ctx), std::move(G), std::move(Config));
253 }
254 
255 } // namespace llvm::jitlink
256