Skip to content

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

Backlog

Description

@ydongyeon

Summary

A few lines of Python can make a release build read memory outside the frame's value stack. This is in 0.6.0 and in the git source at commit ad3268e88a10. code.replace(co_code=...) accepts any bytes that decode to known opcodes, and the eval loop then trusts the stack depth, so COPY 100 on an empty stack reads 100 slots below the stack.

from opcode import opmap

def f():
    pass

code = bytearray(f.__code__.co_code)       # RESUME; <load None>; RETURN_VALUE
code[-4] = opmap["COPY"]                   # replace the load with COPY 100:
code[-3] = 100                             # copy the 100th value from the top of an empty stack
g = f.__code__.replace(co_code=bytes(code))  # accepted
print("built", g, flush=True)
print("returned:", exec(g))                # COPY reads 100 slots below the frame's stack

The COPY handler computes the slot from the current stack length, and the only guards are debug_assert!s (frame.rs#L4765-L4775, frame.rs#L676-L683):

let idx = index.get(arg) as usize;
let stack_len = self.localsplus.stack_len();
debug_assert!(stack_len >= idx, "CopyItem: stack underflow");   // gone in release
let value = self.localsplus.stack_index(stack_len - idx);       // 0 - 100 wraps
self.push_stackref_opt(value.cloned());
fn stack_index(&self, idx: usize) -> Option<&PyStackRef> {
    debug_assert!(idx < self.stack_top as usize);               // gone in release
    let data = self.data_as_slice();
    let raw_idx = self.nlocalsplus as usize + idx;
    unsafe { (*(data.as_ptr().add(raw_idx) as *const Option<PyStackRef>)).as_ref() }   // reads outside the stack
}

Code from the compiler never underflows the stack, so normal programs are fine. But code.replace(co_code=...) only runs CodeUnits::try_from (code.rs#L1287-L1288), which checks that each opcode byte is a known instruction. Nothing checks the stack effect. stack_index is used with stack_len - nargs - 1 style indexes by many other handlers (CALL and friends), so I think they can be reached the same way, but I only tested COPY.

Expected

No read outside the value stack in a release build. A debug build of 0.6.0 already stops with a clean panic:

CopyItem: stack underflow

Other bad bytecode already panics in release as well, with tried to pop from empty stack.

Actual

Release build (cargo run --release -- poc.py at that commit):

built <code object f at 0x3c2c60eaf10, file "poc.py", line 3>

The process is then killed by SIGSEGV (exit status 139).

AddressSanitizer, at the same commit (RUSTFLAGS="-Zsanitizer=address -g" cargo +nightly run --release --target x86_64-unknown-linux-gnu --no-default-features --features stdlib,stdio,importlib,host_env,threading -- poc.py, mimalloc left out so ASan sees the allocation):

ERROR: AddressSanitizer: heap-buffer-overflow
READ of size 8
#0 <rustpython_vm::frame::ExecutingFrame>::run_until::<false>
#1 <rustpython_vm::frame::ExecutingFrame>::run
#2 <rustpython_vm::object::core::Py<rustpython_vm::builtins::function::PyFunction>>::invoke_with_locals
...
is located 416 bytes before 16384-byte region
allocated by:
   <rustpython_vm::datastack::DataStack>::new

With code[-3] = 16 the release build does not crash at that commit or with 0.6.0. exec(g) returns the __main__ globals dict, which was sitting in a slot of another frame.

I get the same segfault and the same ASan report with 0.6.0, and a segfault with 0.5.0, both from crates.io. For those I used a small binary that only calls rustpython::run, like the rustpython binary but without mimalloc and ssl. I could not use Miri, it stops during interpreter start-up on an unsupported access call.

Python Documentation

codeobject.replace: https://docs.python.org/3/reference/datamodel.html#codeobject.replace

The documentation does not say what happens when co_code is not valid bytecode. I know CPython also crashes on bad bytecode and does not treat that as a bug, so you may decide the same here. I am reporting it because a debug build already catches it with a clean panic, and only the release build turns it into a wild read.

Suggested fix

The complete fix would be to verify the stack effect of user-supplied bytecode when the code object is built, but that is a larger change. A small one is to make the bounds checks in the stack accessors real, so every caller is covered:

fn stack_index(&self, idx: usize) -> Option<&PyStackRef> {
    assert!(idx < self.stack_top as usize, "stack index out of range");
    ...
}

fn stack_index_mut(&mut self, idx: usize) -> &mut Option<PyStackRef> {
    assert!(idx < self.stack_top as usize, "stack index out of range");
    ...
}

fn stack_swap(&mut self, a: usize, b: usize) {
    let len = self.stack_top as usize;
    assert!(a < len && b < len, "stack index out of range");
    ...
}

A wrapped index is always larger than stack_top, so it is caught. This adds one compare to hot paths and I did not measure the cost. With this change the script above panics with stack index out of range in a release build. cargo test --release -p rustpython-vm gives the same result as before, and so does rustpython -m test test_code test_dis test_opcodes test_grammar test_generators.

AI disclosure: I used an AI assistant (Claude) for the code analysis and for drafting this report. I reproduced the results above myself and reviewed the text before posting.

Activity

  1. added
    C-bug
    on Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions