Skip to content

Commit

Permalink
Make sure that exported string ends with NUL character
Browse files Browse the repository at this point in the history
  • Loading branch information
vstinner committed Jun 21, 2024
1 parent 53cd937 commit 3a08491
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion Modules/_testlimitedcapi/unicode.c
Original file line number Diff line number Diff line change
Expand Up @@ -1850,11 +1850,33 @@ unicode_export(PyObject *self, PyObject *args)

Py_ssize_t size;
uint32_t format;
const void *data = PyUnicode_Export(obj, requested_formats, &size, &format);
const char *data = PyUnicode_Export(obj, requested_formats, &size, &format);
if (data == NULL) {
return NULL;
}

// Make sure that the exported string ends with a NUL character
switch (format)
{
case PyUnicode_FORMAT_ASCII:
case PyUnicode_FORMAT_UCS1:
assert(data[size] == 0);
break;
case PyUnicode_FORMAT_UCS2:
assert(data[size] == 0);
assert(data[size+1] == 0);
break;
case PyUnicode_FORMAT_UCS4:
assert(data[size] == 0);
assert(data[size+1] == 0);
assert(data[size+2] == 0);
assert(data[size+3] == 0);
break;
case PyUnicode_FORMAT_UTF8:
assert(data[size] == 0);
break;
}

PyObject *res = Py_BuildValue("y#I", data, size, (unsigned int)format);
PyUnicode_ReleaseExport(obj, data, format);
return res;
Expand Down

0 comments on commit 3a08491

Please sign in to comment.