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/Format.h" 20 #include "llvm/Support/MemoryBuffer.h" 21 #include "llvm/Support/SwapByteOrder.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 StringRef BufferName = Ctx->getObjectBuffer().getBufferIdentifier(); 38 Ctx->notifyFailed(make_error<JITLinkError>("Truncated MachO buffer \"" + 39 BufferName + "\"")); 40 return; 41 } 42 43 uint32_t Magic; 44 memcpy(&Magic, Data.data(), sizeof(uint32_t)); 45 LLVM_DEBUG({ 46 dbgs() << "jitLink_MachO: magic = " << format("0x%08" PRIx32, Magic) 47 << ", identifier = \"" 48 << Ctx->getObjectBuffer().getBufferIdentifier() << "\"\n"; 49 }); 50 51 if (Magic == MachO::MH_MAGIC || Magic == MachO::MH_CIGAM) { 52 Ctx->notifyFailed( 53 make_error<JITLinkError>("MachO 32-bit platforms not supported")); 54 return; 55 } else if (Magic == MachO::MH_MAGIC_64 || Magic == MachO::MH_CIGAM_64) { 56 57 if (Data.size() < sizeof(MachO::mach_header_64)) { 58 StringRef BufferName = Ctx->getObjectBuffer().getBufferIdentifier(); 59 Ctx->notifyFailed(make_error<JITLinkError>("Truncated MachO buffer \"" + 60 BufferName + "\"")); 61 return; 62 } 63 64 // Read the CPU type from the header. 65 uint32_t CPUType; 66 memcpy(&CPUType, Data.data() + 4, sizeof(uint32_t)); 67 if (Magic == MachO::MH_CIGAM_64) 68 CPUType = ByteSwap_32(CPUType); 69 70 LLVM_DEBUG({ 71 dbgs() << "jitLink_MachO: cputype = " << format("0x%08" PRIx32, CPUType) 72 << "\n"; 73 }); 74 75 switch (CPUType) { 76 case MachO::CPU_TYPE_ARM64: 77 return jitLink_MachO_arm64(std::move(Ctx)); 78 case MachO::CPU_TYPE_X86_64: 79 return jitLink_MachO_x86_64(std::move(Ctx)); 80 } 81 Ctx->notifyFailed(make_error<JITLinkError>("MachO-64 CPU type not valid")); 82 return; 83 } 84 85 Ctx->notifyFailed(make_error<JITLinkError>("MachO magic not valid")); 86 } 87 88 } // end namespace jitlink 89 } // end namespace llvm 90