Skip to content

Fix x86-64 JIT operand-stack overflow (segfault on deep-push programs) - #9

Merged
MonkeyIsNull merged 1 commit into
mainfrom
fix-x86-jit-stack-overflow
Oct 7, 2026
Merged

MonkeyIsNull merged 1 commit into
mainfrom
fix-x86-jit-stack-overflow

Conversation

@MonkeyIsNull

Copy link
Copy Markdown
Owner

Problem

test_stack_overflow segfaulted on x86-64/Linux (passed on arm64). Root cause is a memory-corruption bug in the x86-64 JIT, not the interpreter: vfm_jit_compile_x86_64 tracks the operand stack in a fixed stack_regs[16] array and does stack_regs[stack_depth++] = reg on every PUSH with no bounds check. A program with 30 consecutive PUSH instructions overflows the array during compilation, clobbers the adjacent next_reg/labels fields, then crashes in free(jit.labels).

arm64 is unaffected because its JIT keeps the operand stack in memory rather than in this register-map array.

Fix

A headroom guard at the top of the compile loop: if compiling the next instruction (widest pushes two slots) would exceed stack_regs, clean up (free(labels) + munmap) and return NULL, falling back to the bounds-checked interpreter — which already enforces VFM_ERROR_STACK_OVERFLOW at runtime (exactly what the test expects). One comparison per instruction at compile time only; no effect on emitted code or fast paths.

Verification

  • x86-64 (Docker gcc:latest, linux/amd64): make clean && make && make test -> 14/14 passed (was SEGV).
  • arm64 (macOS): 14/14 passed, JIT tests pass.
    Both on the default portable (non-NATIVE) build.

The x86-64 JIT tracked the operand stack in a fixed stack_regs[16] array and incremented stack_depth on every PUSH with no bounds check, so a program with many consecutive PUSH instructions overflowed the array during compilation, corrupting the adjacent next_reg/labels fields and crashing in free(). Add a two-slot headroom guard at the top of the compile loop that cleans up and returns NULL (falling back to the bounds-checked interpreter, which enforces VFM_ERROR_STACK_OVERFLOW correctly) when a program's depth exceeds what the JIT can represent. The ARM64 JIT keeps its operand stack in memory and is unaffected. Caught by the new Ubuntu CI; verified on x86-64 (Docker) and arm64.
@MonkeyIsNull
MonkeyIsNull merged commit fac6110 into main Oct 7, 2026
2 checks passed
@MonkeyIsNull
MonkeyIsNull deleted the fix-x86-jit-stack-overflow branch October 7, 2026 21:25
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.

1 participant