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