From c36e1d1b471ed2a12e8249d152e79f53761acc21 Mon Sep 17 00:00:00 2001
From: Hou Zhijie <houzj.fnst@cn.fujitsu.com>
Date: Wed, 11 Oct 2023 13:53:50 +0800
Subject: [PATCH] Add null termination to string received in parallel apply
 worker.

The parallel apply worker didn't add null termination to the string received
from the leader apply worker via the shared memory queue. This action violates
the rule established in StringInfo, which guarantees the presence of a
terminating '\0' at the end of the string.

So fix it by using standard StringInfo to store the received string.
---
 .../replication/logical/applyparallelworker.c    | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/src/backend/replication/logical/applyparallelworker.c b/src/backend/replication/logical/applyparallelworker.c
index 82f48a488e..810828fa20 100644
--- a/src/backend/replication/logical/applyparallelworker.c
+++ b/src/backend/replication/logical/applyparallelworker.c
@@ -737,6 +737,7 @@ LogicalParallelApplyLoop(shm_mq_handle *mqh)
 	shm_mq_result shmq_res;
 	ErrorContextCallback errcallback;
 	MemoryContext oldcxt = CurrentMemoryContext;
+	StringInfoData s;
 
 	/*
 	 * Init the ApplyMessageContext which we clean up after each replication
@@ -754,6 +755,8 @@ LogicalParallelApplyLoop(shm_mq_handle *mqh)
 	errcallback.previous = error_context_stack;
 	error_context_stack = &errcallback;
 
+	initStringInfo(&s);
+
 	for (;;)
 	{
 		void	   *data;
@@ -768,16 +771,19 @@ LogicalParallelApplyLoop(shm_mq_handle *mqh)
 
 		if (shmq_res == SHM_MQ_SUCCESS)
 		{
-			StringInfoData s;
 			int			c;
 
 			if (len == 0)
 				elog(ERROR, "invalid message length");
 
-			s.cursor = 0;
-			s.maxlen = -1;
-			s.data = (char *) data;
-			s.len = len;
+			/*
+			 * Note that the data received via the shared memory queue is not
+			 * null-terminated. So we use the StringInfo API to store the
+			 * string so as to maintain the convention that StringInfos has a
+			 * trailing null.
+			 */
+			resetStringInfo(&s);
+			appendBinaryStringInfo(&s, data, len);
 
 			/*
 			 * The first byte of messages sent from leader apply worker to
-- 
2.30.0.windows.2

