Path: blob/main/contrib/llvm-project/compiler-rt/lib/orc/coff_platform.cpp
39566 views
//===- coff_platform.cpp --------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains code required to load the rest of the COFF runtime.9//10//===----------------------------------------------------------------------===//1112#define NOMINMAX13#include <windows.h>1415#include "coff_platform.h"1617#include "debug.h"18#include "error.h"19#include "wrapper_function_utils.h"2021#include <array>22#include <list>23#include <map>24#include <mutex>25#include <sstream>26#include <string_view>27#include <vector>2829#define DEBUG_TYPE "coff_platform"3031using namespace __orc_rt;3233namespace __orc_rt {3435using COFFJITDylibDepInfo = std::vector<ExecutorAddr>;36using COFFJITDylibDepInfoMap =37std::unordered_map<ExecutorAddr, COFFJITDylibDepInfo>;3839using SPSCOFFObjectSectionsMap =40SPSSequence<SPSTuple<SPSString, SPSExecutorAddrRange>>;4142using SPSCOFFJITDylibDepInfo = SPSSequence<SPSExecutorAddr>;4344using SPSCOFFJITDylibDepInfoMap =45SPSSequence<SPSTuple<SPSExecutorAddr, SPSCOFFJITDylibDepInfo>>;4647} // namespace __orc_rt4849ORC_RT_JIT_DISPATCH_TAG(__orc_rt_coff_symbol_lookup_tag)50ORC_RT_JIT_DISPATCH_TAG(__orc_rt_coff_push_initializers_tag)5152namespace {53class COFFPlatformRuntimeState {54private:55// Ctor/dtor section.56// Manage lists of *tor functions sorted by the last character of subsection57// name.58struct XtorSection {59void Register(char SubsectionChar, span<void (*)(void)> Xtors) {60Subsections[SubsectionChar - 'A'].push_back(Xtors);61SubsectionsNew[SubsectionChar - 'A'].push_back(Xtors);62}6364void RegisterNoRun(char SubsectionChar, span<void (*)(void)> Xtors) {65Subsections[SubsectionChar - 'A'].push_back(Xtors);66}6768void Reset() { SubsectionsNew = Subsections; }6970void RunAllNewAndFlush();7172private:73std::array<std::vector<span<void (*)(void)>>, 26> Subsections;74std::array<std::vector<span<void (*)(void)>>, 26> SubsectionsNew;75};7677struct JITDylibState {78std::string Name;79void *Header = nullptr;80size_t LinkedAgainstRefCount = 0;81size_t DlRefCount = 0;82std::vector<JITDylibState *> Deps;83std::vector<void (*)(void)> AtExits;84XtorSection CInitSection; // XIA~XIZ85XtorSection CXXInitSection; // XCA~XCZ86XtorSection CPreTermSection; // XPA~XPZ87XtorSection CTermSection; // XTA~XTZ8889bool referenced() const {90return LinkedAgainstRefCount != 0 || DlRefCount != 0;91}92};9394public:95static void initialize();96static COFFPlatformRuntimeState &get();97static bool isInitialized() { return CPS; }98static void destroy();99100COFFPlatformRuntimeState() = default;101102// Delete copy and move constructors.103COFFPlatformRuntimeState(const COFFPlatformRuntimeState &) = delete;104COFFPlatformRuntimeState &105operator=(const COFFPlatformRuntimeState &) = delete;106COFFPlatformRuntimeState(COFFPlatformRuntimeState &&) = delete;107COFFPlatformRuntimeState &operator=(COFFPlatformRuntimeState &&) = delete;108109const char *dlerror();110void *dlopen(std::string_view Name, int Mode);111int dlclose(void *Header);112void *dlsym(void *Header, std::string_view Symbol);113114Error registerJITDylib(std::string Name, void *Header);115Error deregisterJITDylib(void *Header);116117Error registerAtExit(ExecutorAddr HeaderAddr, void (*AtExit)(void));118119Error registerObjectSections(120ExecutorAddr HeaderAddr,121std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs,122bool RunInitializers);123Error deregisterObjectSections(124ExecutorAddr HeaderAddr,125std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs);126127void *findJITDylibBaseByPC(uint64_t PC);128129private:130Error registerBlockRange(ExecutorAddr HeaderAddr, ExecutorAddrRange Range);131Error deregisterBlockRange(ExecutorAddr HeaderAddr, ExecutorAddrRange Range);132133Error registerSEHFrames(ExecutorAddr HeaderAddr,134ExecutorAddrRange SEHFrameRange);135Error deregisterSEHFrames(ExecutorAddr HeaderAddr,136ExecutorAddrRange SEHFrameRange);137138Expected<void *> dlopenImpl(std::string_view Path, int Mode);139Error dlopenFull(JITDylibState &JDS);140Error dlopenInitialize(JITDylibState &JDS, COFFJITDylibDepInfoMap &DepInfo);141142Error dlcloseImpl(void *DSOHandle);143Error dlcloseDeinitialize(JITDylibState &JDS);144145JITDylibState *getJITDylibStateByHeader(void *DSOHandle);146JITDylibState *getJITDylibStateByName(std::string_view Path);147Expected<ExecutorAddr> lookupSymbolInJITDylib(void *DSOHandle,148std::string_view Symbol);149150static COFFPlatformRuntimeState *CPS;151152std::recursive_mutex JDStatesMutex;153std::map<void *, JITDylibState> JDStates;154struct BlockRange {155void *Header;156size_t Size;157};158std::map<void *, BlockRange> BlockRanges;159std::unordered_map<std::string_view, void *> JDNameToHeader;160std::string DLFcnError;161};162163} // namespace164165COFFPlatformRuntimeState *COFFPlatformRuntimeState::CPS = nullptr;166167COFFPlatformRuntimeState::JITDylibState *168COFFPlatformRuntimeState::getJITDylibStateByHeader(void *Header) {169auto I = JDStates.find(Header);170if (I == JDStates.end())171return nullptr;172return &I->second;173}174175COFFPlatformRuntimeState::JITDylibState *176COFFPlatformRuntimeState::getJITDylibStateByName(std::string_view Name) {177// FIXME: Avoid creating string copy here.178auto I = JDNameToHeader.find(std::string(Name.data(), Name.size()));179if (I == JDNameToHeader.end())180return nullptr;181void *H = I->second;182auto J = JDStates.find(H);183assert(J != JDStates.end() &&184"JITDylib has name map entry but no header map entry");185return &J->second;186}187188Error COFFPlatformRuntimeState::registerJITDylib(std::string Name,189void *Header) {190ORC_RT_DEBUG({191printdbg("Registering JITDylib %s: Header = %p\n", Name.c_str(), Header);192});193std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);194if (JDStates.count(Header)) {195std::ostringstream ErrStream;196ErrStream << "Duplicate JITDylib registration for header " << Header197<< " (name = " << Name << ")";198return make_error<StringError>(ErrStream.str());199}200if (JDNameToHeader.count(Name)) {201std::ostringstream ErrStream;202ErrStream << "Duplicate JITDylib registration for header " << Header203<< " (header = " << Header << ")";204return make_error<StringError>(ErrStream.str());205}206207auto &JDS = JDStates[Header];208JDS.Name = std::move(Name);209JDS.Header = Header;210JDNameToHeader[JDS.Name] = Header;211return Error::success();212}213214Error COFFPlatformRuntimeState::deregisterJITDylib(void *Header) {215std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);216auto I = JDStates.find(Header);217if (I == JDStates.end()) {218std::ostringstream ErrStream;219ErrStream << "Attempted to deregister unrecognized header " << Header;220return make_error<StringError>(ErrStream.str());221}222223// Remove std::string construction once we can use C++20.224auto J = JDNameToHeader.find(225std::string(I->second.Name.data(), I->second.Name.size()));226assert(J != JDNameToHeader.end() &&227"Missing JDNameToHeader entry for JITDylib");228229ORC_RT_DEBUG({230printdbg("Deregistering JITDylib %s: Header = %p\n", I->second.Name.c_str(),231Header);232});233234JDNameToHeader.erase(J);235JDStates.erase(I);236return Error::success();237}238239void COFFPlatformRuntimeState::XtorSection::RunAllNewAndFlush() {240for (auto &Subsection : SubsectionsNew) {241for (auto &XtorGroup : Subsection)242for (auto &Xtor : XtorGroup)243if (Xtor)244Xtor();245Subsection.clear();246}247}248249const char *COFFPlatformRuntimeState::dlerror() { return DLFcnError.c_str(); }250251void *COFFPlatformRuntimeState::dlopen(std::string_view Path, int Mode) {252ORC_RT_DEBUG({253std::string S(Path.data(), Path.size());254printdbg("COFFPlatform::dlopen(\"%s\")\n", S.c_str());255});256std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);257if (auto H = dlopenImpl(Path, Mode))258return *H;259else {260// FIXME: Make dlerror thread safe.261DLFcnError = toString(H.takeError());262return nullptr;263}264}265266int COFFPlatformRuntimeState::dlclose(void *DSOHandle) {267ORC_RT_DEBUG({268auto *JDS = getJITDylibStateByHeader(DSOHandle);269std::string DylibName;270if (JDS) {271std::string S;272printdbg("COFFPlatform::dlclose(%p) (%s)\n", DSOHandle, S.c_str());273} else274printdbg("COFFPlatform::dlclose(%p) (%s)\n", DSOHandle, "invalid handle");275});276std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);277if (auto Err = dlcloseImpl(DSOHandle)) {278// FIXME: Make dlerror thread safe.279DLFcnError = toString(std::move(Err));280return -1;281}282return 0;283}284285void *COFFPlatformRuntimeState::dlsym(void *Header, std::string_view Symbol) {286auto Addr = lookupSymbolInJITDylib(Header, Symbol);287if (!Addr) {288return 0;289}290291return Addr->toPtr<void *>();292}293294Expected<void *> COFFPlatformRuntimeState::dlopenImpl(std::string_view Path,295int Mode) {296// Try to find JITDylib state by name.297auto *JDS = getJITDylibStateByName(Path);298299if (!JDS)300return make_error<StringError>("No registered JTIDylib for path " +301std::string(Path.data(), Path.size()));302303if (auto Err = dlopenFull(*JDS))304return std::move(Err);305306// Bump the ref-count on this dylib.307++JDS->DlRefCount;308309// Return the header address.310return JDS->Header;311}312313Error COFFPlatformRuntimeState::dlopenFull(JITDylibState &JDS) {314// Call back to the JIT to push the initializers.315Expected<COFFJITDylibDepInfoMap> DepInfoMap((COFFJITDylibDepInfoMap()));316if (auto Err = WrapperFunction<SPSExpected<SPSCOFFJITDylibDepInfoMap>(317SPSExecutorAddr)>::call(&__orc_rt_coff_push_initializers_tag,318DepInfoMap,319ExecutorAddr::fromPtr(JDS.Header)))320return Err;321if (!DepInfoMap)322return DepInfoMap.takeError();323324if (auto Err = dlopenInitialize(JDS, *DepInfoMap))325return Err;326327if (!DepInfoMap->empty()) {328ORC_RT_DEBUG({329printdbg("Unrecognized dep-info key headers in dlopen of %s\n",330JDS.Name.c_str());331});332std::ostringstream ErrStream;333ErrStream << "Encountered unrecognized dep-info key headers "334"while processing dlopen of "335<< JDS.Name;336return make_error<StringError>(ErrStream.str());337}338339return Error::success();340}341342Error COFFPlatformRuntimeState::dlopenInitialize(343JITDylibState &JDS, COFFJITDylibDepInfoMap &DepInfo) {344ORC_RT_DEBUG({345printdbg("COFFPlatformRuntimeState::dlopenInitialize(\"%s\")\n",346JDS.Name.c_str());347});348349// Skip visited dependency.350auto I = DepInfo.find(ExecutorAddr::fromPtr(JDS.Header));351if (I == DepInfo.end())352return Error::success();353354auto DI = std::move(I->second);355DepInfo.erase(I);356357// Run initializers of dependencies in proper order by depth-first traversal358// of dependency graph.359std::vector<JITDylibState *> OldDeps;360std::swap(JDS.Deps, OldDeps);361JDS.Deps.reserve(DI.size());362for (auto DepHeaderAddr : DI) {363auto *DepJDS = getJITDylibStateByHeader(DepHeaderAddr.toPtr<void *>());364if (!DepJDS) {365std::ostringstream ErrStream;366ErrStream << "Encountered unrecognized dep header "367<< DepHeaderAddr.toPtr<void *>() << " while initializing "368<< JDS.Name;369return make_error<StringError>(ErrStream.str());370}371++DepJDS->LinkedAgainstRefCount;372if (auto Err = dlopenInitialize(*DepJDS, DepInfo))373return Err;374}375376// Run static initializers.377JDS.CInitSection.RunAllNewAndFlush();378JDS.CXXInitSection.RunAllNewAndFlush();379380// Decrement old deps.381for (auto *DepJDS : OldDeps) {382--DepJDS->LinkedAgainstRefCount;383if (!DepJDS->referenced())384if (auto Err = dlcloseDeinitialize(*DepJDS))385return Err;386}387388return Error::success();389}390391Error COFFPlatformRuntimeState::dlcloseImpl(void *DSOHandle) {392// Try to find JITDylib state by header.393auto *JDS = getJITDylibStateByHeader(DSOHandle);394395if (!JDS) {396std::ostringstream ErrStream;397ErrStream << "No registered JITDylib for " << DSOHandle;398return make_error<StringError>(ErrStream.str());399}400401// Bump the ref-count.402--JDS->DlRefCount;403404if (!JDS->referenced())405return dlcloseDeinitialize(*JDS);406407return Error::success();408}409410Error COFFPlatformRuntimeState::dlcloseDeinitialize(JITDylibState &JDS) {411ORC_RT_DEBUG({412printdbg("COFFPlatformRuntimeState::dlcloseDeinitialize(\"%s\")\n",413JDS.Name.c_str());414});415416// Run atexits417for (auto AtExit : JDS.AtExits)418AtExit();419JDS.AtExits.clear();420421// Run static terminators.422JDS.CPreTermSection.RunAllNewAndFlush();423JDS.CTermSection.RunAllNewAndFlush();424425// Queue all xtors as new again.426JDS.CInitSection.Reset();427JDS.CXXInitSection.Reset();428JDS.CPreTermSection.Reset();429JDS.CTermSection.Reset();430431// Deinitialize any dependencies.432for (auto *DepJDS : JDS.Deps) {433--DepJDS->LinkedAgainstRefCount;434if (!DepJDS->referenced())435if (auto Err = dlcloseDeinitialize(*DepJDS))436return Err;437}438439return Error::success();440}441442Expected<ExecutorAddr>443COFFPlatformRuntimeState::lookupSymbolInJITDylib(void *header,444std::string_view Sym) {445Expected<ExecutorAddr> Result((ExecutorAddr()));446if (auto Err = WrapperFunction<SPSExpected<SPSExecutorAddr>(447SPSExecutorAddr, SPSString)>::call(&__orc_rt_coff_symbol_lookup_tag,448Result,449ExecutorAddr::fromPtr(header),450Sym))451return std::move(Err);452return Result;453}454455Error COFFPlatformRuntimeState::registerObjectSections(456ExecutorAddr HeaderAddr,457std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs,458bool RunInitializers) {459std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);460auto I = JDStates.find(HeaderAddr.toPtr<void *>());461if (I == JDStates.end()) {462std::ostringstream ErrStream;463ErrStream << "Unrecognized header " << HeaderAddr.getValue();464return make_error<StringError>(ErrStream.str());465}466auto &JDState = I->second;467for (auto &KV : Secs) {468if (auto Err = registerBlockRange(HeaderAddr, KV.second))469return Err;470if (KV.first.empty())471continue;472char LastChar = KV.first.data()[KV.first.size() - 1];473if (KV.first == ".pdata") {474if (auto Err = registerSEHFrames(HeaderAddr, KV.second))475return Err;476} else if (KV.first >= ".CRT$XIA" && KV.first <= ".CRT$XIZ") {477if (RunInitializers)478JDState.CInitSection.Register(LastChar,479KV.second.toSpan<void (*)(void)>());480else481JDState.CInitSection.RegisterNoRun(LastChar,482KV.second.toSpan<void (*)(void)>());483} else if (KV.first >= ".CRT$XCA" && KV.first <= ".CRT$XCZ") {484if (RunInitializers)485JDState.CXXInitSection.Register(LastChar,486KV.second.toSpan<void (*)(void)>());487else488JDState.CXXInitSection.RegisterNoRun(489LastChar, KV.second.toSpan<void (*)(void)>());490} else if (KV.first >= ".CRT$XPA" && KV.first <= ".CRT$XPZ")491JDState.CPreTermSection.Register(LastChar,492KV.second.toSpan<void (*)(void)>());493else if (KV.first >= ".CRT$XTA" && KV.first <= ".CRT$XTZ")494JDState.CTermSection.Register(LastChar,495KV.second.toSpan<void (*)(void)>());496}497return Error::success();498}499500Error COFFPlatformRuntimeState::deregisterObjectSections(501ExecutorAddr HeaderAddr,502std::vector<std::pair<std::string_view, ExecutorAddrRange>> Secs) {503std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);504auto I = JDStates.find(HeaderAddr.toPtr<void *>());505if (I == JDStates.end()) {506std::ostringstream ErrStream;507ErrStream << "Attempted to deregister unrecognized header "508<< HeaderAddr.getValue();509return make_error<StringError>(ErrStream.str());510}511for (auto &KV : Secs) {512if (auto Err = deregisterBlockRange(HeaderAddr, KV.second))513return Err;514if (KV.first == ".pdata")515if (auto Err = deregisterSEHFrames(HeaderAddr, KV.second))516return Err;517}518return Error::success();519}520521Error COFFPlatformRuntimeState::registerSEHFrames(522ExecutorAddr HeaderAddr, ExecutorAddrRange SEHFrameRange) {523int N = (SEHFrameRange.End.getValue() - SEHFrameRange.Start.getValue()) /524sizeof(RUNTIME_FUNCTION);525auto Func = SEHFrameRange.Start.toPtr<PRUNTIME_FUNCTION>();526if (!RtlAddFunctionTable(Func, N,527static_cast<DWORD64>(HeaderAddr.getValue())))528return make_error<StringError>("Failed to register SEH frames");529return Error::success();530}531532Error COFFPlatformRuntimeState::deregisterSEHFrames(533ExecutorAddr HeaderAddr, ExecutorAddrRange SEHFrameRange) {534if (!RtlDeleteFunctionTable(SEHFrameRange.Start.toPtr<PRUNTIME_FUNCTION>()))535return make_error<StringError>("Failed to deregister SEH frames");536return Error::success();537}538539Error COFFPlatformRuntimeState::registerBlockRange(ExecutorAddr HeaderAddr,540ExecutorAddrRange Range) {541assert(!BlockRanges.count(Range.Start.toPtr<void *>()) &&542"Block range address already registered");543BlockRange B = {HeaderAddr.toPtr<void *>(), Range.size()};544BlockRanges.emplace(Range.Start.toPtr<void *>(), B);545return Error::success();546}547548Error COFFPlatformRuntimeState::deregisterBlockRange(ExecutorAddr HeaderAddr,549ExecutorAddrRange Range) {550assert(BlockRanges.count(Range.Start.toPtr<void *>()) &&551"Block range address not registered");552BlockRanges.erase(Range.Start.toPtr<void *>());553return Error::success();554}555556Error COFFPlatformRuntimeState::registerAtExit(ExecutorAddr HeaderAddr,557void (*AtExit)(void)) {558std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);559auto I = JDStates.find(HeaderAddr.toPtr<void *>());560if (I == JDStates.end()) {561std::ostringstream ErrStream;562ErrStream << "Unrecognized header " << HeaderAddr.getValue();563return make_error<StringError>(ErrStream.str());564}565I->second.AtExits.push_back(AtExit);566return Error::success();567}568569void COFFPlatformRuntimeState::initialize() {570assert(!CPS && "COFFPlatformRuntimeState should be null");571CPS = new COFFPlatformRuntimeState();572}573574COFFPlatformRuntimeState &COFFPlatformRuntimeState::get() {575assert(CPS && "COFFPlatformRuntimeState not initialized");576return *CPS;577}578579void COFFPlatformRuntimeState::destroy() {580assert(CPS && "COFFPlatformRuntimeState not initialized");581delete CPS;582}583584void *COFFPlatformRuntimeState::findJITDylibBaseByPC(uint64_t PC) {585std::lock_guard<std::recursive_mutex> Lock(JDStatesMutex);586auto It = BlockRanges.upper_bound(reinterpret_cast<void *>(PC));587if (It == BlockRanges.begin())588return nullptr;589--It;590auto &Range = It->second;591if (PC >= reinterpret_cast<uint64_t>(It->first) + Range.Size)592return nullptr;593return Range.Header;594}595596ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult597__orc_rt_coff_platform_bootstrap(char *ArgData, size_t ArgSize) {598COFFPlatformRuntimeState::initialize();599return WrapperFunctionResult().release();600}601602ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult603__orc_rt_coff_platform_shutdown(char *ArgData, size_t ArgSize) {604COFFPlatformRuntimeState::destroy();605return WrapperFunctionResult().release();606}607608ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult609__orc_rt_coff_register_jitdylib(char *ArgData, size_t ArgSize) {610return WrapperFunction<SPSError(SPSString, SPSExecutorAddr)>::handle(611ArgData, ArgSize,612[](std::string &Name, ExecutorAddr HeaderAddr) {613return COFFPlatformRuntimeState::get().registerJITDylib(614std::move(Name), HeaderAddr.toPtr<void *>());615})616.release();617}618619ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult620__orc_rt_coff_deregister_jitdylib(char *ArgData, size_t ArgSize) {621return WrapperFunction<SPSError(SPSExecutorAddr)>::handle(622ArgData, ArgSize,623[](ExecutorAddr HeaderAddr) {624return COFFPlatformRuntimeState::get().deregisterJITDylib(625HeaderAddr.toPtr<void *>());626})627.release();628}629630ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult631__orc_rt_coff_register_object_sections(char *ArgData, size_t ArgSize) {632return WrapperFunction<SPSError(SPSExecutorAddr, SPSCOFFObjectSectionsMap,633bool)>::634handle(ArgData, ArgSize,635[](ExecutorAddr HeaderAddr,636std::vector<std::pair<std::string_view, ExecutorAddrRange>>637&Secs,638bool RunInitializers) {639return COFFPlatformRuntimeState::get().registerObjectSections(640HeaderAddr, std::move(Secs), RunInitializers);641})642.release();643}644645ORC_RT_INTERFACE orc_rt_CWrapperFunctionResult646__orc_rt_coff_deregister_object_sections(char *ArgData, size_t ArgSize) {647return WrapperFunction<SPSError(SPSExecutorAddr, SPSCOFFObjectSectionsMap)>::648handle(ArgData, ArgSize,649[](ExecutorAddr HeaderAddr,650std::vector<std::pair<std::string_view, ExecutorAddrRange>>651&Secs) {652return COFFPlatformRuntimeState::get().deregisterObjectSections(653HeaderAddr, std::move(Secs));654})655.release();656}657//------------------------------------------------------------------------------658// JIT'd dlfcn alternatives.659//------------------------------------------------------------------------------660661const char *__orc_rt_coff_jit_dlerror() {662return COFFPlatformRuntimeState::get().dlerror();663}664665void *__orc_rt_coff_jit_dlopen(const char *path, int mode) {666return COFFPlatformRuntimeState::get().dlopen(path, mode);667}668669int __orc_rt_coff_jit_dlclose(void *header) {670return COFFPlatformRuntimeState::get().dlclose(header);671}672673void *__orc_rt_coff_jit_dlsym(void *header, const char *symbol) {674return COFFPlatformRuntimeState::get().dlsym(header, symbol);675}676677//------------------------------------------------------------------------------678// COFF SEH exception support679//------------------------------------------------------------------------------680681struct ThrowInfo {682uint32_t attributes;683void *data;684};685686ORC_RT_INTERFACE void __stdcall __orc_rt_coff_cxx_throw_exception(687void *pExceptionObject, ThrowInfo *pThrowInfo) {688#ifdef __clang__689#pragma clang diagnostic push690#pragma clang diagnostic ignored "-Wmultichar"691#endif692constexpr uint32_t EH_EXCEPTION_NUMBER = 'msc' | 0xE0000000;693#ifdef __clang__694#pragma clang diagnostic pop695#endif696constexpr uint32_t EH_MAGIC_NUMBER1 = 0x19930520;697auto BaseAddr = COFFPlatformRuntimeState::get().findJITDylibBaseByPC(698reinterpret_cast<uint64_t>(pThrowInfo));699if (!BaseAddr) {700// This is not from JIT'd region.701// FIXME: Use the default implementation like below when alias api is702// capable. _CxxThrowException(pExceptionObject, pThrowInfo);703fprintf(stderr, "Throwing exception from compiled callback into JIT'd "704"exception handler not supported yet.\n");705abort();706return;707}708const ULONG_PTR parameters[] = {709EH_MAGIC_NUMBER1,710reinterpret_cast<ULONG_PTR>(pExceptionObject),711reinterpret_cast<ULONG_PTR>(pThrowInfo),712reinterpret_cast<ULONG_PTR>(BaseAddr),713};714RaiseException(EH_EXCEPTION_NUMBER, EXCEPTION_NONCONTINUABLE,715_countof(parameters), parameters);716}717718//------------------------------------------------------------------------------719// COFF atexits720//------------------------------------------------------------------------------721722typedef int (*OnExitFunction)(void);723typedef void (*AtExitFunction)(void);724725ORC_RT_INTERFACE OnExitFunction __orc_rt_coff_onexit(void *Header,726OnExitFunction Func) {727if (auto Err = COFFPlatformRuntimeState::get().registerAtExit(728ExecutorAddr::fromPtr(Header), (void (*)(void))Func)) {729consumeError(std::move(Err));730return nullptr;731}732return Func;733}734735ORC_RT_INTERFACE int __orc_rt_coff_atexit(void *Header, AtExitFunction Func) {736if (auto Err = COFFPlatformRuntimeState::get().registerAtExit(737ExecutorAddr::fromPtr(Header), (void (*)(void))Func)) {738consumeError(std::move(Err));739return -1;740}741return 0;742}743744//------------------------------------------------------------------------------745// COFF Run Program746//------------------------------------------------------------------------------747748ORC_RT_INTERFACE int64_t __orc_rt_coff_run_program(const char *JITDylibName,749const char *EntrySymbolName,750int argc, char *argv[]) {751using MainTy = int (*)(int, char *[]);752753void *H =754__orc_rt_coff_jit_dlopen(JITDylibName, __orc_rt::coff::ORC_RT_RTLD_LAZY);755if (!H) {756__orc_rt_log_error(__orc_rt_coff_jit_dlerror());757return -1;758}759760auto *Main =761reinterpret_cast<MainTy>(__orc_rt_coff_jit_dlsym(H, EntrySymbolName));762763if (!Main) {764__orc_rt_log_error(__orc_rt_coff_jit_dlerror());765return -1;766}767768int Result = Main(argc, argv);769770if (__orc_rt_coff_jit_dlclose(H) == -1)771__orc_rt_log_error(__orc_rt_coff_jit_dlerror());772773return Result;774}775776777