Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
using System.Runtime.InteropServices;

//
// Implements the single finalizer thread for a NativeAOT instance. Essentially waits for an event to fire
// indicating finalization is necessary then drains the queue of pending finalizable objects, calling the
// finalize method for each one.
// Runs finalizers on a dedicated thread, or through a current-thread callback without multithreading.
//

namespace System.Runtime
Expand All @@ -22,25 +20,38 @@ public static void ProcessFinalizers()
{
while (true)
{
// Wait until there's some work to be done. If true is returned we should finalize objects,
// otherwise memory is low and we should initiate a collection.
if (InternalCalls.RhpWaitForFinalizerRequest() != 0)
{
int observedFullGcCount = RuntimeImports.RhGetGcCollectionCount(RuntimeImports.RhGetMaxGcGeneration(), false);
uint finalizerCount = DrainQueue();
ProcessFinalizersWorkerIteration();
}
}

// Anyone waiting to drain the Q can now wake up. Note that there is a
// race in that another thread starting a drain, as we leave a drain, may
// consider itself satisfied by the drain that just completed.
// Thus we include the Full GC count that we have certaily observed.
InternalCalls.RhpSignalFinalizationComplete(finalizerCount, observedFullGcCount);
}
else
{
// RhpWaitForFinalizerRequest() returned false and indicated that memory is low. We help
// out by initiating a garbage collection and then go back to waiting for another request.
InternalCalls.RhCollect(0, InternalGCCollectionMode.Blocking, lowMemoryP: Interop.BOOL.TRUE);
}
#if !FEATURE_MULTITHREADING
[UnmanagedCallersOnly(EntryPoint = "ProcessFinalizersWorkerIteration")]
public static void RunFinalizerIteration()
{
ProcessFinalizersWorkerIteration();
Comment thread
MichalStrehovsky marked this conversation as resolved.
Resolved
}
#endif

private static void ProcessFinalizersWorkerIteration()
{
// Wait until there's some work to be done. If true is returned we should finalize objects,
// otherwise memory is low and we should initiate a collection.
if (InternalCalls.RhpWaitForFinalizerRequest() != 0)
{
int observedFullGcCount = RuntimeImports.RhGetGcCollectionCount(RuntimeImports.RhGetMaxGcGeneration(), false);
uint finalizerCount = DrainQueue();

// Anyone waiting to drain the Q can now wake up. Note that there is a
// race in that another thread starting a drain, as we leave a drain, may
// consider itself satisfied by the drain that just completed.
// Thus we include the Full GC count that we have certainly observed.
InternalCalls.RhpSignalFinalizationComplete(finalizerCount, observedFullGcCount);
}
else
{
// RhpWaitForFinalizerRequest() returned false and indicated that memory is low. We help
// out by initiating a garbage collection and then go back to waiting for another request.
InternalCalls.RhCollect(0, InternalGCCollectionMode.Blocking, lowMemoryP: Interop.BOOL.TRUE);
}
}

