From 9ff0c71abf38ccc27ef50bcdf383db5e1749af05 Mon Sep 17 00:00:00 2001 From: Melissa0x1f992 <70096546+Melissa0x1f992@users.noreply.github.com> Date: Tue, 10 Dec 2024 06:13:11 -0600 Subject: [PATCH] gh-126937: ctypes: add test for maximum size of a struct field (GH-126938) This backports the test from GH-126938, with changed limit and exception class. Co-authored-by: Melissa0x1f992 <70096546+Melissa0x1f992@users.noreply.github.com> Co-authored-by: Peter Bierma Co-authored-by: Terry Jan Reedy Co-authored-by: Petr Viktorin --- Lib/test/test_ctypes/test_struct_fields.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Lib/test/test_ctypes/test_struct_fields.py b/Lib/test/test_ctypes/test_struct_fields.py index 7adab794809def..fd9509757a39ad 100644 --- a/Lib/test/test_ctypes/test_struct_fields.py +++ b/Lib/test/test_ctypes/test_struct_fields.py @@ -1,4 +1,5 @@ import unittest +import sys from ctypes import Structure, Union, sizeof, c_char, c_int from ._support import (CField, Py_TPFLAGS_DISALLOW_INSTANTIATION, Py_TPFLAGS_IMMUTABLETYPE) @@ -75,6 +76,27 @@ def __init_subclass__(cls, **kwargs): 'ctypes state is not initialized'): class Subclass(BrokenStructure): ... + def test_max_field_size_gh126937(self): + # Classes for big structs should be created successfully. + # (But they most likely can't be instantiated.) + # The size must fit in Py_ssize_t. + + class X(Structure): + _fields_ = [('char', c_char),] + max_field_size = sys.maxsize + + class Y(Structure): + _fields_ = [('largeField', X * max_field_size)] + class Z(Structure): + _fields_ = [('largeField', c_char * max_field_size)] + + with self.assertRaises(OverflowError): + class TooBig(Structure): + _fields_ = [('largeField', X * (max_field_size + 1))] + with self.assertRaises(OverflowError): + class TooBig(Structure): + _fields_ = [('largeField', c_char * (max_field_size + 1))] + # __set__ and __get__ should raise a TypeError in case their self # argument is not a ctype instance. def test___set__(self):