xref: /freebsd/bin/sh/main.c (revision c11e094d96120a2e0e726ed9705ae0ec08db49b6)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 static char const copyright[] =
39 "@(#) Copyright (c) 1991, 1993\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 #if 0
45 static char sccsid[] = "@(#)main.c	8.6 (Berkeley) 5/28/95";
46 #endif
47 static const char rcsid[] =
48   "$FreeBSD$";
49 #endif /* not lint */
50 
51 #include <stdio.h>
52 #include <signal.h>
53 #include <sys/stat.h>
54 #include <unistd.h>
55 #include <fcntl.h>
56 #include <locale.h>
57 #include <errno.h>
58 
59 #include "shell.h"
60 #include "main.h"
61 #include "mail.h"
62 #include "options.h"
63 #include "output.h"
64 #include "parser.h"
65 #include "nodes.h"
66 #include "expand.h"
67 #include "eval.h"
68 #include "jobs.h"
69 #include "input.h"
70 #include "trap.h"
71 #include "var.h"
72 #include "show.h"
73 #include "memalloc.h"
74 #include "error.h"
75 #include "init.h"
76 #include "mystring.h"
77 #include "exec.h"
78 #include "cd.h"
79 
80 #define PROFILE 0
81 
82 int rootpid;
83 int rootshell;
84 #if PROFILE
85 short profile_buf[16384];
86 extern int etext();
87 #endif
88 
89 STATIC void read_profile(char *);
90 STATIC char *find_dot_file(char *);
91 
92 /*
93  * Main routine.  We initialize things, parse the arguments, execute
94  * profiles if we're a login shell, and then call cmdloop to execute
95  * commands.  The setjmp call sets up the location to jump to when an
96  * exception occurs.  When an exception occurs the variable "state"
97  * is used to figure out how far we had gotten.
98  */
99 
100 int
101 main(int argc, char *argv[])
102 {
103 	struct jmploc jmploc;
104 	struct stackmark smark;
105 	volatile int state;
106 	char *shinit;
107 
108 #if PROFILE
109 	monitor(4, etext, profile_buf, sizeof profile_buf, 50);
110 #endif
111 	(void) setlocale(LC_ALL, "");
112 	state = 0;
113 	if (setjmp(jmploc.loc)) {
114 		/*
115 		 * When a shell procedure is executed, we raise the
116 		 * exception EXSHELLPROC to clean up before executing
117 		 * the shell procedure.
118 		 */
119 		switch (exception) {
120 		case EXSHELLPROC:
121 			rootpid = getpid();
122 			rootshell = 1;
123 			minusc = NULL;
124 			state = 3;
125 			break;
126 
127 		case EXEXEC:
128 			exitstatus = exerrno;
129 			break;
130 
131 		case EXERROR:
132 			exitstatus = 2;
133 			break;
134 
135 		default:
136 			break;
137 		}
138 
139 		if (exception != EXSHELLPROC) {
140 		    if (state == 0 || iflag == 0 || ! rootshell)
141 			    exitshell(exitstatus);
142 		}
143 		reset();
144 		if (exception == EXINT
145 #if ATTY
146 		 && (! attyset() || equal(termval(), "emacs"))
147 #endif
148 		 ) {
149 			out2c('\n');
150 			flushout(&errout);
151 		}
152 		popstackmark(&smark);
153 		FORCEINTON;				/* enable interrupts */
154 		if (state == 1)
155 			goto state1;
156 		else if (state == 2)
157 			goto state2;
158 		else if (state == 3)
159 			goto state3;
160 		else
161 			goto state4;
162 	}
163 	handler = &jmploc;
164 #ifdef DEBUG
165 	opentrace();
166 	trputs("Shell args:  ");  trargs(argv);
167 #endif
168 	rootpid = getpid();
169 	rootshell = 1;
170 	init();
171 	setstackmark(&smark);
172 	procargs(argc, argv);
173 	if (getpwd() == NULL && iflag)
174 		out2str("sh: cannot determine working directory\n");
175 	if (argv[0] && argv[0][0] == '-') {
176 		state = 1;
177 		read_profile("/etc/profile");
178 state1:
179 		state = 2;
180 		if (privileged == 0)
181 			read_profile(".profile");
182 		else
183 			read_profile("/etc/suid_profile");
184 	}
185 state2:
186 	state = 3;
187 	if (!privileged && iflag) {
188 		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
189 			state = 3;
190 			read_profile(shinit);
191 		}
192 	}
193 state3:
194 	state = 4;
195 	if (minusc) {
196 		evalstring(minusc);
197 	}
198 	if (sflag || minusc == NULL) {
199 state4:	/* XXX ??? - why isn't this before the "if" statement */
200 		cmdloop(1);
201 	}
202 #if PROFILE
203 	monitor(0);
204 #endif
205 	exitshell(exitstatus);
206 	/*NOTREACHED*/
207 	return 0;
208 }
209 
210 
211 /*
212  * Read and execute commands.  "Top" is nonzero for the top level command
213  * loop; it turns on prompting if the shell is interactive.
214  */
215 
216 void
217 cmdloop(int top)
218 {
219 	union node *n;
220 	struct stackmark smark;
221 	int inter;
222 	int numeof = 0;
223 
224 	TRACE(("cmdloop(%d) called\n", top));
225 	setstackmark(&smark);
226 	for (;;) {
227 		if (pendingsigs)
228 			dotrap();
229 		inter = 0;
230 		if (iflag && top) {
231 			inter++;
232 			showjobs(1);
233 			chkmail(0);
234 			flushout(&output);
235 		}
236 		n = parsecmd(inter);
237 		/* showtree(n); DEBUG */
238 		if (n == NEOF) {
239 			if (!top || numeof >= 50)
240 				break;
241 			if (!stoppedjobs()) {
242 				if (!Iflag)
243 					break;
244 				out2str("\nUse \"exit\" to leave shell.\n");
245 			}
246 			numeof++;
247 		} else if (n != NULL && nflag == 0) {
248 			job_warning = (job_warning == 2) ? 1 : 0;
249 			numeof = 0;
250 			evaltree(n, 0);
251 		}
252 		popstackmark(&smark);
253 		setstackmark(&smark);
254 		if (evalskip == SKIPFILE) {
255 			evalskip = 0;
256 			break;
257 		}
258 	}
259 	popstackmark(&smark);
260 }
261 
262 
263 
264 /*
265  * Read /etc/profile or .profile.  Return on error.
266  */
267 
268 STATIC void
269 read_profile(char *name)
270 {
271 	int fd;
272 
273 	INTOFF;
274 	if ((fd = open(name, O_RDONLY)) >= 0)
275 		setinputfd(fd, 1);
276 	INTON;
277 	if (fd < 0)
278 		return;
279 	cmdloop(0);
280 	popfile();
281 }
282 
283 
284 
285 /*
286  * Read a file containing shell functions.
287  */
288 
289 void
290 readcmdfile(char *name)
291 {
292 	int fd;
293 
294 	INTOFF;
295 	if ((fd = open(name, O_RDONLY)) >= 0)
296 		setinputfd(fd, 1);
297 	else
298 		error("Can't open %s: %s", name, strerror(errno));
299 	INTON;
300 	cmdloop(0);
301 	popfile();
302 }
303 
304 
305 
306 /*
307  * Take commands from a file.  To be compatible we should do a path
308  * search for the file, which is necessary to find sub-commands.
309  */
310 
311 
312 STATIC char *
313 find_dot_file(char *basename)
314 {
315 	static char localname[FILENAME_MAX+1];
316 	char *fullname;
317 	char *path = pathval();
318 	struct stat statb;
319 
320 	/* don't try this for absolute or relative paths */
321 	if( strchr(basename, '/'))
322 		return basename;
323 
324 	while ((fullname = padvance(&path, basename)) != NULL) {
325 		strcpy(localname, fullname);
326 		stunalloc(fullname);
327 		if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode))
328 			return localname;
329 	}
330 	return basename;
331 }
332 
333 int
334 dotcmd(int argc, char **argv)
335 {
336 	struct strlist *sp;
337 	exitstatus = 0;
338 
339 	for (sp = cmdenviron; sp ; sp = sp->next)
340 		setvareq(savestr(sp->text), VSTRFIXED|VTEXTFIXED);
341 
342 	if (argc >= 2) {		/* That's what SVR2 does */
343 		char *fullname = find_dot_file(argv[1]);
344 
345 		setinputfile(fullname, 1);
346 		commandname = fullname;
347 		cmdloop(0);
348 		popfile();
349 	}
350 	return exitstatus;
351 }
352 
353 
354 int
355 exitcmd(int argc, char **argv)
356 {
357 	extern int oexitstatus;
358 
359 	if (stoppedjobs())
360 		return 0;
361 	if (argc > 1)
362 		exitstatus = number(argv[1]);
363 	else
364 		exitstatus = oexitstatus;
365 	exitshell(exitstatus);
366 	/*NOTREACHED*/
367 	return 0;
368 }
369