llvm-project
775 строк · 25.6 Кб
1//===- coff_platform.cpp --------------------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains code required to load the rest of the COFF runtime.
10//
11//===----------------------------------------------------------------------===//
12
13#define NOMINMAX14#include <windows.h>15
16#include "coff_platform.h"17
18#include "debug.h"19#include "error.h"20#include "wrapper_function_utils.h"21
22#include <array>23#include <list>24#include <map>25#include <mutex>26#include <sstream>27#include <string_view>28#include <vector>29
30#define DEBUG_TYPE "coff_platform"31
32using namespace __orc_rt;33
34namespace __orc_rt {35
36using COFFJITDylibDepInfo = std::vector<ExecutorAddr>;37using COFFJITDylibDepInfoMap =38std::unordered_map<ExecutorAddr, COFFJITDylibDepInfo>;39
40using SPSCOFFObjectSectionsMap =41SPSSequence<SPSTuple<SPSString, SPSExecutorAddrRange>>;42
43using SPSCOFFJITDylibDepInfo = SPSSequence<SPSExecutorAddr>;44
45using SPSCOFFJITDylibDepInfoMap =46SPSSequence<SPSTuple<SPSExecutorAddr, SPSCOFFJITDylibDepInfo>>;47
48} // namespace __orc_rt49
50ORC_RT_JIT_DISPATCH_TAG(__orc_rt_coff_symbol_lookup_tag)51ORC_RT_JIT_DISPATCH_TAG(__orc_rt_coff_push_initializers_tag)52
53namespace {54class COFFPlatformRuntimeState {55private:56// Ctor/dtor section.57// Manage lists of *tor functions sorted by the last character of subsection58// name.59struct XtorSection {60void Register(char SubsectionChar, span<void (*)(void)> Xtors) {61Subsections[SubsectionChar - 'A'].push_back(Xtors);62SubsectionsNew[SubsectionChar - 'A'].push_back(Xtors);63}64
65void RegisterNoRun(char SubsectionChar, span<void (*)(void)> Xtors) {66Subsections[SubsectionChar - 'A'].push_back(Xtors);67}68
69void Reset() { SubsectionsNew = Subsections; }70
71void RunAllNewAndFlush();72
73private:74std::array<std::vector<span<void (*)(void)>>, 26> Subsections;75std::array<std::vector<span<void (*)(void)>>, 26> SubsectionsNew;76};77
78struct JITDylibState {79std::string Name;80void *Header = nullptr;81size_t LinkedAgainstRefCount = 0;82size_t DlRefCount = 0;83std::vector<JITDylibState *> Deps;84std::vector<void (*)(void)> AtExits;85XtorSection CInitSection; // XIA~XIZ86XtorSection CXXInitSection; // XCA~XCZ87XtorSection CPreTermSection; // XPA~XPZ88XtorSection CTermSection; // XTA~XTZ89
90bool referenced() const {91return LinkedAgainstRefCount != 0 || DlRefCount != 0;92}93};94
95public:96static void initialize();97static COFFPlatformRuntimeState &get();98static bool isInitialized() { return CPS; }99static void destroy();100
101COFFPlatformRuntimeState() = default;102
103// Delete copy and move constructors.104COFFPlatformRuntimeState(const COFFPlatformRuntimeState &) = delete;105COFFPlatformRuntimeState &106operator=(const COFFPlatformRuntimeState &) = delete;107COFFPlatformRuntimeState(COFFPlatformRuntimeState &&) = delete;108COFFPlatformRuntimeState &operator=(COFFPlatformRuntimeState &&) = delete;109
110const char *dlerror();111void *dlopen(std::string_view Name, int Mode);112int dlclose(void *Header);113void *dlsym(void *Header, std::string_view Symbol);114
115Error registerJITDylib(std::string Name, void *Header);116Error deregisterJITDylib(void *Header);117
118Error registerAtExit(ExecutorAddr HeaderAddr, void (*AtExit)(void));119
120Error registerObjectSections(121ExecutorAddr HeaderAddr,122std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs,123bool RunInitializers);124Error deregisterObjectSections(125ExecutorAddr HeaderAddr,126std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs);127
128void *findJITDylibBaseByPC(uint64_t PC);129
130private:131Error registerBlockRange(ExecutorAddr HeaderAddr, ExecutorAddrRange Range);132Error deregisterBlockRange(ExecutorAddr HeaderAddr, ExecutorAddrRange Range);133
134Error registerSEHFrames(ExecutorAddr HeaderAddr,135ExecutorAddrRange SEHFrameRange);136Error deregisterSEHFrames(ExecutorAddr HeaderAddr,137ExecutorAddrRange SEHFrameRange);138
139Expected<void *> dlopenImpl(std::string_view Path, int Mode);140Error dlopenFull(JITDylibState &JDS);141Error dlopenInitialize(JITDylibState &JDS, COFFJITDylibDepInfoMap &DepInfo);142
143Error dlcloseImpl(void *DSOHandle);144Error dlcloseDeinitialize(JITDylibState &JDS);145
146JITDylibState *getJITDylibStateByHeader(void *DSOHandle);147JITDylibState *getJITDylibStateByName(std::string_view Path);148Expected<ExecutorAddr> lookupSymbolInJITDylib(void *DSOHandle,149std::string_view Symbol);150
151static COFFPlatformRuntimeState *CPS;152
153std::recursive_mutex JDStatesMutex;154std::map<void *, JITDylibState> JDStates;155struct BlockRange {156void *Header;157size_t Size;158};159std::map<void *, BlockRange> BlockRanges;160std::unordered_map<std::string_view, void *> JDNameToHeader;161std::string DLFcnError;162};163
164} // namespace165
166COFFPlatformRuntimeState *COFFPlatformRuntimeState::CPS = nullptr;167
168COFFPlatformRuntimeState::JITDylibState *169COFFPlatformRuntimeState::getJITDylibStateByHeader(void *Header) {170auto I = JDStates.find(Header);171if (I == JDStates.end())172return nullptr;173return &I->second;174}
175
176COFFPlatformRuntimeState::JITDylibState *177COFFPlatformRuntimeState::getJITDylibStateByName(std::string_view Name) {178// FIXME: Avoid creating string copy here.179auto I = JDNameToHeader.find(std::string(Name.data(), Name.size()));180if (I == JDNameToHeader.end())181return nullptr;182void *H = I->second;183auto J = JDStates.find(H);184assert(J != JDStates.end() &&185"JITDylib has name map entry but no header map entry");186return &J->second;187}
188
189Error COFFPlatformRuntimeState::registerJITDylib(std::string Name,190void *Header) {191ORC_RT_DEBUG({192printdbg("Registering JITDylib %s: Header = %p\n", Name.c_str(), Header);193});194std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);195if (JDStates.count(Header)) {196std::ostringstream ErrStream;197ErrStream << "Duplicate JITDylib registration for header " << Header198<< " (name = " << Name << ")";199return make_error<StringError>(ErrStream.str());200}201if (JDNameToHeader.count(Name)) {202std::ostringstream ErrStream;203ErrStream << "Duplicate JITDylib registration for header " << Header204<< " (header = " << Header << ")";205return make_error<StringError>(ErrStream.str());206}207
208auto &JDS = JDStates[Header];209JDS.Name = std::move(Name);210JDS.Header = Header;211JDNameToHeader[JDS.Name] = Header;212return Error::success();213}
214
215Error COFFPlatformRuntimeState::deregisterJITDylib(void *Header) {216std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);217auto I = JDStates.find(Header);218if (I == JDStates.end()) {219std::ostringstream ErrStream;220ErrStream << "Attempted to deregister unrecognized header " << Header;221return make_error<StringError>(ErrStream.str());222}223
224// Remove std::string construction once we can use C++20.225auto J = JDNameToHeader.find(226std::string(I->second.Name.data(), I->second.Name.size()));227assert(J != JDNameToHeader.end() &&228"Missing JDNameToHeader entry for JITDylib");229
230ORC_RT_DEBUG({231printdbg("Deregistering JITDylib %s: Header = %p\n", I->second.Name.c_str(),232Header);233});234
235JDNameToHeader.erase(J);236JDStates.erase(I);237return Error::success();238}
239
240void COFFPlatformRuntimeState::XtorSection::RunAllNewAndFlush() {241for (auto &Subsection : SubsectionsNew) {242for (auto &XtorGroup : Subsection)243for (auto &Xtor : XtorGroup)244if (Xtor)245Xtor();246Subsection.clear();247}248}
249
250const char *COFFPlatformRuntimeState::dlerror() { return DLFcnError.c_str(); }251
252void *COFFPlatformRuntimeState::dlopen(std::string_view Path, int Mode) {253ORC_RT_DEBUG({254std::string S(Path.data(), Path.size());255printdbg("COFFPlatform::dlopen(\"%s\")\n", S.c_str());256});257std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);258if (auto H = dlopenImpl(Path, Mode))259return *H;260else {261// FIXME: Make dlerror thread safe.262DLFcnError = toString(H.takeError());263return nullptr;264}265}
266
267int COFFPlatformRuntimeState::dlclose(void *DSOHandle) {268ORC_RT_DEBUG({269auto *JDS = getJITDylibStateByHeader(DSOHandle);270std::string DylibName;271if (JDS) {272std::string S;273printdbg("COFFPlatform::dlclose(%p) (%s)\n", DSOHandle, S.c_str());274} else275printdbg("COFFPlatform::dlclose(%p) (%s)\n", DSOHandle, "invalid handle");276});277std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);278if (auto Err = dlcloseImpl(DSOHandle)) {279// FIXME: Make dlerror thread safe.280DLFcnError = toString(std::move(Err));281return -1;282}283return 0;284}
285
286void *COFFPlatformRuntimeState::dlsym(void *Header, std::string_view Symbol) {287auto Addr = lookupSymbolInJITDylib(Header, Symbol);288if (!Addr) {289return 0;290}291
292return Addr->toPtr<void *>();293}
294
295Expected<void *> COFFPlatformRuntimeState::dlopenImpl(std::string_view Path,296int Mode) {297// Try to find JITDylib state by name.298auto *JDS = getJITDylibStateByName(Path);299
300if (!JDS)301return make_error<StringError>("No registered JTIDylib for path " +302std::string(Path.data(), Path.size()));303
304if (auto Err = dlopenFull(*JDS))305return std::move(Err);306
307// Bump the ref-count on this dylib.308++JDS->DlRefCount;309
310// Return the header address.311return JDS->Header;312}
313
314Error COFFPlatformRuntimeState::dlopenFull(JITDylibState &JDS) {315// Call back to the JIT to push the initializers.316Expected<COFFJITDylibDepInfoMap> DepInfoMap((COFFJITDylibDepInfoMap()));317if (auto Err = WrapperFunction<SPSExpected<SPSCOFFJITDylibDepInfoMap>(318SPSExecutorAddr)>::call(&__orc_rt_coff_push_initializers_tag,319DepInfoMap,320ExecutorAddr::fromPtr(JDS.Header)))321return Err;322if (!DepInfoMap)323return DepInfoMap.takeError();324
325if (auto Err = dlopenInitialize(JDS, *DepInfoMap))326return Err;327
328if (!DepInfoMap->empty()) {329ORC_RT_DEBUG({330printdbg("Unrecognized dep-info key headers in dlopen of %s\n",331JDS.Name.c_str());332});333std::ostringstream ErrStream;334ErrStream << "Encountered unrecognized dep-info key headers "335"while processing dlopen of "336<< JDS.Name;337return make_error<StringError>(ErrStream.str());338}339
340return Error::success();341}
342
343Error COFFPlatformRuntimeState::dlopenInitialize(344JITDylibState &JDS, COFFJITDylibDepInfoMap &DepInfo) {345ORC_RT_DEBUG({346printdbg("COFFPlatformRuntimeState::dlopenInitialize(\"%s\")\n",347JDS.Name.c_str());348});349
350// Skip visited dependency.351auto I = DepInfo.find(ExecutorAddr::fromPtr(JDS.Header));352if (I == DepInfo.end())353return Error::success();354
355auto DI = std::move(I->second);356DepInfo.erase(I);357
358// Run initializers of dependencies in proper order by depth-first traversal359// of dependency graph.360std::vector<JITDylibState *> OldDeps;361std::swap(JDS.Deps, OldDeps);362JDS.Deps.reserve(DI.size());363for (auto DepHeaderAddr : DI) {364auto *DepJDS = getJITDylibStateByHeader(DepHeaderAddr.toPtr<void *>());365if (!DepJDS) {366std::ostringstream ErrStream;367ErrStream << "Encountered unrecognized dep header "368<< DepHeaderAddr.toPtr<void *>() << " while initializing "369<< JDS.Name;370return make_error<StringError>(ErrStream.str());371}372++DepJDS->LinkedAgainstRefCount;373if (auto Err = dlopenInitialize(*DepJDS, DepInfo))374return Err;375}376
377// Run static initializers.378JDS.CInitSection.RunAllNewAndFlush();379JDS.CXXInitSection.RunAllNewAndFlush();380
381// Decrement old deps.382for (auto *DepJDS : OldDeps) {383--DepJDS->LinkedAgainstRefCount;384if (!DepJDS->referenced())385if (auto Err = dlcloseDeinitialize(*DepJDS))386return Err;387}388
389return Error::success();390}
391
392Error COFFPlatformRuntimeState::dlcloseImpl(void *DSOHandle) {393// Try to find JITDylib state by header.394auto *JDS = getJITDylibStateByHeader(DSOHandle);395
396if (!JDS) {397std::ostringstream ErrStream;398ErrStream << "No registered JITDylib for " << DSOHandle;399return make_error<StringError>(ErrStream.str());400}401
402// Bump the ref-count.403--JDS->DlRefCount;404
405if (!JDS->referenced())406return dlcloseDeinitialize(*JDS);407
408return Error::success();409}
410
411Error COFFPlatformRuntimeState::dlcloseDeinitialize(JITDylibState &JDS) {412ORC_RT_DEBUG({413printdbg("COFFPlatformRuntimeState::dlcloseDeinitialize(\"%s\")\n",414JDS.Name.c_str());415});416
417// Run atexits418for (auto AtExit : JDS.AtExits)419AtExit();420JDS.AtExits.clear();421
422// Run static terminators.423JDS.CPreTermSection.RunAllNewAndFlush();424JDS.CTermSection.RunAllNewAndFlush();425
426// Queue all xtors as new again.427JDS.CInitSection.Reset();428JDS.CXXInitSection.Reset();429JDS.CPreTermSection.Reset();430JDS.CTermSection.Reset();431
432// Deinitialize any dependencies.433for (auto *DepJDS : JDS.Deps) {434--DepJDS->LinkedAgainstRefCount;435if (!DepJDS->referenced())436if (auto Err = dlcloseDeinitialize(*DepJDS))437return Err;438}439
440return Error::success();441}
442
443Expected<ExecutorAddr>444COFFPlatformRuntimeState::lookupSymbolInJITDylib(void *header,445std::string_view Sym) {446Expected<ExecutorAddr> Result((ExecutorAddr()));447if (auto Err = WrapperFunction<SPSExpected<SPSExecutorAddr>(448SPSExecutorAddr, SPSString)>::call(&__orc_rt_coff_symbol_lookup_tag,449Result,450ExecutorAddr::fromPtr(header),451Sym))452return std::move(Err);453return Result;454}
455
456Error COFFPlatformRuntimeState::registerObjectSections(457ExecutorAddr HeaderAddr,458std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs,459bool RunInitializers) {460std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);461auto I = JDStates.find(HeaderAddr.toPtr<void *>());462if (I == JDStates.end()) {463std::ostringstream ErrStream;464ErrStream << "Unrecognized header " << HeaderAddr.getValue();465return make_error<StringError>(ErrStream.str());466}467auto &JDState = I->second;468for (auto &KV : Secs) {469if (auto Err = registerBlockRange(HeaderAddr, KV.second))470return Err;471if (KV.first.empty())472continue;473char LastChar = KV.first.data()[KV.first.size() - 1];474if (KV.first == ".pdata") {475if (auto Err = registerSEHFrames(HeaderAddr, KV.second))476return Err;477} else if (KV.first >= ".CRT$XIA" && KV.first <= ".CRT$XIZ") {478if (RunInitializers)479JDState.CInitSection.Register(LastChar,480KV.second.toSpan<void (*)(void)>());481else482JDState.CInitSection.RegisterNoRun(LastChar,483KV.second.toSpan<void (*)(void)>());484} else if (KV.first >= ".CRT$XCA" && KV.first <= ".CRT$XCZ") {485if (RunInitializers)486JDState.CXXInitSection.Register(LastChar,487KV.second.toSpan<void (*)(void)>());488else489JDState.CXXInitSection.RegisterNoRun(490LastChar, KV.second.toSpan<void (*)(void)>());491} else if (KV.first >= ".CRT$XPA" && KV.first <= ".CRT$XPZ")492JDState.CPreTermSection.Register(LastChar,493KV.second.toSpan<void (*)(void)>());494else if (KV.first >= ".CRT$XTA" && KV.first <= ".CRT$XTZ")495JDState.CTermSection.Register(LastChar,496KV.second.toSpan<void (*)(void)>());497}498return Error::success();499}
500
501Error COFFPlatformRuntimeState::deregisterObjectSections(502ExecutorAddr HeaderAddr,503std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs) {504std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);505auto I = JDStates.find(HeaderAddr.toPtr<void *>());506if (I == JDStates.end()) {507std::ostringstream ErrStream;508ErrStream << "Attempted to deregister unrecognized header "509<< HeaderAddr.getValue();510return make_error<StringError>(ErrStream.str());511}512for (auto &KV : Secs) {513if (auto Err = deregisterBlockRange(HeaderAddr, KV.second))514return Err;515if (KV.first == ".pdata")516if (auto Err = deregisterSEHFrames(HeaderAddr, KV.second))517return Err;518}519return Error::success();520}
521
522Error COFFPlatformRuntimeState::registerSEHFrames(523ExecutorAddr HeaderAddr, ExecutorAddrRange SEHFrameRange) {524int N = (SEHFrameRange.End.getValue() - SEHFrameRange.Start.getValue()) /525sizeof(RUNTIME_FUNCTION);526auto Func = SEHFrameRange.Start.toPtr<PRUNTIME_FUNCTION>();527if (!RtlAddFunctionTable(Func, N,528static_cast<DWORD64>(HeaderAddr.getValue())))529return make_error<StringError>("Failed to register SEH frames");530return Error::success();531}
532
533Error COFFPlatformRuntimeState::deregisterSEHFrames(534ExecutorAddr HeaderAddr, ExecutorAddrRange SEHFrameRange) {535if (!RtlDeleteFunctionTable(SEHFrameRange.Start.toPtr<PRUNTIME_FUNCTION>()))536return make_error<StringError>("Failed to deregister SEH frames");537return Error::success();538}
539
540Error COFFPlatformRuntimeState::registerBlockRange(ExecutorAddr HeaderAddr,541ExecutorAddrRange Range) {542assert(!BlockRanges.count(Range.Start.toPtr<void *>()) &&543"Block range address already registered");544BlockRange B = {HeaderAddr.toPtr<void *>(), Range.size()};545BlockRanges.emplace(Range.Start.toPtr<void *>(), B);546return Error::success();547}
548
549Error COFFPlatformRuntimeState::deregisterBlockRange(ExecutorAddr HeaderAddr,550ExecutorAddrRange Range) {551assert(BlockRanges.count(Range.Start.toPtr<void *>()) &&552"Block range address not registered");553BlockRanges.erase(Range.Start.toPtr<void *>());554return Error::success();555}
556
557Error COFFPlatformRuntimeState::registerAtExit(ExecutorAddr HeaderAddr,558void (*AtExit)(void)) {559std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);560auto I = JDStates.find(HeaderAddr.toPtr<void *>());561if (I == JDStates.end()) {562std::ostringstream ErrStream;563ErrStream << "Unrecognized header " << HeaderAddr.getValue();564return make_error<StringError>(ErrStream.str());565}566I->second.AtExits.push_back(AtExit);567return Error::success();568}
569
570void COFFPlatformRuntimeState::initialize() {571assert(!CPS && "COFFPlatformRuntimeState should be null");572CPS = new COFFPlatformRuntimeState();573}
574
575COFFPlatformRuntimeState &COFFPlatformRuntimeState::get() {576assert(CPS && "COFFPlatformRuntimeState not initialized");577return *CPS;578}
579
580void COFFPlatformRuntimeState::destroy() {581assert(CPS && "COFFPlatformRuntimeState not initialized");582delete CPS;583}
584
585void *COFFPlatformRuntimeState::findJITDylibBaseByPC(uint64_t PC) {586std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);587auto It = BlockRanges.upper_bound(reinterpret_cast<void *>(PC));588if (It == BlockRanges.begin())589return nullptr;590--It;591auto &Range = It->second;592if (PC >= reinterpret_cast<uint64_t>(It->first) + Range.Size)593return nullptr;594return Range.Header;595}
596
597ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
598__orc_rt_coff_platform_bootstrap(char *ArgData, size_t ArgSize) {599COFFPlatformRuntimeState::initialize();600return WrapperFunctionResult().release();601}
602
603ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
604__orc_rt_coff_platform_shutdown(char *ArgData, size_t ArgSize) {605COFFPlatformRuntimeState::destroy();606return WrapperFunctionResult().release();607}
608
609ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
610__orc_rt_coff_register_jitdylib(char *ArgData, size_t ArgSize) {611return WrapperFunction<SPSError(SPSString, SPSExecutorAddr)>::handle(612ArgData, ArgSize,613[](std::string &Name, ExecutorAddr HeaderAddr) {614return COFFPlatformRuntimeState::get().registerJITDylib(615std::move(Name), HeaderAddr.toPtr<void *>());616})617.release();618}
619
620ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
621__orc_rt_coff_deregister_jitdylib(char *ArgData, size_t ArgSize) {622return WrapperFunction<SPSError(SPSExecutorAddr)>::handle(623ArgData, ArgSize,624[](ExecutorAddr HeaderAddr) {625return COFFPlatformRuntimeState::get().deregisterJITDylib(626HeaderAddr.toPtr<void *>());627})628.release();629}
630
631ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
632__orc_rt_coff_register_object_sections(char *ArgData, size_t ArgSize) {633return WrapperFunction<SPSError(SPSExecutorAddr, SPSCOFFObjectSectionsMap,634bool)>::635handle(ArgData, ArgSize,636[](ExecutorAddr HeaderAddr,637std::vector<std::pair<std::string_view, ExecutorAddrRange>>638&Secs,639bool RunInitializers) {640return COFFPlatformRuntimeState::get().registerObjectSections(641HeaderAddr, std::move(Secs), RunInitializers);642})643.release();644}
645
646ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult
647__orc_rt_coff_deregister_object_sections(char *ArgData, size_t ArgSize) {648return WrapperFunction<SPSError(SPSExecutorAddr, SPSCOFFObjectSectionsMap)>::649handle(ArgData, ArgSize,650[](ExecutorAddr HeaderAddr,651std::vector<std::pair<std::string_view, ExecutorAddrRange>>652&Secs) {653return COFFPlatformRuntimeState::get().deregisterObjectSections(654HeaderAddr, std::move(Secs));655})656.release();657}
658//------------------------------------------------------------------------------
659// JIT'd dlfcn alternatives.
660//------------------------------------------------------------------------------
661
662const char *__orc_rt_coff_jit_dlerror() {663return COFFPlatformRuntimeState::get().dlerror();664}
665
666void *__orc_rt_coff_jit_dlopen(const char *path, int mode) {667return COFFPlatformRuntimeState::get().dlopen(path, mode);668}
669
670int __orc_rt_coff_jit_dlclose(void *header) {671return COFFPlatformRuntimeState::get().dlclose(header);672}
673
674void *__orc_rt_coff_jit_dlsym(void *header, const char *symbol) {675return COFFPlatformRuntimeState::get().dlsym(header, symbol);676}
677
678//------------------------------------------------------------------------------
679// COFF SEH exception support
680//------------------------------------------------------------------------------
681
682struct ThrowInfo {683uint32_t attributes;684void *data;685};686
687ORC_RT_INTERFACE void __stdcall __orc_rt_coff_cxx_throw_exception(688void *pExceptionObject, ThrowInfo *pThrowInfo) {689#ifdef __clang__690#pragma clang diagnostic push691#pragma clang diagnostic ignored "-Wmultichar"692#endif693constexpr uint32_t EH_EXCEPTION_NUMBER = 'msc' | 0xE0000000;694#ifdef __clang__695#pragma clang diagnostic pop696#endif697constexpr uint32_t EH_MAGIC_NUMBER1 = 0x19930520;698auto BaseAddr = COFFPlatformRuntimeState::get().findJITDylibBaseByPC(699reinterpret_cast<uint64_t>(pThrowInfo));700if (!BaseAddr) {701// This is not from JIT'd region.702// FIXME: Use the default implementation like below when alias api is703// capable. _CxxThrowException(pExceptionObject, pThrowInfo);704fprintf(stderr, "Throwing exception from compiled callback into JIT'd "705"exception handler not supported yet.\n");706abort();707return;708}709const ULONG_PTR parameters[] = {710EH_MAGIC_NUMBER1,711reinterpret_cast<ULONG_PTR>(pExceptionObject),712reinterpret_cast<ULONG_PTR>(pThrowInfo),713reinterpret_cast<ULONG_PTR>(BaseAddr),714};715RaiseException(EH_EXCEPTION_NUMBER, EXCEPTION_NONCONTINUABLE,716_countof(parameters), parameters);717}
718
719//------------------------------------------------------------------------------
720// COFF atexits
721//------------------------------------------------------------------------------
722
723typedef int (*OnExitFunction)(void);724typedef void (*AtExitFunction)(void);725
726ORC_RT_INTERFACE OnExitFunction __orc_rt_coff_onexit(void *Header,727OnExitFunction Func) {728if (auto Err = COFFPlatformRuntimeState::get().registerAtExit(729ExecutorAddr::fromPtr(Header), (void (*)(void))Func)) {730consumeError(std::move(Err));731return nullptr;732}733return Func;734}
735
736ORC_RT_INTERFACE int __orc_rt_coff_atexit(void *Header, AtExitFunction Func) {737if (auto Err = COFFPlatformRuntimeState::get().registerAtExit(738ExecutorAddr::fromPtr(Header), (void (*)(void))Func)) {739consumeError(std::move(Err));740return -1;741}742return 0;743}
744
745//------------------------------------------------------------------------------
746// COFF Run Program
747//------------------------------------------------------------------------------
748
749ORC_RT_INTERFACE int64_t __orc_rt_coff_run_program(const char *JITDylibName,750const char *EntrySymbolName,751int argc, char *argv[]) {752using MainTy = int (*)(int, char *[]);753
754void *H =755__orc_rt_coff_jit_dlopen(JITDylibName, __orc_rt::coff::ORC_RT_RTLD_LAZY);756if (!H) {757__orc_rt_log_error(__orc_rt_coff_jit_dlerror());758return -1;759}760
761auto *Main =762reinterpret_cast<MainTy>(__orc_rt_coff_jit_dlsym(H, EntrySymbolName));763
764if (!Main) {765__orc_rt_log_error(__orc_rt_coff_jit_dlerror());766return -1;767}768
769int Result = Main(argc, argv);770
771if (__orc_rt_coff_jit_dlclose(H) == -1)772__orc_rt_log_error(__orc_rt_coff_jit_dlerror());773
774return Result;775}
776