Skip to content

Commit ca1f976

Browse files
committed
Defer WASI finalization to WasiEventLoop instead of running it inline
EnableFinalization is called from inside the GC. The previous WASI implementation ran FinalizerThreadWorkerIteration synchronously from there, which is unsafe: - FinalizerThreadWorkerIteration declares GC_TRIGGERS, so finalizers can request another GC while we are mid-collection. - It transitions thread mode via EnablePreemptiveGC and back to cooperative, which is not legal from inside a GC. - Finalizer-triggered allocations can recurse into EnableFinalization with unbounded stack depth. - Tests that rely on the semantics of finalizers running on a dedicated context (GC.WaitForPendingFinalizers and friends) observe the wrong behavior. Mirror the browser pattern: native EnableFinalization calls SystemJS_ScheduleFinalization, which on WASI dispatches to a function pointer that managed code installed at startup. The managed callback queues SystemJS_ExecuteFinalizationCallback through ThreadPool.UnsafeQueueUserWorkItem so it runs from WasiEventLoop's ThreadPoolWorkQueue.Dispatch() pump, at a point where mode transitions and re-entry into the GC are safe. Pieces: - src/coreclr/vm/finalizerthread.cpp - Hoist SystemJS_ExecuteFinalizationCallback out of the TARGET_BROWSER block so WASI can call back into it. - Add WasiFinalizerScheduler_Register QCall that stores the managed callback pointer, and a SystemJS_ScheduleFinalization implementation for WASI that forwards to it. - Replace the synchronous FinalizerThreadWorkerIteration call in EnableFinalization with SystemJS_ScheduleFinalization. - src/coreclr/vm/wasm/entrypoints.h, src/coreclr/vm/qcallentrypoints.cpp - Declare and register the new WASI entry points. - src/libraries/System.Private.CoreLib/src/System/Threading/Wasi/WasiFinalizerScheduler.cs - New managed-side bridge. ModuleInitializer-driven Register call installs the function pointer; the [UnmanagedCallersOnly] callback queues the work onto ThreadPool. Followups: - Rename SystemJS_* to a host-neutral prefix; the JS naming is inherited from the browser path and is misleading for WASI. - Consider exposing SystemJS_ExecuteFinalizationCallback under a WASI-specific name once the rename lands. Co-authored-by: Copilot <[email protected]>
1 parent a085400 commit ca1f976

6 files changed

Lines changed: 137 additions & 6 deletions

File tree

‎src/coreclr/vm/finalizerthread.cpp‎

Lines changed: 46 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ bool FinalizerThread::IsCurrentThreadFinalizer()
4343
return GetThreadNULLOk() == g_pFinalizerThread;
4444
}
4545

46-
#ifdef TARGET_BROWSER
46+
#if defined(TARGET_BROWSER) || defined(TARGET_WASI)
4747

4848
extern "C" void SystemJS_ScheduleFinalization();
4949

@@ -65,7 +65,44 @@ extern "C" void SystemJS_ExecuteFinalizationCallback()
6565
UNINSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP;
6666
}
6767

68-
#endif // TARGET_BROWSER
68+
#endif // TARGET_BROWSER || TARGET_WASI
69+
70+
#ifdef TARGET_WASI
71+
72+
// Managed code (System.Threading.WasiFinalizerScheduler) registers a callback
73+
// here at startup. The callback uses ThreadPool.UnsafeQueueUserWorkItem to
74+
// defer SystemJS_ExecuteFinalizationCallback to the WasiEventLoop pump, so
75+
// finalization never runs inline from EnableFinalization (which is called
76+
// from inside the GC). Mirrors the browser pattern where the JS event loop
77+
// supplies the deferred-execution mechanism.
78+
typedef void (*WasiScheduleFinalizationFn)();
79+
static WasiScheduleFinalizationFn s_wasiScheduleFinalization = nullptr;
80+
81+
extern "C" void QCALLTYPE WasiFinalizerScheduler_Register(WasiScheduleFinalizationFn callback)
82+
{
83+
QCALL_CONTRACT;
84+
BEGIN_QCALL;
85+
s_wasiScheduleFinalization = callback;
86+
END_QCALL;
87+
}
88+
89+
extern "C" void SystemJS_ScheduleFinalization()
90+
{
91+
if (s_wasiScheduleFinalization != nullptr)
92+
{
93+
s_wasiScheduleFinalization();
94+
}
95+
else
96+
{
97+
// Startup race window before WasiFinalizerScheduler.Register runs.
98+
// Falling back to a no-op is safe: the GC will request finalization
99+
// again on the next collection. The first such collection on WASI
100+
// typically happens after CoreLib is initialized, so this branch
101+
// should never fire in practice.
102+
}
103+
}
104+
105+
#endif // TARGET_WASI
69106

