Skip to content

Reject stack indices that the frame cannot have - #10023

Open
Goldloli wants to merge 1 commit into
RustPython:mainfrom
Goldloli:fix/stack-index-bounds
Open

Goldloli wants to merge 1 commit into
RustPython:mainfrom
Goldloli:fix/stack-index-bounds

Conversation

@Goldloli

@Goldloli Goldloli commented Nov 25, 2026 •

Copy link
Copy Markdown

One of checkbox below must be checked.

  • I did not use AI to write the code of this patch.
  • This PR follows our AI policy

Summary

CodeType.replace(co_code=...) only checks that every byte decodes to a known
opcode. It does not check that the instruction stream is consistent with
itself, so an operand can address a value stack slot the frame never pushed. The
accessors that read those slots guarded the index with debug_assert!, which is
compiled out in release builds. COPY 100 on an empty stack therefore computed
stack_len - idx by wrapping and read outside the frame's storage (issue
#10014 reports this as an out-of-bounds read in a release build).

This keeps the existing "stop with a clear message" behaviour that bad bytecode
already gets (tried to pop from empty stack) and extends it to the indexing
paths:

  • LocalsPlus::stack_index and stack_index_mut check the slot index.
  • LocalsPlus::stack_swap and stack_truncate check both the indices and the new
    length, which also covers SWAP with operand 0.
  • FrameObject::nth_value checks before stack_len - depth - 1 can wrap.
  • Copy, Swap and the call arity paths (execute_call_vectorcall,
    take_call_args, take_native_method_args) check the operand before it
    seeds a subtraction.

The out-of-line #[cold] reporters keep the checked accessors as cheap as
the unchecked ones they replace on the normal path.

Test plan

New integration test crates/vm/tests/stack_bounds.rs builds the two
code.replace(co_code=...) cases from the issue and asserts that the
interpreter rejects them instead of running the bad index.

The same test fails on the unmodified tree, which is the point of the change:

# unmodified, release profile
$ cargo test -p rustpython-vm --no-default-features --features compiler,gc \
    --release --test stack_bounds
index out of bounds: the len is 1 but the index is 18446744073709551615
...
test result: FAILED. 0 passed; 2 failed

# unmodified, debug profile
expected a "COPY index" rejection, got: CopyItem: stack underflow

With the patch, in both profiles:

$ cargo test -p rustpython-vm --no-default-features --features compiler,gc \
    --test stack_bounds
test copy_operand_past_stack_is_rejected ... ok
test swap_operand_past_stack_is_rejected ... ok

$ cargo test -p rustpython-vm --no-default-features --features compiler,gc \
    --release --test stack_bounds
test result: ok. 2 passed; 0 failed

The interpreter tests that cover these paths still pass:

$ ./rustpython -m test test_code test_code_module test_dis
All 3 tests OK. (199 tests)
$ ./rustpython -m test test_funcattrs test_generators test_coroutines test_with \
    test_asyncgen test_exceptions test_opcodes test_compile
All 8 tests OK. (649 tests)

cargo test -p rustpython-vm --lib passes 218 of 219 tests; the one failure,
vm::tests::frozen_origname_matches, fails on the unmodified tree too because
it needs the frozen stdlib that --no-default-features removes. I could not run
the full workspace test command: this machine has no libffi, so the default
host_env/ctypes build of the test binary aborts at load with
Library not loaded: @rpath/libffi.8.dylib. That is an environment limit here, not
something the patch changes; CI runs the full workspace.

Notes for review

  • No behaviour change for compiled code: the compiler's stack model already
    satisfies these checks.
  • The three debug_assert!s that became run-time checks were each the only
    guard on a raw index, so this is not a new class of check on a hot path
    beyond what the release build was already missing.
  • Assisted-by: ZCode:deepseek-v4.1-flash-eco is in the commit message per the
    AI policy; the change was reviewed and verified as described above.

Summary by CodeRabbit

  • Bug Fixes
    • Invalid stack operations now fail with a controlled error instead of risking unsafe memory access. This improves stability when executing malformed or invalid bytecode.

`CodeType.replace(co_code=...)` validates only that every byte decodes to a
known opcode. It does not check that the resulting stream is consistent with
itself, so an operand can address a value stack slot the frame never pushed.
The accessors that read those slots relied on `debug_assert!`, which is
compiled out in release builds: `COPY 100` on an empty stack wrapped
`stack_len - idx` and read outside the frame's storage.

Check the index in `LocalsPlus::stack_index`, `stack_index_mut`, `stack_swap`
and `stack_truncate`, and check the arity-derived indices in `nth_value` and
`execute_call_vectorcall`/`take_call_args`/`take_native_method_args` before the
subtraction can wrap. An inconsistent instruction stream now stops with a
message that names the index, like the existing `tried to pop from empty
stack`.

