Subject: [PATCH v3] builtin/gc: correct total_ram calculation with HAVE_BSD_SYSCTL

From: Carlo Marcelo Arenas Belón <[email-masked]>
Date: Wed, 2 Jul 2025 13:21:18 -0700

The calls to sysctl() assume an 64-bit memory size, but the actual
size depends on the key name and platform, at least for HW_PHYSMEM.

Detect any mismatched reads, and make sure that any non used bytes
are correctly discarded before returning.

Signed-off-by: Carlo Marcelo Arenas Belón <[email-masked]>
---
 builtin/gc.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/builtin/gc.c b/builtin/gc.c
index 845876ff02..c2f248052c 100644
--- a/builtin/gc.c
+++ b/builtin/gc.c
@@ -539,7 +539,7 @@ static uint64_t total_ram(void)
 		return total;
 	}
 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM) || defined(HW_PHYSMEM64))
-	int64_t physical_memory;
+	uint64_t physical_memory;
 	int mib[2];
 	size_t length;
 
@@ -551,9 +551,16 @@ static uint64_t total_ram(void)
 # else
 	mib[1] = HW_PHYSMEM;
 # endif
-	length = sizeof(int64_t);
-	if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
+	length = sizeof(physical_memory);
+	if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0)) {
+		if (length < sizeof(physical_memory)) {
+			unsigned bits = (sizeof(physical_memory) - length) * 8;
+
+			physical_memory <<= bits;
+			physical_memory >>= bits;
+		}
 		return physical_memory;
+	}
 #elif defined(GIT_WINDOWS_NATIVE)
 	MEMORYSTATUSEX memInfo;
 
-- 
2.50.0.145.g83014dc05f.dirty