70107
void FinalizerThread::EnableFinalization()
71108
{
@@ -74,11 +111,14 @@ void FinalizerThread::EnableFinalization()
74111
#ifndef TARGET_WASM
75112
hEventFinalizer->Set();
76113
#else // !TARGET_WASM
77-
#ifdef TARGET_BROWSER
114+
// Defer finalization to the host's event loop. Running it inline from here
115+
// is unsafe: EnableFinalization is called from inside the GC, while
116+
// FinalizerThreadWorkerIteration declares GC_TRIGGERS + MODE_COOPERATIVE
117+
// and re-enters preemptive mode via EnablePreemptiveGC(). Re-entering the
118+
// GC, transitioning thread modes from inside a collection, and the risk
119+
// of unbounded recursion through finalizer-triggered allocations all make
120+
// synchronous execution wrong here.
78121
SystemJS_ScheduleFinalization();
79-
#else
80-
// WASI is not implemented yet
81-
#endif // TARGET_BROWSER
82122
#endif // !TARGET_WASM
83123
}
84124

‎src/coreclr/vm/qcallentrypoints.cpp‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@
7878
#include "entrypoints.h"
7979
#endif // TARGET_BROWSER
8080

81+
#ifdef TARGET_WASI
82+
#include "wasm/entrypoints.h"
83+
#endif // TARGET_WASI
84+
8185
#ifdef FEATURE_INTERPRETER
8286
#include "interpexec.h"
8387
#endif // FEATURE_INTERPRETER
@@ -541,6 +545,10 @@ static const Entry s_QCall[] =
541545
DllImportEntry(SystemJS_ScheduleTimer)
542546
DllImportEntry(SystemJS_ScheduleBackgroundJob)
543547
#endif // TARGET_BROWSER
548+
#ifdef TARGET_WASI
549+
DllImportEntry(WasiFinalizerScheduler_Register)
550+
DllImportEntry(SystemJS_ExecuteFinalizationCallback)
551+
#endif // TARGET_WASI
544552
};
545553

546554
const void* QCallResolveDllImport(const char* name)

‎src/coreclr/vm/wasm/callhelpers-reverse.cpp‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1182,6 +1182,21 @@ extern "C" void SystemJS_ExecuteTimerCallback()
11821182
Call_System_Private_CoreLib_System_Threading_TimerQueue_TimerHandler_Void_RetVoid();
11831183
}
11841184

1185+
// MANUAL ADDITION: matches WasiFinalizerScheduler.cs (deferred-finalization
1186+
// support added in this branch). Regenerating the file from an updated CoreLib
1187+
// scan should produce the same entry; until that pipeline is wired up, keep
1188+
// this in sync with the C# class.
1189+
static MethodDesc* MD_System_Private_CoreLib_System_Threading_WasiFinalizerScheduler_ScheduleFinalization_Void_RetVoid = nullptr;
1190+
static void Call_System_Private_CoreLib_System_Threading_WasiFinalizerScheduler_ScheduleFinalization_Void_RetVoid()
1191+
{
1192+
// Lazy lookup of MethodDesc for the function export scenario.
1193+
if (!MD_System_Private_CoreLib_System_Threading_WasiFinalizerScheduler_ScheduleFinalization_Void_RetVoid)
1194+
{
1195+
LookupUnmanagedCallersOnlyMethodByName("System.Threading.WasiFinalizerScheduler, System.Private.CoreLib", "ScheduleFinalization", &MD_System_Private_CoreLib_System_Threading_WasiFinalizerScheduler_ScheduleFinalization_Void_RetVoid);
1196+
}
1197+
ExecuteInterpretedMethodFromUnmanaged(MD_System_Private_CoreLib_System_Threading_WasiFinalizerScheduler_ScheduleFinalization_Void_RetVoid, nullptr, 0, nullptr, (PCODE)&Call_System_Private_CoreLib_System_Threading_WasiFinalizerScheduler_ScheduleFinalization_Void_RetVoid);
1198+
}
1199+
11851200
const ReverseThunkMapEntry g_ReverseThunks[] =
11861201
{
11871202
{ 3863938719, "<RegisterNoGCRegionCallback>g__Callback|72_0#1:System.Private.CoreLib:System:GC", { &MD_System_Private_CoreLib_System_GC__RegisterNoGCRegionCallback_g__Callback_7C_72_0_I32_RetVoid, (void*)&Call_System_Private_CoreLib_System_GC__RegisterNoGCRegionCallback_g__Callback_7C_72_0_I32_RetVoid } },
@@ -1263,6 +1278,8 @@ const ReverseThunkMapEntry g_ReverseThunks[] =
12631278
{ 3929107505, "RhThrowEx#2:System.Private.CoreLib:System.Runtime:EH", { &MD_System_Private_CoreLib_System_Runtime_EH_RhThrowEx_I32_I32_RetVoid, (void*)&Call_System_Private_CoreLib_System_Runtime_EH_RhThrowEx_I32_I32_RetVoid } },
12641279
{ 504238190, "RhThrowHwEx#2:System.Private.CoreLib:System.Runtime:EH", { &MD_System_Private_CoreLib_System_Runtime_EH_RhThrowHwEx_I32_I32_RetVoid, (void*)&Call_System_Private_CoreLib_System_Runtime_EH_RhThrowHwEx_I32_I32_RetVoid } },
12651280
{ 4273572779, "RunFinalizers#0:System.Private.CoreLib:System:GC", { &MD_System_Private_CoreLib_System_GC_RunFinalizers_Void_RetI32, (void*)&Call_System_Private_CoreLib_System_GC_RunFinalizers_Void_RetI32 } },
1281+
// MANUAL ADDITION: see Call_/MD_ definitions above for context.
1282+
{ 1007743593, "ScheduleFinalization#0:System.Private.CoreLib:System.Threading:WasiFinalizerScheduler", { &MD_System_Private_CoreLib_System_Threading_WasiFinalizerScheduler_ScheduleFinalization_Void_RetVoid, (void*)&Call_System_Private_CoreLib_System_Threading_WasiFinalizerScheduler_ScheduleFinalization_Void_RetVoid } },
12661283
{ 1963568864, "Setup#4:System.Private.CoreLib:System:AppContext", { &MD_System_Private_CoreLib_System_AppContext_Setup_I32_I32_I32_I32_RetVoid, (void*)&Call_System_Private_CoreLib_System_AppContext_Setup_I32_I32_I32_I32_RetVoid } },
12671284
{ 1343309100, "StartAssemblyLoad#3:System.Private.CoreLib:System.Runtime.Loader:AssemblyLoadContext", { &MD_System_Private_CoreLib_System_Runtime_Loader_AssemblyLoadContext_StartAssemblyLoad_I32_I32_I32_RetVoid, (void*)&Call_System_Private_CoreLib_System_Runtime_Loader_AssemblyLoadContext_StartAssemblyLoad_I32_I32_I32_RetVoid } },
12681285
{ 3372184251, "StartCallback#1:System.Private.CoreLib:System.Threading:Thread", { &MD_System_Private_CoreLib_System_Threading_Thread_StartCallback_I32_RetVoid, (void*)&Call_System_Private_CoreLib_System_Threading_Thread_StartCallback_I32_RetVoid } },

‎src/coreclr/vm/wasm/entrypoints.h‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,15 @@ extern "C" void SystemJS_DiagnosticServerQueueJob(size_t (*cb)(void *data), void
1717

1818
#endif
1919

20+
#ifdef TARGET_WASI
21+
// Native callback that runs the finalizer worker; called by managed code from
22+
// the WasiEventLoop pump after EnableFinalization schedules it via
23+
// WasiFinalizerScheduler. See src/coreclr/vm/finalizerthread.cpp.
24+
extern "C" void SystemJS_ExecuteFinalizationCallback();
25+
// Registration entry point used by managed System.Threading.WasiFinalizerScheduler
26+
// to install its ThreadPool-based scheduling callback at startup.
27+
typedef void (*WasiScheduleFinalizationFn)();
28+
extern "C" void QCALLTYPE WasiFinalizerScheduler_Register(WasiScheduleFinalizationFn callback);
29+
#endif // TARGET_WASI
30+
2031
#endif // HAVE_WASM_ENTRYPOINTS_H

‎src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2993,6 +2993,7 @@
29932993
</ItemGroup>
29942994
<ItemGroup Condition="'$(TargetsWasi)' == 'true'">
29952995
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\Wasi\WasiEventLoop.cs" />
2996+
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\Wasi\WasiFinalizerScheduler.cs" />
29962997
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\Wasi\WasiPoll.cs" />
29972998
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\Wasi\WasiPollWorld.wit.Imports.wasi.clocks.v0_2_8.IMonotonicClockImports.cs" />
29982999
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\Wasi\WasiPollWorld.wit.Imports.wasi.clocks.v0_2_8.MonotonicClockImportsInterop.cs" />
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System.Runtime.CompilerServices;
5+
using System.Runtime.InteropServices;
6+
7+
namespace System.Threading
8+
{
9+
// Bridges the CoreCLR native finalizer thread machinery to the WASI event loop.
10+
//
11+
// On WASI there is no separate finalizer thread and no JavaScript event loop
12+
// to defer work to. Native FinalizerThread::EnableFinalization() is invoked
13+
// from within the GC, so it cannot run FinalizerThreadWorkerIteration inline
14+
// (the worker iteration declares GC_TRIGGERS + MODE_COOPERATIVE and switches
15+
// thread mode via EnablePreemptiveGC, which is unsafe to do mid-collection).
16+
//
17+
// Instead, native EnableFinalization calls SystemJS_ScheduleFinalization,
18+
// which dispatches to the function pointer registered here at startup.
19+
// That callback queues SystemJS_ExecuteFinalizationCallback through the
20+
// ThreadPool, where it is picked up by WasiEventLoop's pump at a safe point.
21+
//
22+
// This is the WASI analog of the browser's setTimeout(..., 0) pattern in
23+
// src/native/libs/System.Native.Browser/native/scheduling.ts.
24+
internal static unsafe partial class WasiFinalizerScheduler
25+
{
26+
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "WasiFinalizerScheduler_Register")]
27+
private static partial void Register(delegate* unmanaged<void> callback);
28+
29+
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "SystemJS_ExecuteFinalizationCallback")]
30+
private static partial void ExecuteFinalizationCallback();
31+
32+
#pragma warning disable CA2255 // ModuleInitializer is used here to register the
33+
// scheduler before any GC-driven EnableFinalization
34+
// call. In CoreCLR coreclr_initialize triggers the
35+
// module initializer of CoreLib early enough that
36+
// the function pointer is installed before the GC
37+
// begins requesting finalization.
38+
39+
[ModuleInitializer]
40+
#pragma warning restore CA2255
41+
internal static void Initialize()
42+
{
43+
Register(&ScheduleFinalization);
44+
}
45+
46+
[UnmanagedCallersOnly]
47+
private static void ScheduleFinalization()
48+
{
49+
// UnsafeQueueUserWorkItem doesn't flow ExecutionContext; finalization
50+
// semantically owns its own context anyway.
51+
ThreadPool.UnsafeQueueUserWorkItem(static _ => ExecuteFinalizationCallback(), state: (object?)null, preferLocal: false);
52+
}
53+
}
54+
}

0 commit comments

Comments
 (0)