"Robert P. J. Day" | 63fc1a9 | 2006-07-02 19:47:05 +0000 | [diff] [blame] | 1 | /* vi: set sw=4 ts=4: */ |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 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 | * |
Glenn L McGrath | 393183d | 2003-05-26 14:07:50 +0000 | [diff] [blame] | 7 | * Special function for busybox written by Vladimir Oleynik <dzo@simtreas.ru> |
Denis Vlasenko | db12d1d | 2008-12-07 00:52:58 +0000 | [diff] [blame] | 8 | * |
Denys Vlasenko | 0ef64bd | 2010-08-16 20:14:46 +0200 | [diff] [blame] | 9 | * Licensed under GPLv2, see file LICENSE in this source tree. |
Denis Vlasenko | db12d1d | 2008-12-07 00:52:58 +0000 | [diff] [blame] | 10 | */ |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 11 | #include "libbb.h" |
| 12 | |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 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 | |
Denis Vlasenko | defc1ea | 2008-06-27 02:52:20 +0000 | [diff] [blame] | 18 | char* FAST_FUNC |
Denis Vlasenko | 6ca0444 | 2007-02-11 16:19:28 +0000 | [diff] [blame] | 19 | xrealloc_getcwd_or_warn(char *cwd) |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 20 | { |
Denis Vlasenko | 2450e4b | 2007-09-29 19:19:55 +0000 | [diff] [blame] | 21 | #define PATH_INCR 64 |
| 22 | |
Denis Vlasenko | c290563 | 2006-09-23 16:01:09 +0000 | [diff] [blame] | 23 | char *ret; |
| 24 | unsigned path_max; |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 25 | |
Denys Vlasenko | e4dcba1 | 2010-10-28 18:57:19 +0200 | [diff] [blame] | 26 | path_max = 128; /* 128 + 64 should be enough for 99% of cases */ |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 27 | |
Denis Vlasenko | 2450e4b | 2007-09-29 19:19:55 +0000 | [diff] [blame] | 28 | while (1) { |
Denis Vlasenko | c290563 | 2006-09-23 16:01:09 +0000 | [diff] [blame] | 29 | path_max += PATH_INCR; |
| 30 | cwd = xrealloc(cwd, path_max); |
Denis Vlasenko | 2450e4b | 2007-09-29 19:19:55 +0000 | [diff] [blame] | 31 | ret = getcwd(cwd, path_max); |
| 32 | if (ret == NULL) { |
| 33 | if (errno == ERANGE) |
| 34 | continue; |
| 35 | free(cwd); |
James Byrne | 6937487 | 2019-07-02 11:35:03 +0200 | [diff] [blame] | 36 | bb_simple_perror_msg("getcwd"); |
Denis Vlasenko | 2450e4b | 2007-09-29 19:19:55 +0000 | [diff] [blame] | 37 | return NULL; |
| 38 | } |
| 39 | cwd = xrealloc(cwd, strlen(cwd) + 1); |
| 40 | return cwd; |
Denis Vlasenko | c290563 | 2006-09-23 16:01:09 +0000 | [diff] [blame] | 41 | } |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 42 | } |