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
2 changes: 1 addition & 1 deletion src/Lua/Exceptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ static string GetMessageWithNearToken(string message, string? nearToken)

public class LuaUndumpException(string message) : Exception(message);

class LuaStackOverflowException() : Exception("stack overflow")
public class LuaStackOverflowException() : Exception("stack overflow")
{
public override string ToString()
{
Expand Down
8 changes: 7 additions & 1 deletion src/Lua/Internal/CoroutineCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,13 @@ internal async ValueTask<int> ResumeAsyncCore(
Thread.Dispose();
stack.PopUntil(returnBase);
stack.Push(false);
stack.Push(ex is LuaRuntimeException luaEx ? luaEx.ErrorObject : ex.Message);
// Wrapped C# exceptions carry a message rather than a Lua error object.
// Keep error(nil) intact when the exception originated in Lua.
stack.Push(
ex is LuaRuntimeException { InnerException: null } luaEx
? luaEx.ErrorObject
: ex.Message
);
return 2;
}
else
Expand Down
3 changes: 3 additions & 0 deletions src/Lua/Internal/LuaGlobalState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ sealed class LuaGlobalState
public LuaPlatform Platform { get; set; }
public ILuaModuleLoader? ModuleLoader { get; set; }

// Coroutines share this policy so Lua code cannot reset the limit by creating a new thread.
internal int MaxCallDepth = 100_000;

internal UpValue EnvUpValue => envUpValue;
internal ref FastStackCore<LuaState> ThreadStack => ref stateStack;
internal ref FastStackCore<LuaDebug.LuaDebugBuffer> DebugBufferPool => ref debugBufferPool;
Expand Down
16 changes: 14 additions & 2 deletions src/Lua/LuaFunction.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Runtime.CompilerServices;

namespace Lua;

public class LuaFunction(
Expand All @@ -6,8 +8,18 @@ Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> func
)
{
public string Name { get; } = name;
internal Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> Func { get; } =
func;

// All delegate calls grow the C# stack, including RunAsync, hooks and metamethods.
// Pure Lua-to-Lua calls stay in the VM loop and do not invoke this method.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ValueTask<int> Func(LuaFunctionExecutionContext context, CancellationToken ct)
{
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
{
throw new LuaStackOverflowException();
}
return func(context, ct);
}

public LuaFunction(Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> func)
: this("anonymous", func) { }
Expand Down
48 changes: 47 additions & 1 deletion src/Lua/LuaState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,27 @@ public void Release()
public LuaTable PreloadModules => GlobalState.PreloadModules;
public LuaState MainThread => GlobalState.MainThread;

/// <summary>
/// Gets or sets the positive call-frame limit shared by this state and its coroutines.
/// The default is 100,000. Lua and C# frames count toward the limit; tail calls reuse a frame.
/// Changing this value also applies to existing threads sharing the same global state.
/// </summary>
public int MaxCallDepth
{
get => GlobalState.MaxCallDepth;
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
"Call depth must be positive."
);
}
GlobalState.MaxCallDepth = value;
}
}

