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