From cd4b7b53ebe38a4e049e10cb1a53a6e18abe6db4 Mon Sep 17 00:00:00 2001
From: Simon McVittie <smcv@collabora.com>
Date: Mon, 6 Jan 2025 15:01:43 +0000
Subject: [PATCH] fdio: Avoid relying on VLAs or gcc-specific constant folding

Formally, `strlen("x")` is not a constant expression, although gcc can
and does optimize it to a constant expression in simple cases.
clang 19.1.6 warns about this usage.

Replace it with the size of a static array (1 more than the strlen of
its contents), which is unambiguously a constant expression.

Resolves: https://gitlab.gnome.org/GNOME/libglnx/-/issues/5
Signed-off-by: Simon McVittie <smcv@collabora.com>
---
 glnx-fdio.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/glnx-fdio.c b/glnx-fdio.c
index 98732051a..3d9f9a759 100644
--- a/glnx-fdio.c
+++ b/glnx-fdio.c
@@ -321,6 +321,8 @@ glnx_open_anonymous_tmpfile (int          flags,
                                            error);
 }
 
+static const char proc_self_fd_slash[] = "/proc/self/fd/";
+
 /* Use this after calling glnx_open_tmpfile_linkable_at() to give
  * the file its final name (link into place).
  */
@@ -367,8 +369,8 @@ glnx_link_tmpfile_at (GLnxTmpfile *tmpf,
   else
     {
       /* This case we have O_TMPFILE, so our reference to it is via /proc/self/fd */
-      char proc_fd_path[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(tmpf->fd) + 1];
-      snprintf (proc_fd_path, sizeof (proc_fd_path), "/proc/self/fd/%i", tmpf->fd);
+      char proc_fd_path[sizeof (proc_self_fd_slash) + DECIMAL_STR_MAX(tmpf->fd)];
+      snprintf (proc_fd_path, sizeof (proc_fd_path), "%s%i", proc_self_fd_slash, tmpf->fd);
 
       if (replace)
         {
@@ -455,8 +457,8 @@ glnx_tmpfile_reopen_rdonly (GLnxTmpfile *tmpf,
   else
     {
       /* This case we have O_TMPFILE, so our reference to it is via /proc/self/fd */
-      char proc_fd_path[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(tmpf->fd) + 1];
-      snprintf (proc_fd_path, sizeof (proc_fd_path), "/proc/self/fd/%i", tmpf->fd);
+      char proc_fd_path[sizeof (proc_self_fd_slash) + DECIMAL_STR_MAX(tmpf->fd)];
+      snprintf (proc_fd_path, sizeof (proc_fd_path), "%s%i", proc_self_fd_slash, tmpf->fd);
 
       if (!glnx_openat_rdonly (AT_FDCWD, proc_fd_path, TRUE, &rdonly_fd, error))
         return FALSE;
-- 
GitLab