OSDN Git Service

* alpha.md (addsi3, subsi3): No new temporaries once cse is
[pf3gnuchains/gcc-fork.git] / gcc / getpwd.c
1 /* getpwd.c - get the working directory */
2
3 #include "config.h"
4 #include "system.h"
5 #include <sys/stat.h>
6
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.  */
10
11 #if !(defined (POSIX) || defined (USG) || defined (VMS)) || defined (HAVE_GETWD)
12 #define getcwd(buf,len) getwd(buf)
13 #ifdef MAXPATHLEN
14 #define GUESSPATHLEN (MAXPATHLEN + 1)
15 #else
16 #define GUESSPATHLEN 100
17 #endif
18 #else /* (defined (USG) || defined (VMS)) */
19 /* We actually use this as a starting point, not a limit.  */
20 #define GUESSPATHLEN 100
21 #endif /* (defined (USG) || defined (VMS)) */
22
23 char *xmalloc ();
24
25 #if !(defined (VMS) || (defined(_WIN32) && !defined(__CYGWIN32__)))
26
27 /* Get the working directory.  Use the PWD environment variable if it's
28    set correctly, since this is faster and gives more uniform answers
29    to the user.  Yield the working directory if successful; otherwise,
30    yield 0 and set errno.  */
31
32 char *
33 getpwd ()
34 {
35   static char *pwd;
36   static int failure_errno;
37
38   char *p = pwd;
39   size_t s;
40   struct stat dotstat, pwdstat;
41
42   if (!p && !(errno = failure_errno))
43     {
44       if (! ((p = getenv ("PWD")) != 0
45              && *p == '/'
46              && stat (p, &pwdstat) == 0
47              && stat (".", &dotstat) == 0
48              && dotstat.st_ino == pwdstat.st_ino
49              && dotstat.st_dev == pwdstat.st_dev))
50
51         /* The shortcut didn't work.  Try the slow, ``sure'' way.  */
52         for (s = GUESSPATHLEN;  ! getcwd (p = xmalloc (s), s);  s *= 2)
53           {
54             int e = errno;
55             free (p);
56 #ifdef ERANGE
57             if (e != ERANGE)
58 #endif
59               {
60                 errno = failure_errno = e;
61                 p = 0;
62                 break;
63               }
64           }
65
66       /* Cache the result.  This assumes that the program does
67          not invoke chdir between calls to getpwd.  */
68       pwd = p;
69     }
70   return p;
71 }
72
73 #else   /* VMS || _WIN32 && !__CYGWIN32__ */
74
75 #ifndef MAXPATHLEN
76 #define MAXPATHLEN 255
77 #endif
78
79 char *
80 getpwd ()
81 {
82   static char *pwd = 0;
83
84   if (!pwd)
85     pwd = getcwd (xmalloc (MAXPATHLEN + 1), MAXPATHLEN + 1
86 #ifdef VMS
87                   , 0
88 #endif
89                   );
90   return pwd;
91 }
92
93 #endif  /* VMS || _WIN32 && !__CYGWIN32__ */