public ILuaModuleLoader? ModuleLoader
{
get => GlobalState.ModuleLoader;
Expand Down Expand Up @@ -285,12 +306,37 @@ int callerInstructionIndex
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void PushCallStackFrame(in CallStackFrame frame)
{
ref var callStack = ref CoreData!.CallStack;
if (callStack.Count >= GlobalState.MaxCallDepth)
{
throw new LuaStackOverflowException();
}

CurrentException?.BuildOrGet();
CurrentException = null;
ref var callStack = ref CoreData!.CallStack;
callStack.Push(frame);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void ReplaceCallStackFrame(in CallStackFrame frame)
{
ref var callStack = ref CoreData!.CallStack;
if (callStack.Count > GlobalState.MaxCallDepth)
{
throw new LuaStackOverflowException();
}

// Tail calls retain the depth. Replacing the slot avoids clearing and repushing it,
// but a pending exception must still capture the outgoing frame before it is overwritten.
if (CurrentException != null)
{
ExceptionTrace.Push(callStack.Peek());
CurrentException.BuildOrGet();
CurrentException = null;
}
callStack.PeekRef() = frame;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void PopCallStackFrameWithStackPop()
{
Expand Down
4 changes: 2 additions & 2 deletions src/Lua/Runtime/LuaVirtualMachine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1619,10 +1619,10 @@ static bool TailCall(VirtualMachineExecutionContext context, out bool doRestart)
);
newBase = context.FrameBase + variableArgumentCount;
stack.PopUntil(newBase + argumentCount);

var lastFrame = state.GetCurrentFrame();
state.LastPc = context.Pc;
state.LastCallerFunction = lastFrame.Function;
context.State.PopCallStackFrame();
var newFrame = func.CreateNewTailCallFrame(
context,
newBase,
Expand All @@ -1632,7 +1632,7 @@ static bool TailCall(VirtualMachineExecutionContext context, out bool doRestart)

newFrame.CallerInstructionIndex = lastFrame.CallerInstructionIndex;
newFrame.Version = lastFrame.Version;
state.PushCallStackFrame(newFrame);
state.ReplaceCallStackFrame(newFrame);

if (state.CallOrReturnHookMask.Value != 0 && !context.State.IsInHook)
{
Expand Down
220 changes: 220 additions & 0 deletions tests/Lua.Tests/StackOverflowTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
using System.Runtime.CompilerServices;
using Lua.Standard;

namespace Lua.Tests;

public class StackOverflowTests
{
[Test]
public void ExceedingMaxCallDepth_ThrowsLuaRuntimeException()
{
using var state = LuaState.Create();
state.MaxCallDepth = 5;

var ex = Assert.ThrowsAsync<LuaRuntimeException>(async () =>
await state
.DoStringAsync(
"""
local function f()
f()
end
f()
"""
)
.AsTask()
);

Assert.That(ex!.InnerException, Is.TypeOf<LuaStackOverflowException>());
}

[Test]
public async Task ExceedingMaxCallDepth_WithPCall_ReturnsErrorMessage()
{
using var state = LuaState.Create();
state.OpenStandardLibraries();
state.MaxCallDepth = 5;

var result = await state.DoStringAsync(
"""
local function f()
f()
end
local ok, msg = pcall(f)
return ok, msg
"""
);

Assert.That(result, Has.Length.EqualTo(2));
Assert.That(result[0], Is.EqualTo(new LuaValue(false)));
Assert.That(result[1].Read<string>(), Does.Contain("stack overflow"));
}

[Test]
public async Task UnderMaxCallLimit_Succeeds()
{
using var state = LuaState.Create();
state.MaxCallDepth = 100;

var result = await state.DoStringAsync(
"""
local function f(n)
if n <= 0 then return 0 end
return 1 + f(n - 1)
end
return f(10)
"""
);

Assert.That(result, Has.Length.EqualTo(1));
Assert.That(result[0], Is.EqualTo(new LuaValue(10)));
}

[Test]
public async Task DefaultMaxCallDepth_AllowsDeepRecursion()
{
using var state = LuaState.Create();

var result = await state.DoStringAsync(
"""
local function f(n)
if n <= 0 then return n end
return 1 + f(n - 1)
end
return f(1000)
"""
);

Assert.That(result, Has.Length.EqualTo(1));
Assert.That(result[0], Is.EqualTo(new LuaValue(1000)));
}

[TestCase(0)]
[TestCase(-1)]
public void InvalidMaxCallDepth_IsRejected(int limit)
{
using var state = LuaState.Create();
Assert.Throws<ArgumentOutOfRangeException>(() => state.MaxCallDepth = limit);
Assert.That(state.MaxCallDepth, Is.EqualTo(100_000));
}

[Test]
public void MaxCallDepth_IsSharedWithExistingThreads()
{
using var state = LuaState.Create();
using var child = state.CreateThread();
state.MaxCallDepth = 5;
Assert.That(child.MaxCallDepth, Is.EqualTo(5));
child.MaxCallDepth = 10;
Assert.That(state.MaxCallDepth, Is.EqualTo(10));
}

[TestCase(false)]
[TestCase(true)]
public async Task CoroutineCannotBypassMaxCallDepth(bool wrap)
{
using var state = LuaState.Create();
state.OpenStandardLibraries();
state.MaxCallDepth = 5;
var result = await state.DoStringAsync(
"""
local function body()
local function f(n)
if n == 0 then return 0 end
return 1 + f(n - 1)
end
return f(20)
end
"""
+ "\n"
+ (
wrap
? "return pcall(coroutine.wrap(body))"
: "return coroutine.resume(coroutine.create(body))"
)
);
Assert.That(result[0].ToBoolean(), Is.False);
Assert.That(result[1].Read<string>(), Does.Contain("stack overflow"));
Assert.That(state.CallStackFrameCount, Is.Zero);
Assert.That((await state.DoStringAsync("return 42"))[0].Read<int>(), Is.EqualTo(42));
}

[Test]
public async Task CoroutineResume_PreservesLuaNilErrors()
{
using var state = LuaState.Create();
state.OpenStandardLibraries();
var result = await state.DoStringAsync(
"return coroutine.resume(coroutine.create(function() error(nil) end))"
);
Assert.That(result, Has.Length.EqualTo(2));
Assert.That(result[0].ToBoolean(), Is.False);
Assert.That(result[1], Is.EqualTo(LuaValue.Nil));
}

[Test]
public async Task TailCallsReuseDepthAtTheLimit()
{
using var state = LuaState.Create();
state.MaxCallDepth = 1;
var result = await state.DoStringAsync(
"local function f(n) if n == 0 then return 42 end return f(n - 1) end return f(10000)"
);
Assert.That(result[0].Read<int>(), Is.EqualTo(42));
Assert.That(state.CallStackFrameCount, Is.Zero);
}

[TestCase(false)]
[TestCase(true)]
public void NativeReentryIsGuarded(bool throughLua)
{
Exception? caught = null;
var lowStackEntries = 0;
var calls = 0;
var worker = new Thread(
() =>
{
using var state = LuaState.Create();
LuaFunction? callback = null;
var bridge = state.Load("return bounce()", "bridge.lua");
callback = new LuaFunction(
"bounce",
(context, ct) =>
{
calls++;
// The callback's own frame can cross the runtime's reserve threshold
// after the caller checked it. Allow one such entry; the next guarded
// invocation must throw. Stop on a second entry if a guard is missing,
// while still inside the runtime's stack reserve, rather than overflowing.
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
{
if (++lowStackEntries > 1)
return new(context.Return());
}
if (calls >= 10000)
return new(context.Return());
return context.State.RunAsync(throughLua ? bridge : callback!, ct);
}
);
state.Environment["bounce"] = callback;
try
{
state.RunAsync(callback).GetAwaiter().GetResult();
}
catch (Exception ex)
{
caught = ex;
}
},
1024 * 1024
);
worker.Start();
worker.Join();
Assert.That(lowStackEntries, Is.LessThanOrEqualTo(1));
Assert.That(
caught is LuaStackOverflowException
|| caught?.InnerException is LuaStackOverflowException,
Is.True
);
Assert.That(calls, Is.LessThan(10000));
}
}
Loading