Skip to content

Commit d1adc33

Browse files
committed
gh-156939: Fix xmlcharrefreplace() buffer overflow
Write into a temporay buffer to not write the trailing NUL byte.
1 parent 1f25c33 commit d1adc33

1 file changed

Lines changed: 10 additions & 4 deletions

File tree

Objects/unicodeobject.c

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -879,10 +879,16 @@ xmlcharrefreplace(PyBytesWriter *writer, char *str,
879879

880880
/* generate replacement */
881881
for (i = collstart; i < collend; ++i) {
882-
size = sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
883-
if (size < 0) {
884-
return NULL;
885-
}
882+
// len('&#1114111;\0') is 11 bytes
883+
Py_BUILD_ASSERT(_Py_MAX_UNICODE <= 0x10ffff);
884+
char buffer[11];
885+
Py_UCS4 ch = PyUnicode_READ(kind, data, i);
886+
size = snprintf(buffer, sizeof(buffer), "&#%d;", ch);
887+
assert(5 <= size && (size_t)size <= (sizeof(buffer) - 1));
888+
889+
// Use snprintf() to write into a temporary buffer to not write
890+
// the trailing NUL byte
891+
memcpy(str, buffer, size);
886892
str += size;
887893
}
888894
return str;

0 commit comments

Comments
 (0)