Thanks, I installed that (with minor reformatting of the commit message,
and adding it to ChangeLog), and followed it up with the attached further micro-optimization.
From f53abd0bcf7cf9967bf9573c9ef4e6fa4823a5ac Mon Sep 17 00:00:00 2001
From: Paul Eggert <[email protected]>
Date: Tue, 2 Dec 2025 10:42:52 -0800
Subject: [PATCH] dup2: help the compiler a bit

* lib/dup2.c (klibc_dup2dirfd, klibc_dup2, rpl_dup2): Help the
compiler leave a register alone, and/or test just the sign bit.
---
 ChangeLog  |  6 ++++++
 lib/dup2.c | 15 ++++++++-------
 2 files changed, 14 insertions(+), 7 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 8ea5a65cf9..22bb59ee1d 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,9 @@
+2025-12-02  Paul Eggert  <[email protected]>
+
+	dup2: help the compiler a bit
+	* lib/dup2.c (klibc_dup2dirfd, klibc_dup2, rpl_dup2): Help the
+	compiler leave a register alone, and/or test just the sign bit.
+
 2025-12-02  KO Myung-Hun  <[email protected]>
 
 	dup2, fcntl: Fix the race condition on OS/2 kLIBC
diff --git a/lib/dup2.c b/lib/dup2.c
index 3468fbcb6e..434e78c2bc 100644
--- a/lib/dup2.c
+++ b/lib/dup2.c
@@ -114,8 +114,8 @@ klibc_dup2dirfd (int fd, int desired_fd)
   int dupfd;
 
   tempfd = open ("NUL", O_RDONLY);
-  if (tempfd == -1)
-    return -1;
+  if (tempfd < 0)
+    return tempfd;
 
   if (tempfd >= desired_fd)
     {
@@ -130,8 +130,8 @@ klibc_dup2dirfd (int fd, int desired_fd)
           close (desired_fd);
 
           dupfd = open (path, O_RDONLY);
-          if (dupfd == -1)
-            return -1;
+          if (dupfd < 0)
+            return dupfd;
 
           if (dupfd == desired_fd)
             return dupfd;
@@ -164,7 +164,7 @@ klibc_dup2 (int fd, int desired_fd)
   struct stat sbuf;
 
   dupfd = dup2 (fd, desired_fd);
-  if (dupfd == -1 && errno == ENOTSUP \
+  if (dupfd < 0 && errno == ENOTSUP \
       && !fstat (fd, &sbuf) && S_ISDIR (sbuf.st_mode))
     return klibc_dup2dirfd (fd, desired_fd);
 
@@ -197,10 +197,11 @@ rpl_dup2 (int fd, int desired_fd)
   result = dup2 (fd, desired_fd);
 
   /* Correct an errno value on FreeBSD 6.1 and Cygwin 1.5.x.  */
-  if (result == -1 && errno == EMFILE)
+  if (result < 0 && errno == EMFILE)
     errno = EBADF;
+
 #if REPLACE_FCHDIR
-  if (fd != desired_fd && result != -1)
+  if (! (result < 0 || fd == desired_fd))
     result = _gl_register_dup (fd, result);
 #endif
   return result;
-- 
2.51.0

Reply via email to