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
Domain: github.com
{"@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-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:7713a064-2dbc-cafd-7049-227e72bee034 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | A05C:A70A9:1301BAA:192574E:6B01EE03 |
| html-safe-nonce | b23d1f4021c290a17b9cd0dac67f9eb17c61b15b58c1ee392856cb4bfa3e24f1 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBMDVDOkE3MEE5OjEzMDFCQUE6MTkyNTc0RTo2QjAxRUUwMyIsInZpc2l0b3JfaWQiOiI4MjQ1NzcwNDI5MDUxMDM5MjM1IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 0b9d7ac775777577ac914ad8c2c01e45ba31c35713a5fb2066587c06d79ade72 |
| hovercard-subject-tag | issue:5595193579 |
| 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/python/cpython/158241/issue_layout |
| twitter:image | https://opengraph.githubassets.com/ddcbf8dbdc0c834952ad3470b0ae9a8f4cb8f220ac45e5bb528e7a7f880e3139/python/cpython/issues/158241 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/ddcbf8dbdc0c834952ad3470b0ae9a8f4cb8f220ac45e5bb528e7a7f880e3139/python/cpython/issues/158241 |
| og:image:alt | 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... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | lpyu001 |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| 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 | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | canary-1 |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width