("pathmax.h"): Do not include; no longer needed.

(<stdlib.h>, <unistd.h>): Include if available.
("xalloc.h"): Include.
(xmalloc, xstrdup, free): Remove decls; no longer needed.
(xgetcwd): Don't assume sizes fit in 'unsigned'.
Check for overflow when path size gets too large.
Simplify failure code.
This commit is contained in:
Paul Eggert
2001-08-29 06:36:20 +00:00
parent 6790685098
commit 07c3d5fe32

View File

@@ -28,7 +28,13 @@ extern int errno;
#endif #endif
#include <sys/types.h> #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 #if HAVE_GETCWD
char *getcwd (); char *getcwd ();
@@ -37,9 +43,7 @@ char *getwd ();
# define getcwd(Buf, Max) getwd (Buf) # define getcwd(Buf, Max) getwd (Buf)
#endif #endif
extern void *xmalloc (); #include "xalloc.h"
extern char *xstrdup ();
extern void free ();
/* Return the current directory, newly allocated, arbitrarily long. /* Return the current directory, newly allocated, arbitrarily long.
Return NULL and set errno on error. */ Return NULL and set errno on error. */
@@ -51,7 +55,7 @@ xgetcwd ()
return getcwd (NULL, 0); return getcwd (NULL, 0);
#else #else
char *ret; char *ret;
unsigned path_max; size_t path_max;
char buf[1024]; char buf[1024];
errno = 0; errno = 0;
@@ -61,29 +65,28 @@ xgetcwd ()
if (errno != ERANGE) if (errno != ERANGE)
return NULL; return NULL;
path_max = 1300; path_max = 1 << 10;
path_max += 2; /* The getcwd docs say to do this. */
for (;;) for (;;)
{ {
char *cwd = (char *) xmalloc (path_max); char *cwd = (char *) xmalloc (path_max);
int save_errno;
errno = 0; errno = 0;
ret = getcwd (cwd, path_max); ret = getcwd (cwd, path_max);
if (ret != NULL) if (ret != NULL)
return ret; return ret;
if (errno != ERANGE) save_errno = errno;
free (cwd);
if (save_errno != ERANGE)
{ {
int save_errno = errno;
free (cwd);
errno = save_errno; errno = save_errno;
return NULL; return NULL;
} }
free (cwd); path_max *= 2;
if (path_max == 0)
path_max += path_max / 16; xalloc_die ();
path_max += 32;
} }
#endif #endif
} }