]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.14] gh-151912: Fix segfault in `type()` with NULL `tp_new` metaclasses (GH-151916...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Tue, 14 Jul 2026 16:46:33 +0000 (18:46 +0200)
committerGitHub <noreply@github.com>
Tue, 14 Jul 2026 16:46:33 +0000 (22:16 +0530)
gh-151912: Fix segfault in `type()` with NULL `tp_new` metaclasses (GH-151916)
(cherry picked from commit f160f16373f9ea3f636bc5cd6fb4be7e150bb27f)

Co-authored-by: Santhosh .I 🦇 <santhoshilaiyaraja2006@gmail.com>
Lib/test/test_descr.py
Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-14-48-22.gh-issue-151912.YcxfnU.rst [new file with mode: 0644]
Objects/typeobject.c

index 798074a5f637f61cd398d0cf54f2b58405445721..626e05f4a085235f52210be7e18347c446b6f838 100644 (file)
@@ -815,6 +815,15 @@ class ClassPropertiesAndMethods(unittest.TestCase):
             class X(int(), C):
                 pass
 
+    @unittest.skipIf(_testcapi is None, 'need the _testcapi module')
+    def test_type_with_null_new_metaclass(self):
+        metaclass = _testcapi.HeapCTypeMetaclassNullNew
+        base = _testcapi.pytype_fromspec_meta(metaclass)
+
+        # Exercise type_new's metaclass selection path, not a direct call.
+        with self.assertRaisesRegex(TypeError, r"cannot create '.*' instances"):
+            type("Derived", (base,), {})
+
     def test_module_subclasses(self):
         # Testing Python subclass of module...
         log = []
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-14-48-22.gh-issue-151912.YcxfnU.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-22-14-48-22.gh-issue-151912.YcxfnU.rst
new file mode 100644 (file)
index 0000000..07b7394
--- /dev/null
@@ -0,0 +1 @@
+Fixed a crash in ``type()`` when selecting a metaclass whose ``tp_new`` slot is ``NULL``. Such metaclasses are now rejected with ``TypeError`` instead of causing a NULL pointer dereference.
index 40cb8816c8342a86463d45344905f07d929e4142..c0138933fead47cfe37f66f86bb2af02cadd26e3 100644 (file)
@@ -4733,6 +4733,13 @@ type_new_get_bases(type_new_ctx *ctx, PyObject **type)
 
     if (winner != ctx->metatype) {
         if (winner->tp_new != type_new) {
+            /* Check if tp_new is NULL (cannot instantiate this type) */
+            if (winner->tp_new == NULL) {
+                PyErr_Format(PyExc_TypeError,
+                             "cannot create '%.400s' instances",
+                             winner->tp_name);
+                return -1;
+            }
             /* Pass it to the winner */
             *type = winner->tp_new(winner, ctx->args, ctx->kwds);
             if (*type == NULL) {