From 7eb16ab17d5c01b293aad35f0843e5f3a9a64080 Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Mon, 11 Dec 2017 16:33:20 -0500
Subject: [PATCH] Fix corner-case coredump in _SPI_error_callback().

I noticed that _SPI_execute_plan initially sets spierrcontext.arg = NULL,
and only fills it in some time later.  If an error were to happen in
between, _SPI_error_callback would try to dereference the null pointer.
This is unlikely --- there's not much between those points except
push-snapshot calls --- but it's clearly not impossible.  Tweak the
callback to do nothing if the pointer isn't set yet.

It's been like this for awhile, so back-patch to all supported branches.
---
 src/backend/executor/spi.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/src/backend/executor/spi.c b/src/backend/executor/spi.c
index 2da1cac3e21..f3da2ddd080 100644
--- a/src/backend/executor/spi.c
+++ b/src/backend/executor/spi.c
@@ -2367,6 +2367,9 @@ _SPI_error_callback(void *arg)
 	const char *query = (const char *) arg;
 	int			syntaxerrposition;
 
+	if (query == NULL)			/* in case arg wasn't set yet */
+		return;
+
 	/*
 	 * If there is a syntax error position, convert to internal syntax error;
 	 * otherwise treat the query as an item of context stack