From 889b1d826e9cf0ecbc9af938bad72937592af5e4 Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Thu, 20 Jun 2013 16:24:55 +0100 Subject: [PATCH] Untrack the connection before closing to avoid possible double-free From Gangadharan S.A. Fixes issue #166. --- NEWS | 2 ++ psycopg/connection_type.c | 7 +++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/NEWS b/NEWS index e2f6b7fe..53b1ec28 100644 --- a/NEWS +++ b/NEWS @@ -5,6 +5,8 @@ What's new in psycopg 2.5.1 declared (:ticket:`#146`). - Fixed comparison of `Range` with non-range objects (:ticket:`#164`). Thanks to Chris Withers for the patch. +- Fixed double-free on connection dealloc (:ticket:`#166`). Thanks to + Gangadharan S.A. for the report and fix suggestion. What's new in psycopg 2.5 diff --git a/psycopg/connection_type.c b/psycopg/connection_type.c index e854fa51..b3d4aa63 100644 --- a/psycopg/connection_type.c +++ b/psycopg/connection_type.c @@ -1128,10 +1128,13 @@ connection_dealloc(PyObject* obj) { connectionObject *self = (connectionObject *)obj; - conn_close(self); - + /* Make sure to untrack the connection before calling conn_close, which may + * allow a different thread to try and dealloc the connection again, + * resulting in a double-free segfault (ticket #166). */ PyObject_GC_UnTrack(self); + conn_close(self); + if (self->weakreflist) { PyObject_ClearWeakRefs(obj); }