OSDN Git Service

Initial revision
[pf3gnuchains/pf3gnuchains4x.git] / newlib / libc / unix / getcwd.c
1 /*
2  * Copyright (c) 1989, 1991 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #if defined(LIBC_SCCS) && !defined(lint)
35 static char sccsid[] = "@(#)getcwd.c    5.11 (Berkeley) 2/24/91";
36 #endif /* LIBC_SCCS and not lint */
37
38 #include <sys/stat.h>
39 #include <errno.h>
40 #include <dirent.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <reent.h>
46 #include <_syslist.h>
47
48 #define bcopy(a,b,c)    memmove (b,a,c)
49
50 #define ISDOT(dp) \
51         (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
52             dp->d_name[1] == '.' && dp->d_name[2] == '\0'))
53
54 #ifndef _REENT_ONLY
55
56 char *
57 getcwd (pt, size)
58      char *pt;
59      size_t size;
60 {
61   register struct dirent *dp;
62   register DIR *dir;
63   register dev_t dev;
64   register ino_t ino;
65   register int first;
66   register char *bpt, *bup;
67   struct stat s;
68   dev_t root_dev;
69   ino_t root_ino;
70   size_t ptsize, upsize;
71   int save_errno;
72   char *ept, *eup, *up;
73
74   /*
75    * If no buffer specified by the user, allocate one as necessary.
76    * If a buffer is specified, the size has to be non-zero.  The path
77    * is built from the end of the buffer backwards.
78    */
79
80   if (pt)
81     {
82       ptsize = 0;
83       if (!size)
84         {
85           errno = EINVAL;
86           return (char *) NULL;
87         }
88       ept = pt + size;
89     }
90   else
91     {
92       if (!(pt = (char *) malloc (ptsize = 1024 - 4)))
93         {
94           return (char *) NULL;
95         }
96       ept = pt + ptsize;
97     }
98   bpt = ept - 1;
99   *bpt = '\0';
100
101   /*
102    * Allocate bytes (1024 - malloc space) for the string of "../"'s.
103    * Should always be enough (it's 340 levels).  If it's not, allocate
104    * as necessary.  Special * case the first stat, it's ".", not "..".
105    */
106
107   if (!(up = (char *) malloc (upsize = 1024 - 4)))
108     {
109       goto err;
110     }
111   eup = up + MAXPATHLEN;
112   bup = up;
113   up[0] = '.';
114   up[1] = '\0';
115
116   /* Save root values, so know when to stop. */
117   if (stat ("/", &s))
118     goto err;
119   root_dev = s.st_dev;
120   root_ino = s.st_ino;
121
122   errno = 0;                    /* XXX readdir has no error return. */
123
124   for (first = 1;; first = 0)
125     {
126       /* Stat the current level. */
127       if (_stat (up, &s))
128         goto err;
129
130       /* Save current node values. */
131       ino = s.st_ino;
132       dev = s.st_dev;
133
134       /* Check for reaching root. */
135       if (root_dev == dev && root_ino == ino)
136         {
137           *--bpt = '/';
138           /*
139            * It's unclear that it's a requirement to copy the
140            * path to the beginning of the buffer, but it's always
141            * been that way and stuff would probably break.
142            */
143           (void) bcopy (bpt, pt, ept - bpt);
144           free (up);
145           return pt;
146         }
147
148       /*
149        * Build pointer to the parent directory, allocating memory
150        * as necessary.  Max length is 3 for "../", the largest
151        * possible component name, plus a trailing NULL.
152        */
153
154       if (bup + 3 + MAXNAMLEN + 1 >= eup)
155         {
156           if (!(up = (char *) realloc (up, upsize *= 2)))
157             {
158               goto err;
159             }
160           bup = up;
161           eup = up + upsize;
162         }
163       *bup++ = '.';
164       *bup++ = '.';
165       *bup = '\0';
166
167       /* Open and stat parent directory. */
168       if (!(dir = _opendir (up)) || _fstat (__dirfd (dir), &s))
169         goto err;
170
171       /* Add trailing slash for next directory. */
172       *bup++ = '/';
173
174       /*
175        * If it's a mount point, have to stat each element because
176        * the inode number in the directory is for the entry in the
177        * parent directory, not the inode number of the mounted file.
178        */
179
180       save_errno = 0;
181       if (s.st_dev == dev)
182         {
183           for (;;)
184             {
185               if (!(dp = _readdir (dir)))
186                 goto notfound;
187               if (dp->d_ino == ino)
188                 break;
189             }
190         }
191       else
192         for (;;)
193           {
194             if (!(dp = _readdir (dir)))
195               goto notfound;
196             if (ISDOT (dp))
197               continue;
198             bcopy (dp->d_name, bup, strlen (dp->d_name) + 1);
199
200             /* Save the first error for later. */
201             if (stat (up, &s))
202               {
203                 if (!save_errno)
204                   save_errno = errno;
205                 errno = 0;
206                 continue;
207               }
208             if (s.st_dev == dev && s.st_ino == ino)
209               break;
210           }
211
212       /*
213        * Check for length of the current name, preceding slash,
214        * leading slash.
215        */
216
217       if (bpt - pt <= strlen (dp->d_name) + (first ? 1 : 2))
218         {
219           size_t len, off;
220
221           if (!ptsize)
222             {
223               errno = ERANGE;
224               goto err;
225             }
226           off = bpt - pt;
227           len = ept - bpt;
228           if (!(pt = (char *) realloc (pt, ptsize *= 2)))
229             {
230               goto err;
231             }
232           bpt = pt + off;
233           ept = pt + ptsize;
234           (void) bcopy (bpt, ept - len, len);
235           bpt = ept - len;
236         }
237       if (!first)
238         *--bpt = '/';
239       bpt -= strlen (dp->d_name);
240       bcopy (dp->d_name, bpt, strlen (dp->d_name));
241       (void) _closedir (dir);
242
243       /* Truncate any file name. */
244       *bup = '\0';
245     }
246
247 notfound:
248   /*
249    * If readdir set errno, use it, not any saved error; otherwise,
250    * didn't find the current directory in its parent directory, set
251    * errno to ENOENT.
252    */
253
254   if (!errno)
255     errno = save_errno ? save_errno : ENOENT;
256   /* FALLTHROUGH */
257
258 err:
259   if (ptsize)
260     free (pt);
261   free (up);
262   return (char *) NULL;
263 }
264
265 #endif /* _REENT_ONLY */