Debian Codegraph @

lib/getcwd.c

raw
1 /* Copyright (C) 1991-2026 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published
6 by the Free Software Foundation, either version 3 of the License,
7 or (at your option) any later version.
8
9 This file 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 <https://www.gnu.org/licenses/>. */
16
17 #if !_LIBC
18 # include <config.h>
19 # include <stdio.h>
20 # include <unistd.h>
21 # include "pathmax.h"
22 #else
23 # define HAVE_OPENAT 1
24 # define D_INO_IN_DIRENT 1
25 # define HAVE_MSVC_INVALID_PARAMETER_HANDLER 0
26 # define HAVE_MINIMALLY_WORKING_GETCWD 0
27 #endif
28
29 #include <errno.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <stddef.h>
33
34 #include <fcntl.h> /* For AT_FDCWD on Solaris 9. */
35
36 /* If this host provides the openat function or if we're using the
37 gnulib replacement function with a native fdopendir, then enable
38 code below to make getcwd more efficient and robust. */
39 #if defined HAVE_OPENAT || (defined GNULIB_OPENAT && defined HAVE_FDOPENDIR)
40 # define HAVE_OPENAT_SUPPORT 1
41 #else
42 # define HAVE_OPENAT_SUPPORT 0
43 #endif
44
45 #ifndef __set_errno
46 # define __set_errno(val) (errno = (val))
47 #endif
48
49 #include <dirent.h>
50 #ifndef _D_EXACT_NAMLEN
51 # define _D_EXACT_NAMLEN(d) strlen ((d)->d_name)
52 #endif
53 #ifndef _D_ALLOC_NAMLEN
54 # define _D_ALLOC_NAMLEN(d) (_D_EXACT_NAMLEN (d) + 1)
55 #endif
56
57 #include <unistd.h>
58 #include <stdlib.h>
59 #include <string.h>
60
61 #if _LIBC
62 # ifndef mempcpy
63 # define mempcpy __mempcpy
64 # endif
65 #endif
66
67 #ifndef MAX
68 # define MAX(a, b) ((a) < (b) ? (b) : (a))
69 #endif
70 #ifndef MIN
71 # define MIN(a, b) ((a) < (b) ? (a) : (b))
72 #endif
73
74 /* In this file, PATH_MAX only serves as a threshold for choosing among two
75 algorithms. */
76 #ifndef PATH_MAX
77 # define PATH_MAX 8192
78 #endif
79
80 #if D_INO_IN_DIRENT
81 # define MATCHING_INO(dp, ino) ((dp)->d_ino == (ino))
82 #else
83 # define MATCHING_INO(dp, ino) true
84 #endif
85
86 #if HAVE_MSVC_INVALID_PARAMETER_HANDLER
87 # include "msvc-inval.h"
88 #endif
89
90 #if !_LIBC
91 # define GETCWD_RETURN_TYPE char *
92 # define __close_nocancel_nostatus close
93 # define __getcwd_generic rpl_getcwd
94 # undef stat64
95 # define stat64 stat
96 # define __fstat64 fstat
97 # define __fstatat64 fstatat
98 # define __lstat64 lstat
99 # define __closedir closedir
100 # define __opendir opendir
101 # define __readdir64 readdir
102 # define __fdopendir fdopendir
103 # define __openat openat
104 # define __rewinddir rewinddir
105 # define __openat64 openat
106 # define dirent64 dirent
107 #else
108 # include <not-cancel.h>
109 #endif
110
111 /* The results of opendir() in this file are not used with dirfd and fchdir,
112 and we do not leak fds to any single-threaded code that could use stdio,
113 therefore save some unnecessary recursion in fchdir.c.
114 FIXME - if the kernel ever adds support for multi-thread safety for
115 avoiding standard fds, then we should use opendir_safer and
116 openat_safer. */
117 #ifdef GNULIB_defined_DIR
118 # undef DIR
119 # undef opendir
120 # undef closedir
121 # undef readdir
122 # undef rewinddir
123 #else
124 # ifdef GNULIB_defined_opendir
125 # undef opendir
126 # endif
127 # ifdef GNULIB_defined_closedir
128 # undef closedir
129 # endif
130 #endif
131
132 #if defined _WIN32 && !defined __CYGWIN__
133 # if HAVE_MSVC_INVALID_PARAMETER_HANDLER
134 static char *
135 getcwd_nothrow (char *buf, size_t size)
136 {
137 char *result;
138
139 TRY_MSVC_INVAL
140 {
141 result = _getcwd (buf, size);
142 }
143 CATCH_MSVC_INVAL
144 {
145 result = NULL;
146 errno = ERANGE;
147 }
148 DONE_MSVC_INVAL;
149
150 return result;
151 }
152 # else
153 # define getcwd_nothrow _getcwd
154 # endif
155 # define getcwd_system getcwd_nothrow
156 #else
157 # define getcwd_system getcwd
158 #endif
159
160 /* Get the name of the current working directory, and put it in SIZE
161 bytes of BUF. Returns NULL with errno set if the directory couldn't be
162 determined or SIZE was too small. If successful, returns BUF. In GNU,
163 if BUF is NULL, an array is allocated with 'malloc'; the array is SIZE
164 bytes long, unless SIZE == 0, in which case it is as big as necessary. */
165
166 GETCWD_RETURN_TYPE
167 __getcwd_generic (char *buf, size_t size)
168 {
169 /* Lengths of big file name components and entire file names, and a
170 deep level of file name nesting. These numbers are not upper
171 bounds; they are merely large values suitable for initial
172 allocations, designed to be large enough for most real-world
173 uses. */
174 enum
175 {
176 BIG_FILE_NAME_COMPONENT_LENGTH = 255,
177 BIG_FILE_NAME_LENGTH = MIN (4095, PATH_MAX - 1),
178 DEEP_NESTING = 100
179 };
180
181 #if HAVE_OPENAT_SUPPORT
182 int fd = AT_FDCWD;
183 bool fd_needs_closing = false;
184 # if defined __linux__
185 bool proc_fs_not_mounted = false;
186 # endif
187 #else
188 char dots[DEEP_NESTING * sizeof ".." + BIG_FILE_NAME_COMPONENT_LENGTH + 1];
189 char *dotlist = dots;
190 size_t dotsize = sizeof dots;
191 size_t dotlen = 0;
192 #endif
193
194 #if HAVE_MINIMALLY_WORKING_GETCWD
195 /* If AT_FDCWD is not defined, the algorithm below is O(N**2) and
196 this is much slower than the system getcwd (at least on
197 GNU/Linux). So trust the system getcwd's results unless they
198 look suspicious.
199
200 Use the system getcwd even if we have openat support, since the
201 system getcwd works even when a parent is unreadable, while the
202 openat-based approach does not.
203
204 But on AIX 5.1..7.1, the system getcwd is not even minimally
205 working: If the current directory name is slightly longer than
206 PATH_MAX, it omits the first directory component and returns
207 this wrong result with errno = 0. */
208
209 # undef getcwd
210 {
211 char *dir = getcwd_system (buf, size);
212 if (dir || (size && errno == ERANGE))
213 return dir;
214 }
215
216 /* Solaris getcwd (NULL, 0) fails with errno == EINVAL, but it has
217 internal magic that lets it work even if an ancestor directory is
218 inaccessible, which is better in many cases. So in this case try
219 again with a buffer that's almost always big enough. */
220 if (errno == EINVAL && buf == NULL && size == 0)
221 {
222 char big_buffer[BIG_FILE_NAME_LENGTH + 1];
223 char *dir = getcwd_system (big_buffer, sizeof big_buffer);
224 if (dir)
225 return strdup (dir);
226 }
227
228 # if HAVE_PARTLY_WORKING_GETCWD
229 /* The system getcwd works, except it sometimes fails when it
230 shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT. */
231 if (errno != ERANGE && errno != ENAMETOOLONG && errno != ENOENT)
232 return NULL;
233 # endif
234 #endif
235
236 size_t allocated = size;
237 if (size == 0)
238 {
239 if (buf != NULL)
240 {
241 __set_errno (EINVAL);
242 return NULL;
243 }
244
245 allocated = BIG_FILE_NAME_LENGTH + 1;
246 }
247
248 char *dir;
249 if (buf == NULL)
250 {
251 dir = malloc (allocated);
252 if (dir == NULL)
253 return NULL;
254 }
255 else
256 dir = buf;
257
258 register char *dirp = dir + allocated;
259 *--dirp = '\0';
260
261 DIR *dirstream = NULL;
262
263 dev_t thisdev;
264 ino_t thisino;
265 {
266 struct stat64 st;
267 if (__lstat64 (".", &st) < 0)
268 goto lose;
269 thisdev = st.st_dev;
270 thisino = st.st_ino;
271 }
272
273 dev_t rootdev;
274 ino_t rootino;
275 {
276 struct stat64 st;
277 if (__lstat64 ("/", &st) < 0)
278 goto lose;
279 rootdev = st.st_dev;
280 rootino = st.st_ino;
281 }
282
283 while (!(thisdev == rootdev && thisino == rootino))
284 {
285 /* Look at the parent directory. */
286 dev_t dotdev;
287 ino_t dotino;
288 {
289 struct stat64 st;
290 int parent_status;
291 #if HAVE_OPENAT_SUPPORT
292 fd = __openat64 (fd, "..", O_RDONLY);
293 if (fd < 0)
294 goto lose;
295 fd_needs_closing = true;
296 parent_status = __fstat64 (fd, &st);
297 #else
298 dotlist[dotlen++] = '.';
299 dotlist[dotlen++] = '.';
300 dotlist[dotlen] = '\0';
301 parent_status = __lstat64 (dotlist, &st);
302 #endif
303 if (parent_status != 0)
304 goto lose;
305
306 if (dirstream && __closedir (dirstream) != 0)
307 {
308 dirstream = NULL;
309 goto lose;
310 }
311
312 dotdev = st.st_dev;
313 dotino = st.st_ino;
314 }
315 /* Figure out if this directory is a mount point. */
316 bool mount_point = dotdev != thisdev;
317
318 /* Search for the last directory. */
319 #if HAVE_OPENAT_SUPPORT
320 dirstream = __fdopendir (fd);
321 if (dirstream == NULL)
322 goto lose;
323 fd_needs_closing = false;
324 #else
325 dirstream = __opendir (dotlist);
326 if (dirstream == NULL)
327 goto lose;
328 dotlist[dotlen++] = '/';
329 #endif
330 struct dirent64 *d;
331 bool use_d_ino = true;
332 for (;;)
333 {
334 /* Clear errno to distinguish EOF from error if readdir returns
335 NULL. */
336 __set_errno (0);
337 d = __readdir64 (dirstream);
338
339 /* When we've iterated through all directory entries without finding
340 one with a matching d_ino, rewind the stream and consider each
341 name again, but this time, using lstat. This is necessary in a
342 chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where
343 .., ../.., ../../.., etc. all had the same device number, yet the
344 d_ino values for entries in / did not match those obtained
345 via lstat. */
346 if (d == NULL && errno == 0 && use_d_ino)
347 {
348 use_d_ino = false;
349 __rewinddir (dirstream);
350 d = __readdir64 (dirstream);
351 }
352
353 if (d == NULL)
354 {
355 if (errno == 0)
356 /* EOF on dirstream, which can mean e.g., that the current
357 directory has been removed. */
358 __set_errno (ENOENT);
359 goto lose;
360 }
361 if (d->d_name[0] == '.' &&
362 (d->d_name[1] == '\0' ||
363 (d->d_name[1] == '.' && d->d_name[2] == '\0')))
364 continue;
365
366 if (use_d_ino)
367 {
368 bool match = (MATCHING_INO (d, thisino) || mount_point);
369 if (! match)
370 continue;
371 }
372
373 {
374 struct stat64 st;
375 int entry_status;
376 #if HAVE_OPENAT_SUPPORT
377 entry_status = __fstatat64 (fd, d->d_name, &st, AT_SYMLINK_NOFOLLOW);
378 #else
379 /* Compute size needed for this file name, or for the file
380 name ".." in the same directory, whichever is larger.
381 Room for ".." might be needed the next time through
382 the outer loop. */
383 size_t name_alloc = _D_ALLOC_NAMLEN (d);
384 size_t filesize = dotlen + MAX (sizeof "..", name_alloc);
385
386 if (filesize < dotlen)
387 goto memory_exhausted;
388
389 if (dotsize < filesize)
390 {
391 /* My, what a deep directory tree you have, Grandma. */
392 size_t newsize = MAX (filesize, dotsize * 2);
393 size_t i;
394 if (newsize < dotsize)
395 goto memory_exhausted;
396 if (dotlist != dots)
397 free (dotlist);
398 dotlist = malloc (newsize);
399 if (dotlist == NULL)
400 goto lose;
401 dotsize = newsize;
402
403 i = 0;
404 do
405 {
406 dotlist[i++] = '.';
407 dotlist[i++] = '.';
408 dotlist[i++] = '/';
409 }
410 while (i < dotlen);
411 }
412
413 memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d));
414 entry_status = __lstat64 (dotlist, &st);
415 #endif
416 /* We don't fail here if we cannot stat() a directory entry.
417 This can happen when (network) file systems fail. If this
418 entry is in fact the one we are looking for we will find
419 out soon as we reach the end of the directory without
420 having found anything. */
421 if (entry_status == 0 && S_ISDIR (st.st_mode)
422 && st.st_dev == thisdev && st.st_ino == thisino)
423 break;
424 }
425 }
426
427 size_t dirroom = dirp - dir;
428 size_t namlen = _D_EXACT_NAMLEN (d);
429
430 if (dirroom <= namlen)
431 {
432 if (size != 0)
433 {
434 __set_errno (ERANGE);
435 goto lose;
436 }
437 else
438 {
439 char *tmp;
440 size_t oldsize = allocated;
441
442 allocated += MAX (allocated, namlen);
443 if (allocated < oldsize
444 || ! (tmp = realloc (dir, allocated)))
445 goto memory_exhausted;
446
447 /* Move current contents up to the end of the buffer.
448 This is guaranteed to be non-overlapping. */
449 dirp = memcpy (tmp + allocated - (oldsize - dirroom),
450 tmp + dirroom,
451 oldsize - dirroom);
452 dir = tmp;
453 }
454 }
455 dirp -= namlen;
456 memcpy (dirp, d->d_name, namlen);
457 *--dirp = '/';
458
459 thisdev = dotdev;
460 thisino = dotino;
461
462 #if HAVE_OPENAT_SUPPORT
463 /* On some platforms, a system call returns the directory that FD points
464 to. This is useful if some of the ancestor directories of the
465 directory are unreadable, because in this situation the loop that
466 climbs up the ancestor hierarchy runs into an EACCES error.
467 For example, in some Android app, /data/data/com.termux is readable,
468 but /data/data and /data are not. */
469 # if defined __linux__
470 /* On Linux, in particular, if /proc is mounted,
471 readlink ("/proc/self/fd/<fd>")
472 returns the directory, if its length is < 4096. (If the length is
473 >= 4096, it fails with error ENAMETOOLONG, even if the buffer that we
474 pass to the readlink function would be large enough.) */
475 if (!proc_fs_not_mounted)
476 {
477 char namebuf[14 + 10 + 1];
478 sprintf (namebuf, "/proc/self/fd/%u", (unsigned int) fd);
479 char linkbuf[4096];
480 ssize_t linklen = readlink (namebuf, linkbuf, sizeof linkbuf);
481 if (linklen < 0)
482 {
483 if (errno != ENAMETOOLONG)
484 /* If this call was not successful, the next one will likely be
485 not successful either. */
486 proc_fs_not_mounted = true;
487 }
488 else
489 {
490 /* *dirp is already a '/' (see above). Therefore if the directory
491 ends in a slash, we can remove that slash. This happens in
492 particular if the directory is "/". */
493 if (linklen > 0 && linkbuf[linklen - 1] == '/')
494 linklen--;
495
496 dirroom = dirp - dir;
497 if (dirroom < linklen)
498 {
499 if (size != 0)
500 {
501 __set_errno (ERANGE);
502 goto lose;
503 }
504 else
505 {
506 char *tmp;
507 size_t oldsize = allocated;
508
509 allocated += linklen - dirroom;
510 if (allocated < oldsize
511 || ! (tmp = realloc (dir, allocated)))
512 goto memory_exhausted;
513
514 /* Move current contents up to the end of the buffer. */
515 dirp = memmove (tmp + dirroom + (allocated - oldsize),
516 tmp + dirroom,
517 oldsize - dirroom);
518 dir = tmp;
519 }
520 }
521 dirp -= linklen;
522 memcpy (dirp, linkbuf, linklen);
523 break;
524 }
525 }
526 # endif
527 #endif
528 }
529
530 if (dirstream && __closedir (dirstream) != 0)
531 {
532 dirstream = NULL;
533 goto lose;
534 }
535
536 if (dirp == &dir[allocated - 1])
537 *--dirp = '/';
538
539 #if ! HAVE_OPENAT_SUPPORT
540 if (dotlist != dots)
541 free (dotlist);
542 #endif
543
544 size_t used = dir + allocated - dirp;
545 memmove (dir, dirp, used);
546
547 if (size == 0)
548 /* Ensure that the buffer is only as large as necessary. */
549 buf = (used < allocated ? realloc (dir, used) : dir);
550
551 if (buf == NULL)
552 /* Either buf was NULL all along, or 'realloc' failed but
553 we still have the original string. */
554 buf = dir;
555
556 return buf;
557
558 memory_exhausted:
559 __set_errno (ENOMEM);
560 lose:
561 {
562 int save = errno;
563 if (dirstream)
564 __closedir (dirstream);
565 #if HAVE_OPENAT_SUPPORT
566 if (fd_needs_closing)
567 __close_nocancel_nostatus (fd);
568 #else
569 if (dotlist != dots)
570 free (dotlist);
571 #endif
572 if (buf == NULL)
573 free (dir);
574 __set_errno (save);
575 }
576 return NULL;
577 }
578
579 #if defined _LIBC && !defined GETCWD_RETURN_TYPE
580 libc_hidden_def (__getcwd)
581 weak_alias (__getcwd, getcwd)
582 #endif