From 5014048432b5221fa91b47078a6513665083d0cf Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Mon, 14 Nov 2022 17:40:58 +0100 Subject: [PATCH] gh-99485: Fix gen_new_with_qualname() refleak on the code object --- Modules/_testcapimodule.c | 32 ++++++++++++++++++++++++++++++++ Objects/genobject.c | 1 - 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/Modules/_testcapimodule.c b/Modules/_testcapimodule.c index 62fd1f6ec7aa569..120da891d964d4c 100644 --- a/Modules/_testcapimodule.c +++ b/Modules/_testcapimodule.c @@ -23,6 +23,7 @@ #include "datetime.h" // PyDateTimeAPI #include "marshal.h" // PyMarshal_WriteLongToFile #include "structmember.h" // PyMemberDef +#include "frameobject.h" // PyFrame_New() #include // FLT_MAX #include @@ -6107,6 +6108,36 @@ unwatch_type(PyObject *self, PyObject *args) } +static PyObject * +test_gen_new(PyObject *self, PyObject *Py_UNUSED(args)) +{ + PyCodeObject *code = PyCode_NewEmpty("filename", "func_name", 1); + if (code == NULL) { + return NULL; + } + + PyObject *globals = PyDict_New(); + if (globals == NULL) { + return NULL; + } + PyObject *locals = globals; // borrowed ref + + PyThreadState *tstate = PyThreadState_Get(); + PyFrameObject *frame = PyFrame_New(tstate, code, globals, locals); + if (frame == NULL) { + return NULL; + } + + PyObject *gen = PyGen_New(frame); + Py_DECREF(gen); + + Py_DECREF(code); + Py_DECREF(globals); + Py_DECREF(frame); + Py_RETURN_NONE; +} + + static PyObject *test_buildvalue_issue38913(PyObject *, PyObject *); static PyObject *getargs_s_hash_int(PyObject *, PyObject *, PyObject*); static PyObject *getargs_s_hash_int2(PyObject *, PyObject *, PyObject*); @@ -6414,6 +6445,7 @@ static PyMethodDef TestMethods[] = { {"watch_type", watch_type, METH_VARARGS, NULL}, {"unwatch_type", unwatch_type, METH_VARARGS, NULL}, {"get_type_modified_events", get_type_modified_events, METH_NOARGS, NULL}, + {"test_gen_new", test_gen_new, METH_NOARGS, NULL}, {NULL, NULL} /* sentinel */ }; diff --git a/Objects/genobject.c b/Objects/genobject.c index 3e0e0750970a6d2..d3d6f9018967a7c 100644 --- a/Objects/genobject.c +++ b/Objects/genobject.c @@ -939,7 +939,6 @@ gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f, frame->owner = FRAME_OWNED_BY_GENERATOR; assert(PyObject_GC_IsTracked((PyObject *)f)); gen->gi_code = PyFrame_GetCode(f); - Py_INCREF(gen->gi_code); Py_DECREF(f); gen->gi_weakreflist = NULL; gen->gi_exc_state.exc_value = NULL;