]> git.cworth.org Git - tar/blob - gnu/getcwd.c
504448fce245fa58b1a829e98b93ee4c4c3ca724
[tar] / gnu / getcwd.c
1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* Copyright (C) 1991-1999, 2004-2010 Free Software Foundation, Inc.
4    This file is part of the GNU C Library.
5
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 #if !_LIBC
20 # include <config.h>
21 # include <unistd.h>
22 #endif
23
24 #include <errno.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <stdbool.h>
28 #include <stddef.h>
29
30 #include <fcntl.h> /* For AT_FDCWD on Solaris 9.  */
31
32 /* If this host provides the openat function, then enable
33    code below to make getcwd more efficient and robust.  */
34 #ifdef HAVE_OPENAT
35 # define HAVE_OPENAT_SUPPORT 1
36 #else
37 # define HAVE_OPENAT_SUPPORT 0
38 #endif
39
40 #ifndef __set_errno
41 # define __set_errno(val) (errno = (val))
42 #endif
43
44 #include <dirent.h>
45 #ifndef _D_EXACT_NAMLEN
46 # define _D_EXACT_NAMLEN(d) strlen ((d)->d_name)
47 #endif
48 #ifndef _D_ALLOC_NAMLEN
49 # define _D_ALLOC_NAMLEN(d) (_D_EXACT_NAMLEN (d) + 1)
50 #endif
51
52 #include <unistd.h>
53 #include <stdlib.h>
54 #include <string.h>
55
56 #if _LIBC
57 # ifndef mempcpy
58 #  define mempcpy __mempcpy
59 # endif
60 #endif
61
62 #include <limits.h>
63
64 #ifndef MAX
65 # define MAX(a, b) ((a) < (b) ? (b) : (a))
66 #endif
67 #ifndef MIN
68 # define MIN(a, b) ((a) < (b) ? (a) : (b))
69 #endif
70
71 #ifndef PATH_MAX
72 # ifdef MAXPATHLEN
73 #  define PATH_MAX MAXPATHLEN
74 # else
75 #  define PATH_MAX 1024
76 # endif
77 #endif
78
79 #if D_INO_IN_DIRENT
80 # define MATCHING_INO(dp, ino) ((dp)->d_ino == (ino))
81 #else
82 # define MATCHING_INO(dp, ino) true
83 #endif
84
85 #if !_LIBC
86 # define __getcwd rpl_getcwd
87 # define __lstat lstat
88 # define __closedir closedir
89 # define __opendir opendir
90 # define __readdir readdir
91 #endif
92
93 /* The results of opendir() in this file are not used with dirfd and fchdir,
94    and we do not leak fds to any single-threaded code that could use stdio,
95    therefore save some unnecessary recursion in fchdir.c.
96    FIXME - if the kernel ever adds support for multi-thread safety for
97    avoiding standard fds, then we should use opendir_safer and
98    openat_safer.  */
99 #undef opendir
100 #undef closedir
101 \f
102 /* Get the name of the current working directory, and put it in SIZE
103    bytes of BUF.  Returns NULL if the directory couldn't be determined or
104    SIZE was too small.  If successful, returns BUF.  In GNU, if BUF is
105    NULL, an array is allocated with `malloc'; the array is SIZE bytes long,
106    unless SIZE == 0, in which case it is as big as necessary.  */
107
108 char *
109 __getcwd (char *buf, size_t size)
110 {
111   /* Lengths of big file name components and entire file names, and a
112      deep level of file name nesting.  These numbers are not upper
113      bounds; they are merely large values suitable for initial
114      allocations, designed to be large enough for most real-world
115      uses.  */
116   enum
117     {
118       BIG_FILE_NAME_COMPONENT_LENGTH = 255,
119       BIG_FILE_NAME_LENGTH = MIN (4095, PATH_MAX - 1),
120       DEEP_NESTING = 100
121     };
122
123 #if HAVE_OPENAT_SUPPORT
124   int fd = AT_FDCWD;
125   bool fd_needs_closing = false;
126 #else
127   char dots[DEEP_NESTING * sizeof ".." + BIG_FILE_NAME_COMPONENT_LENGTH + 1];
128   char *dotlist = dots;
129   size_t dotsize = sizeof dots;
130   size_t dotlen = 0;
131 #endif
132   DIR *dirstream = NULL;
133   dev_t rootdev, thisdev;
134   ino_t rootino, thisino;
135   char *dir;
136   register char *dirp;
137   struct stat st;
138   size_t allocated = size;
139   size_t used;
140
141 #if HAVE_PARTLY_WORKING_GETCWD
142   /* The system getcwd works, except it sometimes fails when it
143      shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT.  If
144      AT_FDCWD is not defined, the algorithm below is O(N**2) and this
145      is much slower than the system getcwd (at least on GNU/Linux).
146      So trust the system getcwd's results unless they look
147      suspicious.
148
149      Use the system getcwd even if we have openat support, since the
150      system getcwd works even when a parent is unreadable, while the
151      openat-based approach does not.  */
152
153 # undef getcwd
154   dir = getcwd (buf, size);
155   if (dir || (errno != ERANGE && errno != ENAMETOOLONG && errno != ENOENT))
156     return dir;
157 #endif
158
159   if (size == 0)
160     {
161       if (buf != NULL)
162         {
163           __set_errno (EINVAL);
164           return NULL;
165         }
166
167       allocated = BIG_FILE_NAME_LENGTH + 1;
168     }
169
170   if (buf == NULL)
171     {
172       dir = malloc (allocated);
173       if (dir == NULL)
174         return NULL;
175     }
176   else
177     dir = buf;
178
179   dirp = dir + allocated;
180   *--dirp = '\0';
181
182   if (__lstat (".", &st) < 0)
183     goto lose;
184   thisdev = st.st_dev;
185   thisino = st.st_ino;
186
187   if (__lstat ("/", &st) < 0)
188     goto lose;
189   rootdev = st.st_dev;
190   rootino = st.st_ino;
191
192   while (!(thisdev == rootdev && thisino == rootino))
193     {
194       struct dirent *d;
195       dev_t dotdev;
196       ino_t dotino;
197       bool mount_point;
198       int parent_status;
199       size_t dirroom;
200       size_t namlen;
201       bool use_d_ino = true;
202
203       /* Look at the parent directory.  */
204 #if HAVE_OPENAT_SUPPORT
205       fd = openat (fd, "..", O_RDONLY);
206       if (fd < 0)
207         goto lose;
208       fd_needs_closing = true;
209       parent_status = fstat (fd, &st);
210 #else
211       dotlist[dotlen++] = '.';
212       dotlist[dotlen++] = '.';
213       dotlist[dotlen] = '\0';
214       parent_status = __lstat (dotlist, &st);
215 #endif
216       if (parent_status != 0)
217         goto lose;
218
219       if (dirstream && __closedir (dirstream) != 0)
220         {
221           dirstream = NULL;
222           goto lose;
223         }
224
225       /* Figure out if this directory is a mount point.  */
226       dotdev = st.st_dev;
227       dotino = st.st_ino;
228       mount_point = dotdev != thisdev;
229
230       /* Search for the last directory.  */
231 #if HAVE_OPENAT_SUPPORT
232       dirstream = fdopendir (fd);
233       if (dirstream == NULL)
234         goto lose;
235       /* Reset fd.  It may have been closed by fdopendir.  */
236       fd = dirfd (dirstream);
237       fd_needs_closing = false;
238 #else
239       dirstream = __opendir (dotlist);
240       if (dirstream == NULL)
241         goto lose;
242       dotlist[dotlen++] = '/';
243 #endif
244       for (;;)
245         {
246           /* Clear errno to distinguish EOF from error if readdir returns
247              NULL.  */
248           __set_errno (0);
249           d = __readdir (dirstream);
250
251           /* When we've iterated through all directory entries without finding
252              one with a matching d_ino, rewind the stream and consider each
253              name again, but this time, using lstat.  This is necessary in a
254              chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where
255              .., ../.., ../../.., etc. all had the same device number, yet the
256              d_ino values for entries in / did not match those obtained
257              via lstat.  */
258           if (d == NULL && errno == 0 && use_d_ino)
259             {
260               use_d_ino = false;
261               rewinddir (dirstream);
262               d = __readdir (dirstream);
263             }
264
265           if (d == NULL)
266             {
267               if (errno == 0)
268                 /* EOF on dirstream, which can mean e.g., that the current
269                    directory has been removed.  */
270                 __set_errno (ENOENT);
271               goto lose;
272             }
273           if (d->d_name[0] == '.' &&
274               (d->d_name[1] == '\0' ||
275                (d->d_name[1] == '.' && d->d_name[2] == '\0')))
276             continue;
277
278           if (use_d_ino)
279             {
280               bool match = (MATCHING_INO (d, thisino) || mount_point);
281               if (! match)
282                 continue;
283             }
284
285           {
286             int entry_status;
287 #if HAVE_OPENAT_SUPPORT
288             entry_status = fstatat (fd, d->d_name, &st, AT_SYMLINK_NOFOLLOW);
289 #else
290             /* Compute size needed for this file name, or for the file
291                name ".." in the same directory, whichever is larger.
292                Room for ".." might be needed the next time through
293                the outer loop.  */
294             size_t name_alloc = _D_ALLOC_NAMLEN (d);
295             size_t filesize = dotlen + MAX (sizeof "..", name_alloc);
296
297             if (filesize < dotlen)
298               goto memory_exhausted;
299
300             if (dotsize < filesize)
301               {
302                 /* My, what a deep directory tree you have, Grandma.  */
303                 size_t newsize = MAX (filesize, dotsize * 2);
304                 size_t i;
305                 if (newsize < dotsize)
306                   goto memory_exhausted;
307                 if (dotlist != dots)
308                   free (dotlist);
309                 dotlist = malloc (newsize);
310                 if (dotlist == NULL)
311                   goto lose;
312                 dotsize = newsize;
313
314                 i = 0;
315                 do
316                   {
317                     dotlist[i++] = '.';
318                     dotlist[i++] = '.';
319                     dotlist[i++] = '/';
320                   }
321                 while (i < dotlen);
322               }
323
324             memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d));
325             entry_status = __lstat (dotlist, &st);
326 #endif
327             /* We don't fail here if we cannot stat() a directory entry.
328                This can happen when (network) file systems fail.  If this
329                entry is in fact the one we are looking for we will find
330                out soon as we reach the end of the directory without
331                having found anything.  */
332             if (entry_status == 0 && S_ISDIR (st.st_mode)
333                 && st.st_dev == thisdev && st.st_ino == thisino)
334               break;
335           }
336         }
337
338       dirroom = dirp - dir;
339       namlen = _D_EXACT_NAMLEN (d);
340
341       if (dirroom <= namlen)
342         {
343           if (size != 0)
344             {
345               __set_errno (ERANGE);
346               goto lose;
347             }
348           else
349             {
350               char *tmp;
351               size_t oldsize = allocated;
352
353               allocated += MAX (allocated, namlen);
354               if (allocated < oldsize
355                   || ! (tmp = realloc (dir, allocated)))
356                 goto memory_exhausted;
357
358               /* Move current contents up to the end of the buffer.
359                  This is guaranteed to be non-overlapping.  */
360               dirp = memcpy (tmp + allocated - (oldsize - dirroom),
361                              tmp + dirroom,
362                              oldsize - dirroom);
363               dir = tmp;
364             }
365         }
366       dirp -= namlen;
367       memcpy (dirp, d->d_name, namlen);
368       *--dirp = '/';
369
370       thisdev = dotdev;
371       thisino = dotino;
372     }
373
374   if (dirstream && __closedir (dirstream) != 0)
375     {
376       dirstream = NULL;
377       goto lose;
378     }
379
380   if (dirp == &dir[allocated - 1])
381     *--dirp = '/';
382
383 #if ! HAVE_OPENAT_SUPPORT
384   if (dotlist != dots)
385     free (dotlist);
386 #endif
387
388   used = dir + allocated - dirp;
389   memmove (dir, dirp, used);
390
391   if (size == 0)
392     /* Ensure that the buffer is only as large as necessary.  */
393     buf = realloc (dir, used);
394
395   if (buf == NULL)
396     /* Either buf was NULL all along, or `realloc' failed but
397        we still have the original string.  */
398     buf = dir;
399
400   return buf;
401
402  memory_exhausted:
403   __set_errno (ENOMEM);
404  lose:
405   {
406     int save = errno;
407     if (dirstream)
408       __closedir (dirstream);
409 #if HAVE_OPENAT_SUPPORT
410     if (fd_needs_closing)
411       close (fd);
412 #else
413     if (dotlist != dots)
414       free (dotlist);
415 #endif
416     if (buf == NULL)
417       free (dir);
418     __set_errno (save);
419   }
420   return NULL;
421 }
422
423 #ifdef weak_alias
424 weak_alias (__getcwd, getcwd)
425 #endif