Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-121849: Fix PyUnicodeWriter_WriteSubstring() crash if len=0 #121896

Merged
merged 1 commit into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Lib/test/test_capi/test_unicode.py
Original file line number Diff line number Diff line change
Expand Up @@ -1736,7 +1736,7 @@ def test_basic(self):
writer.write_char('=')

# test PyUnicodeWriter_WriteSubstring()
writer.write_substring("[long]", 1, 5);
writer.write_substring("[long]", 1, 5)

# test PyUnicodeWriter_WriteStr()
writer.write_str(" value ")
Expand Down Expand Up @@ -1862,6 +1862,10 @@ def test_ucs4(self):
with self.assertRaises(ValueError):
writer.write_ucs4("text", -1)

def test_substring_empty(self):
writer = self.create_writer(0)
writer.write_substring("abc", 1, 1)
self.assertEqual(writer.finish(), '')


@unittest.skipIf(ctypes is None, 'need ctypes')
Expand Down
23 changes: 12 additions & 11 deletions Objects/unicodeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -13637,27 +13637,28 @@ int
_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
Py_ssize_t start, Py_ssize_t end)
{
Py_UCS4 maxchar;
Py_ssize_t len;

assert(0 <= start);
assert(end <= PyUnicode_GET_LENGTH(str));
assert(start <= end);

if (end == 0)
picnixz marked this conversation as resolved.
Show resolved Hide resolved
return 0;

if (start == 0 && end == PyUnicode_GET_LENGTH(str))
return _PyUnicodeWriter_WriteStr(writer, str);

if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
Py_ssize_t len = end - start;
picnixz marked this conversation as resolved.
Show resolved Hide resolved
if (len == 0) {
return 0;
}

Py_UCS4 maxchar;
if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar) {
maxchar = _PyUnicode_FindMaxChar(str, start, end);
else
}
else {
maxchar = writer->maxchar;
len = end - start;

if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
}
if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0) {
return -1;
}

_PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
str, start, len);
Expand Down
Loading