xref: /freebsd-13-stable/bin/sh/main.c (revision 973a9a36fd56fefa44ce2ab22eb67bb2077c1f84)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #ifndef lint
36 static char const copyright[] =
37 "@(#) Copyright (c) 1991, 1993\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40 
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)main.c	8.6 (Berkeley) 5/28/95";
44 #endif
45 #endif /* not lint */
46 #include <sys/cdefs.h>
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 #ifndef NO_HISTORY
77 #include "myhistedit.h"
78 #endif
79 
80 int rootpid;
81 int rootshell;
82 struct jmploc main_handler;
83 int localeisutf8, initial_localeisutf8;
84 
85 static void reset(void);
86 static void cmdloop(int);
87 static void read_profile(const char *);
88 static char *find_dot_file(char *);
89 
90 /*
91  * Main routine.  We initialize things, parse the arguments, execute
92  * profiles if we're a login shell, and then call cmdloop to execute
93  * commands.  The setjmp call sets up the location to jump to when an
94  * exception occurs.  When an exception occurs the variable "state"
95  * is used to figure out how far we had gotten.
96  */
97 
98 int
main(int argc,char * argv[])99 main(int argc, char *argv[])
100 {
101 	struct stackmark smark, smark2;
102 	volatile int state;
103 	char *shinit;
104 	int login;
105 
106 	(void) setlocale(LC_ALL, "");
107 	initcharset();
108 	state = 0;
109 	if (setjmp(main_handler.loc)) {
110 		if (state == 0 || iflag == 0 || ! rootshell ||
111 		    exception == EXEXIT)
112 			exitshell(exitstatus);
113 		reset();
114 		if (exception == EXINT)
115 			out2fmt_flush("\n");
116 		popstackmark(&smark);
117 		FORCEINTON;				/* enable interrupts */
118 		if (state == 1)
119 			goto state1;
120 		else if (state == 2)
121 			goto state2;
122 		else if (state == 3)
123 			goto state3;
124 		else
125 			goto state4;
126 	}
127 	handler = &main_handler;
128 #ifdef DEBUG
129 	opentrace();
130 	trputs("Shell args:  ");  trargs(argv);
131 #endif
132 	rootpid = getpid();
133 	rootshell = 1;
134 	INTOFF;
135 	initvar();
136 	setstackmark(&smark);
137 	setstackmark(&smark2);
138 	login = procargs(argc, argv);
139 	trap_init();
140 	pwd_init(iflag);
141 	INTON;
142 	if (iflag)
143 		chkmail(1);
144 	if (login) {
145 		state = 1;
146 		read_profile("/etc/profile");
147 state1:
148 		state = 2;
149 		if (privileged == 0)
150 			read_profile("${HOME-}/.profile");
151 		else
152 			read_profile("/etc/suid_profile");
153 	}
154 state2:
155 	state = 3;
156 	if (!privileged && iflag) {
157 		if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
158 			state = 3;
159 			read_profile(shinit);
160 		}
161 	}
162 #ifndef NO_HISTORY
163 	if (iflag)
164 		histload();
165 #endif
166 state3:
167 	state = 4;
168 	popstackmark(&smark2);
169 	if (minusc) {
170 		evalstring(minusc, sflag ? 0 : EV_EXIT);
171 	}
172 state4:
173 	if (sflag || minusc == NULL) {
174 		cmdloop(1);
175 	}
176 	exitshell(exitstatus);
177 	/*NOTREACHED*/
178 	return 0;
179 }
180 
181 static void
reset(void)182 reset(void)
183 {
184 	reseteval();
185 	resetinput();
186 }
187 
188 /*
189  * Read and execute commands.  "Top" is nonzero for the top level command
190  * loop; it turns on prompting if the shell is interactive.
191  */
192 
193 static void
cmdloop(int top)194 cmdloop(int top)
195 {
196 	union node *n;
197 	struct stackmark smark;
198 	int inter;
199 	int numeof = 0;
200 
201 	TRACE(("cmdloop(%d) called\n", top));
202 	setstackmark(&smark);
203 	for (;;) {
204 		if (pendingsig)
205 			dotrap();
206 		inter = 0;
207 		if (iflag && top) {
208 			inter++;
209 			showjobs(1, SHOWJOBS_DEFAULT);
210 			chkmail(0);
211 			flushout(&output);
212 		}
213 		n = parsecmd(inter);
214 		/* showtree(n); DEBUG */
215 		if (n == NEOF) {
216 			if (!top || numeof >= 50)
217 				break;
218 			if (!stoppedjobs()) {
219 				if (!Iflag)
220 					break;
221 				out2fmt_flush("\nUse \"exit\" to leave shell.\n");
222 			}
223 			numeof++;
224 		} else if (n != NULL && nflag == 0) {
225 			job_warning = (job_warning == 2) ? 1 : 0;
226 			numeof = 0;
227 			evaltree(n, 0);
228 		}
229 		popstackmark(&smark);
230 		setstackmark(&smark);
231 		if (evalskip != 0) {
232 			if (evalskip == SKIPRETURN)
233 				evalskip = 0;
234 			break;
235 		}
236 	}
237 	popstackmark(&smark);
238 	if (top && iflag) {
239 		out2c('\n');
240 		flushout(out2);
241 	}
242 }
243 
244 
245 
246 /*
247  * Read /etc/profile or .profile.  Return on error.
248  */
249 
250 static void
read_profile(const char * name)251 read_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 
275 void
readcmdfile(const char * name)276 readcmdfile(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 
291 static char *
find_dot_file(char * basename)292 find_dot_file(char *basename)
293 {
294 	char *fullname;
295 	const char *opt;
296 	const char *path = pathval();
297 	struct stat statb;
298 
299 	/* don't try this for absolute or relative paths */
300 	if( strchr(basename, '/'))
301 		return basename;
302 
303 	while ((fullname = padvance(&path, &opt, basename)) != NULL) {
304 		if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
305 			/*
306 			 * Don't bother freeing here, since it will
307 			 * be freed by the caller.
308 			 */
309 			return fullname;
310 		}
311 		stunalloc(fullname);
312 	}
313 	return basename;
314 }
315 
316 int
dotcmd(int argc,char ** argv)317 dotcmd(int argc, char **argv)
318 {
319 	char *filename, *fullname;
320 
321 	if (argc < 2)
322 		error("missing filename");
323 
324 	exitstatus = 0;
325 
326 	/*
327 	 * Because we have historically not supported any options,
328 	 * only treat "--" specially.
329 	 */
330 	filename = argc > 2 && strcmp(argv[1], "--") == 0 ? argv[2] : argv[1];
331 
332 	fullname = find_dot_file(filename);
333 	setinputfile(fullname, 1);
334 	commandname = fullname;
335 	cmdloop(0);
336 	popfile();
337 	return exitstatus;
338 }
339 
340 
341 int
exitcmd(int argc,char ** argv)342 exitcmd(int argc, char **argv)
343 {
344 	if (stoppedjobs())
345 		return 0;
346 	if (argc > 1)
347 		exitshell(number(argv[1]));
348 	else
349 		exitshell_savedstatus();
350 }
351