trap.c revision 217175
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
35static char sccsid[] = "@(#)trap.c	8.5 (Berkeley) 6/5/95";
36#endif
37#endif /* not lint */
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: head/bin/sh/trap.c 217175 2011-01-08 23:08:13Z jilles $");
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 "myhistedit.h"
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
74MKINIT char sigmode[NSIG];	/* current value of signal */
75int pendingsigs;		/* indicates some signal received */
76int in_dotrap;			/* do we execute in a trap handler? */
77static char *volatile trap[NSIG];	/* trap handler commands */
78static volatile sig_atomic_t gotsig[NSIG];
79				/* indicates specified signal received */
80static int ignore_sigchld;	/* Used while handling SIGCHLD traps. */
81volatile sig_atomic_t gotwinch;
82
83static int exiting;		/* exitshell() has been called */
84static int exiting_exitstatus;	/* value passed to exitshell() */
85
86static int getsigaction(int, sig_t *);
87
88
89/*
90 * Map a string to a signal number.
91 *
92 * Note: the signal number may exceed NSIG.
93 */
94static int
95sigstring_to_signum(char *sig)
96{
97
98	if (is_number(sig)) {
99		int signo;
100
101		signo = atoi(sig);
102		return ((signo >= 0 && signo < NSIG) ? signo : (-1));
103	} else if (strcasecmp(sig, "exit") == 0) {
104		return (0);
105	} else {
106		int n;
107
108		if (strncasecmp(sig, "sig", 3) == 0)
109			sig += 3;
110		for (n = 1; n < sys_nsig; n++)
111			if (sys_signame[n] &&
112			    strcasecmp(sys_signame[n], sig) == 0)
113				return (n);
114	}
115	return (-1);
116}
117
118
119/*
120 * Print a list of valid signal names.
121 */
122static void
123printsignals(void)
124{
125	int n, outlen;
126
127	outlen = 0;
128	for (n = 1; n < sys_nsig; n++) {
129		if (sys_signame[n]) {
130			out1fmt("%s", sys_signame[n]);
131			outlen += strlen(sys_signame[n]);
132		} else {
133			out1fmt("%d", n);
134			outlen += 3;	/* good enough */
135		}
136		++outlen;
137		if (outlen > 70 || n == sys_nsig - 1) {
138			out1str("\n");
139			outlen = 0;
140		} else {
141			out1c(' ');
142		}
143	}
144}
145
146
147/*
148 * The trap builtin.
149 */
150int
151trapcmd(int argc, char **argv)
152{
153	char *action;
154	int signo;
155	int errors = 0;
156
157	if (argc <= 1) {
158		for (signo = 0 ; signo < sys_nsig ; signo++) {
159			if (signo < NSIG && trap[signo] != NULL) {
160				out1str("trap -- ");
161				out1qstr(trap[signo]);
162				if (signo == 0) {
163					out1str(" exit\n");
164				} else if (sys_signame[signo]) {
165					out1fmt(" %s\n", sys_signame[signo]);
166				} else {
167					out1fmt(" %d\n", signo);
168				}
169			}
170		}
171		return 0;
172	}
173	action = NULL;
174	if (*++argv && strcmp(*argv, "--") == 0)
175		argv++;
176	if (*argv && sigstring_to_signum(*argv) == -1) {
177		if ((*argv)[0] != '-') {
178			action = *argv;
179			argv++;
180		} else if ((*argv)[1] == '\0') {
181			argv++;
182		} else if ((*argv)[1] == 'l' && (*argv)[2] == '\0') {
183			printsignals();
184			return 0;
185		} else {
186			error("bad option %s", *argv);
187		}
188	}
189	while (*argv) {
190		if ((signo = sigstring_to_signum(*argv)) == -1) {
191			warning("bad signal %s", *argv);
192			errors = 1;
193		}
194		INTOFF;
195		if (action)
196			action = savestr(action);
197		if (trap[signo])
198			ckfree(trap[signo]);
199		trap[signo] = action;
200		if (signo != 0)
201			setsignal(signo);
202		INTON;
203		argv++;
204	}
205	return errors;
206}
207
208
209/*
210 * Clear traps on a fork.
211 */
212void
213clear_traps(void)
214{
215	char *volatile *tp;
216
217	for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
218		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
219			INTOFF;
220			ckfree(*tp);
221			*tp = NULL;
222			if (tp != &trap[0])
223				setsignal(tp - trap);
224			INTON;
225		}
226	}
227}
228
229
230/*
231 * Check if we have any traps enabled.
232 */
233int
234have_traps(void)
235{
236	char *volatile *tp;
237
238	for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
239		if (*tp && **tp)	/* trap not NULL or SIG_IGN */
240			return 1;
241	}
242	return 0;
243}
244
245/*
246 * Set the signal handler for the specified signal.  The routine figures
247 * out what it should be set to.
248 */
249void
250setsignal(int signo)
251{
252	int action;
253	sig_t sigact = SIG_DFL;
254	struct sigaction sa;
255	char *t;
256
257	if ((t = trap[signo]) == NULL)
258		action = S_DFL;
259	else if (*t != '\0')
260		action = S_CATCH;
261	else
262		action = S_IGN;
263	if (action == S_DFL) {
264		switch (signo) {
265		case SIGINT:
266			action = S_CATCH;
267			break;
268		case SIGQUIT:
269#ifdef DEBUG
270			{
271			extern int debug;
272
273			if (debug)
274				break;
275			}
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#ifndef NO_HISTORY
291		case SIGWINCH:
292			if (rootshell && iflag)
293				action = S_CATCH;
294			break;
295#endif
296		}
297	}
298
299	t = &sigmode[signo];
300	if (*t == 0) {
301		/*
302		 * current setting unknown
303		 */
304		if (!getsigaction(signo, &sigact)) {
305			/*
306			 * Pretend it worked; maybe we should give a warning
307			 * here, but other shells don't. We don't alter
308			 * sigmode, so that we retry every time.
309			 */
310			return;
311		}
312		if (sigact == SIG_IGN) {
313			if (mflag && (signo == SIGTSTP ||
314			     signo == SIGTTIN || signo == SIGTTOU)) {
315				*t = S_IGN;	/* don't hard ignore these */
316			} else
317				*t = S_HARD_IGN;
318		} else {
319			*t = S_RESET;	/* force to be set */
320		}
321	}
322	if (*t == S_HARD_IGN || *t == action)
323		return;
324	switch (action) {
325		case S_DFL:	sigact = SIG_DFL;	break;
326		case S_CATCH:  	sigact = onsig;		break;
327		case S_IGN:	sigact = SIG_IGN;	break;
328	}
329	*t = action;
330	sa.sa_handler = sigact;
331	sa.sa_flags = 0;
332	sigemptyset(&sa.sa_mask);
333	sigaction(signo, &sa, NULL);
334}
335
336
337/*
338 * Return the current setting for sig w/o changing it.
339 */
340static int
341getsigaction(int signo, sig_t *sigact)
342{
343	struct sigaction sa;
344
345	if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
346		return 0;
347	*sigact = (sig_t) sa.sa_handler;
348	return 1;
349}
350
351
352/*
353 * Ignore a signal.
354 */
355void
356ignoresig(int signo)
357{
358
359	if (sigmode[signo] != S_IGN && sigmode[signo] != S_HARD_IGN) {
360		signal(signo, SIG_IGN);
361	}
362	sigmode[signo] = S_HARD_IGN;
363}
364
365
366#ifdef mkinit
367INCLUDE <signal.h>
368INCLUDE "trap.h"
369
370SHELLPROC {
371	char *sm;
372
373	clear_traps();
374	for (sm = sigmode ; sm < sigmode + NSIG ; sm++) {
375		if (*sm == S_IGN)
376			*sm = S_HARD_IGN;
377	}
378}
379#endif
380
381
382/*
383 * Signal handler.
384 */
385void
386onsig(int signo)
387{
388
389	if (signo == SIGINT && trap[SIGINT] == NULL) {
390		onint();
391		return;
392	}
393
394	if (signo != SIGCHLD || !ignore_sigchld)
395		gotsig[signo] = 1;
396	pendingsigs++;
397
398	/* If we are currently in a wait builtin, prepare to break it */
399	if ((signo == SIGINT || signo == SIGQUIT) && in_waitcmd != 0)
400		breakwaitcmd = 1;
401	/*
402	 * If a trap is set, not ignored and not the null command, we need
403	 * to make sure traps are executed even when a child blocks signals.
404	 */
405	if (Tflag &&
406	    trap[signo] != NULL &&
407	    ! (trap[signo][0] == '\0') &&
408	    ! (trap[signo][0] == ':' && trap[signo][1] == '\0'))
409		breakwaitcmd = 1;
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 */
422void
423dotrap(void)
424{
425	int i;
426	int savestatus;
427
428	in_dotrap++;
429	for (;;) {
430		for (i = 1; i < NSIG; i++) {
431			if (gotsig[i]) {
432				gotsig[i] = 0;
433				if (trap[i]) {
434					/*
435					 * Ignore SIGCHLD to avoid infinite
436					 * recursion if the trap action does
437					 * a fork.
438					 */
439					if (i == SIGCHLD)
440						ignore_sigchld++;
441					savestatus = exitstatus;
442					evalstring(trap[i], 0);
443					exitstatus = savestatus;
444					if (i == SIGCHLD)
445						ignore_sigchld--;
446				}
447				break;
448			}
449		}
450		if (i >= NSIG)
451			break;
452	}
453	in_dotrap--;
454	pendingsigs = 0;
455}
456
457
458/*
459 * Controls whether the shell is interactive or not.
460 */
461void
462setinteractive(int on)
463{
464	static int is_interactive = -1;
465
466	if (on == is_interactive)
467		return;
468	setsignal(SIGINT);
469	setsignal(SIGQUIT);
470	setsignal(SIGTERM);
471#ifndef NO_HISTORY
472	setsignal(SIGWINCH);
473#endif
474	is_interactive = on;
475}
476
477
478/*
479 * Called to exit the shell.
480 */
481void
482exitshell(int status)
483{
484	TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
485	exiting = 1;
486	exiting_exitstatus = status;
487	exitshell_savedstatus();
488}
489
490void
491exitshell_savedstatus(void)
492{
493	struct jmploc loc1, loc2;
494	char *p;
495
496	if (!exiting)
497		exiting_exitstatus = oexitstatus;
498	exitstatus = oexitstatus = exiting_exitstatus;
499	if (setjmp(loc1.loc)) {
500		goto l1;
501	}
502	if (setjmp(loc2.loc)) {
503		goto l2;
504	}
505	handler = &loc1;
506	if ((p = trap[0]) != NULL && *p != '\0') {
507		trap[0] = NULL;
508		evalstring(p, 0);
509	}
510l1:   handler = &loc2;			/* probably unnecessary */
511	flushall();
512#if JOBS
513	setjobctl(0);
514#endif
515l2:   _exit(exiting_exitstatus);
516}
517