From 83e275f01d51ae5ae3f26d29461389c4587c0993 Mon Sep 17 00:00:00 2001
From: Andrey Rachitskiy <pl0h0yp1@gmail.com>
Date: Tue, 17 Nov 2026 11:01:26 +0500
Subject: [PATCH v4] Check the remaining Python API failures in PL/Python

These are the same class of bug as the object construction fix, in the
places that do not build a row or an argument list.

PLy_result_new() left result->nrows NULL when PyLong_FromLong() failed,
so plpy.execute(...).nrows() did Py_INCREF(NULL). PLy_result_colnames()
and its two siblings stored an unchecked object into the list they
return, which leaves a NULL slot that crashes Python on first access.
PLy_spi_execute_fetch_result() and PLy_cursor_fetch() left the result's
status and nrows NULL the same way. PLy_procedure_compile() passed an
unchecked PyDict_Copy() result to PyDict_SetItemString().

PLyUnicode_Bytes() returned the unchecked result of
PyBytes_FromStringAndSize(), and PLyUnicode_AsString() passed it
straight to PyBytes_AsString(), which starts with PyBytes_Check() and
dereferences it. PLy_elog() reaches that path through PLy_traceback(),
so this is the OOM case where the message itself crashes the backend.
PLyUnicode_Bytes() now reports the failure, like its other two error
paths.

PLy_cursor_query() and PLy_cursor_fetch() returned NULL from PG_CATCH
without releasing the object they had built, so an error inside the
subtransaction leaked it. PLy_cursor_plan() and
PLy_spi_execute_fetch_result() already release theirs.

The remaining inserts whose result was ignored are checked too: GD in
PLy_init_interp(), SD in PLy_procedure_compile() and sqlstate in
PLy_generate_spi_exceptions().

Building the trigger TD dictionary now stores "event" as soon as it is
built. Setting it last leaked the string if the NEW or OLD conversion
threw in between.

BUG #19899
Author: Andrey Rachitskiy <pl0h0yp1@gmail.com>
Discussion: https://www.postgresql.org/message-id/19899-3e21845d988f0c0f@postgresql.org
---
 src/pl/plpython/plpy_cursorobject.c | 27 +++++++++++++++++-------
 src/pl/plpython/plpy_exec.c         |  8 +++-----
 src/pl/plpython/plpy_main.c         |  3 ++-
 src/pl/plpython/plpy_plpymodule.c   |  4 ++--
 src/pl/plpython/plpy_procedure.c    |  5 ++++-
 src/pl/plpython/plpy_resultobject.c | 32 ++++++++++++++++++++++-------
 src/pl/plpython/plpy_spi.c          | 23 +++++++++++++++------
 src/pl/plpython/plpy_util.c         | 19 ++++++++++++++---
 8 files changed, 89 insertions(+), 32 deletions(-)

diff --git a/src/pl/plpython/plpy_cursorobject.c b/src/pl/plpython/plpy_cursorobject.c
index 8d29e4725b2..9639f8e25f9 100644
--- a/src/pl/plpython/plpy_cursorobject.c
+++ b/src/pl/plpython/plpy_cursorobject.c
@@ -151,7 +151,12 @@ PLy_cursor_query(const char *query)
 	}
 	PG_CATCH();
 	{
+		/*
+		 * Release the cursor after the abort, so that its deallocator does
+		 * not try to close a portal that the abort has already dropped.
+		 */
 		PLy_spi_subtransaction_abort(oldcontext, oldowner);
+		Py_DECREF(cursor);
 		return NULL;
 	}
 	PG_END_TRY();
@@ -444,9 +449,13 @@ PLy_cursor_fetch(PyObject *self, PyObject *args)
 
 		Py_DECREF(ret->status);
 		ret->status = PyLong_FromLong(SPI_OK_FETCH);
+		if (ret->status == NULL)
+			PLy_elog(ERROR, "could not create the fetch status");
 
 		Py_DECREF(ret->nrows);
 		ret->nrows = PyLong_FromUnsignedLongLong(SPI_processed);
