Skip to content

Commit f83ba68

Browse files
lewingCopilot
andcommitted
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 57c0396 commit f83ba68

5 files changed

Lines changed: 120 additions & 7 deletions

File tree

‎src/coreclr/vm/finalizerthread.cpp‎

Lines changed: 46 additions & 7 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,12 +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: run finalization synchronously (no separate thread, no JS event loop)
81-
FinalizerThreadWorkerIteration(nullptr);
82-
#endif // TARGET_BROWSER
83122
#endif // !TARGET_WASM
84123
}
85124

‎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
@@ -540,6 +544,10 @@ static const Entry s_QCall[] =
540544
DllImportEntry(SystemJS_ScheduleTimer)
541545
DllImportEntry(SystemJS_ScheduleBackgroundJob)
542546
#endif // TARGET_BROWSER
547+
#ifdef TARGET_WASI
548+
DllImportEntry(WasiFinalizerScheduler_Register)
549+
DllImportEntry(SystemJS_ExecuteFinalizationCallback)
550+
#endif // TARGET_WASI
543551
};
544552

545553
const void* QCallResolveDllImport(const char* name)

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,15 @@ extern "C" void SystemJS_ScheduleBackgroundJob();
1616

1717
#endif
1818

19+
#ifdef TARGET_WASI
20+
// Native callback that runs the finalizer worker; called by managed code from
21+
// the WasiEventLoop pump after EnableFinalization schedules it via
22+
// WasiFinalizerScheduler. See src/coreclr/vm/finalizerthread.cpp.
23+
extern "C" void SystemJS_ExecuteFinalizationCallback();
24+
// Registration entry point used by managed System.Threading.WasiFinalizerScheduler
25+
// to install its ThreadPool-based scheduling callback at startup.
26+
typedef void (*WasiScheduleFinalizationFn)();
27+
extern "C" void QCALLTYPE WasiFinalizerScheduler_Register(WasiScheduleFinalizationFn callback);
28+
#endif // TARGET_WASI
29+
1930
#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
@@ -2985,6 +2985,7 @@
29852985
</ItemGroup>
29862986
<ItemGroup Condition="'$(TargetsWasi)' == 'true'">
29872987
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\Wasi\WasiEventLoop.cs" />
2988+
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\Wasi\WasiFinalizerScheduler.cs" />
29882989
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\Wasi\WasiPoll.cs" />
29892990
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\Wasi\WasiPollWorld.wit.imports.wasi.clocks.v0_2_0.MonotonicClockInterop.cs" />
29902991
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\Wasi\WasiPollWorld.wit.imports.wasi.io.v0_2_0.IPoll.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)