From 752f2403322ca02aaae58bee3fa2d5ef6c22f7b8 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 13 Aug 2025 14:25:26 -0400
Subject: [PATCH v3] 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..c9dea7f3c11 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

