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