trap.c revision 281718
1323124Sdes/*-
257429Smarkm * Copyright (c) 1991, 1993
357429Smarkm *	The Regents of the University of California.  All rights reserved.
457429Smarkm *
557429Smarkm * This code is derived from software contributed to Berkeley by
657429Smarkm * Kenneth Almquist.
757429Smarkm *
857429Smarkm * Redistribution and use in source and binary forms, with or without
960573Skris * modification, are permitted provided that the following conditions
1065668Skris * are met:
1165668Skris * 1. Redistributions of source code must retain the above copyright
1265668Skris *    notice, this list of conditions and the following disclaimer.
1365668Skris * 2. Redistributions in binary form must reproduce the above copyright
1465668Skris *    notice, this list of conditions and the following disclaimer in the
1557429Smarkm *    documentation and/or other materials provided with the distribution.
1657429Smarkm * 4. Neither the name of the University nor the names of its contributors
1757429Smarkm *    may be used to endorse or promote products derived from this software
1857429Smarkm *    without specific prior written permission.
19162852Sdes *
20162852Sdes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21162852Sdes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22162852Sdes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23162852Sdes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24162852Sdes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25162852Sdes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26162852Sdes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27162852Sdes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28162852Sdes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29181111Sdes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30181111Sdes * SUCH DAMAGE.
31162852Sdes */
3257429Smarkm
3357429Smarkm#ifndef lint
3476259Sgreen#if 0
3576259Sgreenstatic char sccsid[] = "@(#)trap.c	8.5 (Berkeley) 6/5/95";
36295367Sdes#endif
37323124Sdes#endif /* not lint */
38323124Sdes#include <sys/cdefs.h>
3957429Smarkm__FBSDID("$FreeBSD: head/bin/sh/trap.c 281718 2015-04-18 23:49:57Z bdrewery $");
4076259Sgreen
41323124Sdes#include <signal.h>
42162852Sdes#include <unistd.h>
4376259Sgreen#include <stdlib.h>
4457429Smarkm
4576259Sgreen#include "shell.h"
4676259Sgreen#include "main.h"
4798675Sdes#include "nodes.h"	/* for other headers */
4876259Sgreen#include "eval.h"
4957429Smarkm#include "jobs.h"
5057429Smarkm#include "show.h"
5157429Smarkm#include "options.h"
5257429Smarkm#include "syntax.h"
5357429Smarkm#include "output.h"
5457429Smarkm#include "memalloc.h"
5592555Sdes#include "error.h"
5657429Smarkm#include "trap.h"
5757429Smarkm#include "mystring.h"
5857429Smarkm#include "builtins.h"
5957429Smarkm#include "myhistedit.h"
6057429Smarkm
61295367Sdes
62295367Sdes/*
63181111Sdes * Sigmode records the current value of the signal handlers for the various
64181111Sdes * modes.  A value of zero means that the current handler is not known.
6557429Smarkm * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
6657429Smarkm */
67181111Sdes
6857429Smarkm#define S_DFL 1			/* default signal handling (SIG_DFL) */
69181111Sdes#define S_CATCH 2		/* signal is caught */
70181111Sdes#define S_IGN 3			/* signal is ignored (SIG_IGN) */
71181111Sdes#define S_HARD_IGN 4		/* signal is ignored permanently */
72181111Sdes#define S_RESET 5		/* temporary - to reset a hard ignored sig */
73181111Sdes
74181111Sdes
75181111Sdesstatic char sigmode[NSIG];	/* current value of signal */
76181111Sdesvolatile sig_atomic_t pendingsig;	/* indicates some signal received */
77181111Sdesvolatile sig_atomic_t pendingsig_waitcmd;	/* indicates wait builtin should be interrupted */
78181111Sdesstatic int in_dotrap;			/* do we execute in a trap handler? */
79181111Sdesstatic char *volatile trap[NSIG];	/* trap handler commands */
80181111Sdesstatic volatile sig_atomic_t gotsig[NSIG];
81181111Sdes				/* indicates specified signal received */
82181111Sdesstatic int ignore_sigchld;	/* Used while handling SIGCHLD traps. */
83181111Sdesstatic int last_trapsig;
8457429Smarkm
85295367Sdesstatic int exiting;		/* exitshell() has been called */
86295367Sdesstatic int exiting_exitstatus;	/* value passed to exitshell() */
87295367Sdes
8857429Smarkmstatic int getsigaction(int, sig_t *);
8957429Smarkm
9057429Smarkm
9157429Smarkm/*
9257429Smarkm * Map a string to a signal number.
9357429Smarkm *
9457429Smarkm * Note: the signal number may exceed NSIG.
9557429Smarkm */
9657429Smarkmstatic int
9757429Smarkmsigstring_to_signum(char *sig)
9857429Smarkm{
9957429Smarkm
10057429Smarkm	if (is_number(sig)) {
10157429Smarkm		int signo;
10257429Smarkm
10357429Smarkm		signo = atoi(sig);
10457429Smarkm		return ((signo >= 0 && signo < NSIG) ? signo : (-1));
10557429Smarkm	} else if (strcasecmp(sig, "EXIT") == 0) {
106124208Sdes		return (0);
107124208Sdes	} else {
10857429Smarkm		int n;
10998675Sdes
11057429Smarkm		if (strncasecmp(sig, "SIG", 3) == 0)
11157429Smarkm			sig += 3;
11257429Smarkm		for (n = 1; n < sys_nsig; n++)
11357429Smarkm			if (sys_signame[n] &&
11457429Smarkm			    strcasecmp(sys_signame[n], sig) == 0)
11557429Smarkm				return (n);
11657429Smarkm	}
11757429Smarkm	return (-1);
11857429Smarkm}
11998675Sdes
12057429Smarkm
12157429Smarkm/*
12257429Smarkm * Print a list of valid signal names.
12357429Smarkm */
12457429Smarkmstatic void
12557429Smarkmprintsignals(void)
12657429Smarkm{
12757429Smarkm	int n, outlen;
12857429Smarkm
12957429Smarkm	outlen = 0;
13057429Smarkm	for (n = 1; n < sys_nsig; n++) {
13157429Smarkm		if (sys_signame[n]) {
13257429Smarkm			out1fmt("%s", sys_signame[n]);
13357429Smarkm			outlen += strlen(sys_signame[n]);
13457429Smarkm		} else {
13557429Smarkm			out1fmt("%d", n);
13657429Smarkm			outlen += 3;	/* good enough */
13757429Smarkm		}
13857429Smarkm		++outlen;
13957429Smarkm		if (outlen > 71 || n == sys_nsig - 1) {
14057429Smarkm			out1str("\n");
14157429Smarkm			outlen = 0;
14257429Smarkm		} else {
14357429Smarkm			out1c(' ');
14457429Smarkm		}
14557429Smarkm	}
146295367Sdes}
147295367Sdes
14857429Smarkm
14957429Smarkm/*
15057429Smarkm * The trap builtin.
15157429Smarkm */
15257429Smarkmint
15357429Smarkmtrapcmd(int argc __unused, char **argv)
15457429Smarkm{
155295367Sdes	char *action;
156295367Sdes	int signo;
15757429Smarkm	int errors = 0;
15857429Smarkm	int i;
15957429Smarkm
16057429Smarkm	while ((i = nextopt("l")) != '\0') {
16157429Smarkm		switch (i) {
16257429Smarkm		case 'l':
16357429Smarkm			printsignals();
16457429Smarkm			return (0);
16557429Smarkm		}
16657429Smarkm	}
16757429Smarkm	argv = argptr;
16857429Smarkm
16957429Smarkm	if (*argv == NULL) {
17057429Smarkm		for (signo = 0 ; signo < sys_nsig ; signo++) {
17198675Sdes			if (signo < NSIG && trap[signo] != NULL) {
172149749Sdes				out1str("trap -- ");
17357429Smarkm				out1qstr(trap[signo]);
17457429Smarkm				if (signo == 0) {
17557429Smarkm					out1str(" EXIT\n");
17657429Smarkm				} else if (sys_signame[signo]) {
17757429Smarkm					out1fmt(" %s\n", sys_signame[signo]);
17857429Smarkm				} else {
17957429Smarkm					out1fmt(" %d\n", signo);
18057429Smarkm				}
18157429Smarkm			}
18257429Smarkm		}
18357429Smarkm		return 0;
18457429Smarkm	}
18557429Smarkm	action = NULL;
18657429Smarkm	if (*argv && !is_number(*argv)) {
18757429Smarkm		if (strcmp(*argv, "-") == 0)
18857429Smarkm			argv++;
18957429Smarkm		else {
19060573Skris			action = *argv;
19157429Smarkm			argv++;
19257429Smarkm		}
193323124Sdes	}
19476259Sgreen	for (; *argv; argv++) {
19576259Sgreen		if ((signo = sigstring_to_signum(*argv)) == -1) {
196323124Sdes			warning("bad signal %s", *argv);
197323124Sdes			errors = 1;
19898675Sdes			continue;
19976259Sgreen		}
20076259Sgreen		INTOFF;
20198675Sdes		if (action)
20298675Sdes			action = savestr(action);
20376259Sgreen		if (trap[signo])
20476259Sgreen			ckfree(trap[signo]);
20557429Smarkm		trap[signo] = action;
20657429Smarkm		if (signo != 0)
20757429Smarkm			setsignal(signo);
20876259Sgreen		INTON;
20957429Smarkm	}
21076259Sgreen	return errors;
21176259Sgreen}
21276259Sgreen
21357429Smarkm
21476259Sgreen/*
21557429Smarkm * Clear traps on a fork.
216295367Sdes */
217295367Sdesvoid
21857429Smarkmclear_traps(void)
21957429Smarkm{
22057429Smarkm	char *volatile *tp;
22157429Smarkm
22292555Sdes	for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
22357429Smarkm		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
22457429Smarkm			INTOFF;
22557429Smarkm			ckfree(*tp);
22657429Smarkm			*tp = NULL;
22757429Smarkm			if (tp != &trap[0])
22857429Smarkm				setsignal(tp - trap);
22957429Smarkm			INTON;
23057429Smarkm		}
23157429Smarkm	}
232295367Sdes}
233295367Sdes
234295367Sdes
235295367Sdes/*
23657429Smarkm * Check if we have any traps enabled.
23776259Sgreen */
238295367Sdesint
239295367Sdeshave_traps(void)
24057429Smarkm{
241295367Sdes	char *volatile *tp;
24257429Smarkm
243295367Sdes	for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
244295367Sdes		if (*tp && **tp)	/* trap not NULL or SIG_IGN */
245295367Sdes			return 1;
246295367Sdes	}
247295367Sdes	return 0;
248295367Sdes}
249295367Sdes
25092555Sdes/*
25192555Sdes * Set the signal handler for the specified signal.  The routine figures
252295367Sdes * out what it should be set to.
253295367Sdes */
25457429Smarkmvoid
25557429Smarkmsetsignal(int signo)
25692555Sdes{
25792555Sdes	int action;
258295367Sdes	sig_t sigact = SIG_DFL;
259295367Sdes	struct sigaction sa;
26057429Smarkm	char *t;
26157429Smarkm
26257429Smarkm	if ((t = trap[signo]) == NULL)
263295367Sdes		action = S_DFL;
26457429Smarkm	else if (*t != '\0')
26557429Smarkm		action = S_CATCH;
26657429Smarkm	else
26757429Smarkm		action = S_IGN;
26857429Smarkm	if (action == S_DFL) {
269124208Sdes		switch (signo) {
27098675Sdes		case SIGINT:
27198675Sdes			action = S_CATCH;
27298675Sdes			break;
27357429Smarkm		case SIGQUIT:
27457429Smarkm#ifdef DEBUG
27557429Smarkm			{
27657429Smarkm			extern int debug;
27792555Sdes
278124208Sdes			if (debug)
27998675Sdes				break;
28098675Sdes			}
28198675Sdes#endif
28257429Smarkm			action = S_CATCH;
28357429Smarkm			break;
28457429Smarkm		case SIGTERM:
28576259Sgreen			if (rootshell && iflag)
28657429Smarkm				action = S_IGN;
28757429Smarkm			break;
28857429Smarkm#if JOBS
28992555Sdes		case SIGTSTP:
29057429Smarkm		case SIGTTOU:
29157429Smarkm			if (rootshell && mflag)
29257429Smarkm				action = S_IGN;
29357429Smarkm			break;
29457429Smarkm#endif
29557429Smarkm		}
29657429Smarkm	}
29757429Smarkm
29857429Smarkm	t = &sigmode[signo];
29957429Smarkm	if (*t == 0) {
30057429Smarkm		/*
30157429Smarkm		 * current setting unknown
30257429Smarkm		 */
30357429Smarkm		if (!getsigaction(signo, &sigact)) {
30492555Sdes			/*
305124208Sdes			 * Pretend it worked; maybe we should give a warning
30657429Smarkm			 * here, but other shells don't. We don't alter
30798675Sdes			 * sigmode, so that we retry every time.
30857429Smarkm			 */
30957429Smarkm			return;
310295367Sdes		}
311295367Sdes		if (sigact == SIG_IGN) {
312295367Sdes			if (mflag && (signo == SIGTSTP ||
313295367Sdes			     signo == SIGTTIN || signo == SIGTTOU)) {
31457429Smarkm				*t = S_IGN;	/* don't hard ignore these */
315295367Sdes			} else
316295367Sdes				*t = S_HARD_IGN;
31757429Smarkm		} else {
31857429Smarkm			*t = S_RESET;	/* force to be set */
31957429Smarkm		}
320295367Sdes	}
321295367Sdes	if (*t == S_HARD_IGN || *t == action)
32298675Sdes		return;
32398675Sdes	switch (action) {
32457429Smarkm		case S_DFL:	sigact = SIG_DFL;	break;
32557429Smarkm		case S_CATCH:  	sigact = onsig;		break;
326295367Sdes		case S_IGN:	sigact = SIG_IGN;	break;
327295367Sdes	}
328295367Sdes	*t = action;
32957429Smarkm	sa.sa_handler = sigact;
33057429Smarkm	sa.sa_flags = 0;
33157429Smarkm	sigemptyset(&sa.sa_mask);
33257429Smarkm	sigaction(signo, &sa, NULL);
33357429Smarkm}
33457429Smarkm
33557429Smarkm
33657429Smarkm/*
33798675Sdes * Return the current setting for sig w/o changing it.
33898675Sdes */
33998675Sdesstatic int
34098675Sdesgetsigaction(int signo, sig_t *sigact)
34198675Sdes{
342204917Sdes	struct sigaction sa;
34398675Sdes
344	if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
345		return 0;
346	*sigact = (sig_t) sa.sa_handler;
347	return 1;
348}
349
350
351/*
352 * Ignore a signal.
353 */
354void
355ignoresig(int signo)
356{
357
358	if (sigmode[signo] == 0)
359		setsignal(signo);
360	if (sigmode[signo] != S_IGN && sigmode[signo] != S_HARD_IGN) {
361		signal(signo, SIG_IGN);
362		sigmode[signo] = S_IGN;
363	}
364}
365
366
367int
368issigchldtrapped(void)
369{
370
371	return (trap[SIGCHLD] != NULL && *trap[SIGCHLD] != '\0');
372}
373
374
375/*
376 * Signal handler.
377 */
378void
379onsig(int signo)
380{
381
382	if (signo == SIGINT && trap[SIGINT] == NULL) {
383		/*
384		 * The !in_dotrap here is safe.  The only way we can arrive
385		 * here with in_dotrap set is that a trap handler set SIGINT to
386		 * SIG_DFL and killed itself.
387		 */
388		if (suppressint && !in_dotrap)
389			SET_PENDING_INT;
390		else
391			onint();
392		return;
393	}
394
395	/* If we are currently in a wait builtin, prepare to break it */
396	if (signo == SIGINT || signo == SIGQUIT)
397		pendingsig_waitcmd = signo;
398
399	if (trap[signo] != NULL && trap[signo][0] != '\0' &&
400	    (signo != SIGCHLD || !ignore_sigchld)) {
401		gotsig[signo] = 1;
402		pendingsig = signo;
403		pendingsig_waitcmd = signo;
404	}
405}
406
407
408/*
409 * Called to execute a trap.  Perhaps we should avoid entering new trap
410 * handlers while we are executing a trap handler.
411 */
412void
413dotrap(void)
414{
415	int i;
416	int savestatus, prev_evalskip, prev_skipcount;
417
418	in_dotrap++;
419	for (;;) {
420		pendingsig = 0;
421		pendingsig_waitcmd = 0;
422		for (i = 1; i < NSIG; i++) {
423			if (gotsig[i]) {
424				gotsig[i] = 0;
425				if (trap[i]) {
426					/*
427					 * Ignore SIGCHLD to avoid infinite
428					 * recursion if the trap action does
429					 * a fork.
430					 */
431					if (i == SIGCHLD)
432						ignore_sigchld++;
433
434					/*
435					 * Backup current evalskip
436					 * state and reset it before
437					 * executing a trap, so that the
438					 * trap is not disturbed by an
439					 * ongoing break/continue/return
440					 * statement.
441					 */
442					prev_evalskip  = evalskip;
443					prev_skipcount = skipcount;
444					evalskip = 0;
445
446					last_trapsig = i;
447					savestatus = exitstatus;
448					evalstring(trap[i], 0);
449
450					/*
451					 * If such a command was not
452					 * already in progress, allow a
453					 * break/continue/return in the
454					 * trap action to have an effect
455					 * outside of it.
456					 */
457					if (evalskip == 0 ||
458					    prev_evalskip != 0) {
459						evalskip  = prev_evalskip;
460						skipcount = prev_skipcount;
461						exitstatus = savestatus;
462					}
463
464					if (i == SIGCHLD)
465						ignore_sigchld--;
466				}
467				break;
468			}
469		}
470		if (i >= NSIG)
471			break;
472	}
473	in_dotrap--;
474}
475
476
477/*
478 * Controls whether the shell is interactive or not.
479 */
480void
481setinteractive(int on)
482{
483	static int is_interactive = -1;
484
485	if (on == is_interactive)
486		return;
487	setsignal(SIGINT);
488	setsignal(SIGQUIT);
489	setsignal(SIGTERM);
490	is_interactive = on;
491}
492
493
494/*
495 * Called to exit the shell.
496 */
497void
498exitshell(int status)
499{
500	TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
501	exiting = 1;
502	exiting_exitstatus = status;
503	exitshell_savedstatus();
504}
505
506void
507exitshell_savedstatus(void)
508{
509	struct jmploc loc1, loc2;
510	char *p;
511	int sig = 0;
512	sigset_t sigs;
513
514	if (!exiting) {
515		if (in_dotrap && last_trapsig) {
516			sig = last_trapsig;
517			exiting_exitstatus = sig + 128;
518		} else
519			exiting_exitstatus = oexitstatus;
520	}
521	exitstatus = oexitstatus = exiting_exitstatus;
522	if (!setjmp(loc1.loc)) {
523		handler = &loc1;
524		if ((p = trap[0]) != NULL && *p != '\0') {
525			/*
526			 * Reset evalskip, or the trap on EXIT could be
527			 * interrupted if the last command was a "return".
528			 */
529			evalskip = 0;
530			trap[0] = NULL;
531			evalstring(p, 0);
532		}
533	}
534	if (!setjmp(loc2.loc)) {
535		handler = &loc2;		/* probably unnecessary */
536		flushall();
537#if JOBS
538		setjobctl(0);
539#endif
540	}
541	if (sig != 0 && sig != SIGSTOP && sig != SIGTSTP && sig != SIGTTIN &&
542	    sig != SIGTTOU) {
543		signal(sig, SIG_DFL);
544		sigemptyset(&sigs);
545		sigaddset(&sigs, sig);
546		sigprocmask(SIG_UNBLOCK, &sigs, NULL);
547		kill(getpid(), sig);
548		/* If the default action is to ignore, fall back to _exit(). */
549	}
550	_exit(exiting_exitstatus);
551}
552