]> git.cworth.org Git - tar/blob - gnu/getcwd.c
Imported Upstream version 1.24
[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_RAW_DECL_GETCWD
142   /* If AT_FDCWD is not defined, the algorithm below is O(N**2) and
143      this is much slower than the system getcwd (at least on
144      GNU/Linux).  So trust the system getcwd's results unless they
145      look suspicious.
146
147      Use the system getcwd even if we have openat support, since the
148      system getcwd works even when a parent is unreadable, while the
149      openat-based approach does not.  */
150
151 # undef getcwd
152   dir = getcwd (buf, size);
153   if (dir)
154     return dir;
155
156   /* Solaris getcwd (NULL, 0) fails with errno == EINVAL, but it has
157      internal magic that lets it work even if an ancestor directory is
158      inaccessible, which is better in many cases.  So in this case try
159      again with a buffer that's almost always big enough.  */
160   if (errno == EINVAL && buf == NULL && size == 0)
161     {
162       char big_buffer[BIG_FILE_NAME_LENGTH + 1];
163       dir = getcwd (big_buffer, sizeof big_buffer);
164       if (dir)
165         return strdup (dir);
166     }
167
168 # if HAVE_PARTLY_WORKING_GETCWD
169   /* The system getcwd works, except it sometimes fails when it
170      shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT.    */
171   if (errno != ERANGE && errno != ENAMETOOLONG && errno != ENOENT)
172     return NULL;
173 # endif
174 #endif
175
176   if (size == 0)
177     {
178       if (buf != NULL)
179         {
180           __set_errno (EINVAL);
181           return NULL;
182         }
183
184       allocated = BIG_FILE_NAME_LENGTH + 1;
185     }
186
187   if (buf == NULL)
188     {
189       dir = malloc (allocated);
190       if (dir == NULL)
191         return NULL;
192     }
193   else
194     dir = buf;
195
196   dirp = dir + allocated;
197   *--dirp = '\0';
198
199   if (__lstat (".", &st) < 0)
200     goto lose;
201   thisdev = st.st_dev;
202   thisino = st.st_ino;
203
204   if (__lstat ("/", &st) < 0)
205     goto lose;
206   rootdev = st.st_dev;
207   rootino = st.st_ino;
208
209   while (!(thisdev == rootdev && thisino == rootino))
210     {
211       struct dirent *d;
212       dev_t dotdev;
213       ino_t dotino;
214       bool mount_point;
215       int parent_status;
216       size_t dirroom;
217       size_t namlen;
218       bool use_d_ino = true;
219
220       /* Look at the parent directory.  */
221 #if HAVE_OPENAT_SUPPORT
222       fd = openat (fd, "..", O_RDONLY);
223       if (fd < 0)
224         goto lose;
225       fd_needs_closing = true;
226       parent_status = fstat (fd, &st);
227 #else
228       dotlist[dotlen++] = '.';
229       dotlist[dotlen++] = '.';
230       dotlist[dotlen] = '\0';
231       parent_status = __lstat (dotlist, &st);
232 #endif
233       if (parent_status != 0)
234         goto lose;
235
236       if (dirstream && __closedir (dirstream) != 0)
237         {
238           dirstream = NULL;
239           goto lose;
240         }
241
242       /* Figure out if this directory is a mount point.  */
243       dotdev = st.st_dev;
244       dotino = st.st_ino;
245       mount_point = dotdev != thisdev;
246
247       /* Search for the last directory.  */
248 #if HAVE_OPENAT_SUPPORT
249       dirstream = fdopendir (fd);
250       if (dirstream == NULL)
251         goto lose;
252       fd_needs_closing = false;
253 #else
254       dirstream = __opendir (dotlist);
255       if (dirstream == NULL)
256         goto lose;
257       dotlist[dotlen++] = '/';
258 #endif
259       for (;;)
260         {
261           /* Clear errno to distinguish EOF from error if readdir returns
262              NULL.  */
263           __set_errno (0);
264           d = __readdir (dirstream);
265
266           /* When we've iterated through all directory entries without finding
267              one with a matching d_ino, rewind the stream and consider each
268              name again, but this time, using lstat.  This is necessary in a
269              chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where
270              .., ../.., ../../.., etc. all had the same device number, yet the
271              d_ino values for entries in / did not match those obtained
272              via lstat.  */
273           if (d == NULL && errno == 0 && use_d_ino)
274             {
275               use_d_ino = false;
276               rewinddir (dirstream);
277               d = __readdir (dirstream);
278             }
279
280           if (d == NULL)
281             {
282               if (errno == 0)
283                 /* EOF on dirstream, which can mean e.g., that the current
284                    directory has been removed.  */
285                 __set_errno (ENOENT);
286               goto lose;
287             }
288           if (d->d_name[0] == '.' &&
289               (d->d_name[1] == '\0' ||
290                (d->d_name[1] == '.' && d->d_name[2] == '\0')))
291             continue;
292
293           if (use_d_ino)
294             {
295               bool match = (MATCHING_INO (d, thisino) || mount_point);
296               if (! match)
297                 continue;
298             }
299
300           {
301             int entry_status;
302 #if HAVE_OPENAT_SUPPORT
303             entry_status = fstatat (fd, d->d_name, &st, AT_SYMLINK_NOFOLLOW);
304 #else
305             /* Compute size needed for this file name, or for the file
306                name ".." in the same directory, whichever is larger.
307                Room for ".." might be needed the next time through
308                the outer loop.  */
309             size_t name_alloc = _D_ALLOC_NAMLEN (d);
310             size_t filesize = dotlen + MAX (sizeof "..", name_alloc);
311
312             if (filesize < dotlen)
313               goto memory_exhausted;
314
315             if (dotsize < filesize)
316               {
317                 /* My, what a deep directory tree you have, Grandma.  */
318                 size_t newsize = MAX (filesize, dotsize * 2);
319                 size_t i;
320                 if (newsize < dotsize)
321                   goto memory_exhausted;
322                 if (dotlist != dots)
323                   free (dotlist);
324                 dotlist = malloc (newsize);
325                 if (dotlist == NULL)
326                   goto lose;
327                 dotsize = newsize;
328
329                 i = 0;
330                 do
331                   {
332                     dotlist[i++] = '.';
333                     dotlist[i++] = '.';
334                     dotlist[i++] = '/';
335                   }
336                 while (i < dotlen);
337               }
338
339             memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d));
340             entry_status = __lstat (dotlist, &st);
341 #endif
342             /* We don't fail here if we cannot stat() a directory entry.
343                This can happen when (network) file systems fail.  If this
344                entry is in fact the one we are looking for we will find
345                out soon as we reach the end of the directory without
346                having found anything.  */
347             if (entry_status == 0 && S_ISDIR (st.st_mode)
348                 && st.st_dev == thisdev && st.st_ino == thisino)
349               break;
350           }
351         }
352
353       dirroom = dirp - dir;
354       namlen = _D_EXACT_NAMLEN (d);
355
356       if (dirroom <= namlen)
357         {
358           if (size != 0)
359             {
360               __set_errno (ERANGE);
361               goto lose;
362             }
363           else
364             {
365               char *tmp;
366               size_t oldsize = allocated;
367
368               allocated += MAX (allocated, namlen);
369               if (allocated < oldsize
370                   || ! (tmp = realloc (dir, allocated)))
371                 goto memory_exhausted;
372
373               /* Move current contents up to the end of the buffer.
374                  This is guaranteed to be non-overlapping.  */
375               dirp = memcpy (tmp + allocated - (oldsize - dirroom),
376                              tmp + dirroom,
377                              oldsize - dirroom);
378               dir = tmp;
379             }
380         }
381       dirp -= namlen;
382       memcpy (dirp, d->d_name, namlen);
383       *--dirp = '/';
384
385       thisdev = dotdev;
386       thisino = dotino;
387     }
388
389   if (dirstream && __closedir (dirstream) != 0)
390     {
391       dirstream = NULL;
392       goto lose;
393     }
394
395   if (dirp == &dir[allocated - 1])
396     *--dirp = '/';
397
398 #if ! HAVE_OPENAT_SUPPORT
399   if (dotlist != dots)
400     free (dotlist);
401 #endif
402
403   used = dir + allocated - dirp;
404   memmove (dir, dirp, used);
405
406   if (size == 0)
407     /* Ensure that the buffer is only as large as necessary.  */
408     buf = realloc (dir, used);
409
410   if (buf == NULL)
411     /* Either buf was NULL all along, or `realloc' failed but
412        we still have the original string.  */
413     buf = dir;
414
415   return buf;
416
417  memory_exhausted:
418   __set_errno (ENOMEM);
419  lose:
420   {
421     int save = errno;
422     if (dirstream)
423       __closedir (dirstream);
424 #if HAVE_OPENAT_SUPPORT
425     if (fd_needs_closing)
426       close (fd);
427 #else
428     if (dotlist != dots)
429       free (dotlist);
430 #endif
431     if (buf == NULL)
432       free (dir);
433     __set_errno (save);
434   }
435   return NULL;
436 }
437
438 #ifdef weak_alias
439 weak_alias (__getcwd, getcwd)
440 #endif