blob: f4e76898234f4edd1afe558eef9042eb69153df2 [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>
Denis Vlasenkodb12d1d2008-12-07 00:52:58 +00008 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +02009 * Licensed under GPLv2, see file LICENSE in this source tree.
Denis Vlasenkodb12d1d2008-12-07 00:52:58 +000010 */
Eric Andersene5dfced2001-04-09 22:48:12 +000011#include "libbb.h"
12
Eric Andersene5dfced2001-04-09 22:48:12 +000013/* 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 Vlasenkodefc1ea2008-06-27 02:52:20 +000018char* FAST_FUNC
Denis Vlasenko6ca04442007-02-11 16:19:28 +000019xrealloc_getcwd_or_warn(char *cwd)
Eric Andersene5dfced2001-04-09 22:48:12 +000020{
Denis Vlasenko2450e4b2007-09-29 19:19:55 +000021#define PATH_INCR 64
22
Denis Vlasenkoc2905632006-09-23 16:01:09 +000023 char *ret;
24 unsigned path_max;
Eric Andersene5dfced2001-04-09 22:48:12 +000025
Denys Vlasenkoe4dcba12010-10-28 18:57:19 +020026 path_max = 128; /* 128 + 64 should be enough for 99% of cases */
Eric Andersene5dfced2001-04-09 22:48:12 +000027
Denis Vlasenko2450e4b2007-09-29 19:19:55 +000028 while (1) {
Denis Vlasenkoc2905632006-09-23 16:01:09 +000029 path_max += PATH_INCR;
30 cwd = xrealloc(cwd, path_max);
Denis Vlasenko2450e4b2007-09-29 19:19:55 +000031 ret = getcwd(cwd, path_max);
32 if (ret == NULL) {
33 if (errno == ERANGE)
34 continue;
35 free(cwd);
James Byrne69374872019-07-02 11:35:03 +020036 bb_simple_perror_msg("getcwd");
Denis Vlasenko2450e4b2007-09-29 19:19:55 +000037 return NULL;
38 }
39 cwd = xrealloc(cwd, strlen(cwd) + 1);
40 return cwd;
Denis Vlasenkoc2905632006-09-23 16:01:09 +000041 }
Eric Andersene5dfced2001-04-09 22:48:12 +000042}