Skip to content
Merged
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
11 changes: 11 additions & 0 deletions Jint/Constraints/MemoryLimitConstraint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ public sealed class MemoryLimitConstraint : Constraint
{
private readonly long _memoryLimit;
private long _initialMemoryUsage;
private int _initialThreadId;

#if !NET8_0_OR_GREATER
private static readonly Func<long>? _getAllocatedBytesForCurrentThread;
Expand Down Expand Up @@ -33,6 +34,15 @@ public override void Check()
return;
}

// GC.GetAllocatedBytesForCurrentThread() is per-thread. If an async continuation
// resumed on a different thread pool thread, comparing counters across threads is
// meaningless and can produce false positives or silently bypass the limit.
// Skipping the check is the safe fallback for that case.
if (Environment.CurrentManagedThreadId != _initialThreadId)
{
return;
}

#if NET8_0_OR_GREATER
var usage = GC.GetAllocatedBytesForCurrentThread();
#else
Expand All @@ -51,6 +61,7 @@ public override void Check()

public override void Reset()
{
_initialThreadId = Environment.CurrentManagedThreadId;
#if NET8_0_OR_GREATER
_initialMemoryUsage = GC.GetAllocatedBytesForCurrentThread();
#else
Expand Down
Loading