From ec564e1cff25e94422e8e45a8943f379c82548ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?B=C3=A9n=C3=A9dikt=20Tran?= <10796600+picnixz@users.noreply.github.com> Date: Mon, 1 Sep 2025 10:21:39 +0200 Subject: [PATCH] gh-116946: fully implement GC protocol for `bz2` objects (GH-138266) (cherry picked from commit 9be91f6a20ed2fd9b491c3e779dc45c7392f60ca) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com> --- Modules/_bz2module.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Modules/_bz2module.c b/Modules/_bz2module.c index 9e85e0de42cd8d..f0f64b79d648eb 100644 --- a/Modules/_bz2module.c +++ b/Modules/_bz2module.c @@ -381,13 +381,14 @@ _bz2_BZ2Compressor_impl(PyTypeObject *type, int compresslevel) static void BZ2Compressor_dealloc(PyObject *op) { + PyTypeObject *tp = Py_TYPE(op); + PyObject_GC_UnTrack(op); BZ2Compressor *self = _BZ2Compressor_CAST(op); BZ2_bzCompressEnd(&self->bzs); if (self->lock != NULL) { PyThread_free_lock(self->lock); } - PyTypeObject *tp = Py_TYPE(self); - tp->tp_free((PyObject *)self); + tp->tp_free(self); Py_DECREF(tp); } @@ -420,7 +421,7 @@ static PyType_Spec bz2_compressor_type_spec = { // bz2_compressor_type_spec does not have Py_TPFLAGS_BASETYPE flag // which prevents to create a subclass. // So calling PyType_GetModuleState() in this file is always safe. - .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE), + .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_HAVE_GC), .slots = bz2_compressor_type_slots, }; @@ -686,9 +687,11 @@ _bz2_BZ2Decompressor_impl(PyTypeObject *type) static void BZ2Decompressor_dealloc(PyObject *op) { + PyTypeObject *tp = Py_TYPE(op); + PyObject_GC_UnTrack(op); BZ2Decompressor *self = _BZ2Decompressor_CAST(op); - if(self->input_buffer != NULL) { + if (self->input_buffer != NULL) { PyMem_Free(self->input_buffer); } BZ2_bzDecompressEnd(&self->bzs); @@ -696,9 +699,7 @@ BZ2Decompressor_dealloc(PyObject *op) if (self->lock != NULL) { PyThread_free_lock(self->lock); } - - PyTypeObject *tp = Py_TYPE(self); - tp->tp_free((PyObject *)self); + tp->tp_free(self); Py_DECREF(tp); } @@ -750,7 +751,7 @@ static PyType_Spec bz2_decompressor_type_spec = { // bz2_decompressor_type_spec does not have Py_TPFLAGS_BASETYPE flag // which prevents to create a subclass. // So calling PyType_GetModuleState() in this file is always safe. - .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE), + .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_HAVE_GC), .slots = bz2_decompressor_type_slots, };