#endif
#include <sys/types.h>
-#include "pathmax.h"
+
+#if HAVE_STDLIB_H
+# include <stdlib.h>
+#endif
+#if HAVE_UNISTD_H
+# include <unistd.h>
+#endif
#if HAVE_GETCWD
char *getcwd ();
# define getcwd(Buf, Max) getwd (Buf)
#endif
-extern void *xmalloc ();
-extern char *xstrdup ();
-extern void free ();
+#include "xalloc.h"
/* Return the current directory, newly allocated, arbitrarily long.
Return NULL and set errno on error. */
#if defined __GLIBC__ && __GLIBC__ >= 2
return getcwd (NULL, 0);
#else
- char *ret;
- unsigned path_max;
- char buf[1024];
+ size_t buf_size = 128; /* must be a power of 2 */
+ char *buf = NULL;
- errno = 0;
- ret = getcwd (buf, sizeof (buf));
- if (ret != NULL)
- return xstrdup (buf);
- if (errno != ERANGE)
- return NULL;
-
- path_max = 1300;
- path_max += 2; /* The getcwd docs say to do this. */
-
- for (;;)
+ while (1)
{
- char *cwd = (char *) xmalloc (path_max);
+ char *cwd;
+ buf = (char *) xrealloc (buf, buf_size);
- errno = 0;
- ret = getcwd (cwd, path_max);
- if (ret != NULL)
- return ret;
+ cwd = getcwd (buf, buf_size);
+ if (cwd != NULL)
+ return cwd;
if (errno != ERANGE)
{
- int save_errno = errno;
- free (cwd);
- errno = save_errno;
+ free (buf);
return NULL;
}
- free (cwd);
-
- path_max += path_max / 16;
- path_max += 32;
+ buf_size *= 2;
+ if (buf_size == 0)
+ xalloc_die ();
}
#endif
}