xref: /dragonfly/bin/sh/trap.c (revision 2d8a3be7)
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  * @(#)trap.c	8.5 (Berkeley) 6/5/95
37  * $FreeBSD: src/bin/sh/trap.c,v 1.20.2.2 2002/08/27 01:36:28 tjr Exp $
38  * $DragonFly: src/bin/sh/trap.c,v 1.3 2003/10/14 23:03:08 dillon Exp $
39  */
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 
74 MKINIT char sigmode[NSIG];	/* current value of signal */
75 int pendingsigs;		/* indicates some signal received */
76 int in_dotrap;			/* do we execute in a trap handler? */
77 static char *volatile trap[NSIG];	/* trap handler commands */
78 static volatile sig_atomic_t gotsig[NSIG];
79 				/* indicates specified signal received */
80 static int ignore_sigchld;	/* Used while handling SIGCHLD traps. */
81 volatile sig_atomic_t gotwinch;
82 
83 static int getsigaction(int, sig_t *);
84 
85 
86 /*
87  * Map a string to a signal number.
88  */
89 static int
90 sigstring_to_signum(char *sig)
91 {
92 
93 	if (is_number(sig)) {
94 		int signo;
95 
96 		signo = atoi(sig);
97 		return ((signo >= 0 && signo < NSIG) ? signo : (-1));
98 	} else if (strcasecmp(sig, "exit") == 0) {
99 		return (0);
100 	} else {
101 		int n;
102 
103 		if (strncasecmp(sig, "sig", 3) == 0)
104 			sig += 3;
105 		for (n = 1; n < sys_nsig; n++) {
106 			if (sys_signame[n] && strcasecmp(sys_signame[n], sig) == 0)
107 				return (n);
108 		}
109 	}
110 	return (-1);
111 }
112 
113 
114 /*
115  * Print a list of valid signal names.
116  */
117 static void
118 printsignals(void)
119 {
120 	int n;
121 
122 	for (n = 1; n < sys_nsig; n++) {
123 		out1fmt("%s", sys_signame[n]);
124 		if (n == (NSIG / 2) || n == (NSIG - 1))
125 			out1str("\n");
126 		else
127 			out1c(' ');
128 	}
129 }
130 
131 
132 /*
133  * The trap builtin.
134  */
135 int
136 trapcmd(int argc, char **argv)
137 {
138 	char *action;
139 	int signo;
140 
141 	if (argc <= 1) {
142 		for (signo = 0 ; signo < sys_nsig; signo++) {
143 			if (trap[signo] != NULL) {
144 				out1fmt("trap -- '%s' %s\n", trap[signo],
145 					(signo) ? sys_signame[signo] : "exit");
146 			}
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  */
187 void
188 clear_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  */
209 void
210 setsignal(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 #ifndef NO_HISTORY
250 		case SIGWINCH:
251 			if (rootshell && iflag)
252 				action = S_CATCH;
253 			break;
254 #endif
255 		}
256 	}
257 
258 	t = &sigmode[signo];
259 	if (*t == 0) {
260 		/*
261 		 * current setting unknown
262 		 */
263 		if (!getsigaction(signo, &sigact)) {
264 			/*
265 			 * Pretend it worked; maybe we should give a warning
266 			 * here, but other shells don't. We don't alter
267 			 * sigmode, so that we retry every time.
268 			 */
269 			return;
270 		}
271 		if (sigact == SIG_IGN) {
272 			if (mflag && (signo == SIGTSTP ||
273 			     signo == SIGTTIN || signo == SIGTTOU)) {
274 				*t = S_IGN;	/* don't hard ignore these */
275 			} else
276 				*t = S_HARD_IGN;
277 		} else {
278 			*t = S_RESET;	/* force to be set */
279 		}
280 	}
281 	if (*t == S_HARD_IGN || *t == action)
282 		return;
283 	switch (action) {
284 		case S_DFL:	sigact = SIG_DFL;	break;
285 		case S_CATCH:  	sigact = onsig;		break;
286 		case S_IGN:	sigact = SIG_IGN;	break;
287 	}
288 	*t = action;
289 	sig = signal(signo, sigact);
290 	if (sig != SIG_ERR && action == S_CATCH)
291 		siginterrupt(signo, 1);
292 }
293 
294 
295 /*
296  * Return the current setting for sig w/o changing it.
297  */
298 static int
299 getsigaction(int signo, sig_t *sigact)
300 {
301 	struct sigaction sa;
302 
303 	if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
304 		return 0;
305 	*sigact = (sig_t) sa.sa_handler;
306 	return 1;
307 }
308 
309 
310 /*
311  * Ignore a signal.
312  */
313 void
314 ignoresig(int signo)
315 {
316 
317 	if (sigmode[signo] != S_IGN && sigmode[signo] != S_HARD_IGN) {
318 		signal(signo, SIG_IGN);
319 	}
320 	sigmode[signo] = S_HARD_IGN;
321 }
322 
323 
324 #ifdef mkinit
325 INCLUDE <signal.h>
326 INCLUDE "trap.h"
327 
328 SHELLPROC {
329 	char *sm;
330 
331 	clear_traps();
332 	for (sm = sigmode ; sm < sigmode + NSIG ; sm++) {
333 		if (*sm == S_IGN)
334 			*sm = S_HARD_IGN;
335 	}
336 }
337 #endif
338 
339 
340 /*
341  * Signal handler.
342  */
343 void
344 onsig(int signo)
345 {
346 
347 	if (signo == SIGINT && trap[SIGINT] == NULL) {
348 		onint();
349 		return;
350 	}
351 
352 	if (signo != SIGCHLD || !ignore_sigchld)
353 		gotsig[signo] = 1;
354 	pendingsigs++;
355 
356 	/* If we are currently in a wait builtin, prepare to break it */
357 	if ((signo == SIGINT || signo == SIGQUIT) && in_waitcmd != 0)
358 		breakwaitcmd = 1;
359 	/*
360 	 * If a trap is set, not ignored and not the null command, we need
361 	 * to make sure traps are executed even when a child blocks signals.
362 	 */
363 	if (Tflag &&
364 	    trap[signo] != NULL &&
365 	    ! trap[signo][0] == '\0' &&
366 	    ! (trap[signo][0] == ':' && trap[signo][1] == '\0'))
367 		breakwaitcmd = 1;
368 
369 #ifndef NO_HISTORY
370 	if (signo == SIGWINCH)
371 		gotwinch = 1;
372 #endif
373 }
374 
375 
376 /*
377  * Called to execute a trap.  Perhaps we should avoid entering new trap
378  * handlers while we are executing a trap handler.
379  */
380 void
381 dotrap(void)
382 {
383 	int i;
384 	int savestatus;
385 
386 	in_dotrap++;
387 	for (;;) {
388 		for (i = 1; i < NSIG; i++) {
389 			if (gotsig[i]) {
390 				gotsig[i] = 0;
391 				if (trap[i]) {
392 					/*
393 					 * Ignore SIGCHLD to avoid infinite recursion
394 					 * if the trap action does a fork.
395 					 */
396 					if (i == SIGCHLD)
397 						ignore_sigchld++;
398 					savestatus = exitstatus;
399 					evalstring(trap[i]);
400 					exitstatus = savestatus;
401 					if (i == SIGCHLD)
402 						ignore_sigchld--;
403 				}
404 				break;
405 			}
406 		}
407 		if (i >= NSIG)
408 			break;
409 	}
410 	in_dotrap--;
411 	pendingsigs = 0;
412 }
413 
414 
415 /*
416  * Controls whether the shell is interactive or not.
417  */
418 void
419 setinteractive(int on)
420 {
421 	static int is_interactive = -1;
422 
423 	if (on == is_interactive)
424 		return;
425 	setsignal(SIGINT);
426 	setsignal(SIGQUIT);
427 	setsignal(SIGTERM);
428 #ifndef NO_HISTORY
429 	setsignal(SIGWINCH);
430 #endif
431 	is_interactive = on;
432 }
433 
434 
435 /*
436  * Called to exit the shell.
437  */
438 void
439 exitshell(int status)
440 {
441 	struct jmploc loc1, loc2;
442 	char *p;
443 
444 	TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
445 	if (setjmp(loc1.loc)) {
446 		goto l1;
447 	}
448 	if (setjmp(loc2.loc)) {
449 		goto l2;
450 	}
451 	handler = &loc1;
452 	if ((p = trap[0]) != NULL && *p != '\0') {
453 		trap[0] = NULL;
454 		evalstring(p);
455 	}
456 l1:   handler = &loc2;			/* probably unnecessary */
457 	flushall();
458 #if JOBS
459 	setjobctl(0);
460 #endif
461 l2:   _exit(status);
462 }
463