Skip to content

[3.14] gh-142831: Fix use-after-free in json encoder during re-entrant mutation (gh-142851)#150078

Merged
gpshead merged 1 commit into
python:3.14from
ashm-dev:backport-gh-142831-3.14
May 20, 2026
Merged

[3.14] gh-142831: Fix use-after-free in json encoder during re-entrant mutation (gh-142851)#150078
gpshead merged 1 commit into
python:3.14from
ashm-dev:backport-gh-142831-3.14

Conversation

@ashm-dev
Copy link
Copy Markdown
Contributor

@ashm-dev ashm-dev commented May 19, 2026

Manual backport of #142851 to 3.14 (the bot couldn't cleanly cherry-pick due to refactors in main).

The fix had to be adapted because in 3.14 the dict/list iteration loops were not yet extracted into the _encoder_iterate_*_lock_held helpers introduced later in main. Added the Py_INCREF/Py_DECREF around each borrowed item/key/value inline in encoder_listencode_dict (both the PyMapping_Items and PyDict_Next paths) and encoder_listencode_list.

The two regression tests from the original PR were cherry-picked as-is.

Built --with-pydebug and ran ./python -m test test_json -v locally — all 218 tests pass.

… mutation (pythongh-142851)

User callbacks invoked during JSON encoding (e.g. the `default` callback or
a custom string encoder) can mutate or clear the dict or sequence being
encoded, invalidating borrowed references to items, keys, and values. Hold
strong references unconditionally while iterating.

Co-authored-by: Kumar Aditya <kumaraditya@python.org>
Co-authored-by: Gregory P. Smith <greg@krypto.org>
(cherry picked from commit 235fa72)
@gpshead gpshead self-assigned this May 20, 2026
@gpshead gpshead merged commit bba6c1d into python:3.14 May 20, 2026
56 of 57 checks passed
@ashm-dev ashm-dev deleted the backport-gh-142831-3.14 branch May 20, 2026 03:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants