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