Index: compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake =================================================================== --- compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake +++ compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake @@ -80,3 +80,7 @@ if (UNIX) set(ALL_ORC_SUPPORTED_ARCH ${X86_64} ${ARM64} ${ARM32}) endif() + +if (WIN32) +set(ALL_ORC_SUPPORTED_ARCH ${X86_64}) +endif() Index: compiler-rt/lib/orc/CMakeLists.txt =================================================================== --- compiler-rt/lib/orc/CMakeLists.txt +++ compiler-rt/lib/orc/CMakeLists.txt @@ -1,14 +1,21 @@ # Build for all components of the ORC runtime support library. -# ORC runtime library implementation files. -set(ORC_SOURCES +# ORC runtime library common implementation files. +set(ORC_COMMON_SOURCES debug.cpp extensible_rtti.cpp log_error_to_stderr.cpp + run_program_wrapper.cpp + dlfcn_wrapper.cpp + ) + +# ORC runtime library implementation files for all ORC architectures.s +set(ALL_ORC_SOURCES + ${ORC_COMMON_SOURCES} + coff_platform.cpp + elfnix_platform.cpp macho_ehframe_registration.cpp macho_platform.cpp - elfnix_platform.cpp - run_program_wrapper.cpp dlfcn_wrapper.cpp ) @@ -17,30 +24,37 @@ macho_tlv.x86-64.S macho_tlv.arm64.S elfnix_tls.x86-64.S -) + elfnix_tls.aarch64.S + ) -set(ORC_IMPL_HEADERS -# Implementation headers will go here. +# Common implementation headers will go here. +set(ORC_COMMON_IMPL_HEADERS adt.h - c_api.h common.h compiler.h endianness.h error.h executor_address.h extensible_rtti.h - macho_platform.h simple_packed_serialization.h stl_extras.h wrapper_function_utils.h -) + ) + +# Implementation headers for all ORC architectures. +set(ALL_ORC_IMPL_HEADERS + ${ORC_COMMON_IMPL_HEADERS} + macho_platform.h + coff_platform.h + elfnix_platform.h + ) # Create list of all source files for # consumption by tests. set(ORC_ALL_SOURCE_FILES - ${ORC_SOURCES} + ${ALL_ORC_SOURCES} ${ALL_ORC_ASM_SOURCES} - ${ORC_IMPL_HEADERS} + ${ALL_ORC_IMPL_HEADERS} ) list(REMOVE_DUPLICATES ORC_ALL_SOURCE_FILES) @@ -72,6 +86,17 @@ macho_tlv.x86-64.S macho_tlv.arm64.S ) + + set(ORC_IMPL_HEADERS + ${ORC_COMMON_IMPL_HEADERS} + macho_platform.h + ) + + set(ORC_SOURCES + ${ORC_COMMON_SOURCES} + macho_ehframe_registration.cpp + macho_platform.cpp + ) add_compiler_rt_object_libraries(RTOrc OS ${ORC_SUPPORTED_OS} @@ -91,10 +116,36 @@ LINK_LIBS ${ORC_LINK_LIBS} PARENT_TARGET orc) else() # not Apple - add_asm_sources(ORC_ASM_SOURCES - elfnix_tls.x86-64.S - elfnix_tls.aarch64.S - ) + if (WIN32) + set(ORC_BUILD_TYPE STATIC) + + set(ORC_IMPL_HEADERS + ${ORC_COMMON_IMPL_HEADERS} + coff_platform.h + ) + + set(ORC_SOURCES + ${ORC_COMMON_SOURCES} + coff_platform.cpp + ) + else() + set(ORC_BUILD_TYPE STATIC) + + set(ORC_IMPL_HEADERS + ${ORC_COMMON_IMPL_HEADERS} + elfnix_platform.h + ) + + set(ORC_SOURCES + ${ORC_COMMON_SOURCES} + elfnix_platform.cpp + ) + + add_asm_sources(ORC_ASM_SOURCES + elfnix_tls.x86-64.S + elfnix_tls.aarch64.S + ) + endif() foreach(arch ${ORC_SUPPORTED_ARCH}) if(NOT CAN_TARGET_${arch}) @@ -110,13 +161,13 @@ # Common ORC archive for instrumented binaries. add_compiler_rt_runtime(clang_rt.orc - STATIC - ARCHS ${arch} - CFLAGS ${ORC_CFLAGS} - LINK_FLAGS ${ORC_LINK_FLAGS} - LINK_LIBS ${ORC_LINK_LIBS} - OBJECT_LIBS ${ORC_COMMON_RUNTIME_OBJECT_LIBS} RTOrc - PARENT_TARGET orc) + ${ORC_BUILD_TYPE} + ARCHS ${arch} + CFLAGS ${ORC_CFLAGS} + LINK_FLAGS ${ORC_LINK_FLAGS} + LINK_LIBS ${ORC_LINK_LIBS} + OBJECT_LIBS ${ORC_COMMON_RUNTIME_OBJECT_LIBS} RTOrc + PARENT_TARGET orc) endforeach() endif() # not Apple Index: compiler-rt/lib/orc/coff_platform.h =================================================================== --- /dev/null +++ compiler-rt/lib/orc/coff_platform.h @@ -0,0 +1,24 @@ +//===- cofff_platform.h ------------------------------------------*- C++ +//-*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// ORC Runtime support for dynamic loading features on COFF-based platforms. +// +//===----------------------------------------------------------------------===// + +#ifndef ORC_RT_COFF_PLATFORM_H +#define ORC_RT_COFF_PLATFORM_H + +#include "common.h" +#include "executor_address.h" + +// dlfcn functions. +ORC_RT_INTERFACE void *__orc_rt_coff_jit_dlsym(void *header, + const char *symbol); + +#endif \ No newline at end of file Index: compiler-rt/lib/orc/coff_platform.cpp =================================================================== --- /dev/null +++ compiler-rt/lib/orc/coff_platform.cpp @@ -0,0 +1,406 @@ +//===- coff_platform.cpp --------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains code required to load the rest of the COFF runtime. +// +//===----------------------------------------------------------------------===// + +#define NOMINMAX +#include + +#include "coff_platform.h" + +#include "debug.h" +#include "error.h" +#include "wrapper_function_utils.h" + +#include +#include +#include +#include + +#define DEBUG_TYPE "coff_platform" + +using namespace __orc_rt; + +ORC_RT_JIT_DISPATCH_TAG(__orc_rt_coff_symbol_lookup_tag) + +namespace { +class COFFPlatformRuntimeState { +private: + struct JITDylibState { + std::string Name; + void *Header = nullptr; + }; + +public: + static void initialize(); + static COFFPlatformRuntimeState &get(); + static void destroy(); + + COFFPlatformRuntimeState() = default; + + // Delete copy and move constructors. + COFFPlatformRuntimeState(const COFFPlatformRuntimeState &) = delete; + COFFPlatformRuntimeState & + operator=(const COFFPlatformRuntimeState &) = delete; + COFFPlatformRuntimeState(COFFPlatformRuntimeState &&) = delete; + COFFPlatformRuntimeState &operator=(COFFPlatformRuntimeState &&) = delete; + + void *dlsym(void *DSOHandle, string_view Symbol); + + Error registerJITDylib(std::string Name, void *Header); + Error deregisterJITDylib(void *Header); + + Error registerSEHFrames(ExecutorAddr HeaderAddr, + const std::vector &SEHFrames); + Error deregisterSEHFrames(ExecutorAddr HeaderAddr, + const std::vector &SEHFrames); + + Error registerBlockRanges(ExecutorAddr HeaderAddr, + const std::vector &BlockRanges); + Error + deregisterBlockRanges(ExecutorAddr HeaderAddr, + const std::vector &BlockRanges); + + void *findJITDylibBaseByPC(uint64_t PC); + JITDylibState *getJITDylibStateByHeader(void *DSOHandle); + JITDylibState *getJITDylibStateByName(string_view Path); + +private: + Expected lookupSymbolInJITDylib(void *DSOHandle, + string_view Symbol); + + static COFFPlatformRuntimeState *CPS; + + std::recursive_mutex JDStatesMutex; + std::map JDStates; + struct BlockRange { + void *Header; + size_t Size; + }; + std::map BlockRanges; + std::unordered_map JDNameToHeader; + std::map> FunctionTables; +}; + +} // namespace + +COFFPlatformRuntimeState *COFFPlatformRuntimeState::CPS = nullptr; + +COFFPlatformRuntimeState::JITDylibState * +COFFPlatformRuntimeState::getJITDylibStateByHeader(void *Header) { + auto I = JDStates.find(Header); + if (I == JDStates.end()) + return nullptr; + return &I->second; +} + +COFFPlatformRuntimeState::JITDylibState * +COFFPlatformRuntimeState::getJITDylibStateByName(string_view Name) { + // FIXME: Avoid creating string copy here. + auto I = JDNameToHeader.find(std::string(Name.data(), Name.size())); + if (I == JDNameToHeader.end()) + return nullptr; + void *H = I->second; + auto J = JDStates.find(H); + assert(J != JDStates.end() && + "JITDylib has name map entry but no header map entry"); + return &J->second; +} + +Error COFFPlatformRuntimeState::registerJITDylib(std::string Name, + void *Header) { + ORC_RT_DEBUG({ + printdbg("Registering JITDylib %s: Header = %p\n", Name.c_str(), Header); + }); + std::lock_guard Lock(JDStatesMutex); + if (JDStates.count(Header)) { + std::ostringstream ErrStream; + ErrStream << "Duplicate JITDylib registration for header " << Header + << " (name = " << Name << ")"; + return make_error(ErrStream.str()); + } + if (JDNameToHeader.count(Name)) { + std::ostringstream ErrStream; + ErrStream << "Duplicate JITDylib registration for header " << Header + << " (header = " << Header << ")"; + return make_error(ErrStream.str()); + } + + auto &JDS = JDStates[Header]; + JDS.Name = std::move(Name); + JDS.Header = Header; + JDNameToHeader[JDS.Name] = Header; + return Error::success(); +} + +Error COFFPlatformRuntimeState::deregisterJITDylib(void *Header) { + std::lock_guard Lock(JDStatesMutex); + auto I = JDStates.find(Header); + if (I == JDStates.end()) { + std::ostringstream ErrStream; + ErrStream << "Attempted to deregister unrecognized header " << Header; + return make_error(ErrStream.str()); + } + + // Remove std::string construction once we can use C++20. + auto J = JDNameToHeader.find( + std::string(I->second.Name.data(), I->second.Name.size())); + assert(J != JDNameToHeader.end() && + "Missing JDNameToHeader entry for JITDylib"); + + ORC_RT_DEBUG({ + printdbg("Deregistering JITDylib %s: Header = %p\n", I->second.Name.c_str(), + Header); + }); + + JDNameToHeader.erase(J); + JDStates.erase(I); + return Error::success(); +} + +void *COFFPlatformRuntimeState::dlsym(void *Header, string_view Symbol) { + auto Addr = lookupSymbolInJITDylib(Header, Symbol); + if (!Addr) { + return 0; + } + + return Addr->toPtr(); +} + +Expected +COFFPlatformRuntimeState::lookupSymbolInJITDylib(void *header, + string_view Sym) { + Expected Result((ExecutorAddr())); + if (auto Err = WrapperFunction( + SPSExecutorAddr, SPSString)>::call(&__orc_rt_coff_symbol_lookup_tag, + Result, + ExecutorAddr::fromPtr(header), + Sym)) + return std::move(Err); + return Result; +} + +Error COFFPlatformRuntimeState::registerSEHFrames( + ExecutorAddr HeaderAddr, const std::vector &SEHFrames) { + std::lock_guard Lock(JDStatesMutex); + auto I = JDStates.find(HeaderAddr.toPtr()); + if (I == JDStates.end()) { + std::ostringstream ErrStream; + ErrStream << "Attempted to register unrecognized header " + << HeaderAddr.getValue(); + return make_error(ErrStream.str()); + } + auto &JDState = I->second; + for (auto &SEHFrame : SEHFrames) { + int N = (SEHFrame.End.getValue() - SEHFrame.Start.getValue()) / + sizeof(RUNTIME_FUNCTION); + auto Func = SEHFrame.Start.toPtr(); + if (!RtlAddFunctionTable(Func, N, + static_cast(HeaderAddr.getValue()))) + return make_error("Failed to register SEH frames"); + } + return Error::success(); +} + +Error COFFPlatformRuntimeState::deregisterSEHFrames( + ExecutorAddr HeaderAddr, const std::vector &SEHFrames) { + std::lock_guard Lock(JDStatesMutex); + + return Error::success(); +} + +Error COFFPlatformRuntimeState::registerBlockRanges( + ExecutorAddr HeaderAddr, + const std::vector &BlockRanges) { + for (auto &Block : BlockRanges) { + assert(!this->BlockRanges.count(Block.Start.toPtr()) && + "Block range address already registered"); + BlockRange B = {HeaderAddr.toPtr(), Block.size().getValue()}; + this->BlockRanges.emplace(Block.Start.toPtr(), B); + } + return Error::success(); +} + +Error COFFPlatformRuntimeState::deregisterBlockRanges( + ExecutorAddr HeaderAddr, + const std::vector &BlockRanges) { + for (auto &Block : BlockRanges) { + assert(this->BlockRanges.count(Block.Start.toPtr()) && + "Block range address not registered"); + this->BlockRanges.erase(Block.Start.toPtr()); + } + return Error::success(); +} + +void COFFPlatformRuntimeState::initialize() { + assert(!CPS && "COFFPlatformRuntimeState should be null"); + CPS = new COFFPlatformRuntimeState(); +} + +COFFPlatformRuntimeState &COFFPlatformRuntimeState::get() { + assert(CPS && "COFFPlatformRuntimeState not initialized"); + return *CPS; +} + +void COFFPlatformRuntimeState::destroy() { + assert(CPS && "COFFPlatformRuntimeState not initialized"); + delete CPS; +} + +void *COFFPlatformRuntimeState::findJITDylibBaseByPC(uint64_t PC) { + std::lock_guard Lock(JDStatesMutex); + auto It = BlockRanges.upper_bound(reinterpret_cast(PC)); + if (It == BlockRanges.begin()) + return nullptr; + --It; + auto &Range = It->second; + if (PC >= reinterpret_cast(It->first) + Range.Size) + return nullptr; + return Range.Header; +} + +ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult +__orc_rt_coff_platform_bootstrap(char *ArgData, size_t ArgSize) { + COFFPlatformRuntimeState::initialize(); + return WrapperFunctionResult().release(); +} + +ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult +__orc_rt_coff_platform_shutdown(char *ArgData, size_t ArgSize) { + COFFPlatformRuntimeState::destroy(); + return WrapperFunctionResult().release(); +} + +ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult +__orc_rt_coff_register_jitdylib(char *ArgData, size_t ArgSize) { + return WrapperFunction::handle( + ArgData, ArgSize, + [](std::string &Name, ExecutorAddr HeaderAddr) { + return COFFPlatformRuntimeState::get().registerJITDylib( + std::move(Name), HeaderAddr.toPtr()); + }) + .release(); +} + +ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult +__orc_rt_coff_deregister_jitdylib(char *ArgData, size_t ArgSize) { + return WrapperFunction::handle( + ArgData, ArgSize, + [](ExecutorAddr HeaderAddr) { + return COFFPlatformRuntimeState::get().deregisterJITDylib( + HeaderAddr.toPtr()); + }) + .release(); +} + +ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult +__orc_rt_coff_register_sehframe_section(char *ArgData, size_t ArgSize) { + return WrapperFunction)>:: + handle(ArgData, ArgSize, + [](ExecutorAddr HeaderAddr, + std::vector SEHFrames) -> Error { + return COFFPlatformRuntimeState::get().registerSEHFrames( + HeaderAddr, SEHFrames); + }) + .release(); +} + +ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult +__orc_rt_coff_deregister_sehframe_section(char *ArgData, size_t ArgSize) { + return WrapperFunction)>:: + handle(ArgData, ArgSize, + [](ExecutorAddr HeaderAddr, + std::vector SEHFrames) -> Error { + return COFFPlatformRuntimeState::get().deregisterSEHFrames( + HeaderAddr, SEHFrames); + }) + .release(); +} + +ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult +__orc_rt_coff_register_block_ranges(char *ArgData, size_t ArgSize) { + return WrapperFunction)>:: + handle(ArgData, ArgSize, + [](ExecutorAddr HeaderAddr, + std::vector BlockRanges) -> Error { + return COFFPlatformRuntimeState::get().registerBlockRanges( + HeaderAddr, BlockRanges); + }) + .release(); +} + +ORC_RT_INTERFACE __orc_rt_CWrapperFunctionResult +__orc_rt_coff_deregister_block_ranges(char *ArgData, size_t ArgSize) { + return WrapperFunction)>:: + handle(ArgData, ArgSize, + [](ExecutorAddr HeaderAddr, + std::vector BlockRanges) -> Error { + return COFFPlatformRuntimeState::get().deregisterBlockRanges( + HeaderAddr, BlockRanges); + }) + .release(); +} + +void *__orc_rt_coff_jit_dlsym(void *header, const char *symbol) { + return COFFPlatformRuntimeState::get().dlsym(header, symbol); +} + +struct ThrowInfo { + uint32_t attributes; + void *data; +}; + +ORC_RT_INTERFACE void __stdcall __orc_rt_coff_cxx_throw_exception( + void *pExceptionObject, ThrowInfo *pThrowInfo) { + constexpr uint32_t EH_EXCEPTION_NUMBER = 'msc' | 0xE0000000; + constexpr uint32_t EH_MAGIC_NUMBER1 = 0x19930520; + auto BaseAddr = COFFPlatformRuntimeState::get().findJITDylibBaseByPC( + reinterpret_cast(pThrowInfo)); + if (!BaseAddr) { + + return; + } + const ULONG_PTR parameters[] = { + EH_MAGIC_NUMBER1, + reinterpret_cast(pExceptionObject), + reinterpret_cast(pThrowInfo), + reinterpret_cast(BaseAddr), + }; + RaiseException(EH_EXCEPTION_NUMBER, EXCEPTION_NONCONTINUABLE, + _countof(parameters), parameters); +} + +//------------------------------------------------------------------------------ +// COFF Run Program +//------------------------------------------------------------------------------ + +ORC_RT_INTERFACE int64_t __orc_rt_coff_run_program(const char *JITDylibName, + const char *EntrySymbolName, + int argc, char *argv[]) { + using MainTy = int (*)(int, char *[]); + + auto *JD = + COFFPlatformRuntimeState::get().getJITDylibStateByName(JITDylibName); + if (!JD) + return 1; + + auto *Main = reinterpret_cast( + __orc_rt_coff_jit_dlsym(JD->Header, EntrySymbolName)); + if (!Main) + return 1; + + int Result = Main(argc, argv); + + return Result; +} Index: compiler-rt/lib/orc/common.h =================================================================== --- compiler-rt/lib/orc/common.h +++ compiler-rt/lib/orc/common.h @@ -34,14 +34,14 @@ /// This is declared for use by the runtime, but should be implemented in the /// executor or provided by a definition added to the JIT before the runtime /// is loaded. -extern "C" __orc_rt_Opaque __orc_rt_jit_dispatch_ctx ORC_RT_WEAK_IMPORT; +ORC_RT_IMPORT __orc_rt_Opaque __orc_rt_jit_dispatch_ctx ORC_RT_WEAK_IMPORT; /// For dispatching calls to the JIT object. /// /// This is declared for use by the runtime, but should be implemented in the /// executor or provided by a definition added to the JIT before the runtime /// is loaded. -extern "C" __orc_rt_CWrapperFunctionResult +ORC_RT_IMPORT __orc_rt_CWrapperFunctionResult __orc_rt_jit_dispatch(__orc_rt_Opaque *DispatchCtx, const void *FnTag, const char *Data, size_t Size) ORC_RT_WEAK_IMPORT; Index: compiler-rt/lib/orc/compiler.h =================================================================== --- compiler-rt/lib/orc/compiler.h +++ compiler-rt/lib/orc/compiler.h @@ -15,8 +15,15 @@ #ifndef ORC_RT_COMPILER_H #define ORC_RT_COMPILER_H +#if defined(_WIN32) +#define ORC_RT_INTERFACE extern "C" +#define ORC_RT_HIDDEN +#define ORC_RT_IMPORT extern "C" __declspec(dllimport) +#else #define ORC_RT_INTERFACE extern "C" __attribute__((visibility("default"))) #define ORC_RT_HIDDEN __attribute__((visibility("hidden"))) +#define ORC_RT_IMPORT extern "C" +#endif #ifndef __has_builtin # define __has_builtin(x) 0 @@ -56,8 +63,10 @@ #define ORC_RT_UNLIKELY(EXPR) (EXPR) #endif -#ifdef __APPLE__ +#if defined(__APPLE__) #define ORC_RT_WEAK_IMPORT __attribute__((weak_import)) +#elif defined(_WIN32) +#define ORC_RT_WEAK_IMPORT #else #define ORC_RT_WEAK_IMPORT __attribute__((weak)) #endif Index: compiler-rt/lib/orc/error.h =================================================================== --- compiler-rt/lib/orc/error.h +++ compiler-rt/lib/orc/error.h @@ -113,9 +113,7 @@ bool isChecked() const { return ErrPtr & 0x1; } - void setChecked(bool Checked) { - ErrPtr = (reinterpret_cast(ErrPtr) & ~uintptr_t(1)) | Checked; - } + void setChecked(bool Checked) { ErrPtr = (ErrPtr & ~uintptr_t(1)) | Checked; } template std::unique_ptr takePayload() { static_assert(std::is_base_of::value, Index: compiler-rt/test/orc/TestCases/Windows/lit.local.cfg.py =================================================================== --- /dev/null +++ compiler-rt/test/orc/TestCases/Windows/lit.local.cfg.py @@ -0,0 +1,2 @@ +if config.root.host_os != 'Windows': + config.unsupported = True Index: compiler-rt/test/orc/TestCases/Windows/x86-64/hello-world.c =================================================================== --- /dev/null +++ compiler-rt/test/orc/TestCases/Windows/x86-64/hello-world.c @@ -0,0 +1,10 @@ +// RUN: %clang -c -o %t %s +// RUN: %llvm_jitlink %t 2>&1 | FileCheck %s +// CHECK: Hello, world! + +#include +int main(int argc, char *argv[]) { + printf("Hello, world!\n"); + fflush(stdout); + return 0; +} Index: compiler-rt/test/orc/TestCases/Windows/x86-64/hello-world.cpp =================================================================== --- /dev/null +++ compiler-rt/test/orc/TestCases/Windows/x86-64/hello-world.cpp @@ -0,0 +1,11 @@ +// FIXME: Fix the crash. +// XFAIL: * +// RUN: %clangxx -c -o %t %s +// RUN: %llvm_jitlink %t 2>&1 | FileCheck %s +// CHECK: Hello, world! + +#include +int main(int argc, char *argv[]) { + std::cout << "Hello, world!" << std::endl; + return 0; +} Index: compiler-rt/test/orc/TestCases/Windows/x86-64/lit.local.cfg.py =================================================================== --- /dev/null +++ compiler-rt/test/orc/TestCases/Windows/x86-64/lit.local.cfg.py @@ -0,0 +1,5 @@ +if config.root.host_arch not in ['AMD64','x86_64']: + config.unsupported = True + +if config.target_arch not in ['AMD64','x86_64']: + config.unsupported = True Index: compiler-rt/test/orc/TestCases/Windows/x86-64/sehframe-handling.cpp =================================================================== --- /dev/null +++ compiler-rt/test/orc/TestCases/Windows/x86-64/sehframe-handling.cpp @@ -0,0 +1,15 @@ +// RUN: %clangxx -c -o %t %s +// RUN: %llvm_jitlink %t + +extern "C" __declspec(dllimport) void llvm_jitlink_setTestResultOverride( + long Value); + +int main(int argc, char *argv[]) { + llvm_jitlink_setTestResultOverride(1); + try { + throw 0; + } catch (int X) { + llvm_jitlink_setTestResultOverride(X); + } + return 0; +} Index: compiler-rt/test/orc/TestCases/Windows/x86-64/static-initializer.cpp =================================================================== --- /dev/null +++ compiler-rt/test/orc/TestCases/Windows/x86-64/static-initializer.cpp @@ -0,0 +1,18 @@ +// RUN: %clangxx -c -o %t %s +// RUN: %llvm_jitlink %t + +extern "C" __declspec(dllimport) void llvm_jitlink_setTestResultOverride( + long Value); + +static int init() { return -1; } + +static int init2() { return 1; } + +static int a = init(); +static int b = 0; +static int c = init2(); + +int main(int argc, char *argv[]) { + llvm_jitlink_setTestResultOverride(a + b + c); + return 0; +} Index: compiler-rt/test/orc/lit.cfg.py =================================================================== --- compiler-rt/test/orc/lit.cfg.py +++ compiler-rt/test/orc/lit.cfg.py @@ -29,8 +29,12 @@ config.substitutions.append( ('%clangxx ', build_invocation(config.cxx_mode_flags + [config.target_cflags]))) -config.substitutions.append( - ('%llvm_jitlink', (llvm_jitlink + ' -orc-runtime=' + orc_rt_path))) +if config.host_os == 'Windows': + config.substitutions.append( + ('%llvm_jitlink', (llvm_jitlink + ' -orc-runtime=' + orc_rt_path + ' -no-process-syms=true -slab-allocate=64MB'))) +else: + config.substitutions.append( + ('%llvm_jitlink', (llvm_jitlink + ' -orc-runtime=' + orc_rt_path))) config.substitutions.append( ('%lli_orc_jitlink', (lli + ' -jit-kind=orc -jit-linker=jitlink -orc-runtime=' + orc_rt_path))) @@ -40,5 +44,5 @@ # Exclude Inputs directories. config.excludes = ['Inputs'] -if config.host_os not in ['Darwin', 'FreeBSD', 'Linux']: +if config.host_os not in ['Darwin', 'FreeBSD', 'Linux', 'Windows']: config.unsupported = True Index: llvm/include/llvm/ExecutionEngine/Orc/COFFPlatform.h =================================================================== --- /dev/null +++ llvm/include/llvm/ExecutionEngine/Orc/COFFPlatform.h @@ -0,0 +1,177 @@ +//===--- COFFPlatform.h -- Utilities for executing COFF in Orc --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Utilities for executing JIT'd COFF in Orc. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_EXECUTIONENGINE_ORC_COFFPLATFORM_H +#define LLVM_EXECUTIONENGINE_ORC_COFFPLATFORM_H + +#include "llvm/ADT/StringRef.h" +#include "llvm/ExecutionEngine/Orc/Core.h" +#include "llvm/ExecutionEngine/Orc/ExecutorProcessControl.h" +#include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h" +#include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h" + +#include +#include +#include +#include + +namespace llvm { +namespace orc { + +/// Mediates between COFF initialization and ExecutionSession state. +class COFFPlatform : public Platform { +public: + /// Try to create a COFFPlatform instance, adding the ORC runtime to the + /// given JITDylib. + static Expected> + Create(ExecutionSession &ES, ObjectLinkingLayer &ObjLinkingLayer, + JITDylib &PlatformJD, const char *OrcRuntimePath, + std::vector &ImportedLibraries, + Optional RuntimeAliases = None); + + Error bootstrap(JITDylib &PlatformJD); + + ExecutionSession &getExecutionSession() const { return ES; } + ObjectLinkingLayer &getObjectLinkingLayer() const { return ObjLinkingLayer; } + + Error setupJITDylib(JITDylib &JD) override; + Error teardownJITDylib(JITDylib &JD) override; + Error notifyAdding(ResourceTracker &RT, + const MaterializationUnit &MU) override; + Error notifyRemoving(ResourceTracker &RT) override; + + /// Returns an AliasMap containing the default aliases for the MachOPlatform. + /// This can be modified by clients when constructing the platform to add + /// or remove aliases. + static SymbolAliasMap standardPlatformAliases(ExecutionSession &ES); + + /// Returns the array of required CXX aliases. + static ArrayRef> requiredCXXAliases(); + + /// Returns the array of standard runtime utility aliases for MachO. + static ArrayRef> + standardRuntimeUtilityAliases(); + + static bool isInitializerSection(StringRef Name) { + return Name.startswith(".CRT"); + } + + static StringRef getSEHFrameSectionName() { return ".pdata"; } + +private: + // The COFFPlatformPlugin scans/modifies LinkGraphs to support MachO + // platform features including initializers, exceptions, and language + // runtime registration. + class COFFPlatformPlugin : public ObjectLinkingLayer::Plugin { + public: + COFFPlatformPlugin(COFFPlatform &CP) : CP(CP) {} + + void modifyPassConfig(MaterializationResponsibility &MR, + jitlink::LinkGraph &G, + jitlink::PassConfiguration &Config) override; + + SyntheticSymbolDependenciesMap + getSyntheticSymbolDependencies(MaterializationResponsibility &MR) override; + + // FIXME: We should be tentatively tracking scraped sections and discarding + // if the MR fails. + Error notifyFailed(MaterializationResponsibility &MR) override { + return Error::success(); + } + + Error notifyRemovingResources(ResourceKey K) override { + return Error::success(); + } + + void notifyTransferringResources(ResourceKey DstKey, + ResourceKey SrcKey) override {} + + private: + using InitSymbolDepMap = + DenseMap; + + Error associateJITDylibHeaderSymbol(jitlink::LinkGraph &G, + MaterializationResponsibility &MR, + bool Bootstrap); + + Error preserveInitializerSections(jitlink::LinkGraph &G, + MaterializationResponsibility &MR); + Error registerObjectPlatformSections(jitlink::LinkGraph &G, JITDylib &JD); + Error registerObjectPlatformSectionsInBootstrap(jitlink::LinkGraph &G, + JITDylib &JD); + + std::mutex PluginMutex; + COFFPlatform &CP; + InitSymbolDepMap InitSymbolDeps; + }; + + struct COFFPlatformBootstrapState { + std::string JDName; + ExecutorAddr HeaderAddr; + std::vector SEHFrames; + std::vector BlockRanges; + std::vector> Initializers; + Error runInitializers(ExecutionSession &ES, StringRef Start, StringRef End); + }; + + using SendSymbolAddressFn = unique_function)>; + + static bool supportedTarget(const Triple &TT); + + COFFPlatform(ExecutionSession &ES, ObjectLinkingLayer &ObjLinkingLayer, + JITDylib &PlatformJD, + std::unique_ptr OrcRuntimeGenerator, + Error &Err); + + // Associate MachOPlatform JIT-side runtime support functions with handlers. + Error associateRuntimeSupportFunctions(JITDylib &PlatformJD); + + // Records the addresses of runtime symbols used by the platform. + Error bootstrapCOFFRuntime(JITDylib &PlatformJD); + + // Run a specific void function if it exists. + Error runSymbolIfExists(JITDylib &PlatformJD, StringRef SymbolName); + + // Run collected initializers in boostrap stage. + Error runBootstrapInitializers(JITDylib &PlatformJD); + + void rt_lookupSymbol(SendSymbolAddressFn SendResult, ExecutorAddr Handle, + StringRef SymbolName); + + ExecutionSession &ES; + ObjectLinkingLayer &ObjLinkingLayer; + + SymbolStringPtr COFFHeaderStartSymbol; + + // State of bootstrap in progress + std::unique_ptr BootstrapState; + std::atomic Bootstraping; + + ExecutorAddr orc_rt_coff_platform_bootstrap; + ExecutorAddr orc_rt_coff_platform_shutdown; + ExecutorAddr orc_rt_coff_register_sehframe_section; + ExecutorAddr orc_rt_coff_deregister_sehframe_section; + ExecutorAddr orc_rt_coff_register_block_ranges; + ExecutorAddr orc_rt_coff_deregister_block_ranges; + ExecutorAddr orc_rt_coff_register_jitdylib; + ExecutorAddr orc_rt_coff_deregister_jitdylib; + + DenseMap JITDylibToHeaderAddr; + DenseMap HeaderAddrToJITDylib; + + std::mutex PlatformMutex; +}; + +} // end namespace orc +} // end namespace llvm + +#endif // LLVM_EXECUTIONENGINE_ORC_COFFPLATFORM_H Index: llvm/lib/ExecutionEngine/Orc/CMakeLists.txt =================================================================== --- llvm/lib/ExecutionEngine/Orc/CMakeLists.txt +++ llvm/lib/ExecutionEngine/Orc/CMakeLists.txt @@ -1,5 +1,6 @@ add_llvm_component_library(LLVMOrcJIT COFFVCRuntimeSupport.cpp + COFFPlatform.cpp CompileOnDemandLayer.cpp CompileUtils.cpp Core.cpp Index: llvm/lib/ExecutionEngine/Orc/COFFPlatform.cpp =================================================================== --- /dev/null +++ llvm/lib/ExecutionEngine/Orc/COFFPlatform.cpp @@ -0,0 +1,662 @@ +//===------- COFFPlatform.cpp - Utilities for executing COFF in Orc -------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "llvm/ExecutionEngine/Orc/COFFPlatform.h" +#include "llvm/ExecutionEngine/Orc/DebugUtils.h" +#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" +#include "llvm/ExecutionEngine/Orc/LookupAndRecordAddrs.h" + +#include "llvm/Object/COFF.h" + +#include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h" + +#include "llvm/ExecutionEngine/JITLink/x86_64.h" + +#define DEBUG_TYPE "orc" + +using namespace llvm; +using namespace llvm::orc; +using namespace llvm::orc::shared; + +namespace { + +class COFFHeaderMaterializationUnit : public MaterializationUnit { +public: + COFFHeaderMaterializationUnit(COFFPlatform &CP, + const SymbolStringPtr &HeaderStartSymbol) + : MaterializationUnit(createHeaderInterface(CP, HeaderStartSymbol)), + CP(CP) {} + + StringRef getName() const override { return "COFFHeaderMU"; } + + void materialize(std::unique_ptr R) override { + unsigned PointerSize; + support::endianness Endianness; + const auto &TT = + CP.getExecutionSession().getExecutorProcessControl().getTargetTriple(); + + switch (TT.getArch()) { + case Triple::x86_64: + PointerSize = 8; + Endianness = support::endianness::little; + break; + default: + llvm_unreachable("Unrecognized architecture"); + } + + auto G = std::make_unique( + "", TT, PointerSize, Endianness, + jitlink::getGenericEdgeKindName); + auto &HeaderSection = G->createSection("__header", jitlink::MemProt::Read); + auto &HeaderBlock = createHeaderBlock(*G, HeaderSection); + + // Init symbol is __ImageBase symbol. + auto &ImageBaseSymbol = G->addDefinedSymbol( + HeaderBlock, 0, *R->getInitializerSymbol(), HeaderBlock.getSize(), + jitlink::Linkage::Strong, jitlink::Scope::Default, false, true); + + addImageBaseRelocationEdge(HeaderBlock, ImageBaseSymbol); + + CP.getObjectLinkingLayer().emit(std::move(R), std::move(G)); + } + + void discard(const JITDylib &JD, const SymbolStringPtr &Sym) override {} + +private: + struct HeaderSymbol { + const char *Name; + uint64_t Offset; + }; + + struct NTHeader { + support::ulittle32_t PEMagic; + object::coff_file_header FileHeader; + struct PEHeader { + object::pe32plus_header Header; + object::data_directory DataDirectory[COFF::NUM_DATA_DIRECTORIES + 1]; + } OptionalHeader; + }; + + struct HeaderBlockContent { + object::dos_header DOSHeader; + NTHeader NTHeader; + }; + + static jitlink::Block &createHeaderBlock(jitlink::LinkGraph &G, + jitlink::Section &HeaderSection) { + HeaderBlockContent Hdr = {}; + + // Set up magic + Hdr.DOSHeader.Magic[0] = 'M'; + Hdr.DOSHeader.Magic[1] = 'Z'; + Hdr.DOSHeader.AddressOfNewExeHeader = + offsetof(HeaderBlockContent, NTHeader); + uint32_t PEMagic = *reinterpret_cast(COFF::PEMagic); + Hdr.NTHeader.PEMagic = PEMagic; + Hdr.NTHeader.OptionalHeader.Header.Magic = COFF::PE32Header::PE32_PLUS; + + switch (G.getTargetTriple().getArch()) { + case Triple::x86_64: + Hdr.NTHeader.FileHeader.Machine = COFF::IMAGE_FILE_MACHINE_AMD64; + break; + default: + llvm_unreachable("Unrecognized architecture"); + } + + auto HeaderContent = G.allocateString( + StringRef(reinterpret_cast(&Hdr), sizeof(Hdr))); + + return G.createContentBlock(HeaderSection, HeaderContent, ExecutorAddr(), 8, + 0); + } + + static void addImageBaseRelocationEdge(jitlink::Block &B, + jitlink::Symbol &ImageBase) { + auto ImageBaseOffset = offsetof(HeaderBlockContent, NTHeader) + + offsetof(NTHeader, OptionalHeader) + + offsetof(object::pe32plus_header, ImageBase); + B.addEdge(jitlink::x86_64::Pointer64, ImageBaseOffset, ImageBase, 0); + } + + static MaterializationUnit::Interface + createHeaderInterface(COFFPlatform &MOP, + const SymbolStringPtr &HeaderStartSymbol) { + SymbolFlagsMap HeaderSymbolFlags; + + HeaderSymbolFlags[HeaderStartSymbol] = JITSymbolFlags::Exported; + + return MaterializationUnit::Interface(std::move(HeaderSymbolFlags), + HeaderStartSymbol); + } + + COFFPlatform &CP; +}; + +} // end anonymous namespace + +namespace llvm { +namespace orc { + +Expected> +COFFPlatform::Create(ExecutionSession &ES, ObjectLinkingLayer &ObjLinkingLayer, + JITDylib &PlatformJD, const char *OrcRuntimePath, + std::vector &ImportedLibraries, + Optional RuntimeAliases) { + + auto &EPC = ES.getExecutorProcessControl(); + + // If the target is not supported then bail out immediately. + if (!supportedTarget(EPC.getTargetTriple())) + return make_error("Unsupported COFFPlatform triple: " + + EPC.getTargetTriple().str(), + inconvertibleErrorCode()); + + // Create default aliases if the caller didn't supply any. + if (!RuntimeAliases) + RuntimeAliases = standardPlatformAliases(ES); + + // Define the aliases. + if (auto Err = PlatformJD.define(symbolAliases(std::move(*RuntimeAliases)))) + return std::move(Err); + + // Add JIT-dispatch function support symbols. + if (auto Err = PlatformJD.define(absoluteSymbols( + {{ES.intern("__orc_rt_jit_dispatch"), + {EPC.getJITDispatchInfo().JITDispatchFunction.getValue(), + JITSymbolFlags::Exported}}, + {ES.intern("__orc_rt_jit_dispatch_ctx"), + {EPC.getJITDispatchInfo().JITDispatchContext.getValue(), + JITSymbolFlags::Exported}}}))) + return std::move(Err); + + // Create a generator for the ORC runtime archive. + auto OrcRuntimeArchiveGenerator = + StaticLibraryDefinitionGenerator::Load(ObjLinkingLayer, OrcRuntimePath); + if (!OrcRuntimeArchiveGenerator) + return OrcRuntimeArchiveGenerator.takeError(); + + ImportedLibraries.clear(); + for (auto Lib : (*OrcRuntimeArchiveGenerator)->getImportedDynamicLibraries()) + ImportedLibraries.push_back(Lib); + + // Create the instance. + Error Err = Error::success(); + auto P = std::unique_ptr( + new COFFPlatform(ES, ObjLinkingLayer, PlatformJD, + std::move(*OrcRuntimeArchiveGenerator), Err)); + if (Err) + return std::move(Err); + return std::move(P); +} + +Error COFFPlatform::setupJITDylib(JITDylib &JD) { + if (auto Err = JD.define(std::make_unique( + *this, COFFHeaderStartSymbol))) + return Err; + + return ES.lookup({&JD}, COFFHeaderStartSymbol).takeError(); +} + +Error COFFPlatform::teardownJITDylib(JITDylib &JD) { + std::lock_guard Lock(PlatformMutex); + auto I = JITDylibToHeaderAddr.find(&JD); + if (I != JITDylibToHeaderAddr.end()) { + assert(HeaderAddrToJITDylib.count(I->second) && + "HeaderAddrToJITDylib missing entry"); + HeaderAddrToJITDylib.erase(I->second); + JITDylibToHeaderAddr.erase(I); + } + return Error::success(); +} + +Error COFFPlatform::notifyAdding(ResourceTracker &RT, + const MaterializationUnit &MU) { + const auto &InitSym = MU.getInitializerSymbol(); + if (!InitSym) + return Error::success(); + + LLVM_DEBUG({ + dbgs() << "COFFPlatform: Registered init symbol " << *InitSym << " for MU " + << MU.getName() << "\n"; + }); + return Error::success(); +} + +Error COFFPlatform::notifyRemoving(ResourceTracker &RT) { + llvm_unreachable("Not supported yet"); +} + +static void addAliases(ExecutionSession &ES, SymbolAliasMap &Aliases, + ArrayRef> AL) { + for (auto &KV : AL) { + auto AliasName = ES.intern(KV.first); + assert(!Aliases.count(AliasName) && "Duplicate symbol name in alias map"); + Aliases[std::move(AliasName)] = {ES.intern(KV.second), + JITSymbolFlags::Exported}; + } +} + +SymbolAliasMap COFFPlatform::standardPlatformAliases(ExecutionSession &ES) { + SymbolAliasMap Aliases; + addAliases(ES, Aliases, requiredCXXAliases()); + addAliases(ES, Aliases, standardRuntimeUtilityAliases()); + return Aliases; +} + +ArrayRef> +COFFPlatform::requiredCXXAliases() { + static const std::pair RequiredCXXAliases[] = { + {"_CxxThrowException", "__orc_rt_coff_cxx_throw_exception"}, + }; + + return ArrayRef>(RequiredCXXAliases); +} + +ArrayRef> +COFFPlatform::standardRuntimeUtilityAliases() { + static const std::pair + StandardRuntimeUtilityAliases[] = { + {"__orc_rt_run_program", "__orc_rt_coff_run_program"}, + {"__orc_rt_jit_dlerror", "__orc_rt_coff_jit_dlerror"}, + {"__orc_rt_jit_dlopen", "__orc_rt_coff_jit_dlopen"}, + {"__orc_rt_jit_dlclose", "__orc_rt_coff_jit_dlclose"}, + {"__orc_rt_jit_dlsym", "__orc_rt_coff_jit_dlsym"}, + {"__orc_rt_log_error", "__orc_rt_log_error_to_stderr"}}; + + return ArrayRef>( + StandardRuntimeUtilityAliases); +} + +bool COFFPlatform::supportedTarget(const Triple &TT) { + switch (TT.getArch()) { + case Triple::x86_64: + return true; + default: + return false; + } +} + +COFFPlatform::COFFPlatform( + ExecutionSession &ES, ObjectLinkingLayer &ObjLinkingLayer, + JITDylib &PlatformJD, + std::unique_ptr OrcRuntimeGenerator, Error &Err) + : ES(ES), ObjLinkingLayer(ObjLinkingLayer), + COFFHeaderStartSymbol(ES.intern("__ImageBase")) { + ErrorAsOutParameter _(&Err); + + BootstrapState = std::make_unique(); + BootstrapState->JDName = PlatformJD.getName(); + Bootstraping.store(true); + + ObjLinkingLayer.addPlugin(std::make_unique(*this)); + + // PlatformJD hasn't been set up by the platform yet (since we're creating + // the platform now), so set it up. + if (auto E2 = setupJITDylib(PlatformJD)) { + Err = std::move(E2); + return; + } + + PlatformJD.addGenerator(std::move(OrcRuntimeGenerator)); +} + +Error COFFPlatform::bootstrap(JITDylib &PlatformJD) { + // Associate wrapper function tags with JIT-side function implementations. + if (auto Err = associateRuntimeSupportFunctions(PlatformJD)) { + return Err; + } + + // Lookup addresses of runtime functions callable by the platform, + // call the platform bootstrap function to initialize the platform-state + // object in the executor. + if (auto Err = bootstrapCOFFRuntime(PlatformJD)) { + return Err; + } + + Bootstraping.store(false); + BootstrapState.reset(); + + return Error::success(); +} + +void COFFPlatform::rt_lookupSymbol(SendSymbolAddressFn SendResult, + ExecutorAddr Handle, StringRef SymbolName) { + LLVM_DEBUG({ + dbgs() << "COFFPlatform::rt_lookupSymbol(\"" + << formatv("{0:x}", Handle.getValue()) << "\")\n"; + }); + + JITDylib *JD = nullptr; + + { + std::lock_guard Lock(PlatformMutex); + auto I = HeaderAddrToJITDylib.find(Handle); + if (I != HeaderAddrToJITDylib.end()) + JD = I->second; + } + + if (!JD) { + LLVM_DEBUG({ + dbgs() << " No JITDylib for handle " + << formatv("{0:x}", Handle.getValue()) << "\n"; + }); + SendResult(make_error("No JITDylib associated with handle " + + formatv("{0:x}", Handle.getValue()), + inconvertibleErrorCode())); + return; + } + + // Use functor class to work around XL build compiler issue on AIX. + class RtLookupNotifyComplete { + public: + RtLookupNotifyComplete(SendSymbolAddressFn &&SendResult) + : SendResult(std::move(SendResult)) {} + void operator()(Expected Result) { + if (Result) { + assert(Result->size() == 1 && "Unexpected result map count"); + SendResult(ExecutorAddr(Result->begin()->second.getAddress())); + } else { + SendResult(Result.takeError()); + } + } + + private: + SendSymbolAddressFn SendResult; + }; + + ES.lookup( + LookupKind::DLSym, {{JD, JITDylibLookupFlags::MatchExportedSymbolsOnly}}, + SymbolLookupSet(ES.intern(SymbolName)), SymbolState::Ready, + RtLookupNotifyComplete(std::move(SendResult)), NoDependenciesToRegister); +} + +Error COFFPlatform::associateRuntimeSupportFunctions(JITDylib &PlatformJD) { + ExecutionSession::JITDispatchHandlerAssociationMap WFs; + + using LookupSymbolSPSSig = + SPSExpected(SPSExecutorAddr, SPSString); + WFs[ES.intern("__orc_rt_coff_symbol_lookup_tag")] = + ES.wrapAsyncWithSPS(this, + &COFFPlatform::rt_lookupSymbol); + + return ES.registerJITDispatchHandlers(PlatformJD, std::move(WFs)); +} + +Error COFFPlatform::runBootstrapInitializers(JITDylib &PlatformJD) { + llvm::sort(BootstrapState->Initializers); + if (auto Err = BootstrapState->runInitializers(ES, ".CRT$XIA", ".CRT$XIZ")) + return Err; + + if (auto Err = runSymbolIfExists(PlatformJD, "__run_after_c_init")) + return Err; + + if (auto Err = BootstrapState->runInitializers(ES, ".CRT$XCA", ".CRT$XCZ")) + return Err; + return Error::success(); +} + +Error COFFPlatform::bootstrapCOFFRuntime(JITDylib &PlatformJD) { + if (auto Err = lookupAndRecordAddrs( + ES, LookupKind::Static, makeJITDylibSearchOrder(&PlatformJD), + { + {ES.intern("__orc_rt_coff_platform_bootstrap"), + &orc_rt_coff_platform_bootstrap}, + {ES.intern("__orc_rt_coff_platform_shutdown"), + &orc_rt_coff_platform_shutdown}, + {ES.intern("__orc_rt_coff_register_jitdylib"), + &orc_rt_coff_register_jitdylib}, + {ES.intern("__orc_rt_coff_deregister_jitdylib"), + &orc_rt_coff_deregister_jitdylib}, + {ES.intern("__orc_rt_coff_register_sehframe_section"), + &orc_rt_coff_register_sehframe_section}, + {ES.intern("__orc_rt_coff_deregister_sehframe_section"), + &orc_rt_coff_deregister_sehframe_section}, + {ES.intern("__orc_rt_coff_register_block_ranges"), + &orc_rt_coff_register_block_ranges}, + {ES.intern("__orc_rt_coff_deregister_block_ranges"), + &orc_rt_coff_deregister_block_ranges}, + })) + return Err; + + // Lookup of runtime symbols causes the collection of initializers if + // it's static linking setting. + if (auto Err = runBootstrapInitializers(PlatformJD)) + return Err; + + // Call bootstrap functions + if (auto Err = ES.callSPSWrapper(orc_rt_coff_platform_bootstrap)) + return Err; + + // Do the pending jitdylib registration actions that we couldn't do + // because orc runtime was not linked fully. + if (auto Err = ES.callSPSWrapper( + orc_rt_coff_register_jitdylib, BootstrapState->JDName, + BootstrapState->HeaderAddr)) + return Err; + + if (auto Err = ES.callSPSWrapper)>( + orc_rt_coff_register_sehframe_section, BootstrapState->HeaderAddr, + BootstrapState->SEHFrames)) + return Err; + + if (auto Err = ES.callSPSWrapper)>( + orc_rt_coff_register_block_ranges, BootstrapState->HeaderAddr, + BootstrapState->BlockRanges)) + return Err; + + return Error::success(); +} + +Error COFFPlatform::runSymbolIfExists(JITDylib &PlatformJD, + StringRef SymbolName) { + ExecutorAddr jit_function; + auto AfterCLookupErr = lookupAndRecordAddrs( + ES, LookupKind::Static, makeJITDylibSearchOrder(&PlatformJD), + {{ES.intern(SymbolName), &jit_function}}); + if (!AfterCLookupErr) { + auto Res = ES.getExecutorProcessControl().runAsVoidFunction(jit_function); + if (!Res) + return Res.takeError(); + return Error::success(); + } + if (!AfterCLookupErr.isA()) + return AfterCLookupErr; + return Error::success(); +} + +Error COFFPlatform::COFFPlatformBootstrapState::runInitializers( + ExecutionSession &ES, StringRef Start, StringRef End) { + for (auto &Initializer : Initializers) + if (Initializer.first >= Start && Initializer.first <= End && + Initializer.second) { + auto Res = + ES.getExecutorProcessControl().runAsVoidFunction(Initializer.second); + if (!Res) + return Res.takeError(); + } + return Error::success(); +} + +void COFFPlatform::COFFPlatformPlugin::modifyPassConfig( + MaterializationResponsibility &MR, jitlink::LinkGraph &LG, + jitlink::PassConfiguration &Config) { + + auto IsBootstraping = CP.Bootstraping.load(); + + if (auto InitSymbol = MR.getInitializerSymbol()) { + if (InitSymbol == CP.COFFHeaderStartSymbol) { + Config.PostAllocationPasses.push_back( + [this, &MR, IsBootstraping](jitlink::LinkGraph &G) { + return associateJITDylibHeaderSymbol(G, MR, IsBootstraping); + }); + return; + } + Config.PrePrunePasses.push_back([this, &MR](jitlink::LinkGraph &G) { + return preserveInitializerSections(G, MR); + }); + } + + if (!IsBootstraping) + Config.PostFixupPasses.push_back( + [this, &JD = MR.getTargetJITDylib()](jitlink::LinkGraph &G) { + return registerObjectPlatformSections(G, JD); + }); + else + Config.PostFixupPasses.push_back( + [this, &JD = MR.getTargetJITDylib()](jitlink::LinkGraph &G) { + return registerObjectPlatformSectionsInBootstrap(G, JD); + }); +} + +ObjectLinkingLayer::Plugin::SyntheticSymbolDependenciesMap +COFFPlatform::COFFPlatformPlugin::getSyntheticSymbolDependencies( + MaterializationResponsibility &MR) { + std::lock_guard Lock(PluginMutex); + auto I = InitSymbolDeps.find(&MR); + if (I != InitSymbolDeps.end()) { + SyntheticSymbolDependenciesMap Result; + Result[MR.getInitializerSymbol()] = std::move(I->second); + InitSymbolDeps.erase(&MR); + return Result; + } + return SyntheticSymbolDependenciesMap(); +} + +Error COFFPlatform::COFFPlatformPlugin::associateJITDylibHeaderSymbol( + jitlink::LinkGraph &G, MaterializationResponsibility &MR, + bool IsBootstraping) { + auto I = llvm::find_if(G.defined_symbols(), [this](jitlink::Symbol *Sym) { + return Sym->getName() == *CP.COFFHeaderStartSymbol; + }); + assert(I != G.defined_symbols().end() && "Missing COFF header start symbol"); + + auto &JD = MR.getTargetJITDylib(); + std::lock_guard Lock(CP.PlatformMutex); + auto HeaderAddr = (*I)->getAddress(); + CP.JITDylibToHeaderAddr[&JD] = HeaderAddr; + CP.HeaderAddrToJITDylib[HeaderAddr] = &JD; + if (!IsBootstraping) { + G.allocActions().push_back( + {cantFail(WrapperFunctionCall::Create< + SPSArgList>( + CP.orc_rt_coff_register_jitdylib, JD.getName(), HeaderAddr)), + cantFail(WrapperFunctionCall::Create>( + CP.orc_rt_coff_deregister_jitdylib, HeaderAddr))}); + } else { + G.allocActions().push_back( + {{}, + cantFail(WrapperFunctionCall::Create>( + CP.orc_rt_coff_deregister_jitdylib, HeaderAddr))}); + CP.BootstrapState->HeaderAddr = HeaderAddr; + } + + return Error::success(); +} + +Error COFFPlatform::COFFPlatformPlugin::registerObjectPlatformSections( + jitlink::LinkGraph &G, JITDylib &JD) { + + // Add an action to register the seh-frame. + if (auto *SEHFrameSection = G.findSectionByName(getSEHFrameSectionName())) { + auto HeaderAddr = CP.JITDylibToHeaderAddr[&JD]; + + std::vector Frames; + for (auto *Block : SEHFrameSection->blocks()) + Frames.push_back(Block->getRange()); + + std::vector Blocks; + for (auto *Block : G.blocks()) + Blocks.push_back(Block->getRange()); + + G.allocActions().push_back( + {cantFail(WrapperFunctionCall::Create>>( + CP.orc_rt_coff_register_sehframe_section, HeaderAddr, Frames)), + cantFail(WrapperFunctionCall::Create>>( + CP.orc_rt_coff_deregister_sehframe_section, HeaderAddr, Frames))}); + + G.allocActions().push_back( + {cantFail(WrapperFunctionCall::Create>>( + CP.orc_rt_coff_register_block_ranges, HeaderAddr, Blocks)), + cantFail(WrapperFunctionCall::Create>>( + CP.orc_rt_coff_deregister_block_ranges, HeaderAddr, Blocks))}); + } + + return Error::success(); +} + +Error COFFPlatform::COFFPlatformPlugin::preserveInitializerSections( + jitlink::LinkGraph &G, MaterializationResponsibility &MR) { + JITLinkSymbolSet InitSectionSymbols; + for (auto &Sec : G.sections()) + if (COFFPlatform::isInitializerSection(Sec.getName())) + for (auto *B : Sec.blocks()) + if (!B->edges_empty()) + InitSectionSymbols.insert( + &G.addAnonymousSymbol(*B, 0, 0, false, true)); + + std::lock_guard Lock(PluginMutex); + InitSymbolDeps[&MR] = InitSectionSymbols; + return Error::success(); +} + +Error COFFPlatform::COFFPlatformPlugin:: + registerObjectPlatformSectionsInBootstrap(jitlink::LinkGraph &G, + JITDylib &JD) { + + std::lock_guard Lock(CP.PlatformMutex); + auto HeaderAddr = CP.JITDylibToHeaderAddr[&JD]; + std::vector Frames; + std::vector Blocks; + + // Push seh frames to register + if (auto *SEHFrameSection = G.findSectionByName(getSEHFrameSectionName())) + for (auto *Block : SEHFrameSection->blocks()) { + CP.BootstrapState->SEHFrames.push_back(Block->getRange()); + Frames.push_back(Block->getRange()); + } + + for (auto *Block : G.blocks()) { + CP.BootstrapState->BlockRanges.push_back(Block->getRange()); + Blocks.push_back(Block->getRange()); + } + + G.allocActions().push_back( + {{}, + cantFail(WrapperFunctionCall::Create< + SPSArgList>>( + CP.orc_rt_coff_deregister_sehframe_section, HeaderAddr, Frames))}); + + G.allocActions().push_back( + {{}, + cantFail(WrapperFunctionCall::Create< + SPSArgList>>( + CP.orc_rt_coff_deregister_block_ranges, HeaderAddr, Blocks))}); + + // Collect static initializers + for (auto &S : G.sections()) + if (COFFPlatform::isInitializerSection(S.getName())) + for (auto *B : S.blocks()) { + if (B->edges_empty()) + continue; + for (auto E : B->edges()) + CP.BootstrapState->Initializers.push_back(std::make_pair( + S.getName().str(), + ExecutorAddr(E.getTarget().getAddress() + E.getAddend()))); + } + + return Error::success(); +} + +} // End namespace orc. +} // End namespace llvm. Index: llvm/lib/ExecutionEngine/Orc/ObjectFileInterface.cpp =================================================================== --- llvm/lib/ExecutionEngine/Orc/ObjectFileInterface.cpp +++ llvm/lib/ExecutionEngine/Orc/ObjectFileInterface.cpp @@ -7,6 +7,7 @@ //===----------------------------------------------------------------------===// #include "llvm/ExecutionEngine/Orc/ObjectFileInterface.h" +#include "llvm/ExecutionEngine/Orc/COFFPlatform.h" #include "llvm/ExecutionEngine/Orc/ELFNixPlatform.h" #include "llvm/ExecutionEngine/Orc/MachOPlatform.h" #include "llvm/Object/COFF.h" @@ -214,7 +215,15 @@ I.SymbolFlags[ES.intern(*Name)] = std::move(*SymFlags); } - // FIXME: handle init symbols + SymbolStringPtr InitSymbol; + for (auto &Sec : Obj.sections()) { + if (auto SecName = Sec.getName()) { + if (COFFPlatform::isInitializerSection(*SecName)) { + addInitSymbol(I, ES, Obj.getFileName()); + break; + } + } + } return I; } Index: llvm/tools/llvm-jitlink/llvm-jitlink.cpp =================================================================== --- llvm/tools/llvm-jitlink/llvm-jitlink.cpp +++ llvm/tools/llvm-jitlink/llvm-jitlink.cpp @@ -15,6 +15,8 @@ #include "llvm-jitlink.h" #include "llvm/BinaryFormat/Magic.h" +#include "llvm/ExecutionEngine/Orc/COFFPlatform.h" +#include "llvm/ExecutionEngine/Orc/COFFVCRuntimeSupport.h" #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h" #include "llvm/ExecutionEngine/Orc/DebuggerSupportPlugin.h" #include "llvm/ExecutionEngine/Orc/ELFNixPlatform.h" @@ -1060,6 +1062,12 @@ if (!NoProcessSymbols) ExitOnErr(loadProcessSymbols(*this)); + else + ExitOnErr(MainJD->define(absoluteSymbols( + {{ES.intern("llvm_jitlink_setTestResultOverride"), + {pointerToJITTargetAddress(llvm_jitlink_setTestResultOverride), + JITSymbolFlags::Exported}}}))); + ExitOnErr(loadDylibs(*this)); auto &TT = ES.getExecutorProcessControl().getTargetTriple(); @@ -1085,6 +1093,45 @@ Err = P.takeError(); return; } + } else if (TT.isOSBinFormatCOFF() && !OrcRuntime.empty()) { + auto LoadDynLibrary = [&](JITDylib &JD, StringRef DLLName) { + return loadDynamicLibrary(DLLName); + }; + auto VCRT = COFFVCRuntimeBootstrapper::Create(ES, ObjLayer, + std::move(LoadDynLibrary)); + if (!VCRT) { + Err = VCRT.takeError(); + return; + } + + std::vector ImportedLibraries; + if (auto P = COFFPlatform::Create(ES, ObjLayer, *MainJD, OrcRuntime.c_str(), + ImportedLibraries)) { + for (auto Lib : ImportedLibraries) + if (auto E2 = loadDynamicLibrary(Lib)) { + Err = std::move(E2); + return; + } + + if (auto E2 = (*VCRT)->loadStaticVCRuntime(*MainJD)) { + Err = std::move(E2); + return; + } + + if (auto E2 = (*VCRT)->initializeStaticVCRuntime(*MainJD)) { + Err = std::move(E2); + return; + } + + if (auto E2 = (*P)->bootstrap(*MainJD)) { + Err = std::move(E2); + return; + } + ES.setPlatform(std::move(*P)); + } else { + Err = P.takeError(); + return; + } } else if (TT.isOSBinFormatELF()) { if (!NoExec) ObjLayer.addPlugin(std::make_unique( @@ -1144,7 +1191,7 @@ if (EPC.getTargetTriple().getObjectFormat() == Triple::MachO) return registerMachOGraphInfo(*this, G); - if (EPC.getTargetTriple().isOSWindows()) + if (EPC.getTargetTriple().getObjectFormat() == Triple::COFF) return registerCOFFGraphInfo(*this, G); return make_error("Unsupported object format for GOT/stub " @@ -1275,7 +1322,7 @@ object::ObjectFile::createObjectFile(ObjBuffer->getMemBufferRef())); Triple TT = Obj->makeTriple(); if (Magic == file_magic::coff_object) - TT.setOS(Triple::OSType::Win32); + TT.setObjectFormat(Triple::COFF); return TT; } default: