Merge from vendor branch GCC:
[dragonfly.git] / lib / libc / gen / getcwd.c
1 /*
2  * Copyright (c) 1989, 1991, 1993, 1995
3  *      The Regents of the University of California.  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  * $FreeBSD: src/lib/libc/gen/getcwd.c,v 1.18 1999/09/28 13:24:13 marcel Exp $
34  * $DragonFly: src/lib/libc/gen/getcwd.c,v 1.4 2005/01/31 22:29:15 dillon Exp $
35  *
36  * @(#)getcwd.c 8.5 (Berkeley) 2/7/95
37  */
38
39 #include "namespace.h"
40 #include <sys/param.h>
41 #include <sys/stat.h>
42
43 #include <dirent.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include "un-namespace.h"
52
53 #define ISDOT(dp) \
54         (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
55             (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
56
57 static int have__getcwd = 1;    /* 0 = no, 1 = perhaps, 2 = yes */
58
59 char *
60 getcwd(pt, size)
61         char *pt;
62         size_t size;
63 {
64         struct dirent *dp;
65         DIR *dir = NULL;
66         dev_t dev;
67         ino_t ino;
68         int first;
69         char *bpt, *bup;
70         struct stat s;
71         dev_t root_dev;
72         ino_t root_ino;
73         size_t ptsize, upsize;
74         int save_errno;
75         char *ept, *eup, *up, c;
76
77         /*
78          * If no buffer specified by the user, allocate one as necessary.
79          * If a buffer is specified, the size has to be non-zero.  The path
80          * is built from the end of the buffer backwards.
81          */
82         if (pt) {
83                 ptsize = 0;
84                 if (!size) {
85                         errno = EINVAL;
86                         return (NULL);
87                 }
88                 if (size == 1) {
89                         errno = ERANGE;
90                         return (NULL);
91                 }
92                 ept = pt + size;
93         } else {
94                 if ((pt = malloc(ptsize = 1024 - 4)) == NULL)
95                         return (NULL);
96                 ept = pt + ptsize;
97         }
98 #if     defined(__NETBSD_SYSCALLS)
99         have__getcwd = 0;
100 #else
101         if (have__getcwd) {
102                 struct sigaction sa, osa;
103                 int sigsys_installed = 0;
104                 int ret;
105
106                 if (have__getcwd == 1) {        /* unsure? */
107                         sigemptyset(&sa.sa_mask);
108                         sa.sa_flags = 0;
109                         sa.sa_handler = SIG_IGN;
110                         if (sigaction(SIGSYS, &sa, &osa) >= 0)
111                                 sigsys_installed = 1;
112                 }
113                 ret = __getcwd(pt, ept - pt);
114                 if (sigsys_installed == 1) {
115                         int oerrno = errno;
116                         sigaction(SIGSYS, &osa, NULL);
117                         errno = oerrno;
118                 }
119                 /* XXX a bogus syscall seems to return EINVAL(!) */
120                 if (ret < 0 && (errno == ENOSYS || errno == EINVAL))
121                         have__getcwd = 0;
122                 else if (have__getcwd == 1)
123                         have__getcwd = 2;       /* yep, remember we have it */
124                 if (ret == 0) {
125                         if (*pt != '/') {
126                                 bpt = pt;
127                                 ept = pt + strlen(pt) - 1;
128                                 while (bpt < ept) {
129                                         c = *bpt;
130                                         *bpt++ = *ept;
131                                         *ept-- = c;
132                                 }
133                         }
134                         return (pt);
135                 }
136         }
137 #endif
138         bpt = ept - 1;
139         *bpt = '\0';
140
141         /*
142          * Allocate bytes (1024 - malloc space) for the string of "../"'s.
143          * Should always be enough (it's 340 levels).  If it's not, allocate
144          * as necessary.  Special case the first stat, it's ".", not "..".
145          */
146         if ((up = malloc(upsize = 1024 - 4)) == NULL)
147                 goto err;
148         eup = up + MAXPATHLEN;
149         bup = up;
150         up[0] = '.';
151         up[1] = '\0';
152
153         /* Save root values, so know when to stop. */
154         if (stat("/", &s))
155                 goto err;
156         root_dev = s.st_dev;
157         root_ino = s.st_ino;
158
159         errno = 0;                      /* XXX readdir has no error return. */
160
161         for (first = 1;; first = 0) {
162                 /* Stat the current level. */
163                 if (lstat(up, &s))
164                         goto err;
165
166                 /* Save current node values. */
167                 ino = s.st_ino;
168                 dev = s.st_dev;
169
170                 /* Check for reaching root. */
171                 if (root_dev == dev && root_ino == ino) {
172                         *--bpt = '/';
173                         /*
174                          * It's unclear that it's a requirement to copy the
175                          * path to the beginning of the buffer, but it's always
176                          * been that way and stuff would probably break.
177                          */
178                         bcopy(bpt, pt, ept - bpt);
179                         free(up);
180                         return (pt);
181                 }
182
183                 /*
184                  * Build pointer to the parent directory, allocating memory
185                  * as necessary.  Max length is 3 for "../", the largest
186                  * possible component name, plus a trailing NULL.
187                  */
188                 if (bup + 3  + MAXNAMLEN + 1 >= eup) {
189                         if ((up = reallocf(up, upsize *= 2)) == NULL)
190                                 goto err;
191                         bup = up;
192                         eup = up + upsize;
193                 }
194                 *bup++ = '.';
195                 *bup++ = '.';
196                 *bup = '\0';
197
198                 /* Open and stat parent directory. */
199                 if (!(dir = opendir(up)) || _fstat(dirfd(dir), &s))
200                         goto err;
201
202                 /* Add trailing slash for next directory. */
203                 *bup++ = '/';
204                 *bup = '\0';
205
206                 /*
207                  * If it's a mount point, have to stat each element because
208                  * the inode number in the directory is for the entry in the
209                  * parent directory, not the inode number of the mounted file.
210                  */
211                 save_errno = 0;
212                 if (s.st_dev == dev) {
213                         for (;;) {
214                                 if (!(dp = readdir(dir)))
215                                         goto notfound;
216                                 if (dp->d_fileno == ino)
217                                         break;
218                         }
219                 } else
220                         for (;;) {
221                                 if (!(dp = readdir(dir)))
222                                         goto notfound;
223                                 if (ISDOT(dp))
224                                         continue;
225                                 bcopy(dp->d_name, bup, dp->d_namlen + 1);
226
227                                 /* Save the first error for later. */
228                                 if (lstat(up, &s)) {
229                                         if (!save_errno)
230                                                 save_errno = errno;
231                                         errno = 0;
232                                         continue;
233                                 }
234                                 if (s.st_dev == dev && s.st_ino == ino)
235                                         break;
236                         }
237
238                 /*
239                  * Check for length of the current name, preceding slash,
240                  * leading slash.
241                  */
242                 if (bpt - pt < dp->d_namlen + (first ? 1 : 2)) {
243                         size_t len, off;
244
245                         if (!ptsize) {
246                                 errno = ERANGE;
247                                 goto err;
248                         }
249                         off = bpt - pt;
250                         len = ept - bpt;
251                         if ((pt = realloc(pt, ptsize *= 2)) == NULL)
252                                 goto err;
253                         bpt = pt + off;
254                         ept = pt + ptsize;
255                         bcopy(bpt, ept - len, len);
256                         bpt = ept - len;
257                 }
258                 if (!first)
259                         *--bpt = '/';
260                 bpt -= dp->d_namlen;
261                 bcopy(dp->d_name, bpt, dp->d_namlen);
262                 (void) closedir(dir);
263                 dir = NULL;
264
265                 /* Truncate any file name. */
266                 *bup = '\0';
267         }
268
269 notfound:
270         /*
271          * If readdir set errno, use it, not any saved error; otherwise,
272          * didn't find the current directory in its parent directory, set
273          * errno to ENOENT.
274          */
275         if (!errno)
276                 errno = save_errno ? save_errno : ENOENT;
277         /* FALLTHROUGH */
278 err:
279         save_errno = errno;
280
281         if (ptsize)
282                 free(pt);
283         if (dir)
284                 (void) closedir(dir);
285         free(up);
286
287         errno = save_errno;
288         return (NULL);
289 }