Skip to content

Commit b9a4806

Browse files
gh-143164: Fix incorrect error message for ctypes bitfield overflow (GH-143165)
Signed-off-by: Yongtao Huang <[email protected]>
1 parent 8611f74 commit b9a4806

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

Lib/test/test_ctypes/test_struct_fields.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,21 @@ class S(Structure):
130130
self.check_struct(S)
131131
self.assertEqual(S.largeField.bit_size, size * 8)
132132

133+
def test_bitfield_overflow_error_message(self):
134+
with self.assertRaisesRegex(
135+
ValueError,
136+
r"bit field 'x' overflows its type \(2 \+ 7 > 8\)",
137+
):
138+
CField(
139+
name="x",
140+
type=c_byte,
141+
byte_size=1,
142+
byte_offset=0,
143+
index=0,
144+
_internal_use=True,
145+
bit_size=7,
146+
bit_offset=2,
147+
)
133148

134149
# __set__ and __get__ should raise a TypeError in case their self
135150
# argument is not a ctype instance.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix the ctypes bitfield overflow error message to report the correct offset and size calculation.

Modules/_ctypes/cfield.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,8 @@ PyCField_new_impl(PyTypeObject *type, PyObject *name, PyObject *proto,
160160
if ((bitfield_size + bit_offset) > byte_size * 8) {
161161
PyErr_Format(
162162
PyExc_ValueError,
163-
"bit field %R overflows its type (%zd + %zd >= %zd)",
164-
name, bit_offset, byte_size*8);
163+
"bit field %R overflows its type (%zd + %zd > %zd)",
164+
name, bit_offset, bitfield_size, byte_size * 8);
165165
goto error;
166166
}
167167
}

0 commit comments

Comments
 (0)