diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -894,6 +894,12 @@ fp.close() unlink(TESTFN) + def test_open_handles_NUL_chars(self): + self.write_testfile() + fn_with_NUL = TESTFN + '\0foobar' + self.assertRaises(TypeError, open, fn_with_NUL, 'r') + self.assertRaises(TypeError, open, bytes(fn_with_NUL, 'ascii'), 'r') + def test_ord(self): self.assertEqual(ord(' '), 32) self.assertEqual(ord('A'), 65) diff --git a/Modules/_io/fileio.c b/Modules/_io/fileio.c --- a/Modules/_io/fileio.c +++ b/Modules/_io/fileio.c @@ -265,28 +265,11 @@ #endif if (fd < 0) { - if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) { - Py_ssize_t namelen; - if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0) - return -1; + PyObject *conv_name; + if (!PyUnicode_FSConverter(nameobj, &conv_name)) { + return -1; } - else { - PyObject *u = PyUnicode_FromObject(nameobj); - - if (u == NULL) - return -1; - - stringobj = PyUnicode_EncodeFSDefault(u); - Py_DECREF(u); - if (stringobj == NULL) - return -1; - if (!PyBytes_Check(stringobj)) { - PyErr_SetString(PyExc_TypeError, - "encoder failed to return bytes"); - goto error; - } - name = PyBytes_AS_STRING(stringobj); - } + name = PyBytes_AS_STRING(conv_name); } s = mode;