From 9e41114676aee46c1aec0212405ee95c131c157e Mon Sep 17 00:00:00 2001
From: Peter Eisentraut <peter_e@gmx.net>
Date: Tue, 3 Nov 2009 09:35:18 +0000
Subject: [PATCH] Fix obscure segfault condition in PL/Python

In PLy_output(), when the elog() call in the TRY branch throws an exception
(this can happen when a statement timeout kicks in, for example), the
PyErr_SetString() call in the CATCH branch can cause a segfault, because the
Py_XDECREF(so) call before it releases memory that is still used by the sv
variable that PyErr_SetString() uses as argument, because sv points into
memory owned by so.

Backpatched back to 8.0, where this code was introduced.

I also threw in a couple of volatile declarations for variables that are used
before and after the TRY.  I don't think they caused the crash that I
observed, but they could become issues.
---
 src/pl/plpython/plpython.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/src/pl/plpython/plpython.c b/src/pl/plpython/plpython.c
index c37993829f1..43b1db790a1 100644
--- a/src/pl/plpython/plpython.c
+++ b/src/pl/plpython/plpython.c
@@ -1,7 +1,7 @@
 /**********************************************************************
  * plpython.c - python as a procedural language for PostgreSQL
  *
- *	$PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.130 2009/09/13 22:07:06 petere Exp $
+ *	$PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.131 2009/11/03 09:35:18 petere Exp $
  *
  *********************************************************************
  */
@@ -3076,9 +3076,9 @@ PLy_fatal(PyObject *self, PyObject *args)
 static PyObject *
 PLy_output(volatile int level, PyObject *self, PyObject *args)
 {
-	PyObject   *so;
+	PyObject   *volatile so;
 	char	   *volatile sv;
-	MemoryContext oldcontext;
+	volatile MemoryContext oldcontext;
 
 	so = PyObject_Str(args);
 	if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
@@ -3097,6 +3097,10 @@ PLy_output(volatile int level, PyObject *self, PyObject *args)
 		MemoryContextSwitchTo(oldcontext);
 		PLy_error_in_progress = CopyErrorData();
 		FlushErrorState();
+
+		PyErr_SetString(PLy_exc_error, sv);
+		/* Note: If sv came from PyString_AsString(), it points into
+		 * storage owned by so.  So free so after using sv. */
 		Py_XDECREF(so);
 
 		/*
@@ -3104,7 +3108,6 @@ PLy_output(volatile int level, PyObject *self, PyObject *args)
 		 * control passes back to PLy_procedure_call, we check for PG
 		 * exceptions and re-throw the error.
 		 */
-		PyErr_SetString(PLy_exc_error, sv);
 		return NULL;
 	}
 	PG_END_TRY();
-- 
GitLab