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