From f5c5b73895b68d8c6fd032a4fd5f98a9e5fb8a4a Mon Sep 17 00:00:00 2001 From: Nir Soffer Date: Jun 17 2019 14:05:45 +0000 Subject: python: Streamline initexception When we create the sanlock exception we create a function, create a method from the function, create a dict from the method, and finally create an exception from the dict. This simple flow does not require goto for cleanup. Creating a dict is simpler and less error prone using Py_BuildValue(). When we finish with unused pointers, it is safer to set them to NULL using Py_CLEAR(), ensuring that we don't access freed memory. Signed-off-by: Nir Soffer --- diff --git a/python/sanlock.c b/python/sanlock.c index 21a7a76..5c2fd1a 100644 --- a/python/sanlock.c +++ b/python/sanlock.c @@ -1743,29 +1743,22 @@ sanlock_exception = { static PyObject * initexception(void) { - int rv; - PyObject *dict, *func, *meth, *excp = NULL; - - if ((dict = PyDict_New()) == NULL) - goto exit_fail; - - if ((func = PyCFunction_New(&sanlock_exception, NULL)) == NULL) - goto exit_fail; + PyObject *func = PyCFunction_New(&sanlock_exception, NULL); + if (func == NULL) + return NULL; - meth = PyObject_CallFunction((PyObject *) &PyProperty_Type, "O", func); - Py_DECREF(func); + PyObject *meth = PyObject_CallFunction((PyObject *) &PyProperty_Type, "O", func); + Py_CLEAR(func); if (meth == NULL) - goto exit_fail; - - rv = PyDict_SetItemString(dict, sanlock_exception.ml_name, meth); - Py_DECREF(meth); - if (rv < 0) - goto exit_fail; + return NULL; - excp = PyErr_NewException("sanlock.SanlockException", NULL, dict); + PyObject *dict = Py_BuildValue("{s:O}", sanlock_exception.ml_name, meth); + Py_CLEAR(meth); + if (dict == NULL) + return NULL; -exit_fail: - Py_XDECREF(dict); + PyObject *excp = PyErr_NewException("sanlock.SanlockException", NULL, dict); + Py_CLEAR(dict); return excp; }