Title: Out-of-bounds stack read when running bytecode from `code.replace(co_code=...)` · Issue #10014 · RustPython/RustPython · GitHub
Open Graph Title: Out-of-bounds stack read when running bytecode from `code.replace(co_code=...)` · Issue #10014 · RustPython/RustPython
X Title: Out-of-bounds stack read when running bytecode from `code.replace(co_code=...)` · Issue #10014 · RustPython/RustPython
Description: 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, ...
Open Graph Description: 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 ...
X Description: 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=...) acce...
Opengraph URL: https://github.com/RustPython/RustPython/issues/10014
X: @github
Domain: github.com
IPv4 address: 140.82.114.3
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Out-of-bounds stack read when running bytecode from `code.replace(co_code=...)`","articleBody":"## Summary\n\nA 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.\n\n```python\nfrom opcode import opmap\n\ndef f():\n pass\n\ncode = bytearray(f.__code__.co_code) # RESUME; \u003cload None>; RETURN_VALUE\ncode[-4] = opmap[\"COPY\"] # replace the load with COPY 100:\ncode[-3] = 100 # copy the 100th value from the top of an empty stack\ng = f.__code__.replace(co_code=bytes(code)) # accepted\nprint(\"built\", g, flush=True)\nprint(\"returned:\", exec(g)) # COPY reads 100 slots below the frame's stack\n```\n\nThe `COPY` handler computes the slot from the current stack length, and the only guards are `debug_assert!`s ([frame.rs#L4765-L4775](https://github.com/RustPython/RustPython/blob/ad3268e88a10e6cb9b92cec53263acf023eeead4/crates/vm/src/frame.rs#L4765-L4775), [frame.rs#L676-L683](https://github.com/RustPython/RustPython/blob/ad3268e88a10e6cb9b92cec53263acf023eeead4/crates/vm/src/frame.rs#L676-L683)):\n\n```rust\nlet idx = index.get(arg) as usize;\nlet stack_len = self.localsplus.stack_len();\ndebug_assert!(stack_len >= idx, \"CopyItem: stack underflow\"); // gone in release\nlet value = self.localsplus.stack_index(stack_len - idx); // 0 - 100 wraps\nself.push_stackref_opt(value.cloned());\n```\n\n```rust\nfn stack_index(&self, idx: usize) -> Option\u003c&PyStackRef> {\n debug_assert!(idx \u003c self.stack_top as usize); // gone in release\n let data = self.data_as_slice();\n let raw_idx = self.nlocalsplus as usize + idx;\n unsafe { (*(data.as_ptr().add(raw_idx) as *const Option\u003cPyStackRef>)).as_ref() } // reads outside the stack\n}\n```\n\nCode 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](https://github.com/RustPython/RustPython/blob/ad3268e88a10e6cb9b92cec53263acf023eeead4/crates/vm/src/builtins/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`.\n\n## Expected\n\nNo read outside the value stack in a release build. A debug build of 0.6.0 already stops with a clean panic:\n\n```text\nCopyItem: stack underflow\n```\n\nOther bad bytecode already panics in release as well, with `tried to pop from empty stack`.\n\n## Actual\n\nRelease build (`cargo run --release -- poc.py` at that commit):\n\n```text\nbuilt \u003ccode object f at 0x3c2c60eaf10, file \"poc.py\", line 3>\n```\n\nThe process is then killed by SIGSEGV (exit status 139).\n\nAddressSanitizer, 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):\n\n```text\nERROR: AddressSanitizer: heap-buffer-overflow\nREAD of size 8\n#0 \u003crustpython_vm::frame::ExecutingFrame>::run_until::\u003cfalse>\n#1 \u003crustpython_vm::frame::ExecutingFrame>::run\n#2 \u003crustpython_vm::object::core::Py\u003crustpython_vm::builtins::function::PyFunction>>::invoke_with_locals\n...\nis located 416 bytes before 16384-byte region\nallocated by:\n \u003crustpython_vm::datastack::DataStack>::new\n```\n\nWith `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.\n\nI 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.\n\n## Python Documentation\n\n`codeobject.replace`: https://docs.python.org/3/reference/datamodel.html#codeobject.replace\n\nThe 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.\n\n## Suggested fix\n\nThe 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:\n\n```rust\nfn stack_index(&self, idx: usize) -> Option\u003c&PyStackRef> {\n assert!(idx \u003c self.stack_top as usize, \"stack index out of range\");\n ...\n}\n\nfn stack_index_mut(&mut self, idx: usize) -> &mut Option\u003cPyStackRef> {\n assert!(idx \u003c self.stack_top as usize, \"stack index out of range\");\n ...\n}\n\nfn stack_swap(&mut self, a: usize, b: usize) {\n let len = self.stack_top as usize;\n assert!(a \u003c len && b \u003c len, \"stack index out of range\");\n ...\n}\n```\n\nA 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`.\n\nAI 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.\n","author":{"url":"https://github.com/ydongyeon","@type":"Person","name":"ydongyeon"},"datePublished":"2026-11-24T12:36:07Z","url":"https://github.com/RustPython/RustPython/issues/10014"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:7194b059-af76-73d6-bc89-afe9457a26b6 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | D5A4:28FBD0:820683:AD4974:6B06324B |
| html-safe-nonce | 340882fba03c05feed88075ce80c1459579096b4472921886c7f2429c0ddd1d2 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJENUE0OjI4RkJEMDo4MjA2ODM6QUQ0OTc0OjZCMDYzMjRCIiwidmlzaXRvcl9pZCI6IjU3MTQ4Mjg3MTIxMzUyNDIzMTUiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 828806b3715d69500f26451c2ad39ce8d99e6f5a7cf81348240819c6427ff154 |
| hovercard-subject-tag | issue:6581924413 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/RustPython/RustPython/10014/issue_layout |
| twitter:image | https://opengraph.githubassets.com/5bb70ca7528a18ee45b543d459fcf0b662100fa899df9809dcb1997c11b0805e/RustPython/RustPython/issues/10014 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/5bb70ca7528a18ee45b543d459fcf0b662100fa899df9809dcb1997c11b0805e/RustPython/RustPython/issues/10014 |
| og:image:alt | 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 ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | ydongyeon |
| hostname | github.com |
| expected-hostname | github.com |
| None | c3584c853cd39700ecff6e2cf8364295ffdb5313e571046c41cd2479270f7df0 |
| turbo-cache-control | no-preview |
| go-import | github.com/RustPython/RustPython git https://github.com/RustPython/RustPython.git |
| octolytics-dimension-user_id | 39710557 |
| octolytics-dimension-user_login | RustPython |
| octolytics-dimension-repository_id | 135201145 |
| octolytics-dimension-repository_nwo | RustPython/RustPython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 135201145 |
| octolytics-dimension-repository_network_root_nwo | RustPython/RustPython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 9eb3bb1597d09170a5f282cd38ae376dee1a5ec1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width