From 1c298fd3dc7894fa0718765a161fd4617e6df986 Mon Sep 17 00:00:00 2001
From: Karina Litskevich <litskevichkarina@gmail.com>
Date: Tue, 14 Feb 2023 17:13:17 +0300
Subject: [PATCH v2 1/2] Fix VALGRIND_MAKE_MEM_DEFINED() calls

---
 src/backend/utils/mmgr/aset.c | 32 ++++++++++++++++++++------------
 1 file changed, 20 insertions(+), 12 deletions(-)

diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c
index 740729b5d0..ace4907ce9 100644
--- a/src/backend/utils/mmgr/aset.c
+++ b/src/backend/utils/mmgr/aset.c
@@ -1187,21 +1187,26 @@ AllocSetRealloc(void *pointer, Size size)
 
 #ifdef MEMORY_CONTEXT_CHECKING
 #ifdef RANDOMIZE_ALLOCATED_MEMORY
-		/* We can only fill the extra space if we know the prior request */
+		/*
+		 * We can only fill the extra space if we know the prior request.
+		 * Note: randomize_mem() also marks memory UNDEFINED.
+		 */
 		if (size > chunk->requested_size)
 			randomize_mem((char *) pointer + chunk->requested_size,
 						  size - chunk->requested_size);
-#endif
-
+#else
 		/*
-		 * realloc() (or randomize_mem()) will have left any newly-allocated
-		 * part UNDEFINED, but we may need to adjust trailing bytes from the
-		 * old allocation.
+		 * If this is an increase, realloc() will have left any newly-allocated
+		 * part (from oldsize to chksize) UNDEFINED, but we may need to adjust
+		 * trailing bytes from the old allocation (from chunk->requested_size to
+		 * oldsize) as they are marked NOACCESS.  Make sure not to mark extra
+		 * bytes in case chunk->requested_size < size < oldsize.
 		 */
 #ifdef USE_VALGRIND
-		if (oldsize > chunk->requested_size)
+		if (Min(size, oldsize) > chunk->requested_size)
 			VALGRIND_MAKE_MEM_UNDEFINED((char *) pointer + chunk->requested_size,
-										oldsize - chunk->requested_size);
+										Min(size, oldsize) - chunk->requested_size);
+#endif
 #endif
 
 		chunk->requested_size = size;
@@ -1211,11 +1216,14 @@ AllocSetRealloc(void *pointer, Size size)
 #else							/* !MEMORY_CONTEXT_CHECKING */
 
 		/*
-		 * We don't know how much of the old chunk size was the actual
-		 * allocation; it could have been as small as one byte.  We have to be
-		 * conservative and just mark the entire old portion DEFINED.
+		 * We may need to adjust marking of bytes from the old allocation as
+		 * some of them may be marked NOACCESS.  We don't know how much of the
+		 * old chunk size was the requested size; it could have been as small as
+		 * one byte.  We have to be conservative and just mark the entire old
+		 * portion DEFINED.  Make sure not to mark memory behind the new
+		 * allocation in case it's smaller than old one.
 		 */
-		VALGRIND_MAKE_MEM_DEFINED(pointer, oldsize);
+		VALGRIND_MAKE_MEM_DEFINED(pointer, Min(size, oldsize));
 #endif
 
 		/* Ensure any padding bytes are marked NOACCESS. */
-- 
2.25.1

