Start 1.33.0 development cycle
[oweals/busybox.git] / libbb / xgetcwd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * xgetcwd.c -- return current directory with unlimited length
4  * Copyright (C) 1992, 1996 Free Software Foundation, Inc.
5  * Written by David MacKenzie <djm@gnu.ai.mit.edu>.
6  *
7  * Special function for busybox written by Vladimir Oleynik <dzo@simtreas.ru>
8  *
9  * Licensed under GPLv2, see file LICENSE in this source tree.
10  */
11 #include "libbb.h"
12
13 /* Return the current directory, newly allocated, arbitrarily long.
14    Return NULL and set errno on error.
15    If argument is not NULL (previous usage allocate memory), call free()
16 */
17
18 char* FAST_FUNC
19 xrealloc_getcwd_or_warn(char *cwd)
20 {
21 #define PATH_INCR 64
22
23         char *ret;
24         unsigned path_max;
25
26         path_max = 128; /* 128 + 64 should be enough for 99% of cases */
27
28         while (1) {
29                 path_max += PATH_INCR;
30                 cwd = xrealloc(cwd, path_max);
31                 ret = getcwd(cwd, path_max);
32                 if (ret == NULL) {
33                         if (errno == ERANGE)
34                                 continue;
35                         free(cwd);
36                         bb_simple_perror_msg("getcwd");
37                         return NULL;
38                 }
39                 cwd = xrealloc(cwd, strlen(cwd) + 1);
40                 return cwd;
41         }
42 }