Skip to content

Commit 2cd24eb

Browse files
fix thread safety of io.StringIO.truncate (#133732)
1 parent 308ceff commit 2cd24eb

File tree

2 files changed

+22
-14
lines changed

2 files changed

+22
-14
lines changed

Modules/_io/clinic/stringio.c.h

Lines changed: 5 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Modules/_io/stringio.c

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -444,7 +444,7 @@ stringio_iternext(PyObject *op)
444444
/*[clinic input]
445445
@critical_section
446446
_io.StringIO.truncate
447-
pos as size: Py_ssize_t(accept={int, NoneType}, c_default="((stringio *)self)->pos") = None
447+
pos: object = None
448448
/
449449
450450
Truncate size to pos.
@@ -455,16 +455,26 @@ Returns the new absolute position.
455455
[clinic start generated code]*/
456456

457457
static PyObject *
458-
_io_StringIO_truncate_impl(stringio *self, Py_ssize_t size)
459-
/*[clinic end generated code: output=eb3aef8e06701365 input=fa8a6c98bb2ba780]*/
458+
_io_StringIO_truncate_impl(stringio *self, PyObject *pos)
459+
/*[clinic end generated code: output=c76c43b5ecfaf4e2 input=d59fd2ee49757ae6]*/
460460
{
461461
CHECK_INITIALIZED(self);
462462
CHECK_CLOSED(self);
463463

464-
if (size < 0) {
465-
PyErr_Format(PyExc_ValueError,
466-
"Negative size value %zd", size);
467-
return NULL;
464+
Py_ssize_t size;
465+
if (pos == Py_None) {
466+
size = self->pos;
467+
}
468+
else {
469+
size = PyLong_AsLong(pos);
470+
if (size == -1 && PyErr_Occurred()) {
471+
return NULL;
472+
}
473+
if (size < 0) {
474+
PyErr_Format(PyExc_ValueError,
475+
"negative pos value %zd", size);
476+
return NULL;
477+
}
468478
}
469479

470480
if (size < self->string_size) {

0 commit comments

Comments
 (0)