trap.c revision 125727
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
39static char sccsid[] = "@(#)trap.c	8.5 (Berkeley) 6/5/95";
40#endif
41#endif /* not lint */
42#include <sys/cdefs.h>
43__FBSDID("$FreeBSD: head/bin/sh/trap.c 125727 2004-02-12 05:03:37Z njl $");
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
78MKINIT char sigmode[NSIG];	/* current value of signal */
79int pendingsigs;		/* indicates some signal received */
80int in_dotrap;			/* do we execute in a trap handler? */
81static char *volatile trap[NSIG];	/* trap handler commands */
82static volatile sig_atomic_t gotsig[NSIG];
83				/* indicates specified signal received */
84static int ignore_sigchld;	/* Used while handling SIGCHLD traps. */
85volatile sig_atomic_t gotwinch;
86
87static 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 */
95static int
96sigstring_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] && 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
156	if (argc <= 1) {
157		for (signo = 0 ; signo < sys_nsig ; signo++) {
158			if (signo < NSIG && trap[signo] != NULL) {
159				if (signo == 0) {
160					out1fmt("trap -- '%s' %s\n",
161					    trap[signo], "exit");
162				} else if (sys_signame[signo]) {
163					out1fmt("trap -- '%s' %s\n",
164					    trap[signo], sys_signame[signo]);
165				} else {
166					out1fmt("trap -- '%s' %d\n",
167					    trap[signo], 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			error("bad signal %s", *argv);
192		INTOFF;
193		if (action)
194			action = savestr(action);
195		if (trap[signo])
196			ckfree(trap[signo]);
197		trap[signo] = action;
198		if (signo != 0)
199			setsignal(signo);
200		INTON;
201		argv++;
202	}
203	return 0;
204}
205
206
207/*
208 * Clear traps on a fork.
209 */
210void
211clear_traps(void)
212{
213	char *volatile *tp;
214
215	for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
216		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
217			INTOFF;
218			ckfree(*tp);
219			*tp = NULL;
220			if (tp != &trap[0])
221				setsignal(tp - trap);
222			INTON;
223		}
224	}
225}
226
227
228/*
229 * Set the signal handler for the specified signal.  The routine figures
230 * out what it should be set to.
231 */
232void
233setsignal(int signo)
234{
235	int action;
236	sig_t sig, sigact = SIG_DFL;
237	char *t;
238
239	if ((t = trap[signo]) == NULL)
240		action = S_DFL;
241	else if (*t != '\0')
242		action = S_CATCH;
243	else
244		action = S_IGN;
245	if (action == S_DFL) {
246		switch (signo) {
247		case SIGINT:
248			action = S_CATCH;
249			break;
250		case SIGQUIT:
251#ifdef DEBUG
252			{
253			extern int debug;
254
255			if (debug)
256				break;
257			}
258#endif
259			action = S_CATCH;
260			break;
261		case SIGTERM:
262			if (rootshell && iflag)
263				action = S_IGN;
264			break;
265#if JOBS
266		case SIGTSTP:
267		case SIGTTOU:
268			if (rootshell && mflag)
269				action = S_IGN;
270			break;
271#endif
272#ifndef NO_HISTORY
273		case SIGWINCH:
274			if (rootshell && iflag)
275				action = S_CATCH;
276			break;
277#endif
278		}
279	}
280
281	t = &sigmode[signo];
282	if (*t == 0) {
283		/*
284		 * current setting unknown
285		 */
286		if (!getsigaction(signo, &sigact)) {
287			/*
288			 * Pretend it worked; maybe we should give a warning
289			 * here, but other shells don't. We don't alter
290			 * sigmode, so that we retry every time.
291			 */
292			return;
293		}
294		if (sigact == SIG_IGN) {
295			if (mflag && (signo == SIGTSTP ||
296			     signo == SIGTTIN || signo == SIGTTOU)) {
297				*t = S_IGN;	/* don't hard ignore these */
298			} else
299				*t = S_HARD_IGN;
300		} else {
301			*t = S_RESET;	/* force to be set */
302		}
303	}
304	if (*t == S_HARD_IGN || *t == action)
305		return;
306	switch (action) {
307		case S_DFL:	sigact = SIG_DFL;	break;
308		case S_CATCH:  	sigact = onsig;		break;
309		case S_IGN:	sigact = SIG_IGN;	break;
310	}
311	*t = action;
312	sig = signal(signo, sigact);
313	if (sig != SIG_ERR && action == S_CATCH)
314		siginterrupt(signo, 1);
315}
316
317
318/*
319 * Return the current setting for sig w/o changing it.
320 */
321static int
322getsigaction(int signo, sig_t *sigact)
323{
324	struct sigaction sa;
325
326	if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
327		return 0;
328	*sigact = (sig_t) sa.sa_handler;
329	return 1;
330}
331
332
333/*
334 * Ignore a signal.
335 */
336void
337ignoresig(int signo)
338{
339
340	if (sigmode[signo] != S_IGN && sigmode[signo] != S_HARD_IGN) {
341		signal(signo, SIG_IGN);
342	}
343	sigmode[signo] = S_HARD_IGN;
344}
345
346
347#ifdef mkinit
348INCLUDE <signal.h>
349INCLUDE "trap.h"
350
351SHELLPROC {
352	char *sm;
353
354	clear_traps();
355	for (sm = sigmode ; sm < sigmode + NSIG ; sm++) {
356		if (*sm == S_IGN)
357			*sm = S_HARD_IGN;
358	}
359}
360#endif
361
362
363/*
364 * Signal handler.
365 */
366void
367onsig(int signo)
368{
369
370	if (signo == SIGINT && trap[SIGINT] == NULL) {
371		onint();
372		return;
373	}
374
375	if (signo != SIGCHLD || !ignore_sigchld)
376		gotsig[signo] = 1;
377	pendingsigs++;
378
379	/* If we are currently in a wait builtin, prepare to break it */
380	if ((signo == SIGINT || signo == SIGQUIT) && in_waitcmd != 0)
381		breakwaitcmd = 1;
382	/*
383	 * If a trap is set, not ignored and not the null command, we need
384	 * to make sure traps are executed even when a child blocks signals.
385	 */
386	if (Tflag &&
387	    trap[signo] != NULL &&
388	    ! trap[signo][0] == '\0' &&
389	    ! (trap[signo][0] == ':' && trap[signo][1] == '\0'))
390		breakwaitcmd = 1;
391
392#ifndef NO_HISTORY
393	if (signo == SIGWINCH)
394		gotwinch = 1;
395#endif
396}
397
398
399/*
400 * Called to execute a trap.  Perhaps we should avoid entering new trap
401 * handlers while we are executing a trap handler.
402 */
403void
404dotrap(void)
405{
406	int i;
407	int savestatus;
408
409	in_dotrap++;
410	for (;;) {
411		for (i = 1; i < NSIG; i++) {
412			if (gotsig[i]) {
413				gotsig[i] = 0;
414				if (trap[i]) {
415					/*
416					 * Ignore SIGCHLD to avoid infinite recursion
417					 * if the trap action does a fork.
418					 */
419					if (i == SIGCHLD)
420						ignore_sigchld++;
421					savestatus = exitstatus;
422					evalstring(trap[i]);
423					exitstatus = savestatus;
424					if (i == SIGCHLD)
425						ignore_sigchld--;
426				}
427				break;
428			}
429		}
430		if (i >= NSIG)
431			break;
432	}
433	in_dotrap--;
434	pendingsigs = 0;
435}
436
437
438/*
439 * Controls whether the shell is interactive or not.
440 */
441void
442setinteractive(int on)
443{
444	static int is_interactive = -1;
445
446	if (on == is_interactive)
447		return;
448	setsignal(SIGINT);
449	setsignal(SIGQUIT);
450	setsignal(SIGTERM);
451#ifndef NO_HISTORY
452	setsignal(SIGWINCH);
453#endif
454	is_interactive = on;
455}
456
457
458/*
459 * Called to exit the shell.
460 */
461void
462exitshell(int status)
463{
464	struct jmploc loc1, loc2;
465	char *p;
466
467	TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
468	if (setjmp(loc1.loc)) {
469		goto l1;
470	}
471	if (setjmp(loc2.loc)) {
472		goto l2;
473	}
474	handler = &loc1;
475	if ((p = trap[0]) != NULL && *p != '\0') {
476		trap[0] = NULL;
477		evalstring(p);
478	}
479l1:   handler = &loc2;			/* probably unnecessary */
480	flushall();
481#if JOBS
482	setjobctl(0);
483#endif
484l2:   _exit(status);
485}
486