Backport of: From 7d512c8e4442a896d56505be3e78f1156f443465 Mon Sep 17 00:00:00 2001 From: Riccardo Schirone Date: Wed, 13 Nov 2019 14:54:21 +0100 Subject: [PATCH] Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible double-free. --- psutil/_psutil_aix.c | 18 +++++++------- psutil/_psutil_bsd.c | 30 +++++++++++----------- psutil/_psutil_linux.c | 14 +++++------ psutil/_psutil_osx.c | 39 ++++++++++++++--------------- psutil/_psutil_sunos.c | 43 ++++++++++++++++---------------- psutil/_psutil_windows.c | 54 ++++++++++++++++++++-------------------- 6 files changed, 97 insertions(+), 101 deletions(-) --- a/psutil/_psutil_linux.c +++ b/psutil/_psutil_linux.c @@ -232,9 +232,9 @@ psutil_disk_partitions(PyObject *self, P goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; - Py_DECREF(py_dev); - Py_DECREF(py_mountp); - Py_DECREF(py_tuple); + Py_CLEAR(py_dev); + Py_CLEAR(py_mountp); + Py_CLEAR(py_tuple); } endmntent(file); return py_retlist; @@ -488,10 +488,10 @@ psutil_users(PyObject *self, PyObject *a goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; - Py_DECREF(py_username); - Py_DECREF(py_tty); - Py_DECREF(py_hostname); - Py_DECREF(py_tuple); + Py_CLEAR(py_username); + Py_CLEAR(py_tty); + Py_CLEAR(py_hostname); + Py_CLEAR(py_tuple); } endutent(); return py_retlist;