Skip to content

gh-132470: Prevent crash in ctypes.CField when byte_size is incorrect #132475

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion Lib/test/test_ctypes/test_struct_fields.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import unittest
import sys
from ctypes import Structure, Union, sizeof, c_char, c_int, CField
from ctypes import Structure, Union, sizeof, c_byte, c_char, c_int, CField
from ._support import Py_TPFLAGS_IMMUTABLETYPE, StructCheckMixin


Expand Down Expand Up @@ -75,6 +75,17 @@ def __init_subclass__(cls, **kwargs):
'ctypes state is not initialized'):
class Subclass(BrokenStructure): ...

def test_invalid_byte_size_raises_gh132470(self):
with self.assertRaisesRegex(ValueError, r"does not match type size"):
CField(
name="a",
type=c_byte,
byte_size=2, # Wrong size: c_byte is only 1 byte
byte_offset=2,
index=1,
_internal_use=True
)

def test_max_field_size_gh126937(self):
# Classes for big structs should be created successfully.
# (But they most likely can't be instantiated.)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Creating a :class:`ctypes.CField` with a *byte_size* that does not match the actual
type size now raises a :exc:`ValueError` instead of crashing the interpreter.
7 changes: 6 additions & 1 deletion Modules/_ctypes/cfield.c
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,12 @@ PyCField_new_impl(PyTypeObject *type, PyObject *name, PyObject *proto,
"type of field %R must be a C type", name);
goto error;
}
assert(byte_size == info->size);
if (byte_size != info->size) {
PyErr_Format(PyExc_ValueError,
"byte size of field %R (%zd) does not match type size (%zd)",
name, byte_size, info->size);
goto error;
}

Py_ssize_t bitfield_size = 0;
Py_ssize_t bit_offset = 0;
Expand Down
Loading