From a7b3035175488cd26791cd7f935eb1ed03de304a Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Wed, 2 Aug 2023 14:42:32 +0200 Subject: [PATCH] Fix segfault in Python 3.12b4 In `flo_read` and `flo_write` there were calls to `Py_DECREF` after releasing the GIL. Closes #237 --- yara-python.c | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/yara-python.c b/yara-python.c index 1d851b9..714317c 100644 --- a/yara-python.c +++ b/yara-python.c @@ -1394,29 +1394,28 @@ static size_t flo_read( PyObject* bytes = PyObject_CallMethod( (PyObject*) user_data, "read", "n", (Py_ssize_t) size); - PyGILState_Release(gil_state); - - if (bytes != NULL) + if (bytes == NULL) { - Py_ssize_t len; - char* buffer; - - int result = PyBytes_AsStringAndSize(bytes, &buffer, &len); + PyGILState_Release(gil_state); + return i; + } - if (result == -1 || (size_t) len < size) - { - Py_DECREF(bytes); - return i; - } + Py_ssize_t len; + char* buffer; - memcpy((char*) ptr + i * size, buffer, size); + int result = PyBytes_AsStringAndSize(bytes, &buffer, &len); - Py_DECREF(bytes); - } - else + if (result == -1 || (size_t) len < size) { + Py_DECREF(bytes); + PyGILState_Release(gil_state); return i; } + + memcpy((char*) ptr + i * size, buffer, size); + + Py_DECREF(bytes); + PyGILState_Release(gil_state); } return count; @@ -1444,12 +1443,11 @@ static size_t flo_write( (PyObject*) user_data, "write", "s#", (char*) ptr + i * size, size); #endif + Py_XDECREF(result); PyGILState_Release(gil_state); if (result == NULL) return i; - - Py_DECREF(result); } return count;