Assisted-by: ZCode:deepseek-v4.1-flash-eco
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-25T14:05:45.082333Z
We couldn’t complete this review. Comment @codex review to try again.
735f2f0 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Credits must be used to enable repository wide code reviews.

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The VM now validates stack bounds in release builds for stack accessors, COPY and SWAP operands, call-stack arity, and requested stack depth. New tests run malformed COPY and SWAP bytecode and check for the expected panic messages.

Changes: Stack bounds enforcement

Layer / File(s) Summary
Runtime stack checks and regression tests
crates/vm/src/frame.rs, crates/vm/tests/stack_bounds.rs
Stack accessors, COPY and SWAP handlers, call-argument paths, and nth_value now check bounds and use explicit panic helpers. Tests execute malformed COPY and SWAP bytecode and check the panic messages.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: youknowone, youknowdot, shaharnaveh

Merge Risk: Minimal · up to 735f2

This change makes malformed bytecode fail with a clear panic instead of reading outside the stack in release builds. Normal compiled code should be unaffected, and no merge-blocking risk was found.

Pre-merge checks: Passed 3 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Linked Issues check Inconclusive Issue #10014 requires that release builds never read outside the value stack when code.replace(co_code=...) supplies a bad stack index. The PR description and the AI-generated summary state that `Lo… Provide a readable base-to-head diff of crates/vm/src/frame.rs, or a narrowed read of the LocalsPlus accessor functions and the Copy, Swap, nth_value, and call-arity handlers at head. Confirm that these paths check the index befor…
Passed Passed checks: 3 passed

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Reject stack indices that the frame cannot have" matches the main change. The PR adds runtime bounds checks to LocalsPlus and ExecutingFrame accessors, COPY, SWAP, call-arity, and nth_value…
Out of Scope Changes check Passed The PR description and summary list changes only in crates/vm/src/frame.rs and the new test crates/vm/tests/stack_bounds.rs. The frame.rs changes are stack-index guards in LocalsPlus and `Execut…
Full details: Title check

Explanation

The title "Reject stack indices that the frame cannot have" matches the main change. The PR adds runtime bounds checks to LocalsPlus and ExecutingFrame accessors, COPY, SWAP, call-arity, and nth_value paths, so invalid stack indices panic instead of reading outside frame storage. The title is specific and concise, and it names the primary behavior change.

Full details: Out of Scope Changes check

Explanation

The PR description and summary list changes only in crates/vm/src/frame.rs and the new test crates/vm/tests/stack_bounds.rs. The frame.rs changes are stack-index guards in LocalsPlus and ExecutingFrame, and the COPY, SWAP, nth_value, and call-arity paths named in issue #10014 and its suggested fix. The test exercises the COPY and SWAP cases from the issue. The call-arity checks are the related paths that the issue names as possible reach points. No unrelated behaviour change is described. The frame.rs content could not be read directly, so this verdict relies on the described scope.

Full details: Linked Issues check

Explanation

Issue #10014 requires that release builds never read outside the value stack when code.replace(co_code=...) supplies a bad stack index. The PR description and the AI-generated summary state that LocalsPlus::stack_index, stack_index_mut, stack_swap, stack_truncate, FrameObject::nth_value, Copy, Swap, and the call-arity paths now perform run-time checks in place of debug_assert!. The new test crates/vm/tests/stack_bounds.rs (read at head) runs COPY 100 and SWAP 200 fixtures and requires a panic whose text contains COPY index or SWAP index. The test has no reference to the implementation, so it does not show that the checks exist. The inspection of crates/vm/src/frame.rs failed: the base-to-head diff reported missing changed blobs, and the head file read was truncated at 16000 bytes before the relevant accessors. The COPY index and SWAP index messages, and the checks themselves, are therefore not confirmed in source. The reported test results are author claims and were not re-run. The linked-issue requirement is not established from code evidence.

Resolution

Provide a readable base-to-head diff of crates/vm/src/frame.rs, or a narrowed read of the LocalsPlus accessor functions and the Copy, Swap, nth_value, and call-arity handlers at head. Confirm that these paths check the index before any subtraction or raw pointer access, and that the failing checks emit the COPY index and SWAP index messages that stack_bounds.rs expects.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 9080e66 and 735f2f0.

Files selected for processing: 2

  • crates/vm/src/frame.rs
  • crates/vm/tests/stack_bounds.rs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

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.

Out-of-bounds stack read when running bytecode from code.replace(co_code=...)

1 participant