Skip to content
Open
11 changes: 11 additions & 0 deletions Lib/test/test_io/test_bufferedio.py
Original file line number Diff line number Diff line change
Expand Up @@ -983,6 +983,17 @@ def closed(self):
self.assertRaisesRegex(ValueError, "test", bufio.flush)
self.assertRaisesRegex(ValueError, "test", bufio.close)

def test_gh_143375(self):
bufio = self.tp(self.MockRawIO())

class EvilIndex:
def __index__(self):
bufio.close()
return 0

with self.assertRaisesRegex(ValueError, "seek of closed file"):
bufio.seek(EvilIndex())


class PyBufferedWriterTest(BufferedWriterTest, PyTestCase):
tp = pyio.BufferedWriter
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a crash in :meth:`~io.BufferedWriter.seek` when passing an object with a
specially crafted :meth:`~object.__index__`.
4 changes: 4 additions & 0 deletions Modules/_io/bufferedio.c
Original file line number Diff line number Diff line change
Expand Up @@ -1393,6 +1393,10 @@ _io__Buffered_seek_impl(buffered *self, PyObject *targetobj, int whence)
if (target == -1 && PyErr_Occurred())
return NULL;

// PyNumber_AsOff_t calls user code via __index__, which
// could have closed the file.
CHECK_CLOSED(self, "seek of closed file")
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not think this comment is needed. It is trivial if we do all right, and we do not what to add such comments for each second line.

Remove CHECK_CLOSED above, it is redundant. Also, I think it is better to move PyNumber_AsOff_t immediately after the whence check.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, and CHECK_INITIALIZED also should be after PyNumber_AsOff_t. Add a test for concurrent detach().

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not think this comment is needed.

Removed

Remove CHECK_CLOSED above, it is redundant.

Also removed

Also, I think it is better to move PyNumber_AsOff_t immediately after the whence check.

Done

Add a test for concurrent detach().

Added!


/* SEEK_SET and SEEK_CUR are special because we could seek inside the
buffer. Other whence values must be managed without this optimization.
Some Operating Systems can provide additional values, like
Expand Down
Loading