1 /* Work around platform bugs in stat.
2 Copyright (C) 2009-2024 Free Software Foundation, Inc.
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.
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.
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/>. */
17 /* Written by Eric Blake and Bruno Haible. */
19 /* If the user's config.h happens to include <sys/stat.h>, let it include only
20 the system's <sys/stat.h> here, so that orig_stat doesn't recurse to
22 #define __need_system_sys_stat_h
25 /* Get the original definition of stat. It might be defined as a macro. */
26 #include <sys/types.h>
28 #undef __need_system_sys_stat_h
30 #if defined _WIN32 && ! defined __CYGWIN__
31 # define WINDOWS_NATIVE
34 #if !defined WINDOWS_NATIVE
37 orig_stat (const char *filename
, struct stat
*buf
)
39 return stat (filename
, buf
);
46 /* Write "sys/stat.h" here, not <sys/stat.h>, otherwise OSF/1 5.1 DTK cc
47 eliminates this include because of the preliminary #include <sys/stat.h>
49 # include "sys/stat.h"
51 # include <sys/stat.h>
54 #include "stat-time.h"
63 # define WIN32_LEAN_AND_MEAN
65 # include "stat-w32.h"
66 /* Don't assume that UNICODE is not defined. */
67 # undef WIN32_FIND_DATA
68 # define WIN32_FIND_DATA WIN32_FIND_DATAA
70 # define CreateFile CreateFileA
72 # define FindFirstFile FindFirstFileA
76 /* Return TRUE if the given file name denotes an UNC root. */
78 is_unc_root (const char *rname
)
80 /* Test whether it has the syntax '\\server\share'. */
81 if (ISSLASH (rname
[0]) && ISSLASH (rname
[1]))
83 /* It starts with two slashes. Find the next slash. */
84 const char *p
= rname
+ 2;
86 while (*q
!= '\0' && !ISSLASH (*q
))
88 if (q
> p
&& *q
!= '\0')
90 /* Found the next slash at q. */
93 while (*r
!= '\0' && !ISSLASH (*r
))
95 if (r
> q
&& *r
== '\0')
103 /* Store information about NAME into ST. Work around bugs with
104 trailing slashes. Mingw has other bugs (such as st_ino always
105 being 0 on success) which this wrapper does not work around. But
106 at least this implementation provides the ability to emulate fchdir
110 rpl_stat (char const *name
, struct stat
*buf
)
112 #ifdef WINDOWS_NATIVE
113 /* Fill the fields ourselves, because the original stat function returns
114 values for st_atime, st_mtime, st_ctime that depend on the current time
116 <https://lists.gnu.org/r/bug-gnulib/2017-04/msg00134.html> */
117 /* XXX Should we convert to wchar_t* and prepend '\\?\', in order to work
118 around length limitations
119 <https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file> ? */
121 /* POSIX <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13>
122 specifies: "More than two leading <slash> characters shall be treated as
123 a single <slash> character." */
124 if (ISSLASH (name
[0]) && ISSLASH (name
[1]) && ISSLASH (name
[2]))
127 while (ISSLASH (name
[1]))
131 size_t len
= strlen (name
);
132 size_t drive_prefix_len
= (HAS_DEVICE (name
) ? 2 : 0);
134 /* Remove trailing slashes (except the very first one, at position
135 drive_prefix_len), but remember their presence. */
137 bool check_dir
= false;
140 while (rlen
> drive_prefix_len
&& ISSLASH (name
[rlen
-1]))
143 if (rlen
== drive_prefix_len
+ 1)
148 /* Handle '' and 'C:'. */
149 if (!check_dir
&& rlen
== drive_prefix_len
)
156 if (rlen
== 1 && ISSLASH (name
[0]) && len
>= 2)
167 malloca_rname
= NULL
;
171 malloca_rname
= malloca (rlen
+ 1);
172 if (malloca_rname
== NULL
)
177 memcpy (malloca_rname
, name
, rlen
);
178 malloca_rname
[rlen
] = '\0';
179 rname
= malloca_rname
;
182 /* There are two ways to get at the requested information:
183 - by scanning the parent directory and examining the relevant
185 - by opening the file directly.
186 The first approach fails for root directories (e.g. 'C:\') and
187 UNC root directories (e.g. '\\server\share').
188 The second approach fails for some system files (e.g. 'C:\pagefile.sys'
189 and 'C:\hiberfil.sys'): ERROR_SHARING_VIOLATION.
190 The second approach gives more information (in particular, correct
191 st_dev, st_ino, st_nlink fields).
192 So we use the second approach and, as a fallback except for root and
193 UNC root directories, also the first approach. */
198 /* Approach based on the file. */
200 /* Open a handle to the file.
202 <https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-createfilea>
203 <https://docs.microsoft.com/en-us/windows/desktop/FileIO/creating-and-opening-files> */
206 FILE_READ_ATTRIBUTES
,
207 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
210 /* FILE_FLAG_POSIX_SEMANTICS (treat file names that differ only
211 in case as different) makes sense only when applied to *all*
212 filesystem operations. */
213 FILE_FLAG_BACKUP_SEMANTICS
/* | FILE_FLAG_POSIX_SEMANTICS */,
215 if (h
!= INVALID_HANDLE_VALUE
)
217 ret
= _gl_fstat_by_handle (h
, rname
, buf
);
223 /* Test for root and UNC root directories. */
224 if ((rlen
== drive_prefix_len
+ 1 && ISSLASH (rname
[drive_prefix_len
]))
225 || is_unc_root (rname
))
230 /* Approach based on the directory entry. */
232 if (strchr (rname
, '?') != NULL
|| strchr (rname
, '*') != NULL
)
234 /* Other Windows API functions would fail with error
235 ERROR_INVALID_NAME. */
236 if (malloca_rname
!= NULL
)
237 freea (malloca_rname
);
242 /* Get the details about the directory entry. This can be done through
244 <https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-findfirstfilea>
245 <https://docs.microsoft.com/en-us/windows/desktop/api/minwinbase/ns-minwinbase-_win32_find_dataa>
247 FindFirstFileEx with argument FindExInfoBasic
248 <https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-findfirstfileexa>
249 <https://docs.microsoft.com/en-us/windows/desktop/api/minwinbase/ne-minwinbase-findex_info_levels>
250 <https://docs.microsoft.com/en-us/windows/desktop/api/minwinbase/ns-minwinbase-_win32_find_dataa> */
251 WIN32_FIND_DATA info
;
252 HANDLE h
= FindFirstFile (rname
, &info
);
253 if (h
== INVALID_HANDLE_VALUE
)
256 /* Test for error conditions before starting to fill *buf. */
257 if (sizeof (buf
->st_size
) <= 4 && info
.nFileSizeHigh
> 0)
260 if (malloca_rname
!= NULL
)
261 freea (malloca_rname
);
266 # if _GL_WINDOWS_STAT_INODES
268 # if _GL_WINDOWS_STAT_INODES == 2
269 buf
->st_ino
._gl_ino
[0] = buf
->st_ino
._gl_ino
[1] = 0;
270 # else /* _GL_WINDOWS_STAT_INODES == 1 */
274 /* st_ino is not wide enough for identifying a file on a device.
275 Without st_ino, st_dev is pointless. */
282 /* XXX How to handle FILE_ATTRIBUTE_REPARSE_POINT ? */
283 ((info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) ? _S_IFDIR
| S_IEXEC_UGO
: _S_IFREG
)
285 | ((info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
) ? 0 : S_IWRITE_UGO
);
286 if (!(info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
))
288 /* Determine whether the file is executable by looking at the file
290 if (info
.nFileSizeHigh
> 0 || info
.nFileSizeLow
> 0)
292 const char *last_dot
= NULL
;
294 for (p
= info
.cFileName
; *p
!= '\0'; p
++)
297 if (last_dot
!= NULL
)
299 const char *suffix
= last_dot
+ 1;
300 if (_stricmp (suffix
, "exe") == 0
301 || _stricmp (suffix
, "bat") == 0
302 || _stricmp (suffix
, "cmd") == 0
303 || _stricmp (suffix
, "com") == 0)
310 /* st_nlink. Ignore hard links here. */
313 /* There's no easy way to map the Windows SID concept to an integer. */
317 /* st_rdev is irrelevant for normal files and directories. */
321 if (sizeof (buf
->st_size
) <= 4)
322 /* Range check already done above. */
323 buf
->st_size
= info
.nFileSizeLow
;
325 buf
->st_size
= ((long long) info
.nFileSizeHigh
<< 32) | (long long) info
.nFileSizeLow
;
327 /* st_atime, st_mtime, st_ctime. */
328 # if _GL_WINDOWS_STAT_TIMESPEC
329 buf
->st_atim
= _gl_convert_FILETIME_to_timespec (&info
.ftLastAccessTime
);
330 buf
->st_mtim
= _gl_convert_FILETIME_to_timespec (&info
.ftLastWriteTime
);
331 buf
->st_ctim
= _gl_convert_FILETIME_to_timespec (&info
.ftCreationTime
);
333 buf
->st_atime
= _gl_convert_FILETIME_to_POSIX (&info
.ftLastAccessTime
);
334 buf
->st_mtime
= _gl_convert_FILETIME_to_POSIX (&info
.ftLastWriteTime
);
335 buf
->st_ctime
= _gl_convert_FILETIME_to_POSIX (&info
.ftCreationTime
);
344 if (ret
>= 0 && check_dir
&& !S_ISDIR (buf
->st_mode
))
349 if (malloca_rname
!= NULL
)
351 int saved_errno
= errno
;
352 freea (malloca_rname
);
360 DWORD error
= GetLastError ();
362 fprintf (stderr
, "rpl_stat error 0x%x\n", (unsigned int) error
);
365 if (malloca_rname
!= NULL
)
366 freea (malloca_rname
);
370 /* Some of these errors probably cannot happen with the specific flags
371 that we pass to CreateFile. But who knows... */
372 case ERROR_FILE_NOT_FOUND
: /* The last component of rname does not exist. */
373 case ERROR_PATH_NOT_FOUND
: /* Some directory component in rname does not exist. */
374 case ERROR_BAD_PATHNAME
: /* rname is such as '\\server'. */
375 case ERROR_BAD_NET_NAME
: /* rname is such as '\\server\nonexistentshare'. */
376 case ERROR_INVALID_NAME
: /* rname contains wildcards, misplaced colon, etc. */
377 case ERROR_DIRECTORY
:
381 case ERROR_ACCESS_DENIED
: /* rname is such as 'C:\System Volume Information\foo'. */
382 case ERROR_SHARING_VIOLATION
: /* rname is such as 'C:\pagefile.sys' (second approach only). */
383 /* XXX map to EACCES or EPERM? */
387 case ERROR_OUTOFMEMORY
:
391 case ERROR_WRITE_PROTECT
:
395 case ERROR_WRITE_FAULT
:
396 case ERROR_READ_FAULT
:
397 case ERROR_GEN_FAILURE
:
401 case ERROR_BUFFER_OVERFLOW
:
402 case ERROR_FILENAME_EXCED_RANGE
:
403 errno
= ENAMETOOLONG
;
406 case ERROR_DELETE_PENDING
: /* XXX map to EACCES or EPERM? */
418 int result
= orig_stat (name
, buf
);
421 # if REPLACE_FUNC_STAT_FILE
422 /* Solaris 9 mistakenly succeeds when given a non-directory with a
424 if (!S_ISDIR (buf
->st_mode
))
426 size_t len
= strlen (name
);
427 if (ISSLASH (name
[len
- 1]))
433 # endif /* REPLACE_FUNC_STAT_FILE */
434 result
= stat_time_normalize (result
, buf
);