René's URL Explorer Experiment


Title: Double release of `PyBytesWriter` in `assemble_init()` error path corrupts the bytes writer freelist · Issue #158241 · python/cpython · GitHub

Open Graph Title: Double release of `PyBytesWriter` in `assemble_init()` error path corrupts the bytes writer freelist · Issue #158241 · python/cpython

X Title: Double release of `PyBytesWriter` in `assemble_init()` error path corrupts the bytes writer freelist · Issue #158241 · python/cpython

Description: Bug report Bug description: Summary When a memory allocation fails inside assemble_init() in Python/assemble.c, the writers that were already created are released twice: once by the error: label in assemble_init() and again by assemble_f...

Open Graph Description: Bug report Bug description: Summary When a memory allocation fails inside assemble_init() in Python/assemble.c, the writers that were already created are released twice: once by the error: label in...

X Description: Bug report Bug description: Summary When a memory allocation fails inside assemble_init() in Python/assemble.c, the writers that were already created are released twice: once by the error: label in...

Opengraph URL: https://github.com/python/cpython/issues/158241

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Double release of `PyBytesWriter` in `assemble_init()` error path corrupts the bytes writer freelist","articleBody":"# Bug report\n\n### Bug description:\n\n### Summary\n\nWhen a memory allocation fails inside `assemble_init()` in `Python/assemble.c`, the writers that were already created are released twice: once by the `error:` label in `assemble_init()` and again by `assemble_free()`, which `_PyAssemble_MakeCodeObject()` always calls. The second release corrupts the `bytes_writers` freelist. On a debug build, a later `compile()` aborts with `Assertion 'fl->size > 0' failed` or segfaults. On a release build, no assertion fires. Instead, later `compile()` calls silently return code objects with corrupted `co_code` and `co_linetable`, and the process can segfault when freelists are cleared. Any `compile()` call reaches this path; the source text does not matter.\n\nThis reintroduces the double-release bug fixed by gh-151112/#151142.#155747 reintroduced it for the linetable writer, and #157349 extended it to all three writers.\n\n### Reproduction Code\n\nRequires `_testcapi` (for `set_nomemory`). The assertion requires a `--with-pydebug` build.\n\n```python\nimport _testcapi\ncompile(\"x\", \"\u003cs>\", \"exec\")  # warm up (initialise AST state) before injecting\nfor n in range(1, 300):\n    _testcapi.set_nomemory(n, n + 1)\n    try:\n        compile(\"x\", \"\u003cs>\", \"exec\")\n    except MemoryError:\n        pass\n    finally:\n        _testcapi.remove_mem_hooks()\nprint(\"no crash\")\n```\n\nOn a release build, the corruption shows up as wrong bytecode:\n\n```python\nimport sys, _testcapi\nref = compile(\"x\", \"\u003cs>\", \"exec\")\nfor n in range(500):\n    _testcapi.set_nomemory(n, n + 1)\n    try:\n        compile(\"x\", \"\u003cs>\", \"exec\")\n    except MemoryError:\n        pass\n    finally:\n        _testcapi.remove_mem_hooks()\nco = compile(\"x\", \"\u003cs>\", \"exec\")\nprint(co.co_code == ref.co_code, co.co_linetable == ref.co_linetable)\nprint(ref.co_code.hex(), co.co_code.hex())\nprint(ref.co_linetable.hex(), co.co_linetable.hex())\n```\n\n### Actual Behavior\n\nDebug build, first script:\n\n```\npython: ./Include/internal/pycore_freelist.h:79: _PyFreeList_PopNoStats: Assertion `fl->size > 0' failed.\nAborted (core dumped)\n```\n\nRunning each injection point in a separate process (one failing allocation, then three more `compile(\"x\")` calls) on a debug build gives this: failing the linetable writer allocation (`assemble.c:73`) triggers the assertion above. Failing the exception table writer allocation (`assemble.c:77`) crashes with SIGSEGV. Every other injection point raises `MemoryError` normally.\n\nRelease build, second script. The last two lines vary between runs because the overwritten bytes are pointer values:\n\n```\nFalse False\n8000000059001d004d072100 63bc00005f7000004d072100\nf103010101db0001 f0bc92785f700000\n```\n\nOn a release build, running the first script with the original source `\"try:\\n    pass\\nexcept* (A, B) as e:\\n    raise\\nfinally:\\n    del x\\n\"` (after `import ast`, n from 1 to 200) prints `no crash` and then segfaults during interpreter shutdown (exit code 139):\n\n```\n#0  insert_to_freepool (pool=0x7ffff7b28000, state=...) at Objects/obmalloc.c:2599\n#1  pymalloc_free (_unused_ctx=\u003coptimized out>, p=0x7ffff7b2bcf0, state=...) at Objects/obmalloc.c:2817\n#2  _PyObject_Free (ctx=\u003coptimized out>, p=0x7ffff7b2bcf0) at Objects/obmalloc.c:2831\n#4  clear_freelist (dofree=\u003coptimized out>, is_finalization=\u003coptimized out>, freelist=\u003coptimized out>) at Objects/object.c:908\n#5  _PyObject_ClearFreeLists (freelists=..., is_finalization=is_finalization@entry=0) at Objects/object.c:954\n#6  _PyGC_ClearAllFreeLists (interp=\u003coptimized out>) at Python/gc_gil.c:14\n#7  gc_collect_main (tstate=..., generation=generation@entry=2, reason=reason@entry=_Py_GC_REASON_MANUAL) at Python/gc.c:1611\n```\n\nThe release build's symptoms depend on heap layout. A variant of the second script without `import sys` returned correct code objects.\n\n### Expected Behavior\n\n`compile()` should raise `MemoryError` when an allocation fails, and leave interpreter state intact. Later `compile()` calls should succeed and produce the same code objects as before the failure. This was the behavior after the gh-151112 fix (#151142).\n\n### Detail\n\n#### Faulty control flow\n\n```c\nstatic int\nassemble_init(struct assembler *a, int firstlineno)\n{\n    memset(a, 0, sizeof(struct assembler));\n    ...\n    a->a_bytecode_writer = PyBytesWriter_Create(DEFAULT_CODE_SIZE);      // :69\n    ...\n    a->a_linetable_writer = PyBytesWriter_Create(DEFAULT_CNOTAB_SIZE);   // :73\n    ...\n    a->a_except_table_writer = PyBytesWriter_Create(DEFAULT_LNOTAB_SIZE); // :77\n    ...\n    return SUCCESS;\nerror:\n    PyBytesWriter_Discard(a->a_bytecode_writer);      // fields are not set to NULL\n    PyBytesWriter_Discard(a->a_linetable_writer);\n    PyBytesWriter_Discard(a->a_except_table_writer);\n    return ERROR;\n}\n```\n\n`assemble_emit()` returns `ERROR`, and `_PyAssemble_MakeCodeObject()` then calls `assemble_free()` unconditionally (`assemble.c:820`). `assemble_free()` calls `PyBytesWriter_Discard()` on the same three pointers again.\n\n\n#### Freelist corruption mechanism (debug build)\n\n`Py_bytes_writers_MAXFREELIST` is 1, so the second release does not form a self-loop in the freelist. gdb breakpoints on `PyBytesWriter_Create` and `PyBytesWriter_Discard`, for the round where the linetable allocation fails, show this sequence:\n\n```\n=== INJECTED FAIL in byteswriter_create, FmData.count=195 freelist.size=0 head=(nil)\n#2  assemble_init (a=a@entry=0x7fffffffd1e0, firstlineno=\u003coptimized out>) at Python/assemble.c:73\n--- Discard(0x7ffff77a4170) caller:\n#1  0x00005555557c72f9 in assemble_init (a=a@entry=0x7fffffffd1e0, firstlineno=\u003coptimized out>) at Python/assemble.c:83\n--- Discard(0x7ffff77a4170) caller:\n#1  0x00005555557c80ef in assemble_free (a=a@entry=0x7fffffffd1e0) at Python/assemble.c:92\n--- Create head=0x7ffff77a4170 size=1\n--- Create head=0xdddddddddddddddd size=0\npython: ./Include/internal/pycore_freelist.h:79: _PyFreeList_PopNoStats: Assertion `fl->size > 0' failed.\n```\n\n1. The bytecode writer B is allocated with `PyMem_Malloc`, because the freelist is empty.\n2. The linetable allocation fails. `error:` calls `Discard(B)`, and B is pushed onto the freelist (size 1). `a->a_bytecode_writer` still points to B.\n3. `assemble_free()` calls `Discard(B)` again. The freelist is full, so `_PyFreeList_Push()` refuses the push and B is passed to `PyMem_Free()` while it is still the freelist head.\n4. The next `PyBytesWriter_Create()` pops the freed B, which is a use-after-free. The freelist head becomes `0xdddddddddddddddd` and size becomes 0.\n5. The next `PyBytesWriter_Create()` finds a non-NULL head with size 0 and hits the assertion.\n\nFull stack at the second release:\n\n```\n#0  PyBytesWriter_Discard (writer=0x7ffff77a4170) at Objects/bytesobject.c:3810\n#1  assemble_free (a=a@entry=0x7fffffffd1e0) at Python/assemble.c:92\n#2  _PyAssemble_MakeCodeObject (...) at Python/assemble.c:820\n#3  optimize_and_assemble_code_unit (...) at Python/compile.c:1496\n#4  _PyCompile_OptimizeAndAssemble (c=c@entry=0x7ffff77c3740, addNone=addNone@entry=1) at Python/compile.c:1524\n#5  compiler_mod (...) at Python/compile.c:902\n#6  _PyAST_Compile (...) at Python/compile.c:1537\n#7  _Py_CompileString (...) at Python/pythonrun.c:1595\n```\n\nIf the exception table allocation (`:77`) fails instead, `error:` releases B (pushed to the freelist) and the linetable writer L (freelist full, so passed to `PyMem_Free()`). `assemble_free()` then reads the freed L inside `PyBytesWriter_Discard()`:\n\n```\n#0  PyObject_TypeCheck (ob=ob@entry=0xdddddddddddddddd, type=0x555555b95b00 \u003cPyByteArray_Type>) at ./Include/object.h:375\n#1  PyByteArray_AS_STRING (op=0xdddddddddddddddd) at ./Include/cpython/bytearrayobject.h:26\n#2  _PyBytesWriter_GetData (writer=writer@entry=0x7ffff7b59470) at ./Include/internal/pycore_bytesobject.h:110\n#3  byteswriter_data (writer=0x7ffff7b59470) at Objects/bytesobject.c:3627\n#4  byteswriter_check_canary_byte (writer=writer@entry=0x7ffff7b59470) at Objects/bytesobject.c:3651\n#5  PyBytesWriter_Discard (writer=0x7ffff7b59470) at Objects/bytesobject.c:3816\n#6  assemble_free (a=a@entry=0x7fffffffd0f0) at Python/assemble.c:93\n```\n\nWithout the debug canary check, this path would pass L to `PyMem_Free()` a second time.\n\n\n### CPython versions tested on:\n\nCPython main branch\n\n### Operating systems tested on:\n\nLinux\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-158242\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/lpyu001","@type":"Person","name":"lpyu001"},"datePublished":"2026-09-26T15:40:34Z","url":"https://github.com/python/cpython/issues/158241"}

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:7713a064-2dbc-cafd-7049-227e72bee034
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idA05C:A70A9:1301BAA:192574E:6B01EE03
html-safe-nonceb23d1f4021c290a17b9cd0dac67f9eb17c61b15b58c1ee392856cb4bfa3e24f1
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBMDVDOkE3MEE5OjEzMDFCQUE6MTkyNTc0RTo2QjAxRUUwMyIsInZpc2l0b3JfaWQiOiI4MjQ1NzcwNDI5MDUxMDM5MjM1IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0=
visitor-hmac0b9d7ac775777577ac914ad8c2c01e45ba31c35713a5fb2066587c06d79ade72
hovercard-subject-tagissue:5595193579
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/python/cpython/158241/issue_layout
twitter:imagehttps://opengraph.githubassets.com/ddcbf8dbdc0c834952ad3470b0ae9a8f4cb8f220ac45e5bb528e7a7f880e3139/python/cpython/issues/158241
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/ddcbf8dbdc0c834952ad3470b0ae9a8f4cb8f220ac45e5bb528e7a7f880e3139/python/cpython/issues/158241
og:image:altBug report Bug description: Summary When a memory allocation fails inside assemble_init() in Python/assemble.c, the writers that were already created are released twice: once by the error: label in...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamelpyu001
hostnamegithub.com
expected-hostnamegithub.com
None87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456
turbo-cache-controlno-preview
go-importgithub.com/python/cpython git https://github.com/python/cpython.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id81598961
octolytics-dimension-repository_nwopython/cpython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id81598961
octolytics-dimension-repository_network_root_nwopython/cpython
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
release423dbb54c5e7bfecc838eb387c1435eb3d0e760d
ui-targetcanary-1
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/python/cpython/issues/158241#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F158241
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%2Fpython%2Fcpython%2Fissues%2F158241
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=python%2Fcpython
Reloadhttps://github.com/python/cpython/issues/158241
Reloadhttps://github.com/python/cpython/issues/158241
Reloadhttps://github.com/python/cpython/issues/158241
pythonhttps://github.com/python
cpythonhttps://github.com/python/cpython
Codehttps://github.com/python/cpython
Issues5k+ (5k+)https://github.com/python/cpython/issues
Pull requests2.4k (2.4k)https://github.com/python/cpython/pulls
Actionshttps://github.com/python/cpython/actions
Projectshttps://github.com/python/cpython/projects
Security and qualityhttps://github.com/python/cpython/security
Insightshttps://github.com/python/cpython/insights
https://github.com/python/cpython
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/158241
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/158241
Double release of PyBytesWriter in assemble_init() error path corrupts the bytes writer freelisthttps://github.com/python/cpython/issues/158241#top
interpreter-core(Objects, Python, Grammar, and Parser dirs)https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
type-crashA hard crash of the interpreter, possibly with a core dumphttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-crash%22
https://github.com/lpyu001
lpyu001https://github.com/lpyu001
on Sep 26, 2026https://github.com/python/cpython/issues/158241#issue-5595193579
gh-151112https://github.com/python/cpython/issues/151112
#151142https://github.com/python/cpython/pull/151142
#155747https://github.com/python/cpython/pull/155747
#157349https://github.com/python/cpython/pull/157349
gh-151112https://github.com/python/cpython/issues/151112
#151142https://github.com/python/cpython/pull/151142
gh-158241: Prevent double release of assembler byte writers #158242https://github.com/python/cpython/pull/158242
lpyu001https://github.com/lpyu001
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
on Sep 26, 2026https://github.com/python/cpython/issues/158241#event-31896615294
gvanrossumhttps://github.com/gvanrossum
type-crashA hard crash of the interpreter, possibly with a core dumphttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-crash%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
on Sep 26, 2026https://github.com/python/cpython/issues/158241#event-31896755985
StanFromIrelandhttps://github.com/StanFromIreland
interpreter-core(Objects, Python, Grammar, and Parser dirs)https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
on Sep 26, 2026https://github.com/python/cpython/issues/158241#event-31897855302
vstinnerhttps://github.com/vstinner
on Sep 29, 2026https://github.com/python/cpython/issues/158241#event-32071945984
gh-158241: Prevent double release of assembler byte writers (#158242)https://github.com/python/cpython/commit/aa287d7f443c2e219b43f7b804b209971964d206
gh-158241https://github.com/python/cpython/issues/158241
#158242https://github.com/python/cpython/pull/158242
aa287d7https://github.com/python/cpython/commit/aa287d7f443c2e219b43f7b804b209971964d206
lpyu001https://github.com/lpyu001
completedhttps://github.com/python/cpython/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Acompleted
on Sep 29, 2026https://github.com/python/cpython/issues/158241#event-32073592060
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/cpython/issues/158241
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/cpython/issues/158241
interpreter-core(Objects, Python, Grammar, and Parser dirs)https://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22interpreter-core%22
type-crashA hard crash of the interpreter, possibly with a core dumphttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-crash%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

Viewport: width=device-width


URLs of crawlers that visited me.