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