Debian Codegraph @

lib/stat.c

raw
1 /* Work around platform bugs in stat.
2 Copyright (C) 2009-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 /* Written by Eric Blake and Bruno Haible. */
18
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
21 rpl_stat. */
22 #define __need_system_sys_stat_h
23 #include <config.h>
24
25 /* Get the original definition of stat. It might be defined as a macro. */
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #undef __need_system_sys_stat_h
29
30 #if defined _WIN32 && ! defined __CYGWIN__
31 # define WINDOWS_NATIVE
32 #endif
33
34 #if !defined WINDOWS_NATIVE
35
36 static int
37 orig_stat (const char *filename, struct stat *buf)
38 {
39 return stat (filename, buf);
40 }
41
42 #endif
43
44 /* Specification. */
45 #include <sys/stat.h>
46
47 #include "stat-time.h"
48
49 #include <errno.h>
50 #include <limits.h>
51 #include <string.h>
52 #include "filename.h"
53 #include "malloca.h"
54
55 #ifdef WINDOWS_NATIVE
56 # define WIN32_LEAN_AND_MEAN
57 # include <windows.h>
58 # include "stat-w32.h"
59 /* Don't assume that UNICODE is not defined. */
60 # undef WIN32_FIND_DATA
61 # define WIN32_FIND_DATA WIN32_FIND_DATAA
62 # undef CreateFile
63 # define CreateFile CreateFileA
64 # undef FindFirstFile
65 # define FindFirstFile FindFirstFileA
66 #endif
67
68 #ifdef WINDOWS_NATIVE
69 /* Return TRUE if the given file name denotes an UNC root. */
70 static BOOL
71 is_unc_root (const char *rname)
72 {
73 /* Test whether it has the syntax '\\server\share'. */
74 if (ISSLASH (rname[0]) && ISSLASH (rname[1]))
75 {
76 /* It starts with two slashes. Find the next slash. */
77 const char *p = rname + 2;
78 const char *q = p;
79 while (*q != '\0' && !ISSLASH (*q))
80 q++;
81 if (q > p && *q != '\0')
82 {
83 /* Found the next slash at q. */
84 q++;
85 const char *r = q;
86 while (*r != '\0' && !ISSLASH (*r))
87 r++;
88 if (r > q && *r == '\0')
89 return TRUE;
90 }
91 }
92 return FALSE;
93 }
94 #endif
95
96 /* Store information about NAME into ST. Work around bugs with
97 trailing slashes. Mingw has other bugs (such as st_ino always
98 being 0 on success) which this wrapper does not work around. But
99 at least this implementation provides the ability to emulate fchdir
100 correctly. */
101
102 int
103 rpl_stat (char const *name, struct stat *buf)
104 {
105 #ifdef WINDOWS_NATIVE
106 /* Fill the fields ourselves, because the original stat function returns
107 values for st_atime, st_mtime, st_ctime that depend on the current time
108 zone. See
109 <https://lists.gnu.org/r/bug-gnulib/2017-04/msg00134.html> */
110 /* XXX Should we convert to wchar_t* and prepend '\\?\', in order to work
111 around length limitations
112 <https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file> ? */
113
114 /* To ease portability. Like in open.c. */
115 if (streq (name, "/dev/null"))
116 name = "NUL";
117
118 /* POSIX <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13>
119 specifies: "More than two leading <slash> characters shall be treated as
120 a single <slash> character." */
121 if (ISSLASH (name[0]) && ISSLASH (name[1]) && ISSLASH (name[2]))
122 {
123 name += 2;
124 while (ISSLASH (name[1]))
125 name++;
126 }
127
128 size_t len = strlen (name);
129 size_t drive_prefix_len = (HAS_DEVICE (name) ? 2 : 0);
130
131 /* Remove trailing slashes (except the very first one, at position
132 drive_prefix_len), but remember their presence. */
133 size_t rlen;
134 bool check_dir = false;
135
136 rlen = len;
137 while (rlen > drive_prefix_len && ISSLASH (name[rlen-1]))
138 {
139 check_dir = true;
140 if (rlen == drive_prefix_len + 1)
141 break;
142 rlen--;
143 }
144
145 /* Handle '' and 'C:'. */
146 if (!check_dir && rlen == drive_prefix_len)
147 {
148 errno = ENOENT;
149 return -1;
150 }
151
152 /* Handle '\\'. */
153 if (rlen == 1 && ISSLASH (name[0]) && len >= 2)
154 {
155 errno = ENOENT;
156 return -1;
157 }
158
159 const char *rname;
160 char *malloca_rname;
161 if (rlen == len)
162 {
163 rname = name;
164 malloca_rname = NULL;
165 }
166 else
167 {
168 malloca_rname = malloca (rlen + 1);
169 if (malloca_rname == NULL)
170 {
171 errno = ENOMEM;
172 return -1;
173 }
174 memcpy (malloca_rname, name, rlen);
175 malloca_rname[rlen] = '\0';
176 rname = malloca_rname;
177 }
178
179 /* There are two ways to get at the requested information:
180 - by scanning the parent directory and examining the relevant
181 directory entry,
182 - by opening the file directly.
183 The first approach fails for root directories (e.g. 'C:\') and
184 UNC root directories (e.g. '\\server\share').
185 The second approach fails for some system files (e.g. 'C:\pagefile.sys'
186 and 'C:\hiberfil.sys'): ERROR_SHARING_VIOLATION.
187 The second approach gives more information (in particular, correct
188 st_dev, st_ino, st_nlink fields).
189 So we use the second approach and, as a fallback except for root and
190 UNC root directories, also the first approach. */
191 {
192 int ret;
193
194 {
195 /* Approach based on the file. */
196
197 /* Open a handle to the file.
198 CreateFile
199 <https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-createfilea>
200 <https://docs.microsoft.com/en-us/windows/desktop/FileIO/creating-and-opening-files> */
201 HANDLE h =
202 CreateFile (rname,
203 FILE_READ_ATTRIBUTES,
204 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
205 NULL,
206 OPEN_EXISTING,
207 /* FILE_FLAG_POSIX_SEMANTICS (treat file names that differ only
208 in case as different) makes sense only when applied to *all*
209 filesystem operations. */
210 FILE_FLAG_BACKUP_SEMANTICS /* | FILE_FLAG_POSIX_SEMANTICS */,
211 NULL);
212 if (h != INVALID_HANDLE_VALUE)
213 {
214 ret = _gl_fstat_by_handle (h, rname, buf);
215 CloseHandle (h);
216 goto done;
217 }
218 }
219
220 /* Test for root and UNC root directories. */
221 if ((rlen == drive_prefix_len + 1 && ISSLASH (rname[drive_prefix_len]))
222 || is_unc_root (rname))
223 goto failed;
224
225 /* Fallback. */
226 {
227 /* Approach based on the directory entry. */
228
229 if (strchr (rname, '?') != NULL || strchr (rname, '*') != NULL)
230 {
231 /* Other Windows API functions would fail with error
232 ERROR_INVALID_NAME. */
233 if (malloca_rname != NULL)
234 freea (malloca_rname);
235 errno = ENOENT;
236 return -1;
237 }
238
239 /* Get the details about the directory entry. This can be done through
240 FindFirstFile
241 <https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-findfirstfilea>
242 <https://docs.microsoft.com/en-us/windows/desktop/api/minwinbase/ns-minwinbase-_win32_find_dataa>
243 or through
244 FindFirstFileEx with argument FindExInfoBasic
245 <https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-findfirstfileexa>
246 <https://docs.microsoft.com/en-us/windows/desktop/api/minwinbase/ne-minwinbase-findex_info_levels>
247 <https://docs.microsoft.com/en-us/windows/desktop/api/minwinbase/ns-minwinbase-_win32_find_dataa> */
248 WIN32_FIND_DATA info;
249 HANDLE h = FindFirstFile (rname, &info);
250 if (h == INVALID_HANDLE_VALUE)
251 goto failed;
252
253 /* Test for error conditions before starting to fill *buf. */
254 if (sizeof (buf->st_size) <= 4 && info.nFileSizeHigh > 0)
255 {
256 FindClose (h);
257 if (malloca_rname != NULL)
258 freea (malloca_rname);
259 errno = EOVERFLOW;
260 return -1;
261 }
262
263 # if _GL_WINDOWS_STAT_INODES
264 buf->st_dev = 0;
265 # if _GL_WINDOWS_STAT_INODES == 2
266 buf->st_ino._gl_ino[0] = buf->st_ino._gl_ino[1] = 0;
267 # else /* _GL_WINDOWS_STAT_INODES == 1 */
268 buf->st_ino = 0;
269 # endif
270 # else
271 /* st_ino is not wide enough for identifying a file on a device.
272 Without st_ino, st_dev is pointless. */
273 buf->st_dev = 0;
274 buf->st_ino = 0;
275 # endif
276
277 /* st_mode. */
278 unsigned int mode =
279 /* XXX How to handle FILE_ATTRIBUTE_REPARSE_POINT ? */
280 ((info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? _S_IFDIR | S_IEXEC_UGO : _S_IFREG)
281 | S_IREAD_UGO
282 | ((info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? 0 : S_IWRITE_UGO);
283 if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
284 {
285 /* Determine whether the file is executable by looking at the file
286 name suffix. */
287 if (info.nFileSizeHigh > 0 || info.nFileSizeLow > 0)
288 {
289 const char *last_dot = NULL;
290 for (const char *p = info.cFileName; *p != '\0'; p++)
291 if (*p == '.')
292 last_dot = p;
293 if (last_dot != NULL)
294 {
295 const char *suffix = last_dot + 1;
296 if (_stricmp (suffix, "exe") == 0
297 || _stricmp (suffix, "bat") == 0
298 || _stricmp (suffix, "cmd") == 0
299 || _stricmp (suffix, "com") == 0)
300 mode |= S_IEXEC_UGO;
301 }
302 }
303 }
304 buf->st_mode = mode;
305
306 /* st_nlink. Ignore hard links here. */
307 buf->st_nlink = 1;
308
309 /* There's no easy way to map the Windows SID concept to an integer. */
310 buf->st_uid = 0;
311 buf->st_gid = 0;
312
313 /* st_rdev is irrelevant for normal files and directories. */
314 buf->st_rdev = 0;
315
316 /* st_size. */
317 if (sizeof (buf->st_size) <= 4)
318 /* Range check already done above. */
319 buf->st_size = info.nFileSizeLow;
320 else
321 buf->st_size = ((long long) info.nFileSizeHigh << 32) | (long long) info.nFileSizeLow;
322
323 /* st_atime, st_mtime, st_ctime. */
324 # if _GL_WINDOWS_STAT_TIMESPEC
325 buf->st_atim = _gl_convert_FILETIME_to_timespec (&info.ftLastAccessTime);
326 buf->st_mtim = _gl_convert_FILETIME_to_timespec (&info.ftLastWriteTime);
327 buf->st_ctim = _gl_convert_FILETIME_to_timespec (&info.ftCreationTime);
328 # else
329 buf->st_atime = _gl_convert_FILETIME_to_POSIX (&info.ftLastAccessTime);
330 buf->st_mtime = _gl_convert_FILETIME_to_POSIX (&info.ftLastWriteTime);
331 buf->st_ctime = _gl_convert_FILETIME_to_POSIX (&info.ftCreationTime);
332 # endif
333
334 FindClose (h);
335
336 ret = 0;
337 }
338
339 done:
340 if (ret >= 0 && check_dir && !S_ISDIR (buf->st_mode))
341 {
342 errno = ENOTDIR;
343 ret = -1;
344 }
345 if (malloca_rname != NULL)
346 {
347 int saved_errno = errno;
348 freea (malloca_rname);
349 errno = saved_errno;
350 }
351 return ret;
352 }
353
354 failed:
355 {
356 DWORD error = GetLastError ();
357 #if 0
358 fprintf (stderr, "rpl_stat error 0x%x\n", (unsigned int) error);
359 #endif
360
361 if (malloca_rname != NULL)
362 freea (malloca_rname);
363
364 switch (error)
365 {
366 /* Some of these errors probably cannot happen with the specific flags
367 that we pass to CreateFile. But who knows... */
368 case ERROR_FILE_NOT_FOUND: /* The last component of rname does not exist. */
369 case ERROR_PATH_NOT_FOUND: /* Some directory component in rname does not exist. */
370 case ERROR_BAD_PATHNAME: /* rname is such as '\\server'. */
371 case ERROR_BAD_NET_NAME: /* rname is such as '\\server\nonexistentshare'. */
372 case ERROR_INVALID_NAME: /* rname contains wildcards, misplaced colon, etc. */
373 case ERROR_DIRECTORY:
374 errno = ENOENT;
375 break;
376
377 case ERROR_ACCESS_DENIED: /* rname is such as 'C:\System Volume Information\foo'. */
378 case ERROR_SHARING_VIOLATION: /* rname is such as 'C:\pagefile.sys' (second approach only). */
379 /* XXX map to EACCES or EPERM? */
380 errno = EACCES;
381 break;
382
383 case ERROR_OUTOFMEMORY:
384 errno = ENOMEM;
385 break;
386
387 case ERROR_WRITE_PROTECT:
388 errno = EROFS;
389 break;
390
391 case ERROR_WRITE_FAULT:
392 case ERROR_READ_FAULT:
393 case ERROR_GEN_FAILURE:
394 errno = EIO;
395 break;
396
397 case ERROR_BUFFER_OVERFLOW:
398 case ERROR_FILENAME_EXCED_RANGE:
399 errno = ENAMETOOLONG;
400 break;
401
402 case ERROR_DELETE_PENDING: /* XXX map to EACCES or EPERM? */
403 errno = EPERM;
404 break;
405
406 default:
407 errno = EINVAL;
408 break;
409 }
410
411 return -1;
412 }
413 #else
414 int result = orig_stat (name, buf);
415 if (result == 0)
416 {
417 # if REPLACE_FUNC_STAT_FILE
418 /* Solaris 9 mistakenly succeeds when given a non-directory with a
419 trailing slash. */
420 if (!S_ISDIR (buf->st_mode))
421 {
422 size_t len = strlen (name);
423 if (ISSLASH (name[len - 1]))
424 {
425 errno = ENOTDIR;
426 return -1;
427 }
428 }
429 # endif /* REPLACE_FUNC_STAT_FILE */
430 result = stat_time_normalize (result, buf);
431 }
432 return result;
433 #endif
434 }