]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-82626: Emit a warning when bool is used as a file descriptor (GH-111275)
authorSerhiy Storchaka <storchaka@gmail.com>
Mon, 5 Feb 2024 20:51:11 +0000 (22:51 +0200)
committerGitHub <noreply@github.com>
Mon, 5 Feb 2024 20:51:11 +0000 (22:51 +0200)
Doc/whatsnew/3.13.rst
Lib/_pyio.py
Lib/test/test_fileio.py
Lib/test/test_genericpath.py
Lib/test/test_os.py
Lib/test/test_posix.py
Misc/NEWS.d/next/Library/2023-10-24-19-19-54.gh-issue-82626._hfLRf.rst [new file with mode: 0644]
Modules/_io/fileio.c
Modules/faulthandler.c
Modules/posixmodule.c
Objects/fileobject.c

index 0770e28d230b4b346ce09800d1f76fb033ff67dc..9bac36ba0bffb8c6c498a0111fde5f92fc6966b1 100644 (file)
@@ -145,6 +145,11 @@ Other Language Changes
   is rejected when the global is used in the :keyword:`else` block.
   (Contributed by Irit Katriel in :gh:`111123`.)
 
+* Many functions now emit a warning if a boolean value is passed as
+  a file descriptor argument.
+  This can help catch some errors earlier.
+  (Contributed by Serhiy Storchaka in :gh:`82626`.)
+
 * Added a new environment variable :envvar:`PYTHON_FROZEN_MODULES`. It
   determines whether or not frozen modules are ignored by the import machinery,
   equivalent of the :option:`-X frozen_modules <-X>` command-line option.
index df2c29bfa9caeed653d382902b15e6ab7f428734..8a0d0dc4b1a0b85a4dee9873af8a55e814afe87b 100644 (file)
@@ -1495,6 +1495,11 @@ class FileIO(RawIOBase):
         if isinstance(file, float):
             raise TypeError('integer argument expected, got float')
         if isinstance(file, int):
+            if isinstance(file, bool):
+                import warnings
+                warnings.warn("bool is used as a file descriptor",
+                              RuntimeWarning, stacklevel=2)
+                file = int(file)
             fd = file
             if fd < 0:
                 raise ValueError('negative file descriptor')
index 06d9b454add34cd380e45e5af32caae8f0b889c4..06d5a8abf320835dbed1080d45043b49c7d90498 100644 (file)
@@ -484,6 +484,14 @@ class OtherFileTests:
             import msvcrt
             self.assertRaises(OSError, msvcrt.get_osfhandle, make_bad_fd())
 
+    def testBooleanFd(self):
+        for fd in False, True:
+            with self.assertWarnsRegex(RuntimeWarning,
+                    'bool is used as a file descriptor') as cm:
+                f = self.FileIO(fd, closefd=False)
+            f.close()
+            self.assertEqual(cm.filename, __file__)
+
     def testBadModeArgument(self):
         # verify that we get a sensible error message for bad mode argument
         bad_mode = "qwerty"
index b77cd4c67d6b2ae5762024d7bc226885fe13b860..f407ee3caf154c28ed9d7d7f4e06266256410f0f 100644 (file)
@@ -165,6 +165,12 @@ class GenericTest:
             os.close(w)
         self.assertFalse(self.pathmodule.exists(r))
 
+    def test_exists_bool(self):
+        for fd in False, True:
+            with self.assertWarnsRegex(RuntimeWarning,
+                    'bool is used as a file descriptor'):
+                self.pathmodule.exists(fd)
+
     def test_isdir(self):
         filename = os_helper.TESTFN
         bfilename = os.fsencode(filename)
