getcwd.c revision 109040
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
34#if defined(LIBC_SCCS) && !defined(lint)
35static char sccsid[] = "@(#)getcwd.c	8.5 (Berkeley) 2/7/95";
36#endif /* LIBC_SCCS and not lint */
37#include <sys/cdefs.h>
38__FBSDID("$FreeBSD: head/lib/libc/gen/getcwd.c 109040 2003-01-10 02:58:25Z tjr $");
39
40#include "namespace.h"
41#include <sys/param.h>
42#include <sys/stat.h>
43
44#include <dirent.h>
45#include <errno.h>
46#include <fcntl.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
57extern int __getcwd(char *, size_t);
58
59char *
60getcwd(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	if (__getcwd(pt, ept - pt) == 0) {
100		if (*pt != '/') {
101			bpt = pt;
102			ept = pt + strlen(pt) - 1;
103			while (bpt < ept) {
104				c = *bpt;
105				*bpt++ = *ept;
106				*ept-- = c;
107			}
108		}
109		return (pt);
110	}
111#endif
112	bpt = ept - 1;
113	*bpt = '\0';
114
115	/*
116	 * Allocate bytes (1024 - malloc space) for the string of "../"'s.
117	 * Should always be enough (it's 340 levels).  If it's not, allocate
118	 * as necessary.  Special case the first stat, it's ".", not "..".
119	 */
120	if ((up = malloc(upsize = 1024 - 4)) == NULL)
121		goto err;
122	eup = up + MAXPATHLEN;
123	bup = up;
124	up[0] = '.';
125	up[1] = '\0';
126
127	/* Save root values, so know when to stop. */
128	if (stat("/", &s))
129		goto err;
130	root_dev = s.st_dev;
131	root_ino = s.st_ino;
132
133	errno = 0;			/* XXX readdir has no error return. */
134
135	for (first = 1;; first = 0) {
136		/* Stat the current level. */
137		if (lstat(up, &s))
138			goto err;
139
140		/* Save current node values. */
141		ino = s.st_ino;
142		dev = s.st_dev;
143
144		/* Check for reaching root. */
145		if (root_dev == dev && root_ino == ino) {
146			*--bpt = '/';
147			/*
148			 * It's unclear that it's a requirement to copy the
149			 * path to the beginning of the buffer, but it's always
150			 * been that way and stuff would probably break.
151			 */
152			bcopy(bpt, pt, ept - bpt);
153			free(up);
154			return (pt);
155		}
156
157		/*
158		 * Build pointer to the parent directory, allocating memory
159		 * as necessary.  Max length is 3 for "../", the largest
160		 * possible component name, plus a trailing NUL.
161		 */
162		if (bup + 3  + MAXNAMLEN + 1 >= eup) {
163			if ((up = reallocf(up, upsize *= 2)) == NULL)
164				goto err;
165			bup = up;
166			eup = up + upsize;
167		}
168		*bup++ = '.';
169		*bup++ = '.';
170		*bup = '\0';
171
172		/* Open and stat parent directory. */
173		if (!(dir = opendir(up)) || _fstat(dirfd(dir), &s))
174			goto err;
175
176		/* Add trailing slash for next directory. */
177		*bup++ = '/';
178		*bup = '\0';
179
180		/*
181		 * If it's a mount point, have to stat each element because
182		 * the inode number in the directory is for the entry in the
183		 * parent directory, not the inode number of the mounted file.
184		 */
185		save_errno = 0;
186		if (s.st_dev == dev) {
187			for (;;) {
188				if (!(dp = readdir(dir)))
189					goto notfound;
190				if (dp->d_fileno == ino)
191					break;
192			}
193		} else
194			for (;;) {
195				if (!(dp = readdir(dir)))
196					goto notfound;
197				if (ISDOT(dp))
198					continue;
199				bcopy(dp->d_name, bup, dp->d_namlen + 1);
200
201				/* Save the first error for later. */
202				if (lstat(up, &s)) {
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		if (bpt - pt < dp->d_namlen + (first ? 1 : 2)) {
217			size_t len, off;
218
219			if (!ptsize) {
220				errno = ERANGE;
221				goto err;
222			}
223			off = bpt - pt;
224			len = ept - bpt;
225			if ((pt = reallocf(pt, ptsize *= 2)) == NULL)
226				goto err;
227			bpt = pt + off;
228			ept = pt + ptsize;
229			bcopy(bpt, ept - len, len);
230			bpt = ept - len;
231		}
232		if (!first)
233			*--bpt = '/';
234		bpt -= dp->d_namlen;
235		bcopy(dp->d_name, bpt, dp->d_namlen);
236		(void) closedir(dir);
237		dir = NULL;
238
239		/* Truncate any file name. */
240		*bup = '\0';
241	}
242
243notfound:
244	/*
245	 * If readdir set errno, use it, not any saved error; otherwise,
246	 * didn't find the current directory in its parent directory, set
247	 * errno to ENOENT.
248	 */
249	if (!errno)
250		errno = save_errno ? save_errno : ENOENT;
251	/* FALLTHROUGH */
252err:
253	save_errno = errno;
254
255	if (ptsize)
256		free(pt);
257	if (dir)
258		(void) closedir(dir);
259	free(up);
260
261	errno = save_errno;
262	return (NULL);
263}
264