From 9d443157b7ae2a73d288028a38e7ea605d396df8 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 13 Aug 2025 14:25:26 -0400
Subject: [PATCH v1] Prevent bms_prev_member() from reading beyond the end of
 the map

Add a bounds check for a bit beyond the extent of the capacity of the
bitmap.  Without this check the bms_prev_memeber() function will read
from a location beyond the allocated space for the words encoding the
map at best returning a bad result, at worst a door for reading memory
at a predictable offset beyond the end of a Bitmapset one bit at a time.
---
 src/backend/nodes/bitmapset.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/backend/nodes/bitmapset.c b/src/backend/nodes/bitmapset.c
index bf512cf806f..77f602b882e 100644
--- a/src/backend/nodes/bitmapset.c
+++ b/src/backend/nodes/bitmapset.c
@@ -1380,7 +1380,8 @@ bms_prev_member(const Bitmapset *a, int prevbit)
 		return -2;
 
 	/* transform -1 to the highest possible bit we could have set */
-	if (prevbit == -1)
+	if (prevbit == -1 ||
+		prevbit > a->nwords * BITS_PER_BITMAPWORD - 1)
 		prevbit = a->nwords * BITS_PER_BITMAPWORD - 1;
 	else
 		prevbit--;
-- 
2.49.0

