René's URL Explorer Experiment


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

direct link

Domain: github.com

IPv4 address: 140.82.114.3


Hey, it has json ld scripts:
{"@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-profiling0
react-import-mapreact,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-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:7194b059-af76-73d6-bc89-afe9457a26b6
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idD5A4:28FBD0:820683:AD4974:6B06324B
html-safe-nonce340882fba03c05feed88075ce80c1459579096b4472921886c7f2429c0ddd1d2
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJENUE0OjI4RkJEMDo4MjA2ODM6QUQ0OTc0OjZCMDYzMjRCIiwidmlzaXRvcl9pZCI6IjU3MTQ4Mjg3MTIxMzUyNDIzMTUiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmac828806b3715d69500f26451c2ad39ce8d99e6f5a7cf81348240819c6427ff154
hovercard-subject-tagissue:6581924413
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/RustPython/RustPython/10014/issue_layout
twitter:imagehttps://opengraph.githubassets.com/5bb70ca7528a18ee45b543d459fcf0b662100fa899df9809dcb1997c11b0805e/RustPython/RustPython/issues/10014
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/5bb70ca7528a18ee45b543d459fcf0b662100fa899df9809dcb1997c11b0805e/RustPython/RustPython/issues/10014
og:image:altSummary 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:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameydongyeon
hostnamegithub.com
expected-hostnamegithub.com
Nonec3584c853cd39700ecff6e2cf8364295ffdb5313e571046c41cd2479270f7df0
turbo-cache-controlno-preview
go-importgithub.com/RustPython/RustPython git https://github.com/RustPython/RustPython.git
octolytics-dimension-user_id39710557
octolytics-dimension-user_loginRustPython
octolytics-dimension-repository_id135201145
octolytics-dimension-repository_nwoRustPython/RustPython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id135201145
octolytics-dimension-repository_network_root_nwoRustPython/RustPython
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release9eb3bb1597d09170a5f282cd38ae376dee1a5ec1
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/RustPython/RustPython/issues/10014#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2FRustPython%2FRustPython%2Fissues%2F10014
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2FRustPython%2FRustPython%2Fissues%2F10014
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=RustPython%2FRustPython
Reloadhttps://github.com/RustPython/RustPython/issues/10014
Reloadhttps://github.com/RustPython/RustPython/issues/10014
Reloadhttps://github.com/RustPython/RustPython/issues/10014
RustPythonhttps://github.com/RustPython
RustPythonhttps://github.com/RustPython/RustPython
Codehttps://github.com/RustPython/RustPython
Issues197 (197)https://github.com/RustPython/RustPython/issues
Pull requests144 (144)https://github.com/RustPython/RustPython/pulls
Discussionshttps://github.com/RustPython/RustPython/discussions
Actionshttps://github.com/RustPython/RustPython/actions
Projectshttps://github.com/RustPython/RustPython/projects
Wikihttps://github.com/RustPython/RustPython/wiki
Security and qualityhttps://github.com/RustPython/RustPython/security
Insightshttps://github.com/RustPython/RustPython/insights
https://github.com/RustPython/RustPython
New issuehttps://github.com/login?return_to=https://github.com/RustPython/RustPython/issues/10014
New issuehttps://github.com/login?return_to=https://github.com/RustPython/RustPython/issues/10014
Out-of-bounds stack read when running bytecode from code.replace(co_code=...)https://github.com/RustPython/RustPython/issues/10014#top
C-bughttps://github.com/RustPython/RustPython/issues?q=state%3Aopen%20label%3A%22C-bug%22
https://github.com/ydongyeon
ydongyeonhttps://github.com/ydongyeon
on Nov 24, 2026https://github.com/RustPython/RustPython/issues/10014#issue-6581924413
frame.rs#L4765-L4775https://github.com/RustPython/RustPython/blob/ad3268e88a10e6cb9b92cec53263acf023eeead4/crates/vm/src/frame.rs#L4765-L4775
frame.rs#L676-L683https://github.com/RustPython/RustPython/blob/ad3268e88a10e6cb9b92cec53263acf023eeead4/crates/vm/src/frame.rs#L676-L683
code.rs#L1287-L1288https://github.com/RustPython/RustPython/blob/ad3268e88a10e6cb9b92cec53263acf023eeead4/crates/vm/src/builtins/code.rs#L1287-L1288
https://docs.python.org/3/reference/datamodel.html#codeobject.replacehttps://docs.python.org/3/reference/datamodel.html#codeobject.replace
ydongyeonhttps://github.com/ydongyeon
C-bughttps://github.com/RustPython/RustPython/issues?q=state%3Aopen%20label%3A%22C-bug%22
on Nov 24, 2026https://github.com/RustPython/RustPython/issues/10014#event-37128731876
Sign up for freehttps://github.com/signup?return_to=https://github.com/RustPython/RustPython/issues/10014
Sign in to commenthttps://github.com/login?return_to=https://github.com/RustPython/RustPython/issues/10014
C-bughttps://github.com/RustPython/RustPython/issues?q=state%3Aopen%20label%3A%22C-bug%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Response headers:
Servergithub.com
Content-Typetext/html; charset=utf-8
Cache-Controlmax-age=0, private, must-revalidate

Viewport: width=device-width


URLs of crawlers that visited me.