Expand All @@ -55,7 +66,7 @@ private static unsafe uint DrainQueue()
while (true)
{
object target = InternalCalls.RhpGetNextFinalizableObject();
if (target == null)
if (target is null)
return finalizerCount;

finalizerCount++;
Expand Down
92 changes: 89 additions & 3 deletions src/coreclr/nativeaot/Runtime/FinalizerHelpers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,61 @@ static bool g_ComAndFlsInitSucceeded = false;

EXTERN_C void QCALLTYPE ProcessFinalizers();

#ifndef FEATURE_MULTITHREADING
EXTERN_C void QCALLTYPE ProcessFinalizersWorkerIteration();
#endif // !FEATURE_MULTITHREADING

#if !defined(FEATURE_MULTITHREADING) && (defined(TARGET_BROWSER) || defined(TARGET_WASI))
#ifdef TARGET_BROWSER
EXTERN_C void SystemJS_ScheduleFinalization();
#endif // TARGET_BROWSER

#ifdef TARGET_WASI
EXTERN_C void WasiFinalizer_Schedule();
#endif // TARGET_WASI

static void RunFinalizerIterationOnCurrentThread()
{
ProcessFinalizersWorkerIteration();
}

#ifdef TARGET_BROWSER
EXTERN_C void SystemJS_ExecuteFinalizationCallback()
{
RunFinalizerIterationOnCurrentThread();
}
#else // TARGET_WASI
EXTERN_C void QCALLTYPE WasiFinalizer_RunWorker()
{
RunFinalizerIterationOnCurrentThread();
}
#endif // TARGET_BROWSER
#endif // !FEATURE_MULTITHREADING && (TARGET_BROWSER || TARGET_WASI)

#ifdef TARGET_WASI
#ifdef FEATURE_WASM_MANAGED_THREADS
#error "TARGET_WASI finalization requires a single-threaded runtime."
#endif // FEATURE_WASM_MANAGED_THREADS

static Volatile<bool> s_finalizationPending = false;

EXTERN_C void WasiFinalizer_Schedule()
{
// Called inside the GC; managed callbacks, allocations, and locks are not safe here.
s_finalizationPending = true;
Comment thread
MichalStrehovsky marked this conversation as resolved.
Resolved
Comment thread
MichalStrehovsky marked this conversation as resolved.
Resolved
}

EXTERN_C UInt32_BOOL QCALLTYPE WasiFinalizer_TryClearPending()
{
bool pending = s_finalizationPending;
if (pending)
s_finalizationPending = false;

return pending ? TRUE : FALSE;
}
#endif // TARGET_WASI

#ifdef FEATURE_MULTITHREADING
// Unmanaged front-end to the finalizer thread. We require this because at the point when this thread is
// created we can't run managed code. Instead this method waits
// for the first finalization request (by which time everything must be up and running) and kicks off the
Expand Down Expand Up @@ -77,9 +132,11 @@ uint32_t WINAPI FinalizerStart(void* pContext)
ASSERT(!"Finalizer thread should never return");
return 0;
}
#endif // FEATURE_MULTITHREADING

bool RhInitializeFinalization()
{
#ifdef FEATURE_MULTITHREADING
// Allocate the events the GC expects the finalizer thread to have. The g_FinalizerEvent event is signalled
// by the GC whenever it completes a collection where it found otherwise unreachable finalizable objects.
// The g_FinalizerDoneEvent is set by the finalizer thread every time it wakes up and drains the
Expand All @@ -99,10 +156,12 @@ bool RhInitializeFinalization()
}
#endif

#ifdef FEATURE_MULTITHREADING
// Create the finalizer thread itself.
if (!PalStartFinalizerThread(FinalizerStart, &g_FinalizerEvent))
return false;
#else // FEATURE_MULTITHREADING
// The thread is not attached until the first managed entry.
g_pFinalizerThread = PTR_Thread(ThreadStore::RawGetCurrentThread());
#endif // FEATURE_MULTITHREADING

return true;
Expand All @@ -119,7 +178,13 @@ bool RhWaitForFinalizerThreadStart()

void RhEnableFinalization()
{
#ifdef FEATURE_MULTITHREADING
g_FinalizerEvent.Set();
#elif defined(TARGET_BROWSER)
SystemJS_ScheduleFinalization();
#else // TARGET_WASI
WasiFinalizer_Schedule();
#endif // FEATURE_MULTITHREADING
}

static int32_t g_fullGcCountSeenByFinalization;
Expand All @@ -130,12 +195,15 @@ EXTERN_C void QCALLTYPE RhpSignalFinalizationComplete(uint32_t fcount, int32_t o
FireEtwGCFinalizersEnd_V1(fcount, GetClrInstanceId());

g_fullGcCountSeenByFinalization = observedFullGcCount;

#ifdef FEATURE_MULTITHREADING
g_FinalizerDoneEvent.Set();

if (YieldProcessorNormalization::IsMeasurementScheduled())
{
YieldProcessorNormalization::PerformMeasurement();
}
#endif // FEATURE_MULTITHREADING
}

