footer.kmk: KBUILD_NO_TESTING_PASS_ALIASES.
[kbuild-mirror.git] / src / ash / cd.c
blobaae21f86901fdc44b9ad3443f7bcee71e545d40e
1 /* $NetBSD: cd.c,v 1.34 2003/11/14 20:00:28 dsl Exp $ */
3 /*-
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Kenneth Almquist.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
35 #ifdef HAVE_SYS_CDEFS_H
36 #include <sys/cdefs.h>
37 #endif
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)cd.c 8.2 (Berkeley) 5/4/95";
41 #else
42 __RCSID("$NetBSD: cd.c,v 1.34 2003/11/14 20:00:28 dsl Exp $");
43 #endif
44 #endif /* not lint */
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include <errno.h>
54 * The cd and pwd commands.
57 #include "shell.h"
58 #include "var.h"
59 #include "nodes.h" /* for jobs.h */
60 #include "jobs.h"
61 #include "options.h"
62 #include "output.h"
63 #include "memalloc.h"
64 #include "error.h"
65 #include "exec.h"
66 #include "redir.h"
67 #include "mystring.h"
68 #include "show.h"
69 #include "cd.h"
71 STATIC int docd(char *, int);
72 STATIC char *getcomponent(void);
73 STATIC void updatepwd(char *);
74 STATIC void find_curdir(int noerror);
76 char *curdir = NULL; /* current working directory */
77 char *prevdir; /* previous working directory */
78 STATIC char *cdcomppath;
80 int
81 cdcmd(int argc, char **argv)
83 const char *dest;
84 const char *path;
85 char *p, *d;
86 struct stat statb;
87 int print = cdprint; /* set -cdprint to enable */
89 nextopt(nullstr);
92 * Try (quite hard) to have 'curdir' defined, nothing has set
93 * it on entry to the shell, but we want 'cd fred; cd -' to work.
95 getpwd(1);
96 dest = *argptr;
97 if (dest == NULL) {
98 dest = bltinlookup("HOME", 1);
99 if (dest == NULL)
100 error("HOME not set");
101 } else {
102 if (argptr[1]) {
103 /* Do 'ksh' style substitution */
104 if (!curdir)
105 error("PWD not set");
106 p = strstr(curdir, dest);
107 if (!p)
108 error("bad substitution");
109 d = stalloc(strlen(curdir) + strlen(argptr[1]) + 1);
110 memcpy(d, curdir, p - curdir);
111 strcpy(d + (p - curdir), argptr[1]);
112 strcat(d, p + strlen(dest));
113 dest = d;
114 print = 1;
118 if (dest[0] == '-' && dest[1] == '\0') {
119 dest = prevdir ? prevdir : curdir;
120 print = 1;
122 if (*dest == '\0')
123 dest = ".";
124 if (IS_ROOT(dest) || (path = bltinlookup("CDPATH", 1)) == NULL)
125 path = nullstr;
126 while ((p = padvance(&path, dest)) != NULL) {
127 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
128 if (!print) {
130 * XXX - rethink
132 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
133 p += 2;
134 print = strcmp(p, dest);
136 if (docd(p, print) >= 0)
137 return 0;
141 error("can't cd to %s", dest);
142 /* NOTREACHED */
147 * Actually do the chdir. In an interactive shell, print the
148 * directory name if "print" is nonzero.
151 STATIC int
152 docd(char *dest, int print)
154 char *p;
155 char *q;
156 char *component;
157 struct stat statb;
158 int first;
159 int badstat;
161 TRACE(("docd(\"%s\", %d) called\n", dest, print));
164 * Check each component of the path. If we find a symlink or
165 * something we can't stat, clear curdir to force a getcwd()
166 * next time we get the value of the current directory.
168 badstat = 0;
169 cdcomppath = stalloc(strlen(dest) + 1);
170 scopy(dest, cdcomppath);
171 STARTSTACKSTR(p);
172 if (IS_ROOT(dest)) {
173 STPUTC('/', p);
174 cdcomppath++;
176 first = 1;
177 while ((q = getcomponent()) != NULL) {
178 if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
179 continue;
180 if (! first)
181 STPUTC('/', p);
182 first = 0;
183 component = q;
184 while (*q)
185 STPUTC(*q++, p);
186 if (equal(component, ".."))
187 continue;
188 STACKSTRNUL(p);
189 if ((lstat(stackblock(), &statb) < 0)
190 || (S_ISLNK(statb.st_mode))) {
191 /* print = 1; */
192 badstat = 1;
193 break;
197 INTOFF;
198 if (chdir(dest) < 0) {
199 INTON;
200 return -1;
202 updatepwd(badstat ? NULL : dest);
203 INTON;
204 if (print && iflag && curdir)
205 out1fmt("%s\n", curdir);
206 return 0;
211 * Get the next component of the path name pointed to by cdcomppath.
212 * This routine overwrites the string pointed to by cdcomppath.
215 STATIC char *
216 getcomponent()
218 char *p;
219 char *start;
221 if ((p = cdcomppath) == NULL)
222 return NULL;
223 start = cdcomppath;
224 while (*p != '/' && *p != '\0')
225 p++;
226 if (*p == '\0') {
227 cdcomppath = NULL;
228 } else {
229 *p++ = '\0';
230 cdcomppath = p;
232 return start;
238 * Update curdir (the name of the current directory) in response to a
239 * cd command. We also call hashcd to let the routines in exec.c know
240 * that the current directory has changed.
243 STATIC void
244 updatepwd(char *dir)
246 char *new;
247 char *p;
249 hashcd(); /* update command hash table */
252 * If our argument is NULL, we don't know the current directory
253 * any more because we traversed a symbolic link or something
254 * we couldn't stat().
256 if (dir == NULL || curdir == NULL) {
257 if (prevdir)
258 ckfree(prevdir);
259 INTOFF;
260 prevdir = curdir;
261 curdir = NULL;
262 getpwd(1);
263 INTON;
264 if (curdir)
265 setvar("PWD", curdir, VEXPORT);
266 else
267 unsetvar("PWD", 0);
268 return;
270 cdcomppath = stalloc(strlen(dir) + 1);
271 scopy(dir, cdcomppath);
272 STARTSTACKSTR(new);
273 if (!IS_ROOT(dir)) {
274 p = curdir;
275 while (*p)
276 STPUTC(*p++, new);
277 if (p[-1] == '/')
278 STUNPUTC(new);
280 while ((p = getcomponent()) != NULL) {
281 if (equal(p, "..")) {
282 while (new > stackblock() && (STUNPUTC(new), *new) != '/');
283 } else if (*p != '\0' && ! equal(p, ".")) {
284 STPUTC('/', new);
285 while (*p)
286 STPUTC(*p++, new);
289 if (new == stackblock())
290 STPUTC('/', new);
291 STACKSTRNUL(new);
292 INTOFF;
293 if (prevdir)
294 ckfree(prevdir);
295 prevdir = curdir;
296 curdir = savestr(stackblock());
297 setvar("PWD", curdir, VEXPORT);
298 INTON;
302 * Posix says the default should be 'pwd -L' (as below), however
303 * the 'cd' command (above) does something much nearer to the
304 * posix 'cd -P' (not the posix default of 'cd -L').
305 * If 'cd' is changed to support -P/L then the default here
306 * needs to be revisited if the historic behaviour is to be kept.
310 pwdcmd(int argc, char **argv)
312 int i;
313 char opt = 'L';
315 while ((i = nextopt("LP")) != '\0')
316 opt = i;
317 if (*argptr)
318 error("unexpected argument");
320 if (opt == 'L')
321 getpwd(0);
322 else
323 find_curdir(0);
325 setvar("PWD", curdir, VEXPORT);
326 out1str(curdir);
327 out1c('\n');
328 return 0;
334 #define MAXPWD 256
337 * Find out what the current directory is. If we already know the current
338 * directory, this routine returns immediately.
340 void
341 getpwd(int noerror)
343 char *pwd;
344 struct stat stdot, stpwd;
345 static int first = 1;
347 if (curdir)
348 return;
350 if (first) {
351 first = 0;
352 pwd = getenv("PWD");
353 if (pwd && IS_ROOT(pwd) && stat(".", &stdot) != -1 &&
354 stat(pwd, &stpwd) != -1 &&
355 stdot.st_dev == stpwd.st_dev &&
356 stdot.st_ino == stpwd.st_ino) {
357 curdir = savestr(pwd);
358 return;
362 find_curdir(noerror);
364 return;
367 STATIC void
368 find_curdir(int noerror)
370 int i;
371 char *pwd;
374 * Things are a bit complicated here; we could have just used
375 * getcwd, but traditionally getcwd is implemented using popen
376 * to /bin/pwd. This creates a problem for us, since we cannot
377 * keep track of the job if it is being ran behind our backs.
378 * So we re-implement getcwd(), and we suppress interrupts
379 * throughout the process. This is not completely safe, since
380 * the user can still break out of it by killing the pwd program.
381 * We still try to use getcwd for systems that we know have a
382 * c implementation of getcwd, that does not open a pipe to
383 * /bin/pwd.
385 #if defined(__NetBSD__) || defined(__SVR4) || defined(__INNOTEK_LIBC__) || 1 /* bird: nobody spawns pwd any more (we hope). */
387 for (i = MAXPWD;; i *= 2) {
388 pwd = stalloc(i);
389 if (getcwd(pwd, i) != NULL) {
390 curdir = savestr(pwd);
391 return;
393 stunalloc(pwd);
394 if (errno == ERANGE)
395 continue;
396 if (!noerror)
397 error("getcwd() failed: %s", strerror(errno));
398 return;
400 #else
402 char *p;
403 int status;
404 struct job *jp;
405 int pip[2];
407 pwd = stalloc(MAXPWD);
408 INTOFF;
409 if (pipe(pip) < 0)
410 error("Pipe call failed");
411 jp = makejob((union node *)NULL, 1);
412 if (forkshell(jp, (union node *)NULL, FORK_NOJOB) == 0) {
413 (void) close(pip[0]);
414 if (pip[1] != 1) {
415 close(1);
416 copyfd(pip[1], 1);
417 close(pip[1]);
419 (void) execl("/bin/pwd", "pwd", (char *)0);
420 error("Cannot exec /bin/pwd");
422 (void) close(pip[1]);
423 pip[1] = -1;
424 p = pwd;
425 while ((i = read(pip[0], p, pwd + MAXPWD - p)) > 0
426 || (i == -1 && errno == EINTR)) {
427 if (i > 0)
428 p += i;
430 (void) close(pip[0]);
431 pip[0] = -1;
432 status = waitforjob(jp);
433 if (status != 0)
434 error((char *)0);
435 if (i < 0 || p == pwd || p[-1] != '\n') {
436 if (noerror) {
437 INTON;
438 return;
440 error("pwd command failed");
442 p[-1] = '\0';
443 INTON;
444 curdir = savestr(pwd);
445 return;
447 #endif