From c8b1c953b8be8ede059b104198c5603a251eb19f Mon Sep 17 00:00:00 2001 From: Tom Lane Date: Fri, 15 May 2020 19:05:39 -0400 Subject: [PATCH] Fix bogus initialization of replication origin shared memory state. The previous coding zeroed out offsetof(ReplicationStateCtl, states) more bytes than it was entitled to, as a consequence of starting the zeroing from the wrong pointer (or, if you prefer, using the wrong calculation of how much to zero). It's unsurprising that this has not caused any reported problems, since it can be expected that the newly-allocated block is at the end of what we've used in shared memory, and we always make the shmem block substantially bigger than minimally necessary. Nonetheless, this is wrong and it could bite us someday; plus it's a dangerous model for somebody to copy. This dates back to the introduction of this code (commit 5aa235042), so back-patch to all supported branches. --- src/backend/replication/logical/origin.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/backend/replication/logical/origin.c b/src/backend/replication/logical/origin.c index 4ee19e9f50..01f88eaca8 100644 --- a/src/backend/replication/logical/origin.c +++ b/src/backend/replication/logical/origin.c @@ -148,7 +148,9 @@ typedef struct ReplicationStateOnDisk typedef struct ReplicationStateCtl { + /* Tranche to use for per-origin LWLocks */ int tranche_id; + /* Array of length max_replication_slots */ ReplicationState states[FLEXIBLE_ARRAY_MEMBER]; } ReplicationStateCtl; @@ -165,6 +167,10 @@ TimestampTz replorigin_session_origin_timestamp = 0; * max_replication_slots? */ static ReplicationState *replication_states; + +/* + * Actual shared memory block (replication_states[] is now part of this). + */ static ReplicationStateCtl *replication_states_ctl; /* @@ -480,7 +486,7 @@ ReplicationOriginShmemSize(void) /* * XXX: max_replication_slots is arguably the wrong thing to use, as here * we keep the replay state of *remote* transactions. But for now it seems - * sufficient to reuse it, lest we introduce a separate GUC. + * sufficient to reuse it, rather than introduce a separate GUC. */ if (max_replication_slots == 0) return size; @@ -510,9 +516,9 @@ ReplicationOriginShmemInit(void) { int i; - replication_states_ctl->tranche_id = LWTRANCHE_REPLICATION_ORIGIN; + MemSet(replication_states_ctl, 0, ReplicationOriginShmemSize()); - MemSet(replication_states, 0, ReplicationOriginShmemSize()); + replication_states_ctl->tranche_id = LWTRANCHE_REPLICATION_ORIGIN; for (i = 0; i < max_replication_slots; i++) {