main.c revision 221669
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 221669 2011-05-08 17:40:10Z 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(const 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;
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	procargs(argc, argv);
143	pwd_init(iflag);
144	if (iflag)
145		chkmail(1);
146	if (argv[0] && argv[0][0] == '-') {
147		state = 1;
148		read_profile("/etc/profile");
149state1:
150		state = 2;
151		if (privileged == 0)
152			read_profile(".profile");
153		else
154			read_profile("/etc/suid_profile");
155	}
156state2:
157	state = 3;
158	if (!privileged && iflag) {
159		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
160			state = 3;
161			read_profile(shinit);
162		}
163	}
164state3:
165	state = 4;
166	if (minusc) {
167		evalstring(minusc, sflag ? 0 : EV_EXIT);
168	}
169	if (sflag || minusc == NULL) {
170state4:	/* XXX ??? - why isn't this before the "if" statement */
171		cmdloop(1);
172	}
173	exitshell(exitstatus);
174	/*NOTREACHED*/
175	return 0;
176}
177
178
179/*
180 * Read and execute commands.  "Top" is nonzero for the top level command
181 * loop; it turns on prompting if the shell is interactive.
182 */
183
184void
185cmdloop(int top)
186{
187	union node *n;
188	struct stackmark smark;
189	int inter;
190	int numeof = 0;
191
192	TRACE(("cmdloop(%d) called\n", top));
193	setstackmark(&smark);
194	for (;;) {
195		if (pendingsigs)
196			dotrap();
197		inter = 0;
198		if (iflag && top) {
199			inter++;
200			showjobs(1, SHOWJOBS_DEFAULT);
201			chkmail(0);
202			flushout(&output);
203		}
204		n = parsecmd(inter);
205		/* showtree(n); DEBUG */
206		if (n == NEOF) {
207			if (!top || numeof >= 50)
208				break;
209			if (!stoppedjobs()) {
210				if (!Iflag)
211					break;
212				out2fmt_flush("\nUse \"exit\" to leave shell.\n");
213			}
214			numeof++;
215		} else if (n != NULL && nflag == 0) {
216			job_warning = (job_warning == 2) ? 1 : 0;
217			numeof = 0;
218			evaltree(n, 0);
219		}
220		popstackmark(&smark);
221		setstackmark(&smark);
222		if (evalskip != 0) {
223			if (evalskip == SKIPFILE)
224				evalskip = 0;
225			break;
226		}
227	}
228	popstackmark(&smark);
229}
230
231
232
233/*
234 * Read /etc/profile or .profile.  Return on error.
235 */
236
237static void
238read_profile(const char *name)
239{
240	int fd;
241
242	INTOFF;
243	if ((fd = open(name, O_RDONLY)) >= 0)
244		setinputfd(fd, 1);
245	INTON;
246	if (fd < 0)
247		return;
248	cmdloop(0);
249	popfile();
250}
251
252
253
254/*
255 * Read a file containing shell functions.
256 */
257
258void
259readcmdfile(const char *name)
260{
261	int fd;
262
263	INTOFF;
264	if ((fd = open(name, O_RDONLY)) >= 0)
265		setinputfd(fd, 1);
266	else
267		error("Can't open %s: %s", name, strerror(errno));
268	INTON;
269	cmdloop(0);
270	popfile();
271}
272
273
274
275/*
276 * Take commands from a file.  To be compatible we should do a path
277 * search for the file, which is necessary to find sub-commands.
278 */
279
280
281static char *
282find_dot_file(char *basename)
283{
284	static char localname[FILENAME_MAX+1];
285	char *fullname;
286	const char *path = pathval();
287	struct stat statb;
288
289	/* don't try this for absolute or relative paths */
290	if( strchr(basename, '/'))
291		return basename;
292
293	while ((fullname = padvance(&path, basename)) != NULL) {
294		strcpy(localname, fullname);
295		stunalloc(fullname);
296		if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode))
297			return localname;
298	}
299	return basename;
300}
301
302int
303dotcmd(int argc, char **argv)
304{
305	char *filename, *fullname;
306
307	if (argc < 2)
308		error("missing filename");
309
310	exitstatus = 0;
311
312	/*
313	 * Because we have historically not supported any options,
314	 * only treat "--" specially.
315	 */
316	filename = argc > 2 && strcmp(argv[1], "--") == 0 ? argv[2] : argv[1];
317
318	fullname = find_dot_file(filename);
319	setinputfile(fullname, 1);
320	commandname = fullname;
321	cmdloop(0);
322	popfile();
323	return exitstatus;
324}
325
326
327int
328exitcmd(int argc, char **argv)
329{
330	if (stoppedjobs())
331		return 0;
332	if (argc > 1)
333		exitshell(number(argv[1]));
334	else
335		exitshell_savedstatus();
336}
337