]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-143164: Fix incorrect error message for ctypes bitfield overflow (GH-143165)
authorYongtao Huang <yongtaoh2022@gmail.com>
Thu, 25 Dec 2025 17:08:43 +0000 (01:08 +0800)
committerGitHub <noreply@github.com>
Thu, 25 Dec 2025 17:08:43 +0000 (19:08 +0200)
Signed-off-by: Yongtao Huang <yongtaoh2022@gmail.com>
Lib/test/test_ctypes/test_struct_fields.py
Misc/NEWS.d/next/Library/2025-12-25-08-58-55.gh-issue-142164.XrFztf.rst [new file with mode: 0644]
Modules/_ctypes/cfield.c

index b50bbcbb65c4233865be8ba86c25f17f4bf93669..dc26e26d8a9fb116754da92c28ba76dfb1a4cf13 100644 (file)
@@ -130,6 +130,21 @@ class FieldsTestBase(StructCheckMixin):
             self.check_struct(S)
             self.assertEqual(S.largeField.bit_size, size * 8)
 
+    def test_bitfield_overflow_error_message(self):
+        with self.assertRaisesRegex(
+            ValueError,
+            r"bit field 'x' overflows its type \(2 \+ 7 > 8\)",
+        ):
+            CField(
+                name="x",
+                type=c_byte,
+                byte_size=1,
+                byte_offset=0,
+                index=0,
+                _internal_use=True,
+                bit_size=7,
+                bit_offset=2,
+            )
 
     # __set__ and __get__ should raise a TypeError in case their self
     # argument is not a ctype instance.
diff --git a/Misc/NEWS.d/next/Library/2025-12-25-08-58-55.gh-issue-142164.XrFztf.rst b/Misc/NEWS.d/next/Library/2025-12-25-08-58-55.gh-issue-142164.XrFztf.rst
new file mode 100644 (file)
index 0000000..e75270b
--- /dev/null
@@ -0,0 +1 @@
+Fix the ctypes bitfield overflow error message to report the correct offset and size calculation.
index 547e2471a1cbc045218a91ce174c39ce820f540a..4ebca0e0b3db0a332462858b8afedaefa35f234b 100644 (file)
@@ -160,8 +160,8 @@ PyCField_new_impl(PyTypeObject *type, PyObject *name, PyObject *proto,
         if ((bitfield_size + bit_offset) > byte_size * 8) {
             PyErr_Format(
                 PyExc_ValueError,
-                "bit field %R overflows its type (%zd + %zd >= %zd)",
-                name, bit_offset, byte_size*8);
+                "bit field %R overflows its type (%zd + %zd > %zd)",
+                name, bit_offset, bitfield_size, byte_size * 8);
             goto error;
         }
     }