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