"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> |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 8 | */ |
| 9 | |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 10 | #include "libbb.h" |
| 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. |
| 16 | Return NULL and set errno on error. |
| 17 | If argument is not NULL (previous usage allocate memory), call free() |
| 18 | */ |
| 19 | |
| 20 | char * |
Denis Vlasenko | 6ca0444 | 2007-02-11 16:19:28 +0000 | [diff] [blame^] | 21 | xrealloc_getcwd_or_warn(char *cwd) |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 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 | |
Denis Vlasenko | c290563 | 2006-09-23 16:01:09 +0000 | [diff] [blame] | 26 | path_max = (unsigned) PATH_MAX; |
| 27 | path_max += 2; /* The getcwd docs say to do this. */ |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 28 | |
Denis Vlasenko | 6ca0444 | 2007-02-11 16:19:28 +0000 | [diff] [blame^] | 29 | if (cwd == NULL) |
Denis Vlasenko | c290563 | 2006-09-23 16:01:09 +0000 | [diff] [blame] | 30 | cwd = xmalloc(path_max); |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 31 | |
Denis Vlasenko | c290563 | 2006-09-23 16:01:09 +0000 | [diff] [blame] | 32 | while ((ret = getcwd(cwd, path_max)) == NULL && errno == ERANGE) { |
| 33 | path_max += PATH_INCR; |
| 34 | cwd = xrealloc(cwd, path_max); |
| 35 | } |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 36 | |
Denis Vlasenko | c290563 | 2006-09-23 16:01:09 +0000 | [diff] [blame] | 37 | if (ret == NULL) { |
| 38 | free(cwd); |
| 39 | bb_perror_msg("getcwd"); |
| 40 | return NULL; |
| 41 | } |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 42 | |
Denis Vlasenko | c290563 | 2006-09-23 16:01:09 +0000 | [diff] [blame] | 43 | return cwd; |
Eric Andersen | e5dfced | 2001-04-09 22:48:12 +0000 | [diff] [blame] | 44 | } |