+		if (ret->nrows == NULL)
+			PLy_elog(ERROR, "could not create the fetched row count");
 
 		if (SPI_processed != 0)
 		{
@@ -464,12 +473,7 @@ PLy_cursor_fetch(PyObject *self, PyObject *args)
 
 			Py_DECREF(ret->rows);
 			ret->rows = PyList_New(SPI_processed);
-			if (!ret->rows)
-			{
-				Py_DECREF(ret);
-				ret = NULL;
-			}
-			else
+			if (ret->rows)
 			{
 				PLy_input_setup_tuple(&cursor->result, SPI_tuptable->tupdesc,
 									  exec_ctx->curr_proc);
@@ -481,7 +485,8 @@ PLy_cursor_fetch(PyObject *self, PyObject *args)
 														   SPI_tuptable->tupdesc,
 														   true);
 
-					PyList_SetItem(ret->rows, i, row);
+					PLyList_SetItem(ret->rows, i, row,
+									"could not store a row in the fetch result");
 				}
 			}
 		}
@@ -492,11 +497,19 @@ PLy_cursor_fetch(PyObject *self, PyObject *args)
 	}
 	PG_CATCH();
 	{
+		Py_DECREF(ret);
 		PLy_spi_subtransaction_abort(oldcontext, oldowner);
 		return NULL;
 	}
 	PG_END_TRY();
 
+	/* in case PyList_New() failed above */
+	if (!ret->rows)
+	{
+		Py_DECREF(ret);
+		return NULL;
+	}
+
 	return (PyObject *) ret;
 }
 
