• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_x86_64.h"
18 #include "llvm/Object/ELF.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/Format.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include <cstring>
23 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "jitlink"
27 
28 namespace llvm {
29 namespace jitlink {
30 
readTargetMachineArch(StringRef Buffer)31 Expected<uint16_t> readTargetMachineArch(StringRef Buffer) {
32   const char *Data = Buffer.data();
33 
34   if (Data[ELF::EI_DATA] == ELF::ELFDATA2LSB) {
35     if (Data[ELF::EI_CLASS] == ELF::ELFCLASS64) {
36       if (auto File = llvm::object::ELF64LEFile::create(Buffer)) {
37         return File->getHeader().e_machine;
38       } else {
39         return File.takeError();
40       }
41     } else if (Data[ELF::EI_CLASS] == ELF::ELFCLASS32) {
42       if (auto File = llvm::object::ELF32LEFile::create(Buffer)) {
43         return File->getHeader().e_machine;
44       } else {
45         return File.takeError();
46       }
47     }
48   }
49 
50   return ELF::EM_NONE;
51 }
52 
jitLink_ELF(std::unique_ptr<JITLinkContext> Ctx)53 void jitLink_ELF(std::unique_ptr<JITLinkContext> Ctx) {
54   StringRef Buffer = Ctx->getObjectBuffer().getBuffer();
55   if (Buffer.size() < ELF::EI_MAG3 + 1) {
56     Ctx->notifyFailed(make_error<JITLinkError>("Truncated ELF buffer"));
57     return;
58   }
59 
60   if (memcmp(Buffer.data(), ELF::ElfMagic, strlen(ELF::ElfMagic)) != 0) {
61     Ctx->notifyFailed(make_error<JITLinkError>("ELF magic not valid"));
62     return;
63   }
64 
65   Expected<uint16_t> TargetMachineArch = readTargetMachineArch(Buffer);
66   if (!TargetMachineArch) {
67     Ctx->notifyFailed(TargetMachineArch.takeError());
68     return;
69   }
70 
71   switch (*TargetMachineArch) {
72   case ELF::EM_X86_64:
73     jitLink_ELF_x86_64(std::move(Ctx));
74     return;
75   default:
76     Ctx->notifyFailed(make_error<JITLinkError>(
77         "Unsupported target machine architecture in ELF object " +
78         Ctx->getObjectBuffer().getBufferIdentifier()));
79     return;
80   }
81 }
82 
83 } // end namespace jitlink
84 } // end namespace llvm
85