Skip to content

[2.7] bpo-34068: iobase_close could call PyObject_SetAttrString with an exception set (GH-8282). (GH-8312) #8314

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

Merged
merged 1 commit into from
Jul 17, 2018
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
10 changes: 10 additions & 0 deletions Lib/test/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,16 @@ def read(self, size):
self.assertEqual(stream.readinto(buffer), 5)
self.assertEqual(buffer.tobytes(), b"12345")

def test_close_assert(self):
class R(self.IOBase):
def __setattr__(self, name, value):
pass
def flush(self):
raise OSError()
f = R()
# This would cause an assertion failure.
self.assertRaises(OSError, f.close)


class CIOTest(IOTest):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
In :meth:`io.IOBase.close`, ensure that the :attr:`~io.IOBase.closed`
attribute is not set with a live exception. Patch by Zackery Spytz and Serhiy
Storchaka.
14 changes: 11 additions & 3 deletions Modules/_io/iobase.c
Original file line number Diff line number Diff line change
Expand Up @@ -177,17 +177,25 @@ _PyIOBase_check_closed(PyObject *self, PyObject *args)
static PyObject *
iobase_close(PyObject *self, PyObject *args)
{
PyObject *res;
PyObject *res, *exc, *val, *tb;
int rc;

if (IS_CLOSED(self))
Py_RETURN_NONE;

res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL);
PyObject_SetAttrString(self, "__IOBase_closed", Py_True);

PyErr_Fetch(&exc, &val, &tb);
rc = PyObject_SetAttrString(self, "__IOBase_closed", Py_True);
_PyErr_ReplaceException(exc, val, tb);
if (rc < 0) {
Py_CLEAR(res);
}

if (res == NULL) {
return NULL;
}
Py_XDECREF(res);
Py_DECREF(res);
Py_RETURN_NONE;
}

Expand Down