Commit 27f277fd16 for openssl.org

commit 27f277fd16bd7b72d05a5f2a53036d7563f3cc9e
Author: Bob Beck <beck@openssl.org>
Date:   Wed Jun 17 20:24:11 2026 -0600

    Replace strlen-then-snprintf pattern in save_serial() with a single truncation check.

    This used to be necessary because BIO_snprintf() could not detect truncation
    but now this is silly, and this ends up tripping GCC's -Wformat-truncation

    Reviewed-by: Neil Horman <nhorman@openssl.org>
    Reviewed-by: Andrew Dinh <andrewd@openssl.org>
    MergeDate: Wed Aug 26 16:20:30 2026
    (Merged from https://github.com/openssl/openssl/pull/31640)

diff --git a/apps/lib/apps.c b/apps/lib/apps.c
index 5159e325cc..14b6d6d814 100644
--- a/apps/lib/apps.c
+++ b/apps/lib/apps.c
@@ -1745,25 +1745,25 @@ int save_serial(const char *serialfile, const char *suffix,
     BIO *out = NULL;
     int ret = 0;
     ASN1_INTEGER *ai = NULL;
-    size_t j;
-
-    if (suffix == NULL)
-        j = strlen(serialfile);
-    else
-        j = strlen(serialfile) + strlen(suffix) + 1;
-    if (j >= BSIZE) {
-        BIO_puts(bio_err, "File name too long\n");
-        goto err;
-    }

     if (suffix == NULL) {
-        OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
+        if (OPENSSL_strlcpy(buf[0], serialfile, BSIZE) >= BSIZE) {
+            BIO_puts(bio_err, "File name too long\n");
+            goto err;
+        }
     } else {
+        int n = snprintf(buf[0], sizeof(buf[0]),
 #ifndef OPENSSL_SYS_VMS
-        snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
+            "%s.%s",
 #else
-        snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
+            "%s-%s",
 #endif
+            serialfile, suffix);
+
+        if (n < 0 || (size_t)n >= sizeof(buf[0])) {
+            BIO_puts(bio_err, "File name too long\n");
+            goto err;
+        }
     }
     out = BIO_new_file(buf[0], "w");
     if (out == NULL) {