]> git.eshelyaron.com Git - emacs.git/commitdiff
Don’t trust st_size when scanning file head+tail
authorPaul Eggert <eggert@cs.ucla.edu>
Wed, 22 Jan 2025 19:06:06 +0000 (11:06 -0800)
committerEshel Yaron <me@eshelyaron.com>
Thu, 24 Jul 2025 08:47:23 +0000 (10:47 +0200)
* src/fileio.c (Finsert_file_contents): Do not look at st_size
when scanning the file’s head and tail for a coding system comment.
Instead, just use read and SEEK_END and don’t worry if the latter fails.
st_size and lseek might not work in a /proc file system.

(cherry picked from commit 0a3c8a4df3f9e15737e4e5b4aecd2e63d2abbc4f)

src/fileio.c

index 82ee22d21876f72ed2e208d924f002e8e2f81f34..a3a49d179c48fa95b731ae2fa3a43d77ea3b71a5 100644 (file)
@@ -4271,24 +4271,21 @@ by calling `format-decode', which see.  */)
            {
              /* Find a coding system specified in the heading two
                 lines or in the tailing several lines of the file.
-                We assume that the 1K-byte and 3K-byte for heading
+                Assume that the 1 KiB and 3 KiB for heading
                 and tailing respectively are sufficient for this
-                purpose.  */
-             int nread;
-
-             if (st.st_size <= (1024 * 4))
-               nread = emacs_fd_read (fd, read_buf, 1024 * 4);
-             else
+                purpose.  Because the file may be in /proc,
+                do not use st_size or report any SEEK_END failure.  */
+             ptrdiff_t nread = emacs_fd_read (fd, read_buf, 4 * 1024);
+             if (nread == 4 * 1024)
                {
-                 nread = emacs_fd_read (fd, read_buf, 1024);
-                 if (nread == 1024)
+                 off_t tailoff = emacs_fd_lseek (fd, - 3 * 1024, SEEK_END);
+                 if (tailoff < 0)
+                   seekable = false;
+                 else if (1024 < tailoff)
                    {
-                     int ntail;
-                     if (emacs_fd_lseek (fd, st.st_size - 1024 * 3, SEEK_CUR) < 0)
-                       report_file_error ("Setting file position",
-                                          orig_filename);
-                     ntail = emacs_fd_read (fd, read_buf + nread, 1024 * 3);
-                     nread = ntail < 0 ? ntail : nread + ntail;
+                     ptrdiff_t ntail = emacs_fd_read (fd, read_buf + 1024,
+                                                      3 * 1024);
+                     nread = ntail < 0 ? ntail : 1024 + ntail;
                    }
                }