index 86af1a8ed8ee15474d909deb81f1b4fd70a5594d..2c8823ae47c726ec6d5678c9fbd932ade94d5985 100644 (file)
@@ -2195,12 +2195,15 @@ class Win32ErrorTests(unittest.TestCase):
 class TestInvalidFD(unittest.TestCase):
     singles = ["fchdir", "dup", "fdatasync", "fstat",
                "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
+    singles_fildes = {"fchdir", "fdatasync", "fsync"}
     #singles.append("close")
     #We omit close because it doesn't raise an exception on some platforms
     def get_single(f):
         def helper(self):
             if  hasattr(os, f):
                 self.check(getattr(os, f))
+                if f in self.singles_fildes:
+                    self.check_bool(getattr(os, f))
         return helper
     for f in singles:
         locals()["test_"+f] = get_single(f)
@@ -2214,8 +2217,16 @@ class TestInvalidFD(unittest.TestCase):
             self.fail("%r didn't raise an OSError with a bad file descriptor"
                       % f)
 
+    def check_bool(self, f, *args, **kwargs):
+        with warnings.catch_warnings():
+            warnings.simplefilter("error", RuntimeWarning)
+            for fd in False, True:
+                with self.assertRaises(RuntimeWarning):
+                    f(fd, *args, **kwargs)
+
     def test_fdopen(self):
         self.check(os.fdopen, encoding="utf-8")
+        self.check_bool(os.fdopen, encoding="utf-8")
 
     @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()')
     def test_isatty(self):
@@ -2277,11 +2288,14 @@ class TestInvalidFD(unittest.TestCase):
     def test_fpathconf(self):
         self.check(os.pathconf, "PC_NAME_MAX")
         self.check(os.fpathconf, "PC_NAME_MAX")
+        self.check_bool(os.pathconf, "PC_NAME_MAX")
+        self.check_bool(os.fpathconf, "PC_NAME_MAX")
 
     @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()')
     def test_ftruncate(self):
         self.check(os.truncate, 0)
         self.check(os.ftruncate, 0)
+        self.check_bool(os.truncate, 0)
 
     @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()')
     def test_lseek(self):
index 72e348fbbdcbc14acdd199d44b3da5939caddd93..a45f620e18dc1d0c1b122b69a946bc36d3122bae 100644 (file)
@@ -1514,6 +1514,13 @@ class TestPosixDirFd(unittest.TestCase):
             self.assertRaises(OverflowError,
                     posix.stat, name, dir_fd=10**20)
 
+            for fd in False, True:
+                with self.assertWarnsRegex(RuntimeWarning,
+                        'bool is used as a file descriptor') as cm:
+                    with self.assertRaises(OSError):
+                        posix.stat('nonexisting', dir_fd=fd)
+                self.assertEqual(cm.filename, __file__)
+
     @unittest.skipUnless(os.utime in os.supports_dir_fd, "test needs dir_fd support in os.utime()")
     def test_utime_dir_fd(self):
         with self.prepare_file() as (dir_fd, name, fullname):
diff --git a/Misc/NEWS.d/next/Library/2023-10-24-19-19-54.gh-issue-82626._hfLRf.rst b/Misc/NEWS.d/next/Library/2023-10-24-19-19-54.gh-issue-82626._hfLRf.rst
new file mode 100644 (file)
index 0000000..92a66b5
--- /dev/null
@@ -0,0 +1,2 @@
+Many functions now emit a warning if a boolean value is passed as a file
+descriptor argument.
index 9cf268ca0b26c81a809ee1607711a6674f42798f..6bb156e41fe43cb8291e21a2fe7204ff44606776 100644 (file)
@@ -269,6 +269,13 @@ _io_FileIO___init___impl(fileio *self, PyObject *nameobj, const char *mode,
             self->fd = -1;
     }
 
+    if (PyBool_Check(nameobj)) {
+        if (PyErr_WarnEx(PyExc_RuntimeWarning,
+                "bool is used as a file descriptor", 1))
+        {
+            return -1;
+        }
+    }
     fd = PyLong_AsInt(nameobj);
     if (fd < 0) {
         if (!PyErr_Occurred()) {
index a2e3c2300b3ce8580e82caa37f6ce6aef705321d..95d646c9c65b3c4ff72aa33e5482e23d61c0c319 100644 (file)
@@ -119,6 +119,13 @@ faulthandler_get_fileno(PyObject **file_ptr)
         }
     }
     else if (PyLong_Check(file)) {
+        if (PyBool_Check(file)) {
+            if (PyErr_WarnEx(PyExc_RuntimeWarning,
+                    "bool is used as a file descriptor", 1))
+            {
+                return -1;
+            }
+        }
         fd = PyLong_AsInt(file);
         if (fd == -1 && PyErr_Occurred())
             return -1;
index 40ff131b119d66fcf944e0531c7022cd9c08298e..22891135bde0af7edaeaff9dbb0af1dab2fc05b4 100644 (file)
@@ -969,6 +969,13 @@ _fd_converter(PyObject *o, int *p)
     int overflow;
     long long_value;
 
+    if (PyBool_Check(o)) {
+        if (PyErr_WarnEx(PyExc_RuntimeWarning,
+                "bool is used as a file descriptor", 1))
+        {
+            return 0;
+        }
+    }
     PyObject *index = _PyNumber_Index(o);
     if (index == NULL) {
         return 0;
index 5522eba34eace9b024c01e1f3d8c7c5d90ba4391..e30ab952dff571be77f1329aef99b668ef10d240 100644 (file)
@@ -174,6 +174,13 @@ PyObject_AsFileDescriptor(PyObject *o)
     PyObject *meth;
 
     if (PyLong_Check(o)) {
+        if (PyBool_Check(o)) {
+            if (PyErr_WarnEx(PyExc_RuntimeWarning,
+                    "bool is used as a file descriptor", 1))
+            {
+                return -1;
+            }
+        }
         fd = PyLong_AsInt(o);
     }
     else if (PyObject_GetOptionalAttr(o, &_Py_ID(fileno), &meth) < 0) {