Repository navigation
gh-158925: Fix heap overflow in the UTF-16 encoder - #159007
Open
christianaurichzm wants to merge 1 commit into
Open
christianaurichzm wants to merge 1 commit into
christianaurichzm wants to merge 1 commit into
Conversation
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
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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, soucs4lib_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 byPyBytesWriter_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_bytesandtest_capi.test_unicodepass.The same code is in 3.10, so this should be backported.