diff --git a/src/pl/plpython/plpy_exec.c b/src/pl/plpython/plpy_exec.c
index d31a072ead6..a6e3ab3912a 100644
--- a/src/pl/plpython/plpy_exec.c
+++ b/src/pl/plpython/plpy_exec.c
@@ -909,6 +909,7 @@ PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *r
 			if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
 			{
 				pltevent = PLyUnicode_FromString("INSERT");
+				PLyTD_SetItem(pltdata, "event", pltevent);
 
 				PLyTD_SetItemNone(pltdata, "old");
 				pytnew = PLy_input_from_tuple(&proc->result_in,
@@ -921,6 +922,7 @@ PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *r
 			else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
 			{
 				pltevent = PLyUnicode_FromString("DELETE");
+				PLyTD_SetItem(pltdata, "event", pltevent);
 
 				PLyTD_SetItemNone(pltdata, "new");
 				pytold = PLy_input_from_tuple(&proc->result_in,
@@ -933,6 +935,7 @@ PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *r
 			else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
 			{
 				pltevent = PLyUnicode_FromString("UPDATE");
+				PLyTD_SetItem(pltdata, "event", pltevent);
 
 				pytnew = PLy_input_from_tuple(&proc->result_in,
 											  tdata->tg_newtuple,
@@ -947,12 +950,7 @@ PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *r
 				*rv = tdata->tg_newtuple;
 			}
 			else
-			{
 				elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
-				pltevent = NULL;	/* keep compiler quiet */
-			}
-
-			PLyTD_SetItem(pltdata, "event", pltevent);
 		}
 		else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
 		{
diff --git a/src/pl/plpython/plpy_main.c b/src/pl/plpython/plpy_main.c
index e305f2a848a..d461bdbb562 100644
--- a/src/pl/plpython/plpy_main.c
+++ b/src/pl/plpython/plpy_main.c
@@ -83,7 +83,8 @@ _PG_init(void)
 	GD = PyDict_New();
 	if (GD == NULL)
 		PLy_elog(ERROR, NULL);
-	PyDict_SetItemString(main_dict, "GD", GD);
+	if (PyDict_SetItemString(main_dict, "GD", GD) < 0)
+		PLy_elog(ERROR, NULL);
 
 	/*
 	 * Import plpy.
diff --git a/src/pl/plpython/plpy_plpymodule.c b/src/pl/plpython/plpy_plpymodule.c
index 72806c17e17..9b4ca35eeed 100644
--- a/src/pl/plpython/plpy_plpymodule.c
+++ b/src/pl/plpython/plpy_plpymodule.c
@@ -227,8 +227,8 @@ PLy_generate_spi_exceptions(PyObject *mod, PyObject *base)
 		if (sqlstate == NULL)
 			PLy_elog(ERROR, "could not generate SPI exceptions");
 
-		PyDict_SetItemString(dict, "sqlstate", sqlstate);
-		Py_DECREF(sqlstate);
+		PLyDict_SetItemString(dict, "sqlstate", sqlstate,
+							  "could not generate SPI exceptions");
 
 		exc = PLy_create_exception(exception_map[i].name, base, dict,
 								   exception_map[i].classname, mod);
diff --git a/src/pl/plpython/plpy_procedure.c b/src/pl/plpython/plpy_procedure.c
index 76fee7974a2..8e806cc96bb 100644
--- a/src/pl/plpython/plpy_procedure.c
+++ b/src/pl/plpython/plpy_procedure.c
@@ -355,13 +355,16 @@ PLy_procedure_compile(PLyProcedure *proc, const char *src)
 	PyObject   *code0;
 
 	proc->globals = PyDict_Copy(PLy_interp_globals);
+	if (proc->globals == NULL)
+		PLy_elog(ERROR, NULL);
 
 	/*
 	 * SD is private preserved data between calls. GD is global data shared by
 	 * all functions.  The caller supplies SD.
 	 */
 	Assert(proc->statics != NULL);
-	PyDict_SetItemString(proc->globals, "SD", proc->statics);
+	if (PyDict_SetItemString(proc->globals, "SD", proc->statics) < 0)
+		PLy_elog(ERROR, NULL);
 
 	/*
 	 * insert the function code into the interpreter
diff --git a/src/pl/plpython/plpy_resultobject.c b/src/pl/plpython/plpy_resultobject.c
index d433929b360..9993ebbf850 100644
--- a/src/pl/plpython/plpy_resultobject.c
+++ b/src/pl/plpython/plpy_resultobject.c
@@ -104,7 +104,7 @@ PLy_result_new(void)
 	ob->nrows = PyLong_FromLong(-1);
 	ob->rows = PyList_New(0);
 	ob->tupdesc = NULL;
-	if (!ob->rows)
+	if (!ob->nrows || !ob->rows)
 	{
 		Py_DECREF(ob);
 		return NULL;
@@ -155,8 +155,14 @@ PLy_result_colnames(PyObject *self, PyObject *unused)
 	for (i = 0; i < ob->tupdesc->natts; i++)
 	{
 		Form_pg_attribute attr = TupleDescAttr(ob->tupdesc, i);
-
-		PyList_SetItem(list, i, PLyUnicode_FromString(NameStr(attr->attname)));
+		PyObject   *name = PLyUnicode_FromString(NameStr(attr->attname));
+
+		/* PyList_SetItem consumes name even when the store fails */
+		if (name == NULL || PyList_SetItem(list, i, name) < 0)
+		{
+			Py_DECREF(list);
+			return NULL;
+		}
 	}
 
 	return list;
@@ -181,8 +187,14 @@ PLy_result_coltypes(PyObject *self, PyObject *unused)
 	for (i = 0; i < ob->tupdesc->natts; i++)
 	{
 		Form_pg_attribute attr = TupleDescAttr(ob->tupdesc, i);
-
-		PyList_SetItem(list, i, PyLong_FromLong(attr->atttypid));
+		PyObject   *typid = PyLong_FromLong(attr->atttypid);
+
+		/* PyList_SetItem consumes typid even when the store fails */
+		if (typid == NULL || PyList_SetItem(list, i, typid) < 0)
+		{
+			Py_DECREF(list);
+			return NULL;
+		}
 	}
 
 	return list;
@@ -207,8 +219,14 @@ PLy_result_coltypmods(PyObject *self, PyObject *unused)
 	for (i = 0; i < ob->tupdesc->natts; i++)
 	{
 		Form_pg_attribute attr = TupleDescAttr(ob->tupdesc, i);
-
-		PyList_SetItem(list, i, PyLong_FromLong(attr->atttypmod));
+		PyObject   *typmod = PyLong_FromLong(attr->atttypmod);
+
+		/* PyList_SetItem consumes typmod even when the store fails */
+		if (typmod == NULL || PyList_SetItem(list, i, typmod) < 0)
+		{
+			Py_DECREF(list);
+			return NULL;
+		}
 	}
 
 	return list;
diff --git a/src/pl/plpython/plpy_spi.c b/src/pl/plpython/plpy_spi.c
index 419e0a9b9ae..f455b8c8531 100644
--- a/src/pl/plpython/plpy_spi.c
+++ b/src/pl/plpython/plpy_spi.c
@@ -359,20 +359,30 @@ PLy_spi_execute_fetch_result(SPITupleTable *tuptable, uint64 rows, int status)
 	}
 	Py_DECREF(result->status);
 	result->status = PyLong_FromLong(status);
+	if (result->status == NULL)
+	{
+		Py_DECREF(result);
+		SPI_freetuptable(tuptable);
+		return NULL;
+	}
 
-	if (status > 0 && tuptable == NULL)
+	if (status > 0)
 	{
 		Py_DECREF(result->nrows);
 		result->nrows = PyLong_FromUnsignedLongLong(rows);
+		if (result->nrows == NULL)
+		{
+			Py_DECREF(result);
+			SPI_freetuptable(tuptable);
+			return NULL;
+		}
 	}
-	else if (status > 0 && tuptable != NULL)
+
+	if (status > 0 && tuptable != NULL)
 	{
 		PLyDatumToOb ininfo;
 		MemoryContext cxt;
 
-		Py_DECREF(result->nrows);
-		result->nrows = PyLong_FromUnsignedLongLong(rows);
-
 		cxt = AllocSetContextCreate(CurrentMemoryContext,
 									"PL/Python temp context",
 									ALLOCSET_DEFAULT_SIZES);
@@ -414,7 +424,8 @@ PLy_spi_execute_fetch_result(SPITupleTable *tuptable, uint64 rows, int status)
 															   tuptable->tupdesc,
 															   true);
 
-						PyList_SetItem(result->rows, i, row);
+						PLyList_SetItem(result->rows, i, row,
+										"could not store a row in the query result");
 					}
 				}
 			}