EXTERN_C void QCALLTYPE RhWaitForPendingFinalizers(UInt32_BOOL allowReentrantWait)
Expand All @@ -144,6 +212,7 @@ EXTERN_C void QCALLTYPE RhWaitForPendingFinalizers(UInt32_BOOL allowReentrantWai
// called in cooperative mode.
ASSERT(!ThreadStore::GetCurrentThread()->IsCurrentThreadInCooperativeMode());

#ifdef FEATURE_MULTITHREADING
// Can't call this from the finalizer thread itself.
if (ThreadStore::GetCurrentThread() != g_pFinalizerThread)
{
Expand Down Expand Up @@ -174,12 +243,28 @@ EXTERN_C void QCALLTYPE RhWaitForPendingFinalizers(UInt32_BOOL allowReentrantWai
goto tryAgain;
}
}
#else // !FEATURE_MULTITHREADING
// The sole thread also runs application code, so thread identity cannot detect recursive waits.
static thread_local bool s_inDrain = false;
if (s_inDrain)
Comment thread
MichalStrehovsky marked this conversation as resolved.
Resolved
{
return;
}
s_inDrain = true;

ProcessFinalizersWorkerIteration();

s_inDrain = false;
#endif // FEATURE_MULTITHREADING
}

// Block the current thread until at least one object needs to be finalized (returns true) or memory is low
// (returns false and the finalizer thread should initiate a garbage collection).
EXTERN_C UInt32_BOOL QCALLTYPE RhpWaitForFinalizerRequest()
{
IGCHeap * pHeap = GCHeapUtilities::GetGCHeap();

#ifdef FEATURE_MULTITHREADING
// We can wait for two events; finalization queue has been populated and low memory resource notification.
// But if the latter is signalled we shouldn't wait on it again immediately -- if the garbage collection
// the finalizer thread initiates as a result is not sufficient to remove the low memory condition the
Expand All @@ -189,8 +274,6 @@ EXTERN_C UInt32_BOOL QCALLTYPE RhpWaitForFinalizerRequest()
// request.
static bool fLastEventWasLowMemory = false;

IGCHeap * pHeap = GCHeapUtilities::GetGCHeap();

// Wait in a loop because we may have to retry if we decide to only wait for finalization events but the
// two second timeout expires.
do
Expand All @@ -216,6 +299,7 @@ EXTERN_C UInt32_BOOL QCALLTYPE RhpWaitForFinalizerRequest()
switch (uResult)
{
case WAIT_OBJECT_0:
#endif // FEATURE_MULTITHREADING
// At least one object is ready for finalization.
{
// Process pending finalizer work items from the GC first.
Expand All @@ -230,6 +314,7 @@ EXTERN_C UInt32_BOOL QCALLTYPE RhpWaitForFinalizerRequest()
FireEtwGCFinalizersBegin_V1(GetClrInstanceId());
return TRUE;

#ifdef FEATURE_MULTITHREADING
case WAIT_OBJECT_0 + 1:
// Memory is low, tell the finalizer thread to garbage collect.
ASSERT(!fLastEventWasLowMemory);
Expand All @@ -248,6 +333,7 @@ EXTERN_C UInt32_BOOL QCALLTYPE RhpWaitForFinalizerRequest()
return FALSE;
}
} while (true);
#endif // FEATURE_MULTITHREADING
}

//
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@
<Compile Include="$(RuntimeBasePath)System\Runtime\DispatchResolve.cs">
<Link>Runtime.Base\src\System\Runtime\DispatchResolve.cs</Link>
</Compile>
<Compile Include="$(RuntimeBasePath)System\Runtime\__Finalizer.cs" Condition="'$(TargetsWasm)' != 'true'">
<Compile Include="$(RuntimeBasePath)System\Runtime\__Finalizer.cs">
<Link>Runtime.Base\src\System\Runtime\__Finalizer.cs</Link>
</Compile>
<Compile Include="$(RuntimeBasePath)System\Runtime\MethodTable.Runtime.cs">
Expand Down
Loading
Loading