Debian Codegraph @

lib/fstat.c

raw
1 /* fstat() replacement.
2 Copyright (C) 2011-2026 Free Software Foundation, Inc.
3
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of the
7 License, or (at your option) any later version.
8
9 This file is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
16
17 /* If the user's config.h happens to include <sys/stat.h>, let it include only
18 the system's <sys/stat.h> here, so that orig_fstat doesn't recurse to
19 rpl_fstat. */
20 #define __need_system_sys_stat_h
21 #include <config.h>
22
23 /* Get the original definition of fstat. It might be defined as a macro. */
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #undef __need_system_sys_stat_h
27
28 #if defined _WIN32 && ! defined __CYGWIN__
29 # define WINDOWS_NATIVE
30 #endif
31
32 #if !defined WINDOWS_NATIVE
33
34 static int
35 orig_fstat (int fd, struct stat *buf)
36 {
37 return fstat (fd, buf);
38 }
39
40 #endif
41
42 /* Specification. */
43 #include <sys/stat.h>
44
45 #include "stat-time.h"
46
47 #include <errno.h>
48 #include <unistd.h>
49 #ifdef WINDOWS_NATIVE
50 # define WIN32_LEAN_AND_MEAN
51 # include <windows.h>
52 # if GNULIB_MSVC_NOTHROW
53 # include "msvc-nothrow.h"
54 # else
55 # include <io.h>
56 # endif
57 # include "stat-w32.h"
58 #endif
59
60 int
61 rpl_fstat (int fd, struct stat *buf)
62 {
63 #if REPLACE_FCHDIR && REPLACE_OPEN_DIRECTORY
64 /* Handle the case when rpl_open() used a dummy file descriptor to work
65 around an open() that can't normally visit directories. */
66 const char *name = _gl_directory_name (fd);
67 if (name != NULL)
68 return stat (name, buf);
69 #endif
70
71 #ifdef WINDOWS_NATIVE
72 /* Fill the fields ourselves, because the original fstat function returns
73 values for st_atime, st_mtime, st_ctime that depend on the current time
74 zone. See
75 <https://lists.gnu.org/r/bug-gnulib/2017-04/msg00134.html> */
76 HANDLE h = (HANDLE) _get_osfhandle (fd);
77
78 if (h == INVALID_HANDLE_VALUE)
79 {
80 errno = EBADF;
81 return -1;
82 }
83 return _gl_fstat_by_handle (h, NULL, buf);
84 #else
85 return stat_time_normalize (orig_fstat (fd, buf), buf);
86 #endif
87 }