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