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

From: Carlo Marcelo Arenas Belón <[email-masked]>
Date: Thu, 3 Jul 2025 01:01:11 -0700

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

Detect any mismatched reads, and retry with a shorter variable as
needed.  Make the second tentatively optional in little endian
systems, as the variable was preinitialized and would work AS-IS.

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

diff --git a/builtin/gc.c b/builtin/gc.c
index 7dc94f243d..b680a1f739 100644
--- a/builtin/gc.c
+++ b/builtin/gc.c
@@ -517,7 +517,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 = 0;
 	int mib[2];
 	size_t length;
 
@@ -529,9 +529,18 @@ 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)) {
+# ifndef __LITTLE_ENDIAN__
+		if (length == 4) {
+			unsigned mem;
+
+			if (!sysctl(mib, 2, &mem, &length, NULL, 0))
+				physical_memory = mem;
+		}
+# endif
 		return physical_memory;
+	}
 #elif defined(GIT_WINDOWS_NATIVE)
 	MEMORYSTATUSEX memInfo;
 
-- 
2.50.0.rc0.48.gd8154328d9