1 //===-------------- ELF.cpp - JIT linker function for ELF -------------===//
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
7 //===----------------------------------------------------------------------===//
9 // ELF jit-link function.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ExecutionEngine/JITLink/ELF.h"
15 #include "llvm/BinaryFormat/ELF.h"
16 #include "llvm/ExecutionEngine/JITLink/ELF_riscv.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"
26 #define DEBUG_TYPE "jitlink"
31 Expected
<uint16_t> readTargetMachineArch(StringRef Buffer
) {
32 const char *Data
= Buffer
.data();
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
;
39 return File
.takeError();
41 } else if (Data
[ELF::EI_CLASS
] == ELF::ELFCLASS32
) {
42 if (auto File
= llvm::object::ELF32LEFile::create(Buffer
)) {
43 return File
->getHeader().e_machine
;
45 return File
.takeError();
53 Expected
<std::unique_ptr
<LinkGraph
>>
54 createLinkGraphFromELFObject(MemoryBufferRef ObjectBuffer
) {
55 StringRef Buffer
= ObjectBuffer
.getBuffer();
56 if (Buffer
.size() < ELF::EI_MAG3
+ 1)
57 return make_error
<JITLinkError
>("Truncated ELF buffer");
59 if (memcmp(Buffer
.data(), ELF::ElfMagic
, strlen(ELF::ElfMagic
)) != 0)
60 return make_error
<JITLinkError
>("ELF magic not valid");
62 Expected
<uint16_t> TargetMachineArch
= readTargetMachineArch(Buffer
);
63 if (!TargetMachineArch
)
64 return TargetMachineArch
.takeError();
66 switch (*TargetMachineArch
) {
68 return createLinkGraphFromELFObject_riscv(ObjectBuffer
);
70 return createLinkGraphFromELFObject_x86_64(ObjectBuffer
);
72 return make_error
<JITLinkError
>(
73 "Unsupported target machine architecture in ELF object " +
74 ObjectBuffer
.getBufferIdentifier());
78 void link_ELF(std::unique_ptr
<LinkGraph
> G
,
79 std::unique_ptr
<JITLinkContext
> Ctx
) {
80 switch (G
->getTargetTriple().getArch()) {
83 link_ELF_riscv(std::move(G
), std::move(Ctx
));
86 link_ELF_x86_64(std::move(G
), std::move(Ctx
));
89 Ctx
->notifyFailed(make_error
<JITLinkError
>(
90 "Unsupported target machine architecture in ELF link graph " +
96 } // end namespace jitlink
97 } // end namespace llvm