Skip to content

Fix stack truncation on metamethod return corrupting numeric for loops#326

Open
Jackarunda wants to merge 3 commits into
nuskey8:mainfrom
Jackarunda:metamethod_bug_1
Open

Fix stack truncation on metamethod return corrupting numeric for loops#326
Jackarunda wants to merge 3 commits into
nuskey8:mainfrom
Jackarunda:metamethod_bug_1

Conversation

@Jackarunda

Copy link
Copy Markdown

My first contribution to this project. We're using this interpreter in our upcoming Unity game, so I think it appropriate to contribute where we can. We made our own Vector class in Lua with operator overrides like __add and whatnot. When trying to do these operations in a for loop, it crashes everything. I've explained the issue and fix below as best I can:

Summary

A metamethod that returns a single value could truncate the caller's stack
below still-live registers, causing numeric for loops to run forever.

Root cause

When an opcode's metamethod resolves to a single result, the VM writes the
result into the target register and then pops the metamethod's call frame. The
"one result" path (default: case in LuaVirtualMachine.Call) popped the stack
down to target + 1:

// src/Lua/Runtime/LuaVirtualMachine.cs (before)
default:
    Stack.Get(target) = result.Length == 0 ? LuaValue.Nil : result[0];
    State.PopCallStackFrameWithStackPop(target + 1);
    return true;

That assumes nothing above target is live. But

target = callInstruction.A + FrameBase

is the assignment destination, which can be a low register when the result is stored into a local declared before the current expression. A numeric for loop is the clearest trigger: its hidden control slots (index/limit/step) are allocated in registers above those locals, and ForLoop re-reads them from iA, iA+1, iA+2 on every iteration:

// src/Lua/Runtime/LuaVirtualMachine.cs:897-900
ref var indexRef = ref stack.Get(iA + frameBase);
var limit = Unsafe.Add(ref indexRef, 1).UnsafeReadDouble();
var step  = Unsafe.Add(ref indexRef, 2).UnsafeReadDouble();
var index = indexRef.UnsafeReadDouble() + step;

So for a body like:

local acc = ...            -- low register
for i = 1, n do
    acc = acc + something  -- __add result lands in acc's low register
end

the __add return truncated the stack past acc, discarding the loop's index/limit/step slots. step then reads back as 0, the termination check step >= 0 ? index <= limit : ... never advances, and the loop spins forever

Notably, the sibling Self case already pops to target + 2 rather than target + 1 (LuaVirtualMachine.cs line 164), acknowledging that registers above the result can be live — the default: path simply missed the general case.

Fix

Restore the caller's stack top instead of truncating to the result register. The metamethod frame's ReturnBase, captured as CurrentReturnFrameBase when the frame is entered (LuaVirtualMachine.cs lines 39 and 115), is the caller's top at call time, so it preserves any registers that were live above the result:

// src/Lua/Runtime/LuaVirtualMachine.cs (after)
default:
    Stack.Get(target) = result.Length == 0 ? LuaValue.Nil : result[0];
    State.PopCallStackFrameWithStackPop(Math.Max(target + 1, CurrentReturnFrameBase));
    return true;

Math.Max keeps the original behavior when the result register is already at or above the caller's top, and only extends the retained region when live slots sit above it.

The regression tests I added mirror the situation we were having when we noticed the problem in the first place.

Please review this and let me know if this appropriate to do, or if there's a better way.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes a VM stack-pop bug where returning a single value from a metamethod could truncate the caller’s stack below still-live registers, which could corrupt numeric for loop control slots and lead to non-terminating loops.

Changes:

  • Adjusted the VM’s “single-result return” path to restore the caller’s stack top (using CurrentReturnFrameBase) rather than truncating to the destination register.
  • Added regression tests covering numeric for loops invoking __add and __index metamethods to ensure loop state isn’t corrupted.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
src/Lua/Runtime/LuaVirtualMachine.cs Fixes stack restoration when popping a metamethod call frame that produced a single result.
tests/Lua.Tests/LoopTests.cs Adds regression tests that would previously hang or compute incorrect results if loop control registers were truncated.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants