From 13ca484a712ab44d789d92c8edb6933c0d97f0a0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Deuc=D0=B5?= <shurd@sasktel.net>
Date: Fri, 22 Mar 2024 14:17:41 -0400
Subject: [PATCH] Use strlcpy() for SAFECOPY() and XSAFECOPY() macros.

While we're here, Update strlcpy() to slightly more optimal
FreeBSD-13.3 version.
---
 src/xpdev/gen_defs.h |  4 ++--
 src/xpdev/genwrap.c  | 31 ++++++++++++++++++++-----------
 2 files changed, 22 insertions(+), 13 deletions(-)

diff --git a/src/xpdev/gen_defs.h b/src/xpdev/gen_defs.h
index 3bf2ba89ad..9582e1dacd 100644
--- a/src/xpdev/gen_defs.h
+++ b/src/xpdev/gen_defs.h
@@ -427,9 +427,9 @@ typedef struct {
 #define TERMINATE(str)                      str[sizeof(str)-1]=0
 
 /* This is a bound-safe version of strcpy basically - only works with fixed-length arrays */
-#define SAFECOPY(dst,src)                   (strncpy(dst,src,sizeof(dst)), TERMINATE(dst))
+#define SAFECOPY(dst,src)                   strlcpy(dst,src,sizeof(dst))
 /* Extra-safe SAFECOPY doesn't pass NULL-pointer to strncpy */
-#define XSAFECOPY(dst,src)                  (strncpy(dst,(src)==NULL?"(null)":(src),sizeof(dst)), TERMINATE(dst))
+#define XSAFECOPY(dst,src)                  strlcpy(dst,(src)==NULL?"(null)":(src),sizeof(dst))
 
 #define SAFECAT(dst, src) do { \
 	if(strlen((char*)(dst)) + strlen((char*)(src)) < sizeof(dst)) { \
diff --git a/src/xpdev/genwrap.c b/src/xpdev/genwrap.c
index 6e52893b0f..0e662376a8 100644
--- a/src/xpdev/genwrap.c
+++ b/src/xpdev/genwrap.c
@@ -69,17 +69,26 @@ int safe_snprintf(char *dst, size_t size, const char *fmt, ...)
 #ifdef NEEDS_STRLCPY
 size_t strlcpy(char *dst, const char *src, size_t size)
 {
-	size_t i;
-
-	if(size < 1)
-		return 0;
-
-	for(i = 0; src[i] != '\0'; i++) {
-		if(i < (size - 1))
-			*(dst++) = src[i];
-	}
-	*dst = 0;
-	return i;
+        const char *osrc = src;
+        size_t nleft = dsize;
+
+        /* Copy as many bytes as will fit. */
+        if (nleft != 0) {
+                while (--nleft != 0) {
+                        if ((*dst++ = *src++) == '\0')
+                                break;
+                }
+        }
+
+        /* Not enough room in dst, add NUL and traverse rest of src. */
+        if (nleft == 0) {
+                if (dsize != 0)
+                        *dst = '\0';            /* NUL-terminate dst */
+                while (*src++)
+                        ;
+        }
+
+        return(src - osrc - 1); /* count does not include NUL */
 }
 
 size_t
-- 
GitLab