trap.c revision 217461
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 217461 2011-01-15 21:09:00Z 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 > 71 || 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	int i;
157
158	while ((i = nextopt("l")) != '\0') {
159		switch (i) {
160		case 'l':
161			printsignals();
162			return (0);
163		}
164	}
165	argv = argptr;
166
167	if (*argv == NULL) {
168		for (signo = 0 ; signo < sys_nsig ; signo++) {
169			if (signo < NSIG && trap[signo] != NULL) {
170				out1str("trap -- ");
171				out1qstr(trap[signo]);
172				if (signo == 0) {
173					out1str(" exit\n");
174				} else if (sys_signame[signo]) {
175					out1fmt(" %s\n", sys_signame[signo]);
176				} else {
177					out1fmt(" %d\n", signo);
178				}
179			}
180		}
181		return 0;
182	}
183	action = NULL;
184	if (*argv && sigstring_to_signum(*argv) == -1) {
185		if (strcmp(*argv, "-") == 0)
186			argv++;
187		else {
188			action = *argv;
189			argv++;
190		}
191	}
192	while (*argv) {
193		if ((signo = sigstring_to_signum(*argv)) == -1) {
194			warning("bad signal %s", *argv);
195			errors = 1;
196		}
197		INTOFF;
198		if (action)
199			action = savestr(action);
200		if (trap[signo])
201			ckfree(trap[signo]);
202		trap[signo] = action;
203		if (signo != 0)
204			setsignal(signo);
205		INTON;
206		argv++;
207	}
208	return errors;
209}
210
211
212/*
213 * Clear traps on a fork.
214 */
215void
216clear_traps(void)
217{
218	char *volatile *tp;
219
220	for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
221		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
222			INTOFF;
223			ckfree(*tp);
224			*tp = NULL;
225			if (tp != &trap[0])
226				setsignal(tp - trap);
227			INTON;
228		}
229	}
230}
231
232
233/*
234 * Check if we have any traps enabled.
235 */
236int
237have_traps(void)
238{
239	char *volatile *tp;
240
241	for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
242		if (*tp && **tp)	/* trap not NULL or SIG_IGN */
243			return 1;
244	}
245	return 0;
246}
247
248/*
249 * Set the signal handler for the specified signal.  The routine figures
250 * out what it should be set to.
251 */
252void
253setsignal(int signo)
254{
255	int action;
256	sig_t sigact = SIG_DFL;
257	struct sigaction sa;
258	char *t;
259
260	if ((t = trap[signo]) == NULL)
261		action = S_DFL;
262	else if (*t != '\0')
263		action = S_CATCH;
264	else
265		action = S_IGN;
266	if (action == S_DFL) {
267		switch (signo) {
268		case SIGINT:
269			action = S_CATCH;
270			break;
271		case SIGQUIT:
272#ifdef DEBUG
273			{
274			extern int debug;
275
276			if (debug)
277				break;
278			}
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#ifndef NO_HISTORY
294		case SIGWINCH:
295			if (rootshell && iflag)
296				action = S_CATCH;
297			break;
298#endif
299		}
300	}
301
302	t = &sigmode[signo];
303	if (*t == 0) {
304		/*
305		 * current setting unknown
306		 */
307		if (!getsigaction(signo, &sigact)) {
308			/*
309			 * Pretend it worked; maybe we should give a warning
310			 * here, but other shells don't. We don't alter
311			 * sigmode, so that we retry every time.
312			 */
313			return;
314		}
315		if (sigact == SIG_IGN) {
316			if (mflag && (signo == SIGTSTP ||
317			     signo == SIGTTIN || signo == SIGTTOU)) {
318				*t = S_IGN;	/* don't hard ignore these */
319			} else
320				*t = S_HARD_IGN;
321		} else {
322			*t = S_RESET;	/* force to be set */
323		}
324	}
325	if (*t == S_HARD_IGN || *t == action)
326		return;
327	switch (action) {
328		case S_DFL:	sigact = SIG_DFL;	break;
329		case S_CATCH:  	sigact = onsig;		break;
330		case S_IGN:	sigact = SIG_IGN;	break;
331	}
332	*t = action;
333	sa.sa_handler = sigact;
334	sa.sa_flags = 0;
335	sigemptyset(&sa.sa_mask);
336	sigaction(signo, &sa, NULL);
337}
338
339
340/*
341 * Return the current setting for sig w/o changing it.
342 */
343static int
344getsigaction(int signo, sig_t *sigact)
345{
346	struct sigaction sa;
347
348	if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
349		return 0;
350	*sigact = (sig_t) sa.sa_handler;
351	return 1;
352}
353
354
355/*
356 * Ignore a signal.
357 */
358void
359ignoresig(int signo)
360{
361
362	if (sigmode[signo] != S_IGN && sigmode[signo] != S_HARD_IGN) {
363		signal(signo, SIG_IGN);
364	}
365	sigmode[signo] = S_HARD_IGN;
366}
367
368
369#ifdef mkinit
370INCLUDE <signal.h>
371INCLUDE "trap.h"
372
373SHELLPROC {
374	char *sm;
375
376	clear_traps();
377	for (sm = sigmode ; sm < sigmode + NSIG ; sm++) {
378		if (*sm == S_IGN)
379			*sm = S_HARD_IGN;
380	}
381}
382#endif
383
384
385/*
386 * Signal handler.
387 */
388void
389onsig(int signo)
390{
391
392	if (signo == SIGINT && trap[SIGINT] == NULL) {
393		onint();
394		return;
395	}
396
397	if (signo != SIGCHLD || !ignore_sigchld)
398		gotsig[signo] = 1;
399	pendingsigs++;
400
401	/* If we are currently in a wait builtin, prepare to break it */
402	if ((signo == SIGINT || signo == SIGQUIT) && in_waitcmd != 0)
403		breakwaitcmd = 1;
404	/*
405	 * If a trap is set, not ignored and not the null command, we need
406	 * to make sure traps are executed even when a child blocks signals.
407	 */
408	if (Tflag &&
409	    trap[signo] != NULL &&
410	    ! (trap[signo][0] == '\0') &&
411	    ! (trap[signo][0] == ':' && trap[signo][1] == '\0'))
412		breakwaitcmd = 1;
413
414#ifndef NO_HISTORY
415	if (signo == SIGWINCH)
416		gotwinch = 1;
417#endif
418}
419
420
421/*
422 * Called to execute a trap.  Perhaps we should avoid entering new trap
423 * handlers while we are executing a trap handler.
424 */
425void
426dotrap(void)
427{
428	int i;
429	int savestatus;
430
431	in_dotrap++;
432	for (;;) {
433		for (i = 1; i < NSIG; i++) {
434			if (gotsig[i]) {
435				gotsig[i] = 0;
436				if (trap[i]) {
437					/*
438					 * Ignore SIGCHLD to avoid infinite
439					 * recursion if the trap action does
440					 * a fork.
441					 */
442					if (i == SIGCHLD)
443						ignore_sigchld++;
444					savestatus = exitstatus;
445					evalstring(trap[i], 0);
446					exitstatus = savestatus;
447					if (i == SIGCHLD)
448						ignore_sigchld--;
449				}
450				break;
451			}
452		}
453		if (i >= NSIG)
454			break;
455	}
456	in_dotrap--;
457	pendingsigs = 0;
458}
459
460
461/*
462 * Controls whether the shell is interactive or not.
463 */
464void
465setinteractive(int on)
466{
467	static int is_interactive = -1;
468
469	if (on == is_interactive)
470		return;
471	setsignal(SIGINT);
472	setsignal(SIGQUIT);
473	setsignal(SIGTERM);
474#ifndef NO_HISTORY
475	setsignal(SIGWINCH);
476#endif
477	is_interactive = on;
478}
479
480
481/*
482 * Called to exit the shell.
483 */
484void
485exitshell(int status)
486{
487	TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
488	exiting = 1;
489	exiting_exitstatus = status;
490	exitshell_savedstatus();
491}
492
493void
494exitshell_savedstatus(void)
495{
496	struct jmploc loc1, loc2;
497	char *p;
498
499	if (!exiting)
500		exiting_exitstatus = oexitstatus;
501	exitstatus = oexitstatus = exiting_exitstatus;
502	if (setjmp(loc1.loc)) {
503		goto l1;
504	}
505	if (setjmp(loc2.loc)) {
506		goto l2;
507	}
508	handler = &loc1;
509	if ((p = trap[0]) != NULL && *p != '\0') {
510		trap[0] = NULL;
511		evalstring(p, 0);
512	}
513l1:   handler = &loc2;			/* probably unnecessary */
514	flushall();
515#if JOBS
516	setjobctl(0);
517#endif
518l2:   _exit(exiting_exitstatus);
519}
520