aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--libbb/xgetcwd.c31
1 files changed, 14 insertions, 17 deletions
diff --git a/libbb/xgetcwd.c b/libbb/xgetcwd.c
index ec1d8f7a4..c194e2303 100644
--- a/libbb/xgetcwd.c
+++ b/libbb/xgetcwd.c
@@ -9,9 +9,6 @@
9 9
10#include "libbb.h" 10#include "libbb.h"
11 11
12/* Amount to increase buffer size by in each try. */
13#define PATH_INCR 32
14
15/* Return the current directory, newly allocated, arbitrarily long. 12/* Return the current directory, newly allocated, arbitrarily long.
16 Return NULL and set errno on error. 13 Return NULL and set errno on error.
17 If argument is not NULL (previous usage allocate memory), call free() 14 If argument is not NULL (previous usage allocate memory), call free()
@@ -20,25 +17,25 @@
20char * 17char *
21xrealloc_getcwd_or_warn(char *cwd) 18xrealloc_getcwd_or_warn(char *cwd)
22{ 19{
20#define PATH_INCR 64
21
23 char *ret; 22 char *ret;
24 unsigned path_max; 23 unsigned path_max;
25 24
26 path_max = (unsigned) PATH_MAX; 25 path_max = 128; /* 128 + 64 should be enough for 99% of cases */
27 path_max += 2; /* The getcwd docs say to do this. */
28
29 if (cwd == NULL)
30 cwd = xmalloc(path_max);
31 26
32 while ((ret = getcwd(cwd, path_max)) == NULL && errno == ERANGE) { 27 while (1) {
33 path_max += PATH_INCR; 28 path_max += PATH_INCR;
34 cwd = xrealloc(cwd, path_max); 29 cwd = xrealloc(cwd, path_max);
30 ret = getcwd(cwd, path_max);
31 if (ret == NULL) {
32 if (errno == ERANGE)
33 continue;
34 free(cwd);
35 bb_perror_msg("getcwd");
36 return NULL;
37 }
38 cwd = xrealloc(cwd, strlen(cwd) + 1);
39 return cwd;
35 } 40 }
36
37 if (ret == NULL) {
38 free(cwd);
39 bb_perror_msg("getcwd");
40 return NULL;
41 }
42
43 return cwd;
44} 41}