stat: new module, for mingw bug
[gnulib.git] / lib / stat.c
1 /* Work around platform bugs in stat.
2    Copyright (C) 2009 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program 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 General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 /* written by Eric Blake */
18
19 #include <config.h>
20
21 #include <sys/stat.h>
22
23 #include <errno.h>
24 #include <limits.h>
25 #include <stdbool.h>
26 #include <string.h>
27
28 #undef stat
29
30 /* For now, mingw is the only known platform where stat(".") and
31    stat("./") give different results.  Mingw stat has other bugs (such
32    as st_ino always being 0 on success) which this wrapper does not
33    work around.  But at least this implementation provides the ability
34    to emulate fchdir correctly.  */
35
36 int
37 rpl_stat (char const *name, struct stat *st)
38 {
39   int result = stat (name, st);
40   if (result == -1 && errno == ENOENT)
41     {
42       /* Due to mingw's oddities, there are some directories (like
43          c:\) where stat() only succeeds with a trailing slash, and
44          other directories (like c:\windows) where stat() only
45          succeeds without a trailing slash.  But we want the two to be
46          synonymous, since chdir() manages either style.  Likewise, Mingw also
47          reports ENOENT for names longer than PATH_MAX, when we want
48          ENAMETOOLONG, and for stat("file/"), when we want ENOTDIR.
49          Fortunately, mingw PATH_MAX is small enough for stack
50          allocation.  */
51       char fixed_name[PATH_MAX + 1] = {0};
52       size_t len = strlen (name);
53       bool check_dir = false;
54       if (PATH_MAX <= len)
55         errno = ENAMETOOLONG;
56       else if (len)
57         {
58           strcpy (fixed_name, name);
59           if (ISSLASH (fixed_name[len - 1]))
60             {
61               check_dir = true;
62               while (len && ISSLASH (fixed_name[len - 1]))
63                 fixed_name[--len] = '\0';
64               if (!len)
65                 fixed_name[0] = '/';
66             }
67           else
68             fixed_name[len++] = '/';
69           result = stat (fixed_name, st);
70           if (result == 0 && check_dir && !S_ISDIR (st->st_mode))
71             {
72               result = -1;
73               errno = ENOTDIR;
74             }
75         }
76     }
77   return result;
78 }