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

Assert when prevbit would read beyond the end of the words array
enforcing the requirement in the comment that it be within the
current capacity of the Bitmapset.
---
 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..af265f71f9b 100644
--- a/src/backend/nodes/bitmapset.c
+++ b/src/backend/nodes/bitmapset.c
@@ -1343,7 +1343,7 @@ bms_next_member(const Bitmapset *a, int prevbit)
  *
  * Returns largest member less than "prevbit", or -2 if there is none.
  * "prevbit" must NOT be more than one above the highest possible bit that can
- * be set at the Bitmapset at its current size.
+ * be set in the Bitmapset at its current size.
  *
  * To ease finding the highest set bit for the initial loop, the special
  * prevbit value of -1 can be passed to have the function find the highest
@@ -1371,6 +1371,7 @@ bms_prev_member(const Bitmapset *a, int prevbit)
 	bitmapword	mask;
 
 	Assert(bms_is_valid_set(a));
+	Assert(prevbit <= (a ? a->nwords * BITS_PER_BITMAPWORD : -1));
 
 	/*
 	 * If set is NULL or if there are no more bits to the right then we've
-- 
2.49.0

