[3.14] gh-143164: Fix incorrect error message for ctypes bitfield overflow (GH-143165) (GH-143176)

(cherry picked from commit b9a4806430)

Signed-off-by: Yongtao Huang <yongtaoh2022@gmail.com>
Co-authored-by: Yongtao Huang <yongtaoh2022@gmail.com>
This commit is contained in:
Miss Islington (bot) 2025-12-25 18:34:02 +01:00 committed by GitHub
parent 88a4d0d34b
commit 723ed8c507
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 18 additions and 2 deletions

View file

@ -130,6 +130,21 @@ class S(Structure):
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.

View file

@ -0,0 +1 @@
Fix the ctypes bitfield overflow error message to report the correct offset and size calculation.

View 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;
}
}