Home | History | Annotate | Line # | Download | only in sh
trap.c revision 1.32
      1 /*	$NetBSD: trap.c,v 1.32 2005/07/11 02:37:05 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Kenneth Almquist.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)trap.c	8.5 (Berkeley) 6/5/95";
     39 #else
     40 __RCSID("$NetBSD: trap.c,v 1.32 2005/07/11 02:37:05 christos Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <signal.h>
     45 #include <unistd.h>
     46 #include <stdlib.h>
     47 
     48 #include "shell.h"
     49 #include "main.h"
     50 #include "nodes.h"	/* for other headers */
     51 #include "eval.h"
     52 #include "jobs.h"
     53 #include "show.h"
     54 #include "options.h"
     55 #include "syntax.h"
     56 #include "output.h"
     57 #include "memalloc.h"
     58 #include "error.h"
     59 #include "trap.h"
     60 #include "mystring.h"
     61 #include "var.h"
     62 
     63 
     64 /*
     65  * Sigmode records the current value of the signal handlers for the various
     66  * modes.  A value of zero means that the current handler is not known.
     67  * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
     68  */
     69 
     70 #define S_DFL 1			/* default signal handling (SIG_DFL) */
     71 #define S_CATCH 2		/* signal is caught */
     72 #define S_IGN 3			/* signal is ignored (SIG_IGN) */
     73 #define S_HARD_IGN 4		/* signal is ignored permenantly */
     74 #define S_RESET 5		/* temporary - to reset a hard ignored sig */
     75 
     76 
     77 char *trap[NSIG+1];		/* trap handler commands */
     78 MKINIT char sigmode[NSIG];	/* current value of signal */
     79 char gotsig[NSIG];		/* indicates specified signal received */
     80 int pendingsigs;		/* indicates some signal received */
     81 
     82 static int getsigaction(int, sig_t *);
     83 
     84 /*
     85  * return the signal number described by `p' (as a number or a name)
     86  * or -1 if it isn't one
     87  */
     88 
     89 static int
     90 signame_to_signum(const char *p)
     91 {
     92 	int i;
     93 
     94 	if (is_number(p))
     95 		return number(p);
     96 
     97 	if (strcasecmp(p, "exit") == 0 )
     98 		return 0;
     99 
    100 	if (strncasecmp(p, "sig", 3) == 0)
    101 		p += 3;
    102 
    103 	for (i = 0; i < NSIG; ++i)
    104 		if (strcasecmp (p, sys_signame[i]) == 0)
    105 			return i;
    106 	return -1;
    107 }
    108 
    109 /*
    110  * Print a list of valid signal names
    111  */
    112 static void
    113 printsignals(void)
    114 {
    115 	int n;
    116 
    117 	out1str("EXIT ");
    118 
    119 	for (n = 1; n < NSIG; n++) {
    120 		out1fmt("%s", sys_signame[n]);
    121 		if ((n == NSIG/2) ||  n == (NSIG - 1))
    122 			out1str("\n");
    123 		else
    124 			out1c(' ');
    125 	}
    126 }
    127 
    128 /*
    129  * The trap builtin.
    130  */
    131 
    132 int
    133 trapcmd(int argc, char **argv)
    134 {
    135 	char *action;
    136 	char **ap;
    137 	int signo;
    138 
    139 	if (argc <= 1) {
    140 		for (signo = 0 ; signo <= NSIG ; signo++)
    141 			if (trap[signo] != NULL) {
    142 				out1fmt("trap -- ");
    143 				print_quoted(trap[signo]);
    144 				out1fmt(" %s\n",
    145 				    (signo) ? sys_signame[signo] : "EXIT");
    146 			}
    147 		return 0;
    148 	}
    149 	ap = argv + 1;
    150 
    151 	action = NULL;
    152 
    153 	if (strcmp(*ap, "--") == 0)
    154 		if (*++ap == NULL)
    155 			return 0;
    156 
    157 	if (signame_to_signum(*ap) == -1) {
    158 		if ((*ap)[0] == '-') {
    159 			if ((*ap)[1] == '\0')
    160 				ap++;
    161 			else if ((*ap)[1] == 'l' && (*ap)[2] == '\0') {
    162 				printsignals();
    163 				return 0;
    164 			}
    165 			else
    166 				error("bad option %s\n", *ap);
    167 		}
    168 		else
    169 			action = *ap++;
    170 	}
    171 
    172 	while (*ap) {
    173 		if (is_number(*ap))
    174 			signo = number(*ap);
    175 		else
    176 			signo = signame_to_signum(*ap);
    177 
    178 		if (signo < 0 || signo > NSIG)
    179 			error("%s: bad trap", *ap);
    180 
    181 		INTOFF;
    182 		if (action)
    183 			action = savestr(action);
    184 
    185 		if (trap[signo])
    186 			ckfree(trap[signo]);
    187 
    188 		trap[signo] = action;
    189 
    190 		if (signo != 0)
    191 			setsignal(signo, 0);
    192 		INTON;
    193 		ap++;
    194 	}
    195 	return 0;
    196 }
    197 
    198 
    199 
    200 /*
    201  * Clear traps on a fork or vfork.
    202  * Takes one arg vfork, to tell it to not be destructive of
    203  * the parents variables.
    204  */
    205 
    206 void
    207 clear_traps(int vforked)
    208 {
    209 	char **tp;
    210 
    211 	for (tp = trap ; tp <= &trap[NSIG] ; tp++) {
    212 		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
    213 			INTOFF;
    214 			if (!vforked) {
    215 				ckfree(*tp);
    216 				*tp = NULL;
    217 			}
    218 			if (tp != &trap[0])
    219 				setsignal(tp - trap, vforked);
    220 			INTON;
    221 		}
    222 	}
    223 }
    224 
    225 
    226 
    227 /*
    228  * Set the signal handler for the specified signal.  The routine figures
    229  * out what it should be set to.
    230  */
    231 
    232 sig_t
    233 setsignal(int signo, int vforked)
    234 {
    235 	int action;
    236 	sig_t sigact = SIG_DFL, sig;
    237 	char *t, tsig;
    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 (rootshell && !vforked && action == S_DFL) {
    246 		switch (signo) {
    247 		case SIGINT:
    248 			if (iflag || minusc || sflag == 0)
    249 				action = S_CATCH;
    250 			break;
    251 		case SIGQUIT:
    252 #ifdef DEBUG
    253 			if (debug)
    254 				break;
    255 #endif
    256 			/* FALLTHROUGH */
    257 		case SIGTERM:
    258 			if (iflag)
    259 				action = S_IGN;
    260 			break;
    261 #if JOBS
    262 		case SIGTSTP:
    263 		case SIGTTOU:
    264 			if (mflag)
    265 				action = S_IGN;
    266 			break;
    267 #endif
    268 		}
    269 	}
    270 
    271 	t = &sigmode[signo - 1];
    272 	tsig = *t;
    273 	if (tsig == 0) {
    274 		/*
    275 		 * current setting unknown
    276 		 */
    277 		if (!getsigaction(signo, &sigact)) {
    278 			/*
    279 			 * Pretend it worked; maybe we should give a warning
    280 			 * here, but other shells don't. We don't alter
    281 			 * sigmode, so that we retry every time.
    282 			 */
    283 			return 0;
    284 		}
    285 		if (sigact == SIG_IGN) {
    286 			/*
    287 			 * When we set a trap handler we want it to work,
    288 			 * even when our parent called us ignoring the
    289 			 * signal. This is what other shells do, so we
    290 			 * do not set S_HARD_IGN here.
    291 			 */
    292 			tsig = S_IGN;
    293 		} else {
    294 			tsig = S_RESET;	/* force to be set */
    295 		}
    296 	}
    297 	if (tsig == S_HARD_IGN || tsig == action)
    298 		return 0;
    299 	switch (action) {
    300 		case S_DFL:	sigact = SIG_DFL;	break;
    301 		case S_CATCH:  	sigact = onsig;		break;
    302 		case S_IGN:	sigact = SIG_IGN;	break;
    303 	}
    304 	sig = signal(signo, sigact);
    305 	if (sig != SIG_ERR) {
    306 		sigset_t ss;
    307 		if (!vforked)
    308 			*t = action;
    309 		if (action == S_CATCH)
    310 			(void)siginterrupt(signo, 1);
    311 		/*
    312 		 * If our parent accidentally blocked signals for
    313 		 * us make sure we unblock them
    314 		 */
    315 		(void)sigemptyset(&ss);
    316 		(void)sigaddset(&ss, signo);
    317 		(void)sigprocmask(SIG_UNBLOCK, &ss, NULL);
    318 	}
    319 	return sig;
    320 }
    321 
    322 /*
    323  * Return the current setting for sig w/o changing it.
    324  */
    325 static int
    326 getsigaction(int signo, sig_t *sigact)
    327 {
    328 	struct sigaction sa;
    329 
    330 	if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
    331 		return 0;
    332 	*sigact = (sig_t) sa.sa_handler;
    333 	return 1;
    334 }
    335 
    336 /*
    337  * Ignore a signal.
    338  */
    339 
    340 void
    341 ignoresig(int signo, int vforked)
    342 {
    343 	if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
    344 		signal(signo, SIG_IGN);
    345 	}
    346 	if (!vforked)
    347 		sigmode[signo - 1] = S_HARD_IGN;
    348 }
    349 
    350 
    351 #ifdef mkinit
    352 INCLUDE <signal.h>
    353 INCLUDE "trap.h"
    354 
    355 SHELLPROC {
    356 	char *sm;
    357 
    358 	clear_traps(0);
    359 	for (sm = sigmode ; sm < sigmode + NSIG ; sm++) {
    360 		if (*sm == S_IGN)
    361 			*sm = S_HARD_IGN;
    362 	}
    363 }
    364 #endif
    365 
    366 
    367 
    368 /*
    369  * Signal handler.
    370  */
    371 
    372 void
    373 onsig(int signo)
    374 {
    375 	signal(signo, onsig);
    376 	if (signo == SIGINT && trap[SIGINT] == NULL) {
    377 		onint();
    378 		return;
    379 	}
    380 	gotsig[signo - 1] = 1;
    381 	pendingsigs++;
    382 }
    383 
    384 
    385 
    386 /*
    387  * Called to execute a trap.  Perhaps we should avoid entering new trap
    388  * handlers while we are executing a trap handler.
    389  */
    390 
    391 void
    392 dotrap(void)
    393 {
    394 	int i;
    395 	int savestatus;
    396 
    397 	for (;;) {
    398 		for (i = 1 ; ; i++) {
    399 			if (gotsig[i - 1])
    400 				break;
    401 			if (i >= NSIG)
    402 				goto done;
    403 		}
    404 		gotsig[i - 1] = 0;
    405 		savestatus=exitstatus;
    406 		evalstring(trap[i], 0);
    407 		exitstatus=savestatus;
    408 	}
    409 done:
    410 	pendingsigs = 0;
    411 }
    412 
    413 
    414 
    415 /*
    416  * Controls whether the shell is interactive or not.
    417  */
    418 
    419 
    420 void
    421 setinteractive(int on)
    422 {
    423 	static int is_interactive;
    424 
    425 	if (on == is_interactive)
    426 		return;
    427 	setsignal(SIGINT, 0);
    428 	setsignal(SIGQUIT, 0);
    429 	setsignal(SIGTERM, 0);
    430 	is_interactive = on;
    431 }
    432 
    433 
    434 
    435 /*
    436  * Called to exit the shell.
    437  */
    438 
    439 void
    440 exitshell(int status)
    441 {
    442 	struct jmploc loc1, loc2;
    443 	char *p;
    444 
    445 	TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
    446 	if (setjmp(loc1.loc)) {
    447 		goto l1;
    448 	}
    449 	if (setjmp(loc2.loc)) {
    450 		goto l2;
    451 	}
    452 	handler = &loc1;
    453 	if ((p = trap[0]) != NULL && *p != '\0') {
    454 		trap[0] = NULL;
    455 		evalstring(p, 0);
    456 	}
    457 l1:   handler = &loc2;			/* probably unnecessary */
    458 	flushall();
    459 #if JOBS
    460 	setjobctl(0);
    461 #endif
    462 l2:   _exit(status);
    463 	/* NOTREACHED */
    464 }
    465