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