]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-125118: don't copy arbitrary values to _Bool in the struct module (GH-125169)
authorSergey B Kirpichev <skirpichev@gmail.com>
Thu, 10 Oct 2024 12:42:03 +0000 (15:42 +0300)
committerGitHub <noreply@github.com>
Thu, 10 Oct 2024 12:42:03 +0000 (14:42 +0200)
memcopy'ing arbitrary values to _Bool variable triggers undefined
behaviour. Avoid this.
We assume that `false` is represented by all zero bytes.

Credits to Alex Gaynor.

Co-authored-by: Sam Gross <colesbury@gmail.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
Co-authored-by: Petr Viktorin <encukou@gmail.com>
Lib/test/test_struct.py
Misc/NEWS.d/next/Library/2024-10-09-07-09-00.gh-issue-125118.J9rQ1S.rst [new file with mode: 0644]
Modules/_struct.c

index e3193c7863fbaef11ade54acc15f2edeaaa92067..04ec3ed0837c82b5725a5a261c58ddcbd6ad1772 100644 (file)
@@ -540,6 +540,9 @@ class StructTest(ComplexesAreIdenticalMixin, unittest.TestCase):
 
         for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']:
             self.assertTrue(struct.unpack('>?', c)[0])
+            self.assertTrue(struct.unpack('<?', c)[0])
+            self.assertTrue(struct.unpack('=?', c)[0])
+            self.assertTrue(struct.unpack('@?', c)[0])
 
     def test_count_overflow(self):
         hugecount = '{}b'.format(sys.maxsize+1)
diff --git a/Misc/NEWS.d/next/Library/2024-10-09-07-09-00.gh-issue-125118.J9rQ1S.rst b/Misc/NEWS.d/next/Library/2024-10-09-07-09-00.gh-issue-125118.J9rQ1S.rst
new file mode 100644 (file)
index 0000000..5d57cdb
--- /dev/null
@@ -0,0 +1 @@
+Don't copy arbitrary values to :c:expr:`_Bool` in the :mod:`struct` module.
index 4387c55b7c88486efc810bb03e3c40283e513214..21582b945be23d1399ebf1772a568d57189e564f 100644 (file)
@@ -497,9 +497,8 @@ nu_ulonglong(_structmodulestate *state, const char *p, const formatdef *f)
 static PyObject *
 nu_bool(_structmodulestate *state, const char *p, const formatdef *f)
 {
-    _Bool x;
-    memcpy(&x, p, sizeof x);
-    return PyBool_FromLong(x != 0);
+    const _Bool bool_false = 0;
+    return PyBool_FromLong(memcmp(p, &bool_false, sizeof(_Bool)));
 }