main.c revision 223060
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 223060 2011-06-13 21:03:27Z 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#include "builtins.h"
76
77int rootpid;
78int rootshell;
79struct jmploc main_handler;
80int localeisutf8, initial_localeisutf8;
81
82static void read_profile(char *);
83static char *find_dot_file(char *);
84
85/*
86 * Main routine.  We initialize things, parse the arguments, execute
87 * profiles if we're a login shell, and then call cmdloop to execute
88 * commands.  The setjmp call sets up the location to jump to when an
89 * exception occurs.  When an exception occurs the variable "state"
90 * is used to figure out how far we had gotten.
91 */
92
93int
94main(int argc, char *argv[])
95{
96	struct stackmark smark, smark2;
97	volatile int state;
98	char *shinit;
99
100	(void) setlocale(LC_ALL, "");
101	initcharset();
102	state = 0;
103	if (setjmp(main_handler.loc)) {
104		switch (exception) {
105		case EXEXEC:
106			exitstatus = exerrno;
107			break;
108
109		case EXERROR:
110			exitstatus = 2;
111			break;
112
113		default:
114			break;
115		}
116
117		if (state == 0 || iflag == 0 || ! rootshell ||
118		    exception == EXEXIT)
119			exitshell(exitstatus);
120		reset();
121		if (exception == EXINT)
122			out2fmt_flush("\n");
123		popstackmark(&smark);
124		FORCEINTON;				/* enable interrupts */
125		if (state == 1)
126			goto state1;
127		else if (state == 2)
128			goto state2;
129		else if (state == 3)
130			goto state3;
131		else
132			goto state4;
133	}
134	handler = &main_handler;
135#ifdef DEBUG
136	opentrace();
137	trputs("Shell args:  ");  trargs(argv);
138#endif
139	rootpid = getpid();
140	rootshell = 1;
141	init();
142	setstackmark(&smark);
143	setstackmark(&smark2);
144	procargs(argc, argv);
145	pwd_init(iflag);
146	if (iflag)
147		chkmail(1);
148	if (argv[0] && argv[0][0] == '-') {
149		state = 1;
150		read_profile("/etc/profile");
151state1:
152		state = 2;
153		if (privileged == 0)
154			read_profile("${HOME-}/.profile");
155		else
156			read_profile("/etc/suid_profile");
157	}
158state2:
159	state = 3;
160	if (!privileged && iflag) {
161		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
162			state = 3;
163			read_profile(shinit);
164		}
165	}
166state3:
167	state = 4;
168	popstackmark(&smark2);
169	if (minusc) {
170		evalstring(minusc, sflag ? 0 : EV_EXIT);
171	}
172	if (sflag || minusc == NULL) {
173state4:	/* XXX ??? - why isn't this before the "if" statement */
174		cmdloop(1);
175	}
176	exitshell(exitstatus);
177	/*NOTREACHED*/
178	return 0;
179}
180
181
182/*
183 * Read and execute commands.  "Top" is nonzero for the top level command
184 * loop; it turns on prompting if the shell is interactive.
185 */
186
187void
188cmdloop(int top)
189{
190	union node *n;
191	struct stackmark smark;
192	int inter;
193	int numeof = 0;
194
195	TRACE(("cmdloop(%d) called\n", top));
196	setstackmark(&smark);
197	for (;;) {
198		if (pendingsigs)
199			dotrap();
200		inter = 0;
201		if (iflag && top) {
202			inter++;
203			showjobs(1, SHOWJOBS_DEFAULT);
204			chkmail(0);
205			flushout(&output);
206		}
207		n = parsecmd(inter);
208		/* showtree(n); DEBUG */
209		if (n == NEOF) {
210			if (!top || numeof >= 50)
211				break;
212			if (!stoppedjobs()) {
213				if (!Iflag)
214					break;
215				out2fmt_flush("\nUse \"exit\" to leave shell.\n");
216			}
217			numeof++;
218		} else if (n != NULL && nflag == 0) {
219			job_warning = (job_warning == 2) ? 1 : 0;
220			numeof = 0;
221			evaltree(n, 0);
222		}
223		popstackmark(&smark);
224		setstackmark(&smark);
225		if (evalskip != 0) {
226			if (evalskip == SKIPFILE)
227				evalskip = 0;
228			break;
229		}
230	}
231	popstackmark(&smark);
232}
233
234
235
236/*
237 * Read /etc/profile or .profile.  Return on error.
238 */
239
240static void
241read_profile(char *name)
242{
243	int fd;
244	const char *expandedname;
245
246	expandedname = expandstr(name);
247	if (expandedname == NULL)
248		return;
249	INTOFF;
250	if ((fd = open(expandedname, O_RDONLY)) >= 0)
251		setinputfd(fd, 1);
252	INTON;
253	if (fd < 0)
254		return;
255	cmdloop(0);
256	popfile();
257}
258
259
260
261/*
262 * Read a file containing shell functions.
263 */
264
265void
266readcmdfile(const char *name)
267{
268	int fd;
269
270	INTOFF;
271	if ((fd = open(name, O_RDONLY)) >= 0)
272		setinputfd(fd, 1);
273	else
274		error("cannot open %s: %s", name, strerror(errno));
275	INTON;
276	cmdloop(0);
277	popfile();
278}
279
280
281
282/*
283 * Take commands from a file.  To be compatible we should do a path
284 * search for the file, which is necessary to find sub-commands.
285 */
286
287
288static char *
289find_dot_file(char *basename)
290{
291	char *fullname;
292	const char *path = pathval();
293	struct stat statb;
294
295	/* don't try this for absolute or relative paths */
296	if( strchr(basename, '/'))
297		return basename;
298
299	while ((fullname = padvance(&path, basename)) != NULL) {
300		if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
301			/*
302			 * Don't bother freeing here, since it will
303			 * be freed by the caller.
304			 */
305			return fullname;
306		}
307		stunalloc(fullname);
308	}
309	return basename;
310}
311
312int
313dotcmd(int argc, char **argv)
314{
315	char *filename, *fullname;
316
317	if (argc < 2)
318		error("missing filename");
319
320	exitstatus = 0;
321
322	/*
323	 * Because we have historically not supported any options,
324	 * only treat "--" specially.
325	 */
326	filename = argc > 2 && strcmp(argv[1], "--") == 0 ? argv[2] : argv[1];
327
328	fullname = find_dot_file(filename);
329	setinputfile(fullname, 1);
330	commandname = fullname;
331	cmdloop(0);
332	popfile();
333	return exitstatus;
334}
335
336
337int
338exitcmd(int argc, char **argv)
339{
340	if (stoppedjobs())
341		return 0;
342	if (argc > 1)
343		exitshell(number(argv[1]));
344	else
345		exitshell_savedstatus();
346}
347