Undo June 11th change
[official-gcc.git] / gcc / getpwd.c
blob6830c164acf12aa50841ade400092dc7eca0a125
1 /* getpwd.c - get the working directory */
3 #include "config.h"
4 #include "system.h"
5 #include <sys/stat.h>
7 /* Virtually every UN*X system now in common use (except for pre-4.3-tahoe
8 BSD systems) now provides getcwd as called for by POSIX. Allow for
9 the few exceptions to the general rule here. */
11 #if !(defined (POSIX) || defined (USG) || defined (VMS)) || defined (HAVE_GETWD)
12 extern char *getwd ();
13 #define getcwd(buf,len) getwd(buf)
14 #ifdef MAXPATHLEN
15 #define GUESSPATHLEN (MAXPATHLEN + 1)
16 #else
17 #define GUESSPATHLEN 100
18 #endif
19 #else /* (defined (USG) || defined (VMS)) */
20 extern char *getcwd ();
21 /* We actually use this as a starting point, not a limit. */
22 #define GUESSPATHLEN 100
23 #endif /* (defined (USG) || defined (VMS)) */
25 char *xmalloc ();
27 #if !(defined (VMS) || (defined(_WIN32) && !defined(__CYGWIN32__)))
29 /* Get the working directory. Use the PWD environment variable if it's
30 set correctly, since this is faster and gives more uniform answers
31 to the user. Yield the working directory if successful; otherwise,
32 yield 0 and set errno. */
34 char *
35 getpwd ()
37 static char *pwd;
38 static int failure_errno;
40 char *p = pwd;
41 size_t s;
42 struct stat dotstat, pwdstat;
44 if (!p && !(errno = failure_errno))
46 if (! ((p = getenv ("PWD")) != 0
47 && *p == '/'
48 && stat (p, &pwdstat) == 0
49 && stat (".", &dotstat) == 0
50 && dotstat.st_ino == pwdstat.st_ino
51 && dotstat.st_dev == pwdstat.st_dev))
53 /* The shortcut didn't work. Try the slow, ``sure'' way. */
54 for (s = GUESSPATHLEN; ! getcwd (p = xmalloc (s), s); s *= 2)
56 int e = errno;
57 free (p);
58 #ifdef ERANGE
59 if (e != ERANGE)
60 #endif
62 errno = failure_errno = e;
63 p = 0;
64 break;
68 /* Cache the result. This assumes that the program does
69 not invoke chdir between calls to getpwd. */
70 pwd = p;
72 return p;
75 #else /* VMS || _WIN32 && !__CYGWIN32__ */
77 #ifndef MAXPATHLEN
78 #define MAXPATHLEN 255
79 #endif
81 char *
82 getpwd ()
84 static char *pwd = 0;
86 if (!pwd)
87 pwd = getcwd (xmalloc (MAXPATHLEN + 1), MAXPATHLEN + 1
88 #ifdef VMS
89 , 0
90 #endif
92 return pwd;
95 #endif /* VMS || _WIN32 && !__CYGWIN32__ */