FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

gh-158925: Fix heap overflow in the UTF-16 encoder by christianaurichzm · Pull Request #159007 · python/cpython · GitHub

Repository navigation

gh-158925: Fix heap overflow in the UTF-16 encoder - #159007

Open
christianaurichzm wants to merge 1 commit into
python:mainfrom
christianaurichzm:gh-158925-utf16-encode-backward
Open

christianaurichzm wants to merge 1 commit into
python:mainfrom
christianaurichzm:gh-158925-utf16-encode-backward

Conversation

christianaurichzm commented Oct 8, 2026 •
edited by bedevere-app Bot
Loading

Copy link
Copy Markdown
Contributor

Fixes #158925

If an encode error handler returns a position before the error, _PyUnicode_EncodeUTF16() grows the buffer by one code unit for each character it will encode again (moreunits += pos - newpos). In a UCS-4 string a non-BMP character takes two units, so ucs4lib_utf16_encode() ends up writing past the end of the buffer.

Fix: in that case reserve two units per character, same as the UTF-8 encoder does for backward jumps (max_char_size * (startpos - newpos)). Whatever isn't used gets trimmed by PyBytesWriter_FinishWithPointer(). UCS-2 strings and forward jumps don't need it, and UTF-32 is always 4 bytes per character so it's fine.

Tested on a debug build: the reproducer from the issue and the new test both crash without the patch and pass with it (also with -R 3:3). The test checks the UTF-8, UTF-16 and UTF-32 encoders. test_codeccallbacks, test_codecs, test_str, test_bytes and test_capi.test_unicode pass.

The same code is in 3.10, so this should be backported.

When an encode error handler returned a position before the error,
_PyUnicode_EncodeUTF16() reserved one code unit for each character to
be re-encoded, but non-BMP characters take two (a surrogate pair). This
underestimated the buffer size and caused a heap buffer overflow.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

_PyUnicode_EncodeUTF16 backward error-handler under-reserve leading to heap overflow

1 participant


Back | FazBrowse Home | New Git URL