From cefef286a62dbb82d1376c94e376580a5423c00f Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Fri, 4 Apr 2014 19:16:41 +0100 Subject: [PATCH] Fixed use of Python object with refcount 0 in cursor_init Caused segfault running test_cursor.CursorTests.test_invalid_name under Python 3.4 built in debug mode. --- NEWS | 1 + psycopg/cursor_type.c | 25 ++++++++++++++----------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/NEWS b/NEWS index e553b89e..79d88d6b 100644 --- a/NEWS +++ b/NEWS @@ -16,6 +16,7 @@ What's new in psycopg 2.5.3 (:ticket:`#203`). - Don't segfault using poorly defined cursor subclasses which forgot to call the superclass init (:ticket:`#195`). +- Fixed possible segfault in named cursors creation. - Fixed debug build on Windows, thanks to James Emerton. diff --git a/psycopg/cursor_type.c b/psycopg/cursor_type.c index 877e3390..d7294006 100644 --- a/psycopg/cursor_type.c +++ b/psycopg/cursor_type.c @@ -1899,31 +1899,34 @@ cursor_init(PyObject *obj, PyObject *args, PyObject *kwargs) { PyObject *conn; PyObject *name = Py_None; - const char *cname; + PyObject *bname = NULL; + const char *cname = NULL; + int rv = -1; static char *kwlist[] = {"conn", "name", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!|O", kwlist, &connectionType, &conn, &name)) { - return -1; + goto exit; } - if (name == Py_None) { - cname = NULL; - } else { + if (name != Py_None) { Py_INCREF(name); /* for ensure_bytes */ - if (!(name = psycopg_ensure_bytes(name))) { + if (!(bname = psycopg_ensure_bytes(name))) { /* name has had a ref stolen */ - return -1; + goto exit; } - Py_DECREF(name); - if (!(cname = Bytes_AsString(name))) { - return -1; + if (!(cname = Bytes_AsString(bname))) { + goto exit; } } - return cursor_setup((cursorObject *)obj, (connectionObject *)conn, cname); + rv = cursor_setup((cursorObject *)obj, (connectionObject *)conn, cname); + +exit: + Py_XDECREF(bname); + return rv; } static PyObject *