xref: /freebsd/bin/sh/trap.c (revision d2387d42b8da231a5b95cbc313825fb2aadf26f6)
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  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 #if 0
39 static char sccsid[] = "@(#)trap.c	8.5 (Berkeley) 6/5/95";
40 #endif
41 #endif /* not lint */
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include <signal.h>
46 #include <unistd.h>
47 #include <stdlib.h>
48 
49 #include "shell.h"
50 #include "main.h"
51 #include "nodes.h"	/* for other headers */
52 #include "eval.h"
53 #include "jobs.h"
54 #include "show.h"
55 #include "options.h"
56 #include "syntax.h"
57 #include "output.h"
58 #include "memalloc.h"
59 #include "error.h"
60 #include "trap.h"
61 #include "mystring.h"
62 #include "myhistedit.h"
63 
64 
65 /*
66  * Sigmode records the current value of the signal handlers for the various
67  * modes.  A value of zero means that the current handler is not known.
68  * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
69  */
70 
71 #define S_DFL 1			/* default signal handling (SIG_DFL) */
72 #define S_CATCH 2		/* signal is caught */
73 #define S_IGN 3			/* signal is ignored (SIG_IGN) */
74 #define S_HARD_IGN 4		/* signal is ignored permanently */
75 #define S_RESET 5		/* temporary - to reset a hard ignored sig */
76 
77 
78 MKINIT char sigmode[NSIG];	/* current value of signal */
79 int pendingsigs;		/* indicates some signal received */
80 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 volatile sig_atomic_t gotwinch;
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 > 70 || 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, char **argv)
153 {
154 	char *action;
155 	int signo;
156 
157 	if (argc <= 1) {
158 		for (signo = 0 ; signo < sys_nsig ; signo++) {
159 			if (signo < NSIG && trap[signo] != NULL) {
160 				if (signo == 0) {
161 					out1fmt("trap -- '%s' %s\n",
162 					    trap[signo], "exit");
163 				} else if (sys_signame[signo]) {
164 					out1fmt("trap -- '%s' %s\n",
165 					    trap[signo], sys_signame[signo]);
166 				} else {
167 					out1fmt("trap -- '%s' %d\n",
168 					    trap[signo], signo);
169 				}
170 			}
171 		}
172 		return 0;
173 	}
174 	action = NULL;
175 	if (*++argv && strcmp(*argv, "--") == 0)
176 		argv++;
177 	if (*argv && sigstring_to_signum(*argv) == -1) {
178 		if ((*argv)[0] != '-') {
179 			action = *argv;
180 			argv++;
181 		} else if ((*argv)[1] == '\0') {
182 			argv++;
183 		} else if ((*argv)[1] == 'l' && (*argv)[2] == '\0') {
184 			printsignals();
185 			return 0;
186 		} else {
187 			error("bad option %s", *argv);
188 		}
189 	}
190 	while (*argv) {
191 		if ((signo = sigstring_to_signum(*argv)) == -1)
192 			error("bad signal %s", *argv);
193 		INTOFF;
194 		if (action)
195 			action = savestr(action);
196 		if (trap[signo])
197 			ckfree(trap[signo]);
198 		trap[signo] = action;
199 		if (signo != 0)
200 			setsignal(signo);
201 		INTON;
202 		argv++;
203 	}
204 	return 0;
205 }
206 
207 
208 /*
209  * Clear traps on a fork.
210  */
211 void
212 clear_traps(void)
213 {
214 	char *volatile *tp;
215 
216 	for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
217 		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
218 			INTOFF;
219 			ckfree(*tp);
220 			*tp = NULL;
221 			if (tp != &trap[0])
222 				setsignal(tp - trap);
223 			INTON;
224 		}
225 	}
226 }
227 
228 
229 /*
230  * Set the signal handler for the specified signal.  The routine figures
231  * out what it should be set to.
232  */
233 void
234 setsignal(int signo)
235 {
236 	int action;
237 	sig_t sig, sigact = SIG_DFL;
238 	char *t;
239 
240 	if ((t = trap[signo]) == NULL)
241 		action = S_DFL;
242 	else if (*t != '\0')
243 		action = S_CATCH;
244 	else
245 		action = S_IGN;
246 	if (action == S_DFL) {
247 		switch (signo) {
248 		case SIGINT:
249 			action = S_CATCH;
250 			break;
251 		case SIGQUIT:
252 #ifdef DEBUG
253 			{
254 			extern int debug;
255 
256 			if (debug)
257 				break;
258 			}
259 #endif
260 			action = S_CATCH;
261 			break;
262 		case SIGTERM:
263 			if (rootshell && iflag)
264 				action = S_IGN;
265 			break;
266 #if JOBS
267 		case SIGTSTP:
268 		case SIGTTOU:
269 			if (rootshell && mflag)
270 				action = S_IGN;
271 			break;
272 #endif
273 #ifndef NO_HISTORY
274 		case SIGWINCH:
275 			if (rootshell && iflag)
276 				action = S_CATCH;
277 			break;
278 #endif
279 		}
280 	}
281 
282 	t = &sigmode[signo];
283 	if (*t == 0) {
284 		/*
285 		 * current setting unknown
286 		 */
287 		if (!getsigaction(signo, &sigact)) {
288 			/*
289 			 * Pretend it worked; maybe we should give a warning
290 			 * here, but other shells don't. We don't alter
291 			 * sigmode, so that we retry every time.
292 			 */
293 			return;
294 		}
295 		if (sigact == SIG_IGN) {
296 			if (mflag && (signo == SIGTSTP ||
297 			     signo == SIGTTIN || signo == SIGTTOU)) {
298 				*t = S_IGN;	/* don't hard ignore these */
299 			} else
300 				*t = S_HARD_IGN;
301 		} else {
302 			*t = S_RESET;	/* force to be set */
303 		}
304 	}
305 	if (*t == S_HARD_IGN || *t == action)
306 		return;
307 	switch (action) {
308 		case S_DFL:	sigact = SIG_DFL;	break;
309 		case S_CATCH:  	sigact = onsig;		break;
310 		case S_IGN:	sigact = SIG_IGN;	break;
311 	}
312 	*t = action;
313 	sig = signal(signo, sigact);
314 	if (sig != SIG_ERR && action == S_CATCH)
315 		siginterrupt(signo, 1);
316 }
317 
318 
319 /*
320  * Return the current setting for sig w/o changing it.
321  */
322 static int
323 getsigaction(int signo, sig_t *sigact)
324 {
325 	struct sigaction sa;
326 
327 	if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
328 		return 0;
329 	*sigact = (sig_t) sa.sa_handler;
330 	return 1;
331 }
332 
333 
334 /*
335  * Ignore a signal.
336  */
337 void
338 ignoresig(int signo)
339 {
340 
341 	if (sigmode[signo] != S_IGN && sigmode[signo] != S_HARD_IGN) {
342 		signal(signo, SIG_IGN);
343 	}
344 	sigmode[signo] = S_HARD_IGN;
345 }
346 
347 
348 #ifdef mkinit
349 INCLUDE <signal.h>
350 INCLUDE "trap.h"
351 
352 SHELLPROC {
353 	char *sm;
354 
355 	clear_traps();
356 	for (sm = sigmode ; sm < sigmode + NSIG ; sm++) {
357 		if (*sm == S_IGN)
358 			*sm = S_HARD_IGN;
359 	}
360 }
361 #endif
362 
363 
364 /*
365  * Signal handler.
366  */
367 void
368 onsig(int signo)
369 {
370 
371 	if (signo == SIGINT && trap[SIGINT] == NULL) {
372 		onint();
373 		return;
374 	}
375 
376 	if (signo != SIGCHLD || !ignore_sigchld)
377 		gotsig[signo] = 1;
378 	pendingsigs++;
379 
380 	/* If we are currently in a wait builtin, prepare to break it */
381 	if ((signo == SIGINT || signo == SIGQUIT) && in_waitcmd != 0)
382 		breakwaitcmd = 1;
383 	/*
384 	 * If a trap is set, not ignored and not the null command, we need
385 	 * to make sure traps are executed even when a child blocks signals.
386 	 */
387 	if (Tflag &&
388 	    trap[signo] != NULL &&
389 	    ! trap[signo][0] == '\0' &&
390 	    ! (trap[signo][0] == ':' && trap[signo][1] == '\0'))
391 		breakwaitcmd = 1;
392 
393 #ifndef NO_HISTORY
394 	if (signo == SIGWINCH)
395 		gotwinch = 1;
396 #endif
397 }
398 
399 
400 /*
401  * Called to execute a trap.  Perhaps we should avoid entering new trap
402  * handlers while we are executing a trap handler.
403  */
404 void
405 dotrap(void)
406 {
407 	int i;
408 	int savestatus;
409 
410 	in_dotrap++;
411 	for (;;) {
412 		for (i = 1; i < NSIG; i++) {
413 			if (gotsig[i]) {
414 				gotsig[i] = 0;
415 				if (trap[i]) {
416 					/*
417 					 * Ignore SIGCHLD to avoid infinite
418 					 * recursion if the trap action does
419 					 * a fork.
420 					 */
421 					if (i == SIGCHLD)
422 						ignore_sigchld++;
423 					savestatus = exitstatus;
424 					evalstring(trap[i]);
425 					exitstatus = savestatus;
426 					if (i == SIGCHLD)
427 						ignore_sigchld--;
428 				}
429 				break;
430 			}
431 		}
432 		if (i >= NSIG)
433 			break;
434 	}
435 	in_dotrap--;
436 	pendingsigs = 0;
437 }
438 
439 
440 /*
441  * Controls whether the shell is interactive or not.
442  */
443 void
444 setinteractive(int on)
445 {
446 	static int is_interactive = -1;
447 
448 	if (on == is_interactive)
449 		return;
450 	setsignal(SIGINT);
451 	setsignal(SIGQUIT);
452 	setsignal(SIGTERM);
453 #ifndef NO_HISTORY
454 	setsignal(SIGWINCH);
455 #endif
456 	is_interactive = on;
457 }
458 
459 
460 /*
461  * Called to exit the shell.
462  */
463 void
464 exitshell(int status)
465 {
466 	struct jmploc loc1, loc2;
467 	char *p;
468 
469 	TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
470 	if (setjmp(loc1.loc)) {
471 		goto l1;
472 	}
473 	if (setjmp(loc2.loc)) {
474 		goto l2;
475 	}
476 	handler = &loc1;
477 	if ((p = trap[0]) != NULL && *p != '\0') {
478 		trap[0] = NULL;
479 		evalstring(p);
480 	}
481 l1:   handler = &loc2;			/* probably unnecessary */
482 	flushall();
483 #if JOBS
484 	setjobctl(0);
485 #endif
486 l2:   _exit(status);
487 }
488