From 7feed212172266444a2f3e09d183a005a673a8bd Mon Sep 17 00:00:00 2001
From: Anthonin Bonnefoy <anthonin.bonnefoy@datadoghq.com>
Date: Thu, 22 Jan 2026 15:50:29 +0100
Subject: Check for overflow when rounding up allocsize

The amount of shared memory to mmap is calculated using
CalculateShmemSize, which takes care of checking for possible overflow
using add_size.

When using huge pages, the final allocation size is rounded up to the
next required huge pages when necessary. However, there's no overflow
check when doing this round up, leaving the possibility for an
overflow.

This patch uses add_size when rounding up to check for possible
overflow.
---
 src/backend/port/sysv_shmem.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/backend/port/sysv_shmem.c b/src/backend/port/sysv_shmem.c
index de491897118..5239b6acbbc 100644
--- a/src/backend/port/sysv_shmem.c
+++ b/src/backend/port/sysv_shmem.c
@@ -34,6 +34,7 @@
 #include "storage/fd.h"
 #include "storage/ipc.h"
 #include "storage/pg_shmem.h"
+#include "storage/shmem.h"
 #include "utils/guc.h"
 #include "utils/guc_hooks.h"
 #include "utils/pidfile.h"
@@ -617,7 +618,7 @@ CreateAnonymousSegment(Size *size)
 		GetHugePageSize(&hugepagesize, &mmap_flags);
 
 		if (allocsize % hugepagesize != 0)
-			allocsize += hugepagesize - (allocsize % hugepagesize);
+			allocsize = add_size(allocsize, hugepagesize - (allocsize % hugepagesize));
 
 		ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
 				   PG_MMAP_FLAGS | mmap_flags, -1, 0);
-- 
2.52.0

