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