]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-145623: Fix crashes on uninitialized struct.Struct objects (gh-145624)...
authorRamin Farajpour Cami <ramin.blackhat@gmail.com>
Mon, 9 Mar 2026 16:41:45 +0000 (20:11 +0330)
committerGitHub <noreply@github.com>
Mon, 9 Mar 2026 16:41:45 +0000 (17:41 +0100)
Lib/test/test_struct.py
Misc/NEWS.d/next/Library/2026-03-07-15-00-00.gh-issue-145623.2Y7LzT.rst [new file with mode: 0644]
Modules/_struct.c

index e602eeb6289808e744cf12a5c83a9df7aadcbbc4..a3f8fad7a9a0f91788013d2c6d234fa33a1d91dd 100644 (file)
@@ -806,6 +806,8 @@ class StructTest(unittest.TestCase):
         self.assertRaises(RuntimeError, S.unpack, spam)
         self.assertRaises(RuntimeError, S.unpack_from, spam)
         self.assertRaises(RuntimeError, getattr, S, 'format')
+        self.assertRaises(RuntimeError, S.__sizeof__)
+        self.assertRaises(RuntimeError, repr, S)
         self.assertEqual(S.size, -1)
 
 
diff --git a/Misc/NEWS.d/next/Library/2026-03-07-15-00-00.gh-issue-145623.2Y7LzT.rst b/Misc/NEWS.d/next/Library/2026-03-07-15-00-00.gh-issue-145623.2Y7LzT.rst
new file mode 100644 (file)
index 0000000..77b43e7
--- /dev/null
@@ -0,0 +1,3 @@
+Fix crash in :mod:`struct` when calling :func:`repr` or
+``__sizeof__()`` on an uninitialized :class:`struct.Struct`
+object created via ``Struct.__new__()`` without calling ``__init__()``.
index 55b32f074779b75c8116de0a9d15bd5c0cec2fe6..c3ca125e41ab6481cf873b6692308202d88c3a42 100644 (file)
@@ -2196,6 +2196,7 @@ PyDoc_STRVAR(s_sizeof__doc__,
 static PyObject *
 s_sizeof(PyStructObject *self, void *unused)
 {
+    ENSURE_STRUCT_IS_READY(self);
     size_t size = _PyObject_SIZE(Py_TYPE(self)) + sizeof(formatcode);
     for (formatcode *code = self->s_codes; code->fmtdef != NULL; code++) {
         size += sizeof(formatcode);
@@ -2206,6 +2207,7 @@ s_sizeof(PyStructObject *self, void *unused)
 static PyObject *
 s_repr(PyStructObject *self)
 {
+    ENSURE_STRUCT_IS_READY(self);
     PyObject* fmt = PyUnicode_FromStringAndSize(
         PyBytes_AS_STRING(self->s_format), PyBytes_GET_SIZE(self->s_format));
     if (fmt == NULL) {