ELF_i386.cpp 8.5 KB

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