xref: /minix3/bin/sh/trap.c (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1 /*	$NetBSD: trap.c,v 1.37 2015/08/22 12:12:47 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.37 2015/08/22 12:12:47 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 "builtins.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 "var.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 permenantly */
75 #define S_RESET 5		/* temporary - to reset a hard ignored sig */
76 
77 
78 char *trap[NSIG+1];		/* trap handler commands */
79 MKINIT char sigmode[NSIG];	/* current value of signal */
80 static volatile char gotsig[NSIG];/* indicates specified signal received */
81 volatile int pendingsigs;	/* indicates some signal received */
82 
83 static int getsigaction(int, sig_t *);
84 
85 /*
86  * return the signal number described by `p' (as a number or a name)
87  * or -1 if it isn't one
88  */
89 
90 static int
signame_to_signum(const char * p)91 signame_to_signum(const char *p)
92 {
93 	int i;
94 
95 	if (is_number(p))
96 		return number(p);
97 
98 	if (strcasecmp(p, "exit") == 0 )
99 		return 0;
100 
101 	if (strncasecmp(p, "sig", 3) == 0)
102 		p += 3;
103 
104 	for (i = 0; i < NSIG; ++i)
105 		if (strcasecmp (p, sys_signame[i]) == 0)
106 			return i;
107 	return -1;
108 }
109 
110 /*
111  * Print a list of valid signal names
112  */
113 static void
printsignals(void)114 printsignals(void)
115 {
116 	int n;
117 
118 	out1str("EXIT ");
119 
120 	for (n = 1; n < NSIG; n++) {
121 		out1fmt("%s", sys_signame[n]);
122 		if ((n == NSIG/2) ||  n == (NSIG - 1))
123 			out1str("\n");
124 		else
125 			out1c(' ');
126 	}
127 }
128 
129 /*
130  * The trap builtin.
131  */
132 
133 int
trapcmd(int argc,char ** argv)134 trapcmd(int argc, char **argv)
135 {
136 	char *action;
137 	char **ap;
138 	int signo;
139 
140 	if (argc <= 1) {
141 		for (signo = 0 ; signo <= NSIG ; signo++)
142 			if (trap[signo] != NULL) {
143 				out1fmt("trap -- ");
144 				print_quoted(trap[signo]);
145 				out1fmt(" %s\n",
146 				    (signo) ? sys_signame[signo] : "EXIT");
147 			}
148 		return 0;
149 	}
150 	ap = argv + 1;
151 
152 	action = NULL;
153 
154 	if (strcmp(*ap, "--") == 0)
155 		if (*++ap == NULL)
156 			return 0;
157 
158 	if (signame_to_signum(*ap) == -1) {
159 		if ((*ap)[0] == '-') {
160 			if ((*ap)[1] == '\0')
161 				ap++;
162 			else if ((*ap)[1] == 'l' && (*ap)[2] == '\0') {
163 				printsignals();
164 				return 0;
165 			}
166 			else
167 				error("bad option %s\n", *ap);
168 		}
169 		else
170 			action = *ap++;
171 	}
172 
173 	while (*ap) {
174 		if (is_number(*ap))
175 			signo = number(*ap);
176 		else
177 			signo = signame_to_signum(*ap);
178 
179 		if (signo < 0 || signo > NSIG)
180 			error("%s: bad trap", *ap);
181 
182 		INTOFF;
183 		if (action)
184 			action = savestr(action);
185 
186 		if (trap[signo])
187 			ckfree(trap[signo]);
188 
189 		trap[signo] = action;
190 
191 		if (signo != 0)
192 			setsignal(signo, 0);
193 		INTON;
194 		ap++;
195 	}
196 	return 0;
197 }
198 
199 
200 
201 /*
202  * Clear traps on a fork or vfork.
203  * Takes one arg vfork, to tell it to not be destructive of
204  * the parents variables.
205  */
206 
207 void
clear_traps(int vforked)208 clear_traps(int vforked)
209 {
210 	char **tp;
211 
212 	for (tp = trap ; tp <= &trap[NSIG] ; tp++) {
213 		if (*tp && **tp) {	/* trap not NULL or SIG_IGN */
214 			INTOFF;
215 			if (!vforked) {
216 				ckfree(*tp);
217 				*tp = NULL;
218 			}
219 			if (tp != &trap[0])
220 				setsignal(tp - trap, vforked);
221 			INTON;
222 		}
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  */
232 
233 sig_t
setsignal(int signo,int vforked)234 setsignal(int signo, int vforked)
235 {
236 	int action;
237 	sig_t sigact = SIG_DFL, sig;
238 	char *t, tsig;
239 
240 	if ((t = trap[signo]) == NULL)
241 		action = S_DFL;
242 	else if (*t != '\0')
243 		action = S_CATCH;
244 	else
245 		action = S_IGN;
246 	if (rootshell && !vforked && action == S_DFL) {
247 		switch (signo) {
248 		case SIGINT:
249 			if (iflag || minusc || sflag == 0)
250 				action = S_CATCH;
251 			break;
252 		case SIGQUIT:
253 #ifdef DEBUG
254 			if (debug)
255 				break;
256 #endif
257 			/* FALLTHROUGH */
258 		case SIGTERM:
259 			if (iflag)
260 				action = S_IGN;
261 			break;
262 #if JOBS
263 		case SIGTSTP:
264 		case SIGTTOU:
265 			if (mflag)
266 				action = S_IGN;
267 			break;
268 #endif
269 		}
270 	}
271 
272 	t = &sigmode[signo - 1];
273 	tsig = *t;
274 	if (tsig == 0) {
275 		/*
276 		 * current setting unknown
277 		 */
278 		if (!getsigaction(signo, &sigact)) {
279 			/*
280 			 * Pretend it worked; maybe we should give a warning
281 			 * here, but other shells don't. We don't alter
282 			 * sigmode, so that we retry every time.
283 			 */
284 			return 0;
285 		}
286 		if (sigact == SIG_IGN) {
287 			/*
288 			 * POSIX 3.14.13 states that non-interactive shells
289 			 * should ignore trap commands for signals that were
290 			 * ignored upon entry, and leaves the behavior
291 			 * unspecified for interactive shells. On interactive
292 			 * shells, or if job control is on, and we have a job
293 			 * control related signal, we allow the trap to work.
294 			 *
295 			 * This change allows us to be POSIX compliant, and
296 			 * at the same time override the default behavior if
297 			 * we need to by setting the interactive flag.
298 			 */
299 			if ((mflag && (signo == SIGTSTP ||
300 			     signo == SIGTTIN || signo == SIGTTOU)) || iflag) {
301 				tsig = S_IGN;
302 			} else
303 				tsig = S_HARD_IGN;
304 		} else {
305 			tsig = S_RESET;	/* force to be set */
306 		}
307 	}
308 	if (tsig == S_HARD_IGN || tsig == action)
309 		return 0;
310 	switch (action) {
311 		case S_DFL:	sigact = SIG_DFL;	break;
312 		case S_CATCH:  	sigact = onsig;		break;
313 		case S_IGN:	sigact = SIG_IGN;	break;
314 	}
315 	sig = signal(signo, sigact);
316 	if (sig != SIG_ERR) {
317 		sigset_t ss;
318 		if (!vforked)
319 			*t = action;
320 		if (action == S_CATCH)
321 			(void)siginterrupt(signo, 1);
322 		/*
323 		 * If our parent accidentally blocked signals for
324 		 * us make sure we unblock them
325 		 */
326 		(void)sigemptyset(&ss);
327 		(void)sigaddset(&ss, signo);
328 		(void)sigprocmask(SIG_UNBLOCK, &ss, NULL);
329 	}
330 	return sig;
331 }
332 
333 /*
334  * Return the current setting for sig w/o changing it.
335  */
336 static int
getsigaction(int signo,sig_t * sigact)337 getsigaction(int signo, sig_t *sigact)
338 {
339 	struct sigaction sa;
340 
341 	if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
342 		return 0;
343 	*sigact = (sig_t) sa.sa_handler;
344 	return 1;
345 }
346 
347 /*
348  * Ignore a signal.
349  */
350 
351 void
ignoresig(int signo,int vforked)352 ignoresig(int signo, int vforked)
353 {
354 	if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
355 		signal(signo, SIG_IGN);
356 	}
357 	if (!vforked)
358 		sigmode[signo - 1] = S_HARD_IGN;
359 }
360 
361 
362 #ifdef mkinit
363 INCLUDE <signal.h>
364 INCLUDE "trap.h"
365 
366 SHELLPROC {
367 	char *sm;
368 
369 	clear_traps(0);
370 	for (sm = sigmode ; sm < sigmode + NSIG ; sm++) {
371 		if (*sm == S_IGN)
372 			*sm = S_HARD_IGN;
373 	}
374 }
375 #endif
376 
377 
378 
379 /*
380  * Signal handler.
381  */
382 
383 void
onsig(int signo)384 onsig(int signo)
385 {
386 	signal(signo, onsig);
387 	if (signo == SIGINT && trap[SIGINT] == NULL) {
388 		onint();
389 		return;
390 	}
391 	gotsig[signo - 1] = 1;
392 	pendingsigs++;
393 }
394 
395 
396 
397 /*
398  * Called to execute a trap.  Perhaps we should avoid entering new trap
399  * handlers while we are executing a trap handler.
400  */
401 
402 void
dotrap(void)403 dotrap(void)
404 {
405 	int i;
406 	int savestatus;
407 
408 	for (;;) {
409 		for (i = 1 ; ; i++) {
410 			if (gotsig[i - 1])
411 				break;
412 			if (i >= NSIG)
413 				goto done;
414 		}
415 		gotsig[i - 1] = 0;
416 		savestatus=exitstatus;
417 		evalstring(trap[i], 0);
418 		exitstatus=savestatus;
419 	}
420 done:
421 	pendingsigs = 0;
422 }
423 
424 int
lastsig(void)425 lastsig(void)
426 {
427 	int i;
428 
429 	for (i = NSIG; i > 0; i--)
430 		if (gotsig[i - 1])
431 			return i;
432 	return SIGINT;	/* XXX */
433 }
434 
435 /*
436  * Controls whether the shell is interactive or not.
437  */
438 
439 
440 void
setinteractive(int on)441 setinteractive(int on)
442 {
443 	static int is_interactive;
444 
445 	if (on == is_interactive)
446 		return;
447 	setsignal(SIGINT, 0);
448 	setsignal(SIGQUIT, 0);
449 	setsignal(SIGTERM, 0);
450 	is_interactive = on;
451 }
452 
453 
454 
455 /*
456  * Called to exit the shell.
457  */
458 
459 void
exitshell(int status)460 exitshell(int status)
461 {
462 	struct jmploc loc1, loc2;
463 	char *p;
464 
465 	TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
466 	if (setjmp(loc1.loc)) {
467 		goto l1;
468 	}
469 	if (setjmp(loc2.loc)) {
470 		goto l2;
471 	}
472 	handler = &loc1;
473 	if ((p = trap[0]) != NULL && *p != '\0') {
474 		trap[0] = NULL;
475 		evalstring(p, 0);
476 	}
477 l1:   handler = &loc2;			/* probably unnecessary */
478 	flushall();
479 #if JOBS
480 	setjobctl(0);
481 #endif
482 l2:   _exit(status);
483 	/* NOTREACHED */
484 }
485