blob: eefe1d6600f864aba8de06786bfb7388e9f84f04 [file] [log] [blame]
"Robert P. J. Day"63fc1a92006-07-02 19:47:05 +00001/* vi: set sw=4 ts=4: */
Eric Andersene5dfced2001-04-09 22:48:12 +00002/*
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 McGrath393183d2003-05-26 14:07:50 +00007 * Special function for busybox written by Vladimir Oleynik <dzo@simtreas.ru>
Eric Andersene5dfced2001-04-09 22:48:12 +00008*/
9
Eric Andersene5dfced2001-04-09 22:48:12 +000010#include "libbb.h"
11
Eric Andersene5dfced2001-04-09 22:48:12 +000012/* Return the current directory, newly allocated, arbitrarily long.
13 Return NULL and set errno on error.
14 If argument is not NULL (previous usage allocate memory), call free()
15*/
16
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +000017char* FAST_FUNC
Denis Vlasenko6ca04442007-02-11 16:19:28 +000018xrealloc_getcwd_or_warn(char *cwd)
Eric Andersene5dfced2001-04-09 22:48:12 +000019{
Denis Vlasenko2450e4b2007-09-29 19:19:55 +000020#define PATH_INCR 64
21
Denis Vlasenkoc2905632006-09-23 16:01:09 +000022 char *ret;
23 unsigned path_max;
Eric Andersene5dfced2001-04-09 22:48:12 +000024
Denis Vlasenko2450e4b2007-09-29 19:19:55 +000025 path_max = 128; /* 128 + 64 should be enough for 99% of cases */
Eric Andersene5dfced2001-04-09 22:48:12 +000026
Denis Vlasenko2450e4b2007-09-29 19:19:55 +000027 while (1) {
Denis Vlasenkoc2905632006-09-23 16:01:09 +000028 path_max += PATH_INCR;
29 cwd = xrealloc(cwd, path_max);
Denis Vlasenko2450e4b2007-09-29 19:19:55 +000030 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;
Denis Vlasenkoc2905632006-09-23 16:01:09 +000040 }
Eric Andersene5dfced2001-04-09 22:48:12 +000041}