Skip to content

Commit af76c92

Browse files
Add support for inline pinvokes to Wasm Ryujit (#130384)
- They should always be READYTORUN_FIXUP_PInvokeTarget instead of READYTORUN_FIXUP_IndirectPInvokeTarget - There is a debug version of JIT_PinvokeEnd which validates that sp == the __stack_pointer global. I believe our codegen will maintain this invariant, so we should be ok to skip resetting the __stack_pointer global before calls to the C++ implementation of JIT_PInvokeEnd - One detail which is no longer true after this work is merged is that the __stack_pointer global will be set to increasingly unpredictable values during execution. This is not a new phenomena, as it was happening during EH flow, but now it will happen in normal execution flow. Since the interpreter to R2R thunks will reset the stack before we return to any emscripten compiled code, we should be ok with this. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 3a8b52c commit af76c92

4 files changed

Lines changed: 100 additions & 11 deletions

File tree

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3220,8 +3220,12 @@ private void getAddressOfPInvokeTarget(CORINFO_METHOD_STRUCT_* method, ref CORIN
32203220
ModuleToken moduleToken = new ModuleToken(ecmaMethod.Module, ecmaMethod.Handle);
32213221
MethodWithToken methodWithToken = new MethodWithToken(ecmaMethod, moduleToken, constrainedType: null, unboxing: false, genericContextObject: null);
32223222

3223-
if ((ecmaMethod.GetPInvokeMethodCallingConventions() & UnmanagedCallingConventions.IsSuppressGcTransition) != 0)
3223+
if (((ecmaMethod.GetPInvokeMethodCallingConventions() & UnmanagedCallingConventions.IsSuppressGcTransition) != 0)
3224+
|| _compilation.NodeFactory.Target.IsWasm)
32243225
{
3226+
// Suppress GC transition P/Invokes are called directly, since we can't do a GC transition at this point.
3227+
// On Wasm, we also call directly because the runtime doesn't generate P/Invoke import precodes/stubs; instead,
3228+
// errors are reported when we fix up the method.
32253229
pLookup.addr = (void*)ObjectToHandle(_compilation.SymbolNodeFactory.GetPInvokeTargetNode(methodWithToken));
32263230
pLookup.accessType = InfoAccessType.IAT_PVALUE;
32273231
}

‎src/coreclr/vm/jithelpers.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1114,7 +1114,7 @@ HRESULT EEToProfInterfaceImpl::SetEnterLeaveFunctionHooksForJit(FunctionEnter3 *
11141114
// tailored to the post-pinvoke operations.
11151115
extern "C" VOID JIT_PInvokeEndRarePath();
11161116

1117-
void JIT_PInvokeEndRarePath()
1117+
NOINLINE void JIT_PInvokeEndRarePath()
11181118
{
11191119
PreserveLastErrorHolder preserveLastError;
11201120

‎src/coreclr/vm/jitinterface.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14334,6 +14334,7 @@ BOOL LoadDynamicInfoEntry(Module *currentModule,
1433414334
}
1433514335
break;
1433614336

14337+
#ifdef HAS_PINVOKE_IMPORT_PRECODE
1433714338
case READYTORUN_FIXUP_IndirectPInvokeTarget:
1433814339
{
1433914340
MethodDesc *pMethod = ZapSig::DecodeMethod(currentModule, pInfoModule, pBlob);
@@ -14343,6 +14344,7 @@ BOOL LoadDynamicInfoEntry(Module *currentModule,
1434314344
result = (size_t)(LPVOID)&(pMD->m_pPInvokeTarget);
1434414345
}
1434514346
break;
14347+
#endif // HAS_PINVOKE_IMPORT_PRECODE
1434614348

1434714349
case READYTORUN_FIXUP_PInvokeTarget:
1434814350
{

‎src/coreclr/vm/wasm/helpers.cpp‎

Lines changed: 92 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
#define WASM_STRINGIFY_HELPER(value) #value
1515
#define WASM_STRINGIFY(value) WASM_STRINGIFY_HELPER(value)
16+
#define INLINED_PINVOKE_FROM_R2R 1
1617

1718
void ExecuteInterpretedMethodWithArgs_PortableEntryPoint(PCODE portableEntrypoint, TransitionBlock* block, size_t argsSize, int8_t* retBuff);
1819

@@ -491,13 +492,22 @@ void InlinedCallFrame::UpdateRegDisplay_Impl(const PREGDISPLAY pRD, bool updateF
491492
return;
492493
}
493494

494-
pRD->pCurrentContext->InterpreterIP = *(DWORD *)&m_pCallerReturnAddress;
495-
496495
pRD->IsCallerContextValid = FALSE;
497496

498-
pRD->pCurrentContext->InterpreterSP = *(DWORD *)&m_pCallSiteSP;
499-
pRD->pCurrentContext->InterpreterFP = *(DWORD *)&m_pCalleeSavedFP;
500-
497+
if (m_pCallerReturnAddress == INLINED_PINVOKE_FROM_R2R)
498+
{
499+
pRD->pCurrentContext->InterpreterSP = (TADDR)m_pCallSiteSP;
500+
pRD->pCurrentContext->InterpreterIP = GetWasmVirtualIPFromStackPointer((TADDR)m_pCallSiteSP);
501+
_ASSERTE(pRD->pCurrentContext->InterpreterIP != 0); // We should be in RyuJit compiled code here
502+
pRD->pCurrentContext->InterpreterFP = GetWasmFramePointerFromStackPointer((TADDR)m_pCallSiteSP, (PCODE)pRD->pCurrentContext->InterpreterIP);
503+
}
504+
else
505+
{
506+
pRD->pCurrentContext->InterpreterIP = *(DWORD *)&m_pCallerReturnAddress;
507+
pRD->pCurrentContext->InterpreterSP = *(DWORD *)&m_pCallSiteSP;
508+
pRD->pCurrentContext->InterpreterFP = *(DWORD *)&m_pCalleeSavedFP;
509+
}
510+
501511
SyncRegDisplayToCurrentContext(pRD);
502512

503513
#ifdef FEATURE_INTERPRETER
@@ -681,15 +691,88 @@ extern "C" void STDCALL GenericPInvokeCalliHelper(void)
681691
PORTABILITY_ASSERT("GenericPInvokeCalliHelper is not implemented on wasm");
682692
}
683693

684-
EXTERN_C void JIT_PInvokeBegin(InlinedCallFrame* pFrame)
694+
// Does the pinvoke frame transition; the naked wrappers below have already set the wasm
695+
// __stack_pointer global to sp so it is safe to run native code here.
696+
EXTERN_C void JIT_PInvokeBeginImpl(void* sp, InlinedCallFrame* pFrame)
697+
{
698+
Thread* pThread = GetThread();
699+
700+
// Initialize the JIT-provided frame storage, deriving its state from sp/pep since wasm
701+
// has no machine registers to read the caller SP / return address from.
702+
::new ((void*)pFrame) InlinedCallFrame();
703+
pFrame->m_pCallSiteSP = sp;
704+
pFrame->m_pCallerReturnAddress = INLINED_PINVOKE_FROM_R2R; // When this is true, UpdateRegDisplay_Impl derives state from m_pCallSiteSP.
705+
pFrame->m_pCalleeSavedFP = 0;
706+
pFrame->m_pThread = pThread;
707+
708+
// Link the frame and transition to preemptive GC mode for the native call.
709+
pFrame->Push();
710+
pThread->EnablePreemptiveGC();
711+
}
712+
713+
// R2R keeps its shadow SP in a local and leaves the __stack_pointer global stale, so publish
714+
// the incoming sp to __stack_pointer before any native code runs and leave it there so the
715+
// subsequent native pinvoke target is also safe.
716+
extern "C" __attribute__((naked)) void JIT_PInvokeBegin(void* sp, InlinedCallFrame* pFrame, PCODE pep)
717+
{
718+
asm("local.get 0\n" /* sp */
719+
"global.set __stack_pointer\n" /* __stack_pointer = sp before any native code runs */
720+
"local.get 0\n" /* sp */
721+
"local.get 1\n" /* pFrame */
722+
"call %0\n"
723+
"return" ::"i"(JIT_PInvokeBeginImpl));
724+
}
725+
726+
extern "C" VOID JIT_PInvokeEndRarePath();
727+
728+
#ifdef DEBUG
729+
// Debug variant of these apis tests that sp and __stack_pointer are in sync
730+
EXTERN_C void JIT_PInvokeEndImpl(TADDR sp, TADDR stack_pointer_global_value, InlinedCallFrame* pFrame)
685731
{
686-
PORTABILITY_ASSERT("JIT_PInvokeBegin is not implemented on wasm");
732+
_ASSERTE(sp == stack_pointer_global_value);
733+
Thread* pThread = (Thread*)pFrame->m_pThread;
734+
735+
pThread->m_fPreemptiveGCDisabled.StoreWithoutBarrier(1);
736+
if (g_TrapReturningThreads)
737+
{
738+
JIT_PInvokeEndRarePath();
739+
}
740+
else
741+
{
742+
pFrame->Pop();
743+
}
687744
}
688745

689-
EXTERN_C void JIT_PInvokeEnd(InlinedCallFrame* pFrame)
746+
extern "C" __attribute__((naked)) void JIT_PInvokeEnd(void* sp, InlinedCallFrame* pFrame, PCODE pep)
747+
{
748+
asm(
749+
"local.get 0\n" /* sp */
750+
"global.get __stack_pointer\n" /* __stack_pointer */
751+
"local.get 1\n" /* pFrame */
752+
"local.get 0\n" /* sp */
753+
"global.set __stack_pointer\n" /* __stack_pointer = sp before any native code runs, set this here, so that if the assumption around sp == __stack_pointer is wrong the assert logic will work correctly. */
754+
"call %0\n"
755+
"return" ::"i"(JIT_PInvokeEndImpl));
756+
}
757+
#else
758+
extern "C" void JIT_PInvokeEnd(void* sp, InlinedCallFrame* pFrame, PCODE pep)
690759
{
691-
PORTABILITY_ASSERT("JIT_PInvokeEnd is not implemented on wasm");
760+
UNREFERENCED_PARAMETER(sp);
761+
UNREFERENCED_PARAMETER(pep);
762+
763+
Thread* pThread = (Thread*)pFrame->m_pThread;
764+
765+
pThread->m_fPreemptiveGCDisabled.StoreWithoutBarrier(1);
766+
if (g_TrapReturningThreads)
767+
{
768+
JIT_PInvokeEndRarePath();
769+
}
770+
else
771+
{
772+
pFrame->Pop();
773+
}
692774
}
775+
#endif
693776

694777
extern "C" void STDCALL JIT_StackProbe()
695778
{

0 commit comments

Comments
 (0)