Subject: [PATCH] * src/lread.c (load): Try reuse the fd if it was opened in binary mode
From: Lin Sun <[email-masked]>
To: "[email-masked]" <[email-masked]>
Date: Sat, 17 May 2025 07:09:06 +0000
List-Id: <debbugs-submit.debbugs.gnu.org>

This patch will let Emacs avoid always close the fd then open the file with desired fmode in the "Fload" function on windows. It will reduce the counts on calling the "CreateFile" api.

On my dev windows environment, Emacs startup time reduces from 4.551s to 4.378s with 352 packages. 
From f425ab8f6bba2be765d60ed764ed7fa30e98cda8 Mon Sep 17 00:00:00 2001
From: Lin Sun <[email-masked]>
Date: Fri, 16 May 2025 06:30:49 -0700
Subject: [PATCH] * src/lread.c (load): Try reuse the fd if it was open on
 binary mode

---
 src/lread.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/src/lread.c b/src/lread.c
index 95c9e71..4d3bd02 100644
--- a/src/lread.c
+++ b/src/lread.c
@@ -1645,10 +1645,17 @@ DEFUN ("load", Fload, Sload, 1, 5, 0,
   else if (!is_module && !is_native_elisp)
     {
 #ifdef WINDOWSNT
-      emacs_close (fd);
-      clear_unwind_protect (fd_index);
-      efound = ENCODE_FILE (found);
-      stream = emacs_fopen (SSDATA (efound), fmode);
+      /* fdopen() a fd with different fmode as the fd was opened is
+	 undefined behavior on Windows. */
+      if (fmode[1] == FOPEN_BINARY)
+	stream = emacs_fdopen (fd, fmode);
+      else
+	{
+	  emacs_close (fd);
+	  clear_unwind_protect (fd_index);
+	  efound = ENCODE_FILE (found);
+	  stream = emacs_fopen (SSDATA (efound), fmode);
+	}
 #else
 #if !defined USE_ANDROID_ASSETS
       stream = emacs_fdopen (fd, fmode);
-- 
2.49.0