xref: /freebsd/bin/sh/trap.c (revision 266f97b5)
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 #if 0
37 static char sccsid[] = "@(#)trap.c	8.5 (Berkeley) 6/5/95";
38 #endif
39 #endif /* not lint */
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 #include <signal.h>
44 #include <unistd.h>
45 #include <stdlib.h>
46 
47 #include "shell.h"
48 #include "main.h"
49 #include "nodes.h"	/* for other headers */
50 #include "eval.h"
51 #include "jobs.h"
52 #include "show.h"
53 #include "options.h"
54 #include "syntax.h"
55 #include "output.h"
56 #include "memalloc.h"
57 #include "error.h"
58 #include "trap.h"
59 #include "mystring.h"
60 #include "builtins.h"
61 #ifndef NO_HISTORY
62 #include "myhistedit.h"
63 #endif
64 
65 
66 /*
67  * Sigmode records the current value of the signal handlers for the various
68  * modes.  A value of zero means that the current handler is not known.
69  * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
70  */
71 
72 #define S_DFL 1			/* default signal handling (SIG_DFL) */
73 #define S_CATCH 2		/* signal is caught */
74 #define S_IGN 3			/* signal is ignored (SIG_IGN) */
75 #define S_HARD_IGN 4		/* signal is ignored permanently */
76 #define S_RESET 5		/* temporary - to reset a hard ignored sig */
77 
78 
79 static char sigmode[NSIG];	/* current value of signal */
80 volatile sig_atomic_t pendingsig;	/* indicates some signal received */
81 volatile sig_atomic_t pendingsig_waitcmd;	/* indicates wait builtin should be interrupted */
82 static int in_dotrap;			/* do we execute in a trap handler? */
83 static char *volatile trap[NSIG];	/* trap handler commands */
84 static volatile sig_atomic_t gotsig[NSIG];
85 				/* indicates specified signal received */
86 static int ignore_sigchld;	/* Used while handling SIGCHLD traps. */
87 static int last_trapsig;
88 
89 static int exiting;		/* exitshell() has been called */
90 static int exiting_exitstatus;	/* value passed to exitshell() */
91 
92 static int getsigaction(int, sig_t *);
93 
94 
95 /*
96  * Map a string to a signal number.
97  *
98  * Note: the signal number may exceed NSIG.
99  */
100 static int
101 sigstring_to_signum(char *sig)
102 {
103 
104 	if (is_number(sig)) {
105 		int signo;
106 
107 		signo = atoi(sig);
108 		return ((signo >= 0 && signo < NSIG) ? signo : (-1));
109 	} else if (strcasecmp(sig, "EXIT") == 0) {
110 		return (0);
111 	} else {
112 		int n;
113 
114 		if (strncasecmp(sig, "SIG", 3) == 0)
115 			sig += 3;
116 		for (n = 1; n < sys_nsig; n++)
117 			if (sys_signame[n] &&
118 			    strcasecmp(sys_signame[n], sig) == 0)
119 				return (n);
120 	}
121 	return (-1);
122 }
123 
124 
125 /*
126  * Print a list of valid signal names.
127  */
128 static void
129 printsignals(void)
130 {
131 	int n, outlen;
132 
133 	outlen = 0;
134 	for (n = 1; n < sys_nsig; n++) {
135 		if (sys_signame[n]) {
136 			out1fmt("%s", sys_signame[n]);
137 			outlen += strlen(sys_signame[n]);
138 		} else {
139 			out1fmt("%d", n);
140 			outlen += 3;	/* good enough */
141 		}
142 		++outlen;
143 		if (outlen > 71 || n == sys_nsig - 1) {
144 			out1str("\n");
145 			outlen = 0;
146 		} else {
147 			out1c(' ');
148 		}
149 	}
150 }
151 
152 
153 /*
154  * The trap builtin.
155  */
156 int
157 trapcmd(int argc __unused, char **argv)
158 {
159 	char *action;
160 	int signo;
161 	int errors = 0;
162 	int i;
163 
164 	while ((i = nextopt("l")) != '\0') {
165 		switch (i) {
166 		case 'l':
167 			printsignals();
168 			return (0);
169 		}
170 	}
171 	argv = argptr;
172 
173 	if (*argv == NULL) {
174 		for (signo = 0 ; signo < sys_nsig ; signo++) {
175 			if (signo < NSIG && trap[signo] != NULL) {
176 				out1str("trap -- ");
177 				out1qstr(trap[signo]);
178 				if (signo == 0) {
179 					out1str(" EXIT\n");
180 				} else if (sys_signame[signo]) {
181 					out1fmt(" %s\n", sys_signame[signo]);
182 				} else {
183 					out1fmt(" %d\n", signo);
184 				}
185 			}
186 		}
187 		return 0;
188 	}
189 	action = NULL;
190 	if (*argv && !is_number(*argv)) {
191 		if (strcmp(*argv, "-") == 0)
192 			argv++;
193 		else {
194 			action = *argv;
195 			argv++;
196 		}
197 	}
198 	for (; *argv; argv++) {
199 		if ((signo = sigstring_to_signum(*argv)) == -1) {
200 			warning("bad signal %s", *argv);
201 			errors = 1;
202 			continue;
203 		}
204 		INTOFF;
205 		if (action)
206 			action = savestr(action);
207 		if (trap[signo])
208 			ckfree(trap[signo]);
209 		trap[signo] = action;
210 		if (signo != 0)
211 			setsignal(signo);
212 		INTON;
213 	}
214 	return errors;
215 }
216 
217 
218 /*
219  * Clear traps on a fork.
220  */
221 void
222 clear_traps(void)
223 {
224 	char *volatile *tp;
225 
226 	for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
227 		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
228 			INTOFF;
229 			ckfree(*tp);
230 			*tp = NULL;
231 			if (tp != &trap[0])
232 				setsignal(tp - trap);
233 			INTON;
234 		}
235 	}
236 }
237 
238 
239 /*
240  * Check if we have any traps enabled.
241  */
242 int
243 have_traps(void)
244 {
245 	char *volatile *tp;
246 
247 	for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
248 		if (*tp && **tp)	/* trap not NULL or SIG_IGN */
249 			return 1;
250 	}
251 	return 0;
252 }
253 
254 /*
255  * Set the signal handler for the specified signal.  The routine figures
256  * out what it should be set to.
257  */
258 void
259 setsignal(int signo)
260 {
261 	int action;
262 	sig_t sigact = SIG_DFL;
263 	struct sigaction sa;
264 	char *t;
265 
266 	if ((t = trap[signo]) == NULL)
267 		action = S_DFL;
268 	else if (*t != '\0')
269 		action = S_CATCH;
270 	else
271 		action = S_IGN;
272 	if (action == S_DFL) {
273 		switch (signo) {
274 		case SIGINT:
275 			action = S_CATCH;
276 			break;
277 		case SIGQUIT:
278 #ifdef DEBUG
279 			if (debug)
280 				break;
281 #endif
282 			action = S_CATCH;
283 			break;
284 		case SIGTERM:
285 			if (rootshell && iflag)
286 				action = S_IGN;
287 			break;
288 #if JOBS
289 		case SIGTSTP:
290 		case SIGTTOU:
291 			if (rootshell && mflag)
292 				action = S_IGN;
293 			break;
294 #endif
295 		}
296 	}
297 
298 	t = &sigmode[signo];
299 	if (*t == 0) {
300 		/*
301 		 * current setting unknown
302 		 */
303 		if (!getsigaction(signo, &sigact)) {
304 			/*
305 			 * Pretend it worked; maybe we should give a warning
306 			 * here, but other shells don't. We don't alter
307 			 * sigmode, so that we retry every time.
308 			 */
309 			return;
310 		}
311 		if (sigact == SIG_IGN) {
312 			if (mflag && (signo == SIGTSTP ||
313 			     signo == SIGTTIN || signo == SIGTTOU)) {
314 				*t = S_IGN;	/* don't hard ignore these */
315 			} else
316 				*t = S_HARD_IGN;
317 		} else {
318 			*t = S_RESET;	/* force to be set */
319 		}
320 	}
321 	if (*t == S_HARD_IGN || *t == action)
322 		return;
323 	switch (action) {
324 		case S_DFL:	sigact = SIG_DFL;	break;
325 		case S_CATCH:  	sigact = onsig;		break;
326 		case S_IGN:	sigact = SIG_IGN;	break;
327 	}
328 	*t = action;
329 	sa.sa_handler = sigact;
330 	sa.sa_flags = 0;
331 	sigemptyset(&sa.sa_mask);
332 	sigaction(signo, &sa, NULL);
333 }
334 
335 
336 /*
337  * Return the current setting for sig w/o changing it.
338  */
339 static int
340 getsigaction(int signo, sig_t *sigact)
341 {
342 	struct sigaction sa;
343 
344 	if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
345 		return 0;
346 	*sigact = (sig_t) sa.sa_handler;
347 	return 1;
348 }
349 
350 
351 /*
352  * Ignore a signal.
353  */
354 void
355 ignoresig(int signo)
356 {
357 
358 	if (sigmode[signo] == 0)
359 		setsignal(signo);
360 	if (sigmode[signo] != S_IGN && sigmode[signo] != S_HARD_IGN) {
361 		signal(signo, SIG_IGN);
362 		sigmode[signo] = S_IGN;
363 	}
364 }
365 
366 
367 int
368 issigchldtrapped(void)
369 {
370 
371 	return (trap[SIGCHLD] != NULL && *trap[SIGCHLD] != '\0');
372 }
373 
374 
375 /*
376  * Signal handler.
377  */
378 void
379 onsig(int signo)
380 {
381 
382 	if (signo == SIGINT && trap[SIGINT] == NULL) {
383 		if (suppressint)
384 			SET_PENDING_INT;
385 		else
386 			onint();
387 		return;
388 	}
389 
390 	/* If we are currently in a wait builtin, prepare to break it */
391 	if (signo == SIGINT || signo == SIGQUIT)
392 		pendingsig_waitcmd = signo;
393 
394 	if (trap[signo] != NULL && trap[signo][0] != '\0' &&
395 	    (signo != SIGCHLD || !ignore_sigchld)) {
396 		gotsig[signo] = 1;
397 		pendingsig = signo;
398 		pendingsig_waitcmd = signo;
399 	}
400 }
401 
402 
403 /*
404  * Called to execute a trap.  Perhaps we should avoid entering new trap
405  * handlers while we are executing a trap handler.
406  */
407 void
408 dotrap(void)
409 {
410 	struct stackmark smark;
411 	int i;
412 	int savestatus, prev_evalskip, prev_skipcount;
413 
414 	in_dotrap++;
415 	for (;;) {
416 		pendingsig = 0;
417 		pendingsig_waitcmd = 0;
418 		for (i = 1; i < NSIG; i++) {
419 			if (gotsig[i]) {
420 				gotsig[i] = 0;
421 				if (trap[i]) {
422 					/*
423 					 * Ignore SIGCHLD to avoid infinite
424 					 * recursion if the trap action does
425 					 * a fork.
426 					 */
427 					if (i == SIGCHLD)
428 						ignore_sigchld++;
429 
430 					/*
431 					 * Backup current evalskip
432 					 * state and reset it before
433 					 * executing a trap, so that the
434 					 * trap is not disturbed by an
435 					 * ongoing break/continue/return
436 					 * statement.
437 					 */
438 					prev_evalskip  = evalskip;
439 					prev_skipcount = skipcount;
440 					evalskip = 0;
441 
442 					last_trapsig = i;
443 					savestatus = exitstatus;
444 					setstackmark(&smark);
445 					evalstring(stsavestr(trap[i]), 0);
446 					popstackmark(&smark);
447 
448 					/*
449 					 * If such a command was not
450 					 * already in progress, allow a
451 					 * break/continue/return in the
452 					 * trap action to have an effect
453 					 * outside of it.
454 					 */
455 					if (evalskip == 0 ||
456 					    prev_evalskip != 0) {
457 						evalskip  = prev_evalskip;
458 						skipcount = prev_skipcount;
459 						exitstatus = savestatus;
460 					}
461 
462 					if (i == SIGCHLD)
463 						ignore_sigchld--;
464 				}
465 				break;
466 			}
467 		}
468 		if (i >= NSIG)
469 			break;
470 	}
471 	in_dotrap--;
472 }
473 
474 
475 void
476 trap_init(void)
477 {
478 	setsignal(SIGINT);
479 	setsignal(SIGQUIT);
480 }
481 
482 
483 /*
484  * Controls whether the shell is interactive or not based on iflag.
485  */
486 void
487 setinteractive(void)
488 {
489 	setsignal(SIGTERM);
490 }
491 
492 
493 /*
494  * Called to exit the shell.
495  */
496 void
497 exitshell(int status)
498 {
499 	TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
500 	exiting = 1;
501 	exiting_exitstatus = status;
502 	exitshell_savedstatus();
503 }
504 
505 void
506 exitshell_savedstatus(void)
507 {
508 	struct jmploc loc1, loc2;
509 	char *p;
510 	int sig = 0;
511 	sigset_t sigs;
512 
513 	if (!exiting) {
514 		if (in_dotrap && last_trapsig) {
515 			sig = last_trapsig;
516 			exiting_exitstatus = sig + 128;
517 		} else
518 			exiting_exitstatus = oexitstatus;
519 	}
520 	exitstatus = oexitstatus = exiting_exitstatus;
521 	if (!setjmp(loc1.loc)) {
522 		handler = &loc1;
523 		if ((p = trap[0]) != NULL && *p != '\0') {
524 			/*
525 			 * Reset evalskip, or the trap on EXIT could be
526 			 * interrupted if the last command was a "return".
527 			 */
528 			evalskip = 0;
529 			trap[0] = NULL;
530 			FORCEINTON;
531 			evalstring(p, 0);
532 		}
533 	}
534 	if (!setjmp(loc2.loc)) {
535 		handler = &loc2;		/* probably unnecessary */
536 		FORCEINTON;
537 		flushall();
538 #if JOBS
539 		setjobctl(0);
540 #endif
541 #ifndef NO_HISTORY
542 		histsave();
543 #endif
544 	}
545 	if (sig != 0 && sig != SIGSTOP && sig != SIGTSTP && sig != SIGTTIN &&
546 	    sig != SIGTTOU) {
547 		signal(sig, SIG_DFL);
548 		sigemptyset(&sigs);
549 		sigaddset(&sigs, sig);
550 		sigprocmask(SIG_UNBLOCK, &sigs, NULL);
551 		kill(getpid(), sig);
552 		/* If the default action is to ignore, fall back to _exit(). */
553 	}
554 	_exit(exiting_exitstatus);
555 }
556