From 984f1eb68d22b45de08fd7230fe42d35b626d14f Mon Sep 17 00:00:00 2001
From: "Rob Swindell (on Debian Linux)" <rob@synchro.net>
Date: Sat, 24 Feb 2024 02:05:19 -0800
Subject: [PATCH] Insure all builds of safe_strerror() write the string to the
 passed buf

The GNU_SOURCE build of this function was (sometimes?) just returning the
string and not actually copying it to the passed buf. This is consistent
with the GNU manpage on strerror_r():
"This may be either a pointer to a string that the function stores in buf ..."
but was inconsistent with all the other build types of this function.

Also updated to use strlcpy and write the problematic error number to the
default string (if unknown).
---
 src/xpdev/genwrap.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/src/xpdev/genwrap.c b/src/xpdev/genwrap.c
index 0292cfb6a1..0ad7defb8c 100644
--- a/src/xpdev/genwrap.c
+++ b/src/xpdev/genwrap.c
@@ -1123,16 +1123,16 @@ bool terminate_pid(pid_t pid)
 /****************************************************************************/
 char* safe_strerror(int errnum, char *buf, size_t buflen)
 {
-	strncpy(buf, "Unknown error", buflen);
-	buf[buflen - 1] = 0;
+	snprintf(buf, buflen, "Unknown error: %d", errnum);
 
 #if defined(_MSC_VER)
 	strerror_s(buf, buflen, errnum);
 #elif defined(_WIN32) || defined(__EMSCRIPTEN__)
-	strncpy(buf, strerror(errnum), buflen);
-	buf[buflen - 1] = 0;
+	strlcpy(buf, strerror(errnum), buflen);
 #elif defined(_GNU_SOURCE)
-	buf = strerror_r(errnum, buf, buflen);
+	char* ret = strerror_r(errnum, buf, buflen);
+	if (ret != buf)
+		strlcpy(buf, ret, buflen);
 #else
 	strerror_r(errnum, buf, buflen);
 #endif
-- 
GitLab