From abce42b691d94ea17cc186681b946a28c12b2b22 Mon Sep 17 00:00:00 2001
From: Froz <froz@42paris.fr>
Date: Sat, 22 Feb 2025 11:43:42 +0100
Subject: [PATCH] runtime/cgo: add error checks for safe stack retrieval on
 Unix

---
 src/runtime/cgo/gcc_stack_unix.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)

diff --git a/src/runtime/cgo/gcc_stack_unix.c b/src/runtime/cgo/gcc_stack_unix.c
index 9550cd783941a8..764cb4abbfb695 100644
--- a/src/runtime/cgo/gcc_stack_unix.c
+++ b/src/runtime/cgo/gcc_stack_unix.c
@@ -17,19 +17,30 @@ x_cgo_getstackbound(uintptr bounds[2])
 	pthread_attr_t attr;
 	void *addr;
 	size_t size;
+	int err;
 
 	// Needed before pthread_getattr_np, too, since before glibc 2.32
 	// it did not call pthread_attr_init in all cases (see #65625).
-	pthread_attr_init(&attr);
+	err = pthread_attr_init(&attr);
+	if (err != 0)
+		fatalf("pthread_attr_init failed: %d", err);
 #if defined(__GLIBC__) || defined(__BIONIC__) || (defined(__sun) && !defined(__illumos__))
 	// pthread_getattr_np is a GNU extension supported in glibc.
 	// Solaris is not glibc but does support pthread_getattr_np
 	// (and the fallback doesn't work...). Illumos does not.
-	pthread_getattr_np(pthread_self(), &attr);  // GNU extension
-	pthread_attr_getstack(&attr, &addr, &size); // low address
+	err = pthread_getattr_np(pthread_self(), &attr);
+	if (err != 0)
+		fatalf("pthread_getattr_np failed: %d", err);
+	err = pthread_attr_getstack(&attr, &addr, &size);
+	if (err != 0)
+		fatalf("pthread_attr_getstack failed: %d", err);
 #elif defined(__illumos__)
-	pthread_attr_get_np(pthread_self(), &attr);
-	pthread_attr_getstack(&attr, &addr, &size); // low address
+	err = pthread_attr_get_np(pthread_self(), &attr);
+	if (err != 0)
+		fatalf("pthread_attr_get_np failed: %d", err);
+	err = pthread_attr_getstack(&attr, &addr, &size);
+	if (err != 0)
+		fatalf("pthread_attr_getstack failed: %d", err);
 #else
 	// We don't know how to get the current stacks, leave it as
 	// 0 and the caller will use an estimate based on the current