diff --git a/src/pl/plpython/plpy_util.c b/src/pl/plpython/plpy_util.c
index 1b8a53f2401..ed25dfcfdfc 100644
--- a/src/pl/plpython/plpy_util.c
+++ b/src/pl/plpython/plpy_util.c
@@ -13,7 +13,8 @@
 /*
  * Convert a Python unicode object to a Python string/bytes object in
  * PostgreSQL server encoding.  Reference ownership is passed to the
- * caller.
+ * caller.  Failure is reported with PLy_elog(ERROR), so the result is
+ * never NULL.
  */
 PyObject *
 PLyUnicode_Bytes(PyObject *unicode)
@@ -69,6 +70,10 @@ PLyUnicode_Bytes(PyObject *unicode)
 		pfree(encoded);
 
 	Py_DECREF(bytes);
+
+	if (rv == NULL)
+		PLy_elog(ERROR, "could not create bytes representation of Python object");
+
 	return rv;
 }
 
@@ -81,9 +86,17 @@ char *
 PLyUnicode_AsString(PyObject *unicode)
 {
 	PyObject   *o = PLyUnicode_Bytes(unicode);
-	char	   *rv = pstrdup(PyBytes_AsString(o));
+	char	   *s = PyBytes_AsString(o);
+	char	   *rv;
+
+	if (s == NULL)
+	{
+		Py_DECREF(o);
+		PLy_elog(ERROR, "could not extract bytes from encoded string");
+	}
 
-	Py_XDECREF(o);
+	rv = pstrdup(s);
+	Py_DECREF(o);
 	return rv;
 }
 
-- 
2.53.0

