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
24using namespace llvm;
25
26#define DEBUG_TYPE "jitlink"
27
28namespace llvm {
29namespace jitlink {
30
31Expected<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
53Expected<std::unique_ptr<LinkGraph>>
54createLinkGraphFromELFObject(MemoryBufferRef ObjectBuffer) {
55 StringRef Buffer = ObjectBuffer.getBuffer();
56 if (Buffer.size() < ELF::EI_MAG3 + 1)
57 return make_error<JITLinkError>("Truncated ELF buffer");
58
59 if (memcmp(Buffer.data(), ELF::ElfMagic, strlen(ELF::ElfMagic)) != 0)
60 return make_error<JITLinkError>("ELF magic not valid");
61
62 Expected<uint16_t> TargetMachineArch = readTargetMachineArch(Buffer);
63 if (!TargetMachineArch)
64 return TargetMachineArch.takeError();
65
66 switch (*TargetMachineArch) {
67 case ELF::EM_X86_64:
68 return createLinkGraphFromELFObject_x86_64(ObjectBuffer);
69 default:
70 return make_error<JITLinkError>(
71 "Unsupported target machine architecture in ELF object " +
72 ObjectBuffer.getBufferIdentifier());
73 }
74}
75
76void link_ELF(std::unique_ptr<LinkGraph> G,
77 std::unique_ptr<JITLinkContext> Ctx) {
78 switch (G->getTargetTriple().getArch()) {
79 case Triple::x86_64:
80 link_ELF_x86_64(std::move(G), std::move(Ctx));
81 return;
82 default:
83 Ctx->notifyFailed(make_error<JITLinkError>(
84 "Unsupported target machine architecture in ELF link graph " +
85 G->getName()));
86 return;
87 }
88}
89
90} // end namespace jitlink
91} // end namespace llvm
92