1 //===-------------- ELF.cpp - JIT linker function for ELF -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // ELF jit-link function. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ExecutionEngine/JITLink/ELF.h" 15 16 #include "llvm/BinaryFormat/ELF.h" 17 #include "llvm/ExecutionEngine/JITLink/ELF_riscv.h" 18 #include "llvm/ExecutionEngine/JITLink/ELF_x86_64.h" 19 #include "llvm/Object/ELF.h" 20 #include "llvm/Support/Endian.h" 21 #include "llvm/Support/Format.h" 22 #include "llvm/Support/MemoryBuffer.h" 23 #include <cstring> 24 25 using namespace llvm; 26 27 #define DEBUG_TYPE "jitlink" 28 29 namespace llvm { 30 namespace jitlink { 31 32 Expected<uint16_t> readTargetMachineArch(StringRef Buffer) { 33 const char *Data = Buffer.data(); 34 35 if (Data[ELF::EI_DATA] == ELF::ELFDATA2LSB) { 36 if (Data[ELF::EI_CLASS] == ELF::ELFCLASS64) { 37 if (auto File = llvm::object::ELF64LEFile::create(Buffer)) { 38 return File->getHeader().e_machine; 39 } else { 40 return File.takeError(); 41 } 42 } else if (Data[ELF::EI_CLASS] == ELF::ELFCLASS32) { 43 if (auto File = llvm::object::ELF32LEFile::create(Buffer)) { 44 return File->getHeader().e_machine; 45 } else { 46 return File.takeError(); 47 } 48 } 49 } 50 51 return ELF::EM_NONE; 52 } 53 54 Expected<std::unique_ptr<LinkGraph>> 55 createLinkGraphFromELFObject(MemoryBufferRef ObjectBuffer) { 56 StringRef Buffer = ObjectBuffer.getBuffer(); 57 if (Buffer.size() < ELF::EI_MAG3 + 1) 58 return make_error<JITLinkError>("Truncated ELF buffer"); 59 60 if (memcmp(Buffer.data(), ELF::ElfMagic, strlen(ELF::ElfMagic)) != 0) 61 return make_error<JITLinkError>("ELF magic not valid"); 62 63 Expected<uint16_t> TargetMachineArch = readTargetMachineArch(Buffer); 64 if (!TargetMachineArch) 65 return TargetMachineArch.takeError(); 66 67 switch (*TargetMachineArch) { 68 case ELF::EM_RISCV: 69 return createLinkGraphFromELFObject_riscv(ObjectBuffer); 70 case ELF::EM_X86_64: 71 return createLinkGraphFromELFObject_x86_64(ObjectBuffer); 72 default: 73 return make_error<JITLinkError>( 74 "Unsupported target machine architecture in ELF object " + 75 ObjectBuffer.getBufferIdentifier()); 76 } 77 } 78 79 void link_ELF(std::unique_ptr<LinkGraph> G, 80 std::unique_ptr<JITLinkContext> Ctx) { 81 switch (G->getTargetTriple().getArch()) { 82 case Triple::riscv32: 83 case Triple::riscv64: 84 link_ELF_riscv(std::move(G), std::move(Ctx)); 85 return; 86 case Triple::x86_64: 87 link_ELF_x86_64(std::move(G), std::move(Ctx)); 88 return; 89 default: 90 Ctx->notifyFailed(make_error<JITLinkError>( 91 "Unsupported target machine architecture in ELF link graph " + 92 G->getName())); 93 return; 94 } 95 } 96 97 } // end namespace jitlink 98 } // end namespace llvm 99