From fc023ba9eb5be813e855f64f09732d69062fa404 Mon Sep 17 00:00:00 2001
From: Andrey Rachitskiy <pl0h0yp1@gmail.com>
Date: Thu, 19 Nov 2026 20:17:25 +0500
Subject: [PATCH] Fix SQL-function argument read after buffer unpin

A lazy SQL-language SRF that stops early is shut down from
ShutdownSQLFunction. standard_ExecutorEnd reaches that callback only
after ExecEndPlan has dropped the scan's buffer pins.
postquel_sub_params left a pass-by-ref argument pointing at the
caller's heap tuple, so auto_explain's BuildParamLogString read the
unpinned page.

Copy those arguments into the lazy function's subcontext in
postquel_start, while the caller still holds the pins. postquel_end
deletes that context only after ExecutorEnd.

Bug: #19921
Reported-by: Fin <nakamurajames123@gmail.com>
---
 contrib/auto_explain/Makefile             |   4 +-
 contrib/auto_explain/auto_explain.c       |  11 +++
 contrib/auto_explain/meson.build          |   4 +
 contrib/auto_explain/t/002_param_unpin.pl | 113 ++++++++++++++++++++++
 src/backend/executor/functions.c          |  36 ++++++-
 5 files changed, 164 insertions(+), 4 deletions(-)
 create mode 100644 contrib/auto_explain/t/002_param_unpin.pl

diff --git a/contrib/auto_explain/Makefile b/contrib/auto_explain/Makefile
index 1f608b1d733..4ae1d0de1e9 100644
--- a/contrib/auto_explain/Makefile
+++ b/contrib/auto_explain/Makefile
@@ -6,7 +6,9 @@ OBJS = \
 	auto_explain.o
 PGFILEDESC = "auto_explain - logging facility for execution plans"
 
-EXTRA_INSTALL = contrib/pg_overexplain
+EXTRA_INSTALL = contrib/pg_overexplain \
+				contrib/pg_buffercache \
+				src/test/modules/injection_points
 REGRESS = alter_reset extension_options
 
 TAP_TESTS = 1
diff --git a/contrib/auto_explain/auto_explain.c b/contrib/auto_explain/auto_explain.c
index 97ce498d0c1..2b9e74d42c0 100644
--- a/contrib/auto_explain/auto_explain.c
+++ b/contrib/auto_explain/auto_explain.c
@@ -25,6 +25,7 @@
 #include "nodes/value.h"
 #include "parser/scansup.h"
 #include "utils/guc.h"
+#include "utils/injection_point.h"
 #include "utils/varlena.h"
 
 PG_MODULE_MAGIC_EXT(
@@ -453,6 +454,16 @@ explain_ExecutorEnd(QueryDesc *queryDesc)
 
 			ExplainBeginOutput(es);
 			ExplainQueryText(es, queryDesc);
+
+			/*
+			 * A test can stop here, after the caller has dropped its buffer
+			 * pins and before the parameter values are read. A lazy SQL
+			 * function reaches this point from that caller's ExecutorEnd.
+			 */
+			if (queryDesc->params != NULL &&
+				queryDesc->params->numParams > 0)
+				INJECTION_POINT("auto-explain-before-params", NULL);
+
 			ExplainQueryParameters(es, queryDesc->params, auto_explain_log_parameter_max_length);
 			ExplainPrintPlan(es, queryDesc);
 			if (es->analyze && auto_explain_log_triggers)
diff --git a/contrib/auto_explain/meson.build b/contrib/auto_explain/meson.build
index d2b0650af1c..a1b645fb8a5 100644
--- a/contrib/auto_explain/meson.build
+++ b/contrib/auto_explain/meson.build
@@ -27,8 +27,12 @@ tests += {
     ],
   },
   'tap': {
+    'env': {
+      'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
+    },
     'tests': [
       't/001_auto_explain.pl',
+      't/002_param_unpin.pl',
     ],
   },
 }
diff --git a/contrib/auto_explain/t/002_param_unpin.pl b/contrib/auto_explain/t/002_param_unpin.pl
new file mode 100644
index 00000000000..b56d3060242
--- /dev/null
+++ b/contrib/auto_explain/t/002_param_unpin.pl
@@ -0,0 +1,113 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# A lazy SQL-language SRF is shut down from the caller's ExecutorEnd, after
+# that plan has dropped its buffer pins. auto_explain then formats the
+# function arguments. This test stops at that point, replaces the unpinned
+# page, and checks that the logged parameter is still the original value.
+
+use strict;
+use warnings FATAL => 'all';
+
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+use Time::HiRes qw(usleep);
+
+plan skip_all => 'Injection points not supported by this build'
+  unless $ENV{enable_injection_points} eq 'yes';
+
+my $node = PostgreSQL::Test::Cluster->new('main');
+
+$node->init;
+$node->append_conf(
+	'postgresql.conf', q{
+shared_buffers = 1MB
+shared_preload_libraries = 'auto_explain,injection_points'
+auto_explain.log_min_duration = 0
+auto_explain.log_nested_statements = on
+auto_explain.log_parameter_max_length = -1
+log_min_messages = log
+});
+$node->start;
+
+plan skip_all => 'Extension injection_points not installed'
+  unless $node->check_extension('injection_points');
+plan skip_all => 'Extension pg_buffercache not installed'
+  unless $node->check_extension('pg_buffercache');
+
+$node->safe_psql(
+	'postgres', q{
+CREATE EXTENSION injection_points;
+CREATE EXTENSION pg_buffercache;
+
+CREATE TABLE t (v text);
+INSERT INTO t SELECT repeat('abc', 10) FROM generate_series(1, 100);
+CREATE FUNCTION srf(a text) RETURNS SETOF int LANGUAGE sql
+  AS $$ SELECT g FROM generate_series(1, 10) g $$;
+});
+
+my $point = 'auto-explain-before-params';
+
+$node->safe_psql('postgres',
+	"SELECT injection_points_attach('$point', 'wait');");
+
+my $victim = $node->background_psql('postgres', on_error_stop => 0);
+
+$victim->query_until(
+	qr/starting_select/, q{
+\echo starting_select
+SELECT srf(v) FROM t LIMIT 1;
+});
+
+ok(wait_for_injection_point($node, $point), "hit injection point $point");
+
+# Evict leaves the old bytes in place. A second relation has to reuse the page.
+$node->safe_psql(
+	'postgres', q{
+SELECT buffers_evicted FROM pg_buffercache_evict_all();
+CREATE TABLE filler (v text);
+INSERT INTO filler SELECT repeat('Z', 2000) FROM generate_series(1, 800);
+SELECT count(*) FROM filler;
+});
+
+$node->safe_psql(
+	'postgres', qq{
+SELECT injection_points_detach('$point');
+SELECT injection_points_wakeup('$point');
+});
+
+my ($out, $failed) = $victim->query('\\echo done_select');
+is($failed, 0, 'query did not error')
+  or diag($victim->{stderr});
+like($out, qr/\b1\b/, 'query returned a row');
+
+my $log = slurp_file($node->logfile);
+like(
+	$log,
+	qr/Query Parameters: \$1 = 'abcabcabcabcabcabcabcabcabcabc'/,
+	'logged parameter is the original value');
+
+$victim->quit;
+$node->stop;
+
+done_testing();
+
+sub wait_for_injection_point
+{
+	my ($node, $point_name, $timeout) = @_;
+	$timeout //= $PostgreSQL::Test::Utils::timeout_default / 2;
+
+	for (my $elapsed = 0; $elapsed < $timeout * 10; $elapsed++)
+	{
+		my $pid = $node->safe_psql(
+			'postgres', qq{
+			SELECT pid FROM pg_stat_activity
+			WHERE wait_event_type = 'InjectionPoint'
+			  AND wait_event = '$point_name'
+			LIMIT 1;
+		});
+		return 1 if $pid ne '';
+		usleep(100_000);
+	}
+	return 0;
+}
diff --git a/src/backend/executor/functions.c b/src/backend/executor/functions.c
index 8fec79a2f76..0a6ea0f0002 100644
--- a/src/backend/executor/functions.c
+++ b/src/backend/executor/functions.c
@@ -119,6 +119,7 @@ typedef struct SQLFunctionHashEntry
 
 	SQLFunctionParseInfoPtr pinfo;	/* data for parser callback hooks */
 	int16	   *argtyplen;		/* lengths of the input argument types */
+	bool	   *argtypbyval;	/* pass-by-value flags for argtyplen */
 
 	Oid			rettype;		/* actual return type */
 	int16		typlen;			/* length of the return type */
@@ -1129,13 +1130,18 @@ sql_compile_callback(FunctionCallInfo fcinfo,
 	MemoryContextSwitchTo(oldcontext);
 
 	/*
-	 * Now that we have the resolved argument types, collect their typlens for
-	 * use in postquel_sub_params.
+	 * Now that we have the resolved argument types, collect their physical
+	 * properties. postquel_sub_params uses the lengths. Lazy execution also
+	 * copies pass-by-ref values out of the caller's buffer.
 	 */
 	func->argtyplen = (int16 *)
 		MemoryContextAlloc(hcontext, func->pinfo->nargs * sizeof(int16));
+	func->argtypbyval = (bool *)
+		MemoryContextAlloc(hcontext, func->pinfo->nargs * sizeof(bool));
 	for (int i = 0; i < func->pinfo->nargs; i++)
-		func->argtyplen[i] = get_typlen(func->pinfo->argtypes[i]);
+		get_typlenbyval(func->pinfo->argtypes[i],
+						&func->argtyplen[i],
+						&func->argtypbyval[i]);
 
 	/*
 	 * And of course we need the function body text.
@@ -1341,6 +1347,30 @@ postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
 	/* Switch into the selected subcontext (might be a no-op) */
 	MemoryContextSwitchTo(fcache->subcontext);
 
+	/*
+	 * A lazy SRF can be shut down from the caller's ExecutorEnd, after that
+	 * plan has dropped its buffer pins. Pass-by-ref arguments still point
+	 * into those pages. Copy them into subcontext while fmgr_sql is still
+	 * running and the pins are held. postquel_end calls ExecutorEnd, which
+	 * reads the copies, and only then deletes subcontext.
+	 */
+	if (es->lazyEval && fcache->ownSubcontext && fcache->paramLI != NULL)
+	{
+		ParamListInfo paramLI = fcache->paramLI;
+		int16	   *argtyplen = fcache->func->argtyplen;
+		bool	   *argtypbyval = fcache->func->argtypbyval;
+
+		for (int i = 0; i < paramLI->numParams; i++)
+		{
+			ParamExternData *prm = &paramLI->params[i];
+
+			if (!prm->isnull)
+				prm->value = datumCopy(prm->value,
+									   argtypbyval[i],
+									   argtyplen[i]);
+		}
+	}
+
 	/*
 	 * If this query produces the function result, collect its output using
 	 * our custom DestReceiver; else discard any output.
-- 
2.53.0

