From 29bfecd52f2356f0101f0db47f753e00e197cb48 Mon Sep 17 00:00:00 2001
From: Amit Kapila <akapila@postgresql.org>
Date: Thu, 24 Nov 2022 16:28:23 +0530
Subject: [PATCH v2] Fix uninitialized access to InitialRunningXacts during
 decoding.

In commit 272248a0c, we introduced an InitialRunningXacts array to
remember transactions and subtransactions that were running when the
xl_running_xacts record that we decoded was written. This array was
allocated in the snapshot builder memory context after we restore
serialized snapshot but we forgot to reset the array while freeing the
builder memory context. So, the next when starting decoding in the same
session where we don't restore any serialized snapshot, we ended up using
the uninitialized array and that can lead to unpredictable behavior.

Reported-by: Maxim Orlov
Author: Masahiko Sawada
Reviewed-by: Amit Kapila, Maxim Orlov
Backpatch-through: 11
Discussion: https://postgr.es/m/CACG=ezZoz_KG+Ryh9MrU_g5e0HiVoHocEvqFF=NRrhrwKmEQJQ@mail.gmail.com
---
 src/backend/replication/logical/snapbuild.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c
index aa2e9f303e..02d73e5c93 100644
--- a/src/backend/replication/logical/snapbuild.c
+++ b/src/backend/replication/logical/snapbuild.c
@@ -377,6 +377,9 @@ AllocateSnapshotBuilder(ReorderBuffer *reorder,
 
 	MemoryContextSwitchTo(oldcontext);
 
+	/* The initial running transactions array must be empty. */
+	Assert(NInitialRunningXacts == 0 && InitialRunningXacts == NULL);
+
 	return builder;
 }
 
@@ -397,6 +400,10 @@ FreeSnapshotBuilder(SnapBuild *builder)
 
 	/* other resources are deallocated via memory context reset */
 	MemoryContextDelete(context);
+
+	/* InitialRunningXacts is freed along with the context */
+	NInitialRunningXacts = 0;
+	InitialRunningXacts = NULL;
 }
 
 /*
-- 
2.28.0.windows.1

