xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/JITLink/MachO.cpp (revision 62cfcf62f627e5093fb37026a6d8c98e4d2ef04c)
1 //===-------------- MachO.cpp - JIT linker function for MachO -------------===//
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 // MachO jit-link function.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ExecutionEngine/JITLink/MachO.h"
15 
16 #include "llvm/BinaryFormat/MachO.h"
17 #include "llvm/ExecutionEngine/JITLink/MachO_arm64.h"
18 #include "llvm/ExecutionEngine/JITLink/MachO_x86_64.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/Format.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "jitlink"
26 
27 namespace llvm {
28 namespace jitlink {
29 
30 void jitLink_MachO(std::unique_ptr<JITLinkContext> Ctx) {
31 
32   // We don't want to do full MachO validation here. Just parse enough of the
33   // header to find out what MachO linker to use.
34 
35   StringRef Data = Ctx->getObjectBuffer().getBuffer();
36   if (Data.size() < 4) {
37     Ctx->notifyFailed(make_error<JITLinkError>("Truncated MachO buffer"));
38     return;
39   }
40 
41   uint32_t Magic;
42   memcpy(&Magic, Data.data(), sizeof(uint32_t));
43   LLVM_DEBUG({
44     dbgs() << "jitLink_MachO: magic = " << format("0x%08" PRIx32, Magic)
45            << ", identifier = \""
46            << Ctx->getObjectBuffer().getBufferIdentifier() << "\"\n";
47   });
48 
49   if (Magic == MachO::MH_MAGIC || Magic == MachO::MH_CIGAM) {
50     Ctx->notifyFailed(
51         make_error<JITLinkError>("MachO 32-bit platforms not supported"));
52     return;
53   } else if (Magic == MachO::MH_MAGIC_64 || Magic == MachO::MH_CIGAM_64) {
54     MachO::mach_header_64 Header;
55 
56     memcpy(&Header, Data.data(), sizeof(MachO::mach_header_64));
57     if (Magic == MachO::MH_CIGAM_64)
58       swapStruct(Header);
59 
60     LLVM_DEBUG({
61       dbgs() << "jitLink_MachO: cputype = "
62              << format("0x%08" PRIx32, Header.cputype)
63              << ", cpusubtype = " << format("0x%08" PRIx32, Header.cpusubtype)
64              << "\n";
65     });
66 
67     switch (Header.cputype) {
68     case MachO::CPU_TYPE_ARM64:
69       return jitLink_MachO_arm64(std::move(Ctx));
70     case MachO::CPU_TYPE_X86_64:
71       return jitLink_MachO_x86_64(std::move(Ctx));
72     }
73     Ctx->notifyFailed(make_error<JITLinkError>("MachO-64 CPU type not valid"));
74     return;
75   }
76 
77   Ctx->notifyFailed(make_error<JITLinkError>("MachO magic not valid"));
78 }
79 
80 } // end namespace jitlink
81 } // end namespace llvm
82