getcwd.c 14 KB

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