trap.c revision 90111
165532Snectar/*-
265532Snectar * Copyright (c) 1991, 1993
31573Srgrimes *	The Regents of the University of California.  All rights reserved.
41573Srgrimes *
51573Srgrimes * This code is derived from software contributed to Berkeley by
61573Srgrimes * Kenneth Almquist.
71573Srgrimes *
81573Srgrimes * Redistribution and use in source and binary forms, with or without
91573Srgrimes * modification, are permitted provided that the following conditions
101573Srgrimes * are met:
111573Srgrimes * 1. Redistributions of source code must retain the above copyright
121573Srgrimes *    notice, this list of conditions and the following disclaimer.
131573Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141573Srgrimes *    notice, this list of conditions and the following disclaimer in the
151573Srgrimes *    documentation and/or other materials provided with the distribution.
161573Srgrimes * 3. All advertising materials mentioning features or use of this software
171573Srgrimes *    must display the following acknowledgement:
181573Srgrimes *	This product includes software developed by the University of
191573Srgrimes *	California, Berkeley and its contributors.
201573Srgrimes * 4. Neither the name of the University nor the names of its contributors
211573Srgrimes *    may be used to endorse or promote products derived from this software
221573Srgrimes *    without specific prior written permission.
231573Srgrimes *
241573Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
251573Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
261573Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
271573Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
281573Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
291573Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
301573Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31141580Sru * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
321573Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3365532Snectar * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
341573Srgrimes * SUCH DAMAGE.
3565532Snectar */
361573Srgrimes
371573Srgrimes#ifndef lint
381573Srgrimes#if 0
391573Srgrimesstatic char sccsid[] = "@(#)trap.c	8.5 (Berkeley) 6/5/95";
4065532Snectar#endif
4159460Sphantomstatic const char rcsid[] =
4259460Sphantom  "$FreeBSD: head/bin/sh/trap.c 90111 2002-02-02 06:50:57Z imp $";
431573Srgrimes#endif /* not lint */
4484306Sru
451573Srgrimes#include <signal.h>
461573Srgrimes#include <unistd.h>
471573Srgrimes#include <stdlib.h>
481573Srgrimes
491573Srgrimes#include "shell.h"
501573Srgrimes#include "main.h"
511573Srgrimes#include "nodes.h"	/* for other headers */
521573Srgrimes#include "eval.h"
531573Srgrimes#include "jobs.h"
541573Srgrimes#include "show.h"
5565532Snectar#include "options.h"
5665532Snectar#include "syntax.h"
5765532Snectar#include "output.h"
5865532Snectar#include "memalloc.h"
591573Srgrimes#include "error.h"
601573Srgrimes#include "trap.h"
611573Srgrimes#include "mystring.h"
621573Srgrimes
631573Srgrimes
6465532Snectar/*
651573Srgrimes * Sigmode records the current value of the signal handlers for the various
661573Srgrimes * modes.  A value of zero means that the current handler is not known.
671573Srgrimes * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
681573Srgrimes */
691573Srgrimes
701573Srgrimes#define S_DFL 1			/* default signal handling (SIG_DFL) */
711573Srgrimes#define S_CATCH 2		/* signal is caught */
721573Srgrimes#define S_IGN 3			/* signal is ignored (SIG_IGN) */
731573Srgrimes#define S_HARD_IGN 4		/* signal is ignored permanently */
741573Srgrimes#define S_RESET 5		/* temporary - to reset a hard ignored sig */
751573Srgrimes
761573Srgrimes
771573SrgrimesMKINIT char sigmode[NSIG];	/* current value of signal */
781573Srgrimesint pendingsigs;		/* indicates some signal received */
791573Srgrimesint in_dotrap;			/* do we execute in a trap handler? */
801573Srgrimesstatic char *volatile trap[NSIG];	/* trap handler commands */
811573Srgrimesstatic volatile sig_atomic_t gotsig[NSIG];
821573Srgrimes				/* indicates specified signal received */
831573Srgrimesstatic int ignore_sigchld;	/* Used while handling SIGCHLD traps. */
841573Srgrimes
8565532Snectarstatic int getsigaction(int, sig_t *);
861573Srgrimes
871573Srgrimes
881573Srgrimes/*
891573Srgrimes * Map a string to a signal number.
9067967Sasmodai */
911573Srgrimesstatic int
921573Srgrimessigstring_to_signum(char *sig)
931573Srgrimes{
941573Srgrimes
951573Srgrimes	if (is_number(sig)) {
9668959Ssheldonh		int signo;
9768959Ssheldonh
981573Srgrimes		signo = atoi(sig);
991573Srgrimes		return ((signo >= 0 && signo < NSIG) ? signo : (-1));
100	} else if (strcasecmp(sig, "exit") == 0) {
101		return (0);
102	} else {
103		int n;
104
105		if (strncasecmp(sig, "sig", 3) == 0)
106			sig += 3;
107		for (n = 1; n < NSIG; n++)
108			if (strcasecmp(sys_signame[n], sig) == 0)
109				return (n);
110	}
111	return (-1);
112}
113
114
115/*
116 * Print a list of valid signal names.
117 */
118static void
119printsignals(void)
120{
121	int n;
122
123	for (n = 1; n < NSIG; n++) {
124		out1fmt("%s", sys_signame[n]);
125		if (n == (NSIG / 2) || n == (NSIG - 1))
126			out1str("\n");
127		else
128			out1c(' ');
129	}
130}
131
132
133/*
134 * The trap builtin.
135 */
136int
137trapcmd(int argc, char **argv)
138{
139	char *action;
140	int signo;
141
142	if (argc <= 1) {
143		for (signo = 0 ; signo < NSIG ; signo++) {
144			if (trap[signo] != NULL)
145				out1fmt("trap -- '%s' %s\n", trap[signo],
146					(signo) ? sys_signame[signo] : "exit");
147		}
148		return 0;
149	}
150	action = NULL;
151	if (*++argv && strcmp(*argv, "--") == 0)
152		argv++;
153	if (*argv && sigstring_to_signum(*argv) == -1) {
154		if ((*argv)[0] != '-') {
155			action = *argv;
156			argv++;
157		} else if ((*argv)[1] == '\0') {
158			argv++;
159		} else if ((*argv)[1] == 'l' && (*argv)[2] == '\0') {
160			printsignals();
161			return 0;
162		} else {
163			error("bad option %s", *argv);
164		}
165	}
166	while (*argv) {
167		if ((signo = sigstring_to_signum(*argv)) == -1)
168			error("bad signal %s", *argv);
169		INTOFF;
170		if (action)
171			action = savestr(action);
172		if (trap[signo])
173			ckfree(trap[signo]);
174		trap[signo] = action;
175		if (signo != 0)
176			setsignal(signo);
177		INTON;
178		argv++;
179	}
180	return 0;
181}
182
183
184/*
185 * Clear traps on a fork.
186 */
187void
188clear_traps(void)
189{
190	char *volatile *tp;
191
192	for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
193		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
194			INTOFF;
195			ckfree(*tp);
196			*tp = NULL;
197			if (tp != &trap[0])
198				setsignal(tp - trap);
199			INTON;
200		}
201	}
202}
203
204
205/*
206 * Set the signal handler for the specified signal.  The routine figures
207 * out what it should be set to.
208 */
209void
210setsignal(int signo)
211{
212	int action;
213	sig_t sig, sigact = SIG_DFL;
214	char *t;
215
216	if ((t = trap[signo]) == NULL)
217		action = S_DFL;
218	else if (*t != '\0')
219		action = S_CATCH;
220	else
221		action = S_IGN;
222	if (action == S_DFL) {
223		switch (signo) {
224		case SIGINT:
225			action = S_CATCH;
226			break;
227		case SIGQUIT:
228#ifdef DEBUG
229			{
230			extern int debug;
231
232			if (debug)
233				break;
234			}
235#endif
236			action = S_CATCH;
237			break;
238		case SIGTERM:
239			if (rootshell && iflag)
240				action = S_IGN;
241			break;
242#if JOBS
243		case SIGTSTP:
244		case SIGTTOU:
245			if (rootshell && mflag)
246				action = S_IGN;
247			break;
248#endif
249		}
250	}
251
252	t = &sigmode[signo];
253	if (*t == 0) {
254		/*
255		 * current setting unknown
256		 */
257		if (!getsigaction(signo, &sigact)) {
258			/*
259			 * Pretend it worked; maybe we should give a warning
260			 * here, but other shells don't. We don't alter
261			 * sigmode, so that we retry every time.
262			 */
263			return;
264		}
265		if (sigact == SIG_IGN) {
266			if (mflag && (signo == SIGTSTP ||
267			     signo == SIGTTIN || signo == SIGTTOU)) {
268				*t = S_IGN;	/* don't hard ignore these */
269			} else
270				*t = S_HARD_IGN;
271		} else {
272			*t = S_RESET;	/* force to be set */
273		}
274	}
275	if (*t == S_HARD_IGN || *t == action)
276		return;
277	switch (action) {
278		case S_DFL:	sigact = SIG_DFL;	break;
279		case S_CATCH:  	sigact = onsig;		break;
280		case S_IGN:	sigact = SIG_IGN;	break;
281	}
282	*t = action;
283	sig = signal(signo, sigact);
284#ifdef BSD
285	if (sig != SIG_ERR && action == S_CATCH)
286		siginterrupt(signo, 1);
287#endif
288}
289
290
291/*
292 * Return the current setting for sig w/o changing it.
293 */
294static int
295getsigaction(int signo, sig_t *sigact)
296{
297	struct sigaction sa;
298
299	if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
300		return 0;
301	*sigact = (sig_t) sa.sa_handler;
302	return 1;
303}
304
305
306/*
307 * Ignore a signal.
308 */
309void
310ignoresig(int signo)
311{
312
313	if (sigmode[signo] != S_IGN && sigmode[signo] != S_HARD_IGN) {
314		signal(signo, SIG_IGN);
315	}
316	sigmode[signo] = S_HARD_IGN;
317}
318
319
320#ifdef mkinit
321INCLUDE <signal.h>
322INCLUDE "trap.h"
323
324SHELLPROC {
325	char *sm;
326
327	clear_traps();
328	for (sm = sigmode ; sm < sigmode + NSIG ; sm++) {
329		if (*sm == S_IGN)
330			*sm = S_HARD_IGN;
331	}
332}
333#endif
334
335
336/*
337 * Signal handler.
338 */
339void
340onsig(int signo)
341{
342
343#ifndef BSD
344	signal(signo, onsig);
345#endif
346	if (signo == SIGINT && trap[SIGINT] == NULL) {
347		onint();
348		return;
349	}
350
351	if (signo != SIGCHLD || !ignore_sigchld)
352		gotsig[signo] = 1;
353	pendingsigs++;
354
355	/* If we are currently in a wait builtin, prepare to break it */
356	if ((signo == SIGINT || signo == SIGQUIT) && in_waitcmd != 0)
357		breakwaitcmd = 1;
358	/*
359	 * If a trap is set, not ignored and not the null command, we need
360	 * to make sure traps are executed even when a child blocks signals.
361	 */
362	if (Tflag &&
363	    trap[signo] != NULL &&
364	    ! trap[signo][0] == '\0' &&
365	    ! (trap[signo][0] == ':' && trap[signo][1] == '\0'))
366		breakwaitcmd = 1;
367}
368
369
370/*
371 * Called to execute a trap.  Perhaps we should avoid entering new trap
372 * handlers while we are executing a trap handler.
373 */
374void
375dotrap(void)
376{
377	int i;
378	int savestatus;
379
380	in_dotrap++;
381	for (;;) {
382		for (i = 1; i < NSIG; i++) {
383			if (gotsig[i]) {
384				gotsig[i] = 0;
385				if (trap[i]) {
386					/*
387					 * Ignore SIGCHLD to avoid infinite recursion
388					 * if the trap action does a fork.
389					 */
390					if (i == SIGCHLD)
391						ignore_sigchld++;
392					savestatus = exitstatus;
393					evalstring(trap[i]);
394					exitstatus = savestatus;
395					if (i == SIGCHLD)
396						ignore_sigchld--;
397				}
398				break;
399			}
400		}
401		if (i >= NSIG)
402			break;
403	}
404	in_dotrap--;
405	pendingsigs = 0;
406}
407
408
409/*
410 * Controls whether the shell is interactive or not.
411 */
412void
413setinteractive(int on)
414{
415	static int is_interactive = -1;
416
417	if (on == is_interactive)
418		return;
419	setsignal(SIGINT);
420	setsignal(SIGQUIT);
421	setsignal(SIGTERM);
422	is_interactive = on;
423}
424
425
426/*
427 * Called to exit the shell.
428 */
429void
430exitshell(int status)
431{
432	struct jmploc loc1, loc2;
433	char *p;
434
435	TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
436	if (setjmp(loc1.loc)) {
437		goto l1;
438	}
439	if (setjmp(loc2.loc)) {
440		goto l2;
441	}
442	handler = &loc1;
443	if ((p = trap[0]) != NULL && *p != '\0') {
444		trap[0] = NULL;
445		evalstring(p);
446	}
447l1:   handler = &loc2;			/* probably unnecessary */
448	flushall();
449#if JOBS
450	setjobctl(0);
451#endif
452l2:   _exit(status);
453}
454