trap.c revision 1.46 1 /* $NetBSD: trap.c,v 1.46 2018/10/28 18:26:52 kre 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.46 2018/10/28 18:26:52 kre Exp $");
41 #endif
42 #endif /* not lint */
43
44 #include <signal.h>
45 #include <unistd.h>
46 #include <stdlib.h>
47 #include <stdio.h>
48
49 #include "shell.h"
50 #include "main.h"
51 #include "nodes.h" /* for other headers */
52 #include "eval.h"
53 #include "jobs.h"
54 #include "show.h"
55 #include "options.h"
56 #include "builtins.h"
57 #include "syntax.h"
58 #include "output.h"
59 #include "memalloc.h"
60 #include "error.h"
61 #include "trap.h"
62 #include "mystring.h"
63 #include "var.h"
64
65
66 /*
67 * Sigmode records the current value of the signal handlers for the various
68 * modes. A value of zero means that the current handler is not known.
69 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
70 */
71
72 #define S_DFL 1 /* default signal handling (SIG_DFL) */
73 #define S_CATCH 2 /* signal is caught */
74 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
75 #define S_HARD_IGN 4 /* signal is ignored permenantly */
76 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
77
78
79 char *trap[NSIG]; /* trap handler commands */
80 MKINIT char sigmode[NSIG]; /* current value of signal */
81 static volatile char gotsig[NSIG];/* indicates specified signal received */
82 volatile int pendingsigs; /* indicates some signal received */
83
84 static int getsigaction(int, sig_t *);
85 STATIC const char *trap_signame(int);
86 void printsignals(struct output *, int);
87
88 /*
89 * return the signal number described by `p' (as a number or a name)
90 * or -1 if it isn't one
91 */
92
93 static int
94 signame_to_signum(const char *p)
95 {
96 int i;
97
98 if (is_number(p))
99 return number(p);
100
101 if (strcasecmp(p, "exit") == 0 )
102 return 0;
103
104 i = signalnumber(p);
105 if (i == 0)
106 i = -1;
107 return i;
108 }
109
110 /*
111 * return the name of a signal used by the "trap" command
112 */
113 STATIC const char *
114 trap_signame(int signo)
115 {
116 static char nbuf[12];
117 const char *p;
118
119 if (signo == 0)
120 return "EXIT";
121 p = signalname(signo);
122 if (p != NULL)
123 return p;
124 (void)snprintf(nbuf, sizeof nbuf, "%d", signo);
125 return nbuf;
126 }
127
128 #if 0 /* Share the version of this in src/bin/kill/kill.c */
129 /*
130 * Print a list of valid signal names
131 */
132 void
133 printsignals(struct output *out, int len)
134 {
135 int n;
136
137 if (len != 0)
138 outc(' ', out);
139 for (n = 1; n < NSIG; n++) {
140 outfmt(out, "%s", trap_signame(n));
141 if ((n == NSIG/2) || n == (NSIG - 1))
142 outstr("\n", out);
143 else
144 outc(' ', out);
145 }
146 }
147 #endif
148
149 /*
150 * The trap builtin.
151 */
152
153 int
154 trapcmd(int argc, char **argv)
155 {
156 char *action;
157 char **ap;
158 int signo;
159 int errs = 0;
160 int printonly = 0;
161
162 ap = argv + 1;
163
164 if (argc == 2 && strcmp(*ap, "-l") == 0) {
165 out1str("EXIT");
166 printsignals(out1, 4);
167 return 0;
168 }
169 if (argc == 2 && strcmp(*ap, "-") == 0) {
170 for (signo = 0; signo < NSIG; signo++) {
171 if (trap[signo] == NULL)
172 continue;
173 INTOFF;
174 ckfree(trap[signo]);
175 trap[signo] = NULL;
176 if (signo != 0)
177 setsignal(signo, 0);
178 INTON;
179 }
180 return 0;
181 }
182 if (argc >= 2 && strcmp(*ap, "-p") == 0) {
183 printonly = 1;
184 ap++;
185 argc--;
186 }
187
188 if (argc > 1 && strcmp(*ap, "--") == 0) {
189 argc--;
190 ap++;
191 }
192
193 if (argc <= 1) {
194 int count;
195
196 if (printonly) {
197 for (count = 0, signo = 0 ; signo < NSIG ; signo++)
198 if (trap[signo] == NULL) {
199 if (count == 0)
200 out1str("trap -- -");
201 out1fmt(" %s", trap_signame(signo));
202 /* oh! unlucky 13 */
203 if (++count >= 13) {
204 out1str("\n");
205 count = 0;
206 }
207 }
208 if (count)
209 out1str("\n");
210 }
211
212 for (count = 0, signo = 0 ; signo < NSIG ; signo++)
213 if (trap[signo] != NULL && trap[signo][0] == '\0') {
214 if (count == 0)
215 out1str("trap -- ''");
216 out1fmt(" %s", trap_signame(signo));
217 /*
218 * the prefix is 10 bytes, with 4 byte
219 * signal names (common) we have room in
220 * the 70 bytes left on a normal line for
221 * 70/(4+1) signals, that's 14, but to
222 * allow for the occasional longer sig name
223 * we output one less...
224 */
225 if (++count >= 13) {
226 out1str("\n");
227 count = 0;
228 }
229 }
230 if (count)
231 out1str("\n");
232
233 for (signo = 0 ; signo < NSIG ; signo++)
234 if (trap[signo] != NULL && trap[signo][0] != '\0') {
235 out1str("trap -- ");
236 print_quoted(trap[signo]);
237 out1fmt(" %s\n", trap_signame(signo));
238 }
239
240 return 0;
241 }
242
243 action = NULL;
244
245 if (!printonly && !is_number(*ap)) {
246 if ((*ap)[0] == '-' && (*ap)[1] == '\0')
247 ap++; /* reset to default */
248 else
249 action = *ap++; /* can be '' for "ignore" */
250 argc--;
251 }
252
253 if (argc < 2) { /* there must be at least 1 condition */
254 out2str("Usage: trap [-l]\n"
255 " trap -p [condition ...]\n"
256 " trap action condition ...\n"
257 " trap N condition ...\n");
258 return 2;
259 }
260
261
262 while (*ap) {
263 signo = signame_to_signum(*ap);
264
265 if (signo < 0 || signo >= NSIG) {
266 /* This is not a fatal error, so sayeth posix */
267 outfmt(out2, "trap: '%s' bad condition\n", *ap);
268 errs = 1;
269 ap++;
270 continue;
271 }
272 ap++;
273
274 if (printonly) {
275 out1str("trap -- ");
276 if (trap[signo] == NULL)
277 out1str("-");
278 else
279 print_quoted(trap[signo]);
280 out1fmt(" %s\n", trap_signame(signo));
281 continue;
282 }
283
284 INTOFF;
285 if (action)
286 action = savestr(action);
287
288 if (trap[signo])
289 ckfree(trap[signo]);
290
291 trap[signo] = action;
292
293 if (signo != 0)
294 setsignal(signo, 0);
295 INTON;
296 }
297 return errs;
298 }
299
300
301
302 /*
303 * Clear traps on a fork or vfork.
304 * Takes one arg vfork, to tell it to not be destructive of
305 * the parents variables.
306 */
307
308 void
309 clear_traps(int vforked)
310 {
311 char **tp;
312
313 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
314 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
315 INTOFF;
316 if (!vforked) {
317 ckfree(*tp);
318 *tp = NULL;
319 }
320 if (tp != &trap[0])
321 setsignal(tp - trap, vforked);
322 INTON;
323 }
324 }
325 }
326
327 /*
328 * See if there are any defined traps
329 */
330 int
331 have_traps(void)
332 {
333 char **tp;
334
335 for (tp = trap ; tp < &trap[NSIG] ; tp++)
336 if (*tp && **tp) /* trap not NULL or SIG_IGN */
337 return 1;
338 return 0;
339 }
340
341 /*
342 * Set the signal handler for the specified signal. The routine figures
343 * out what it should be set to.
344 */
345
346 sig_t
347 setsignal(int signo, int vforked)
348 {
349 int action;
350 sig_t sigact = SIG_DFL, sig;
351 char *t, tsig;
352
353 if ((t = trap[signo]) == NULL)
354 action = S_DFL;
355 else if (*t != '\0')
356 action = S_CATCH;
357 else
358 action = S_IGN;
359 if (rootshell && !vforked && action == S_DFL) {
360 switch (signo) {
361 case SIGINT:
362 if (iflag || minusc || sflag == 0)
363 action = S_CATCH;
364 break;
365 case SIGQUIT:
366 #ifdef DEBUG
367 if (debug)
368 break;
369 #endif
370 /* FALLTHROUGH */
371 case SIGTERM:
372 if (iflag)
373 action = S_IGN;
374 break;
375 #if JOBS
376 case SIGTSTP:
377 case SIGTTOU:
378 if (mflag)
379 action = S_IGN;
380 break;
381 #endif
382 }
383 }
384
385 t = &sigmode[signo - 1];
386 tsig = *t;
387 if (tsig == 0) {
388 /*
389 * current setting unknown
390 */
391 if (!getsigaction(signo, &sigact)) {
392 /*
393 * Pretend it worked; maybe we should give a warning
394 * here, but other shells don't. We don't alter
395 * sigmode, so that we retry every time.
396 */
397 return 0;
398 }
399 if (sigact == SIG_IGN) {
400 /*
401 * POSIX 3.14.13 states that non-interactive shells
402 * should ignore trap commands for signals that were
403 * ignored upon entry, and leaves the behavior
404 * unspecified for interactive shells. On interactive
405 * shells, or if job control is on, and we have a job
406 * control related signal, we allow the trap to work.
407 *
408 * This change allows us to be POSIX compliant, and
409 * at the same time override the default behavior if
410 * we need to by setting the interactive flag.
411 */
412 if ((mflag && (signo == SIGTSTP ||
413 signo == SIGTTIN || signo == SIGTTOU)) || iflag) {
414 tsig = S_IGN;
415 } else
416 tsig = S_HARD_IGN;
417 } else {
418 tsig = S_RESET; /* force to be set */
419 }
420 }
421 if (tsig == S_HARD_IGN || tsig == action)
422 return 0;
423 switch (action) {
424 case S_DFL: sigact = SIG_DFL; break;
425 case S_CATCH: sigact = onsig; break;
426 case S_IGN: sigact = SIG_IGN; break;
427 }
428 sig = signal(signo, sigact);
429 if (sig != SIG_ERR) {
430 sigset_t ss;
431 if (!vforked)
432 *t = action;
433 if (action == S_CATCH)
434 (void)siginterrupt(signo, 1);
435 /*
436 * If our parent accidentally blocked signals for
437 * us make sure we unblock them
438 */
439 (void)sigemptyset(&ss);
440 (void)sigaddset(&ss, signo);
441 (void)sigprocmask(SIG_UNBLOCK, &ss, NULL);
442 }
443 return sig;
444 }
445
446 /*
447 * Return the current setting for sig w/o changing it.
448 */
449 static int
450 getsigaction(int signo, sig_t *sigact)
451 {
452 struct sigaction sa;
453
454 if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
455 return 0;
456 *sigact = (sig_t) sa.sa_handler;
457 return 1;
458 }
459
460 /*
461 * Ignore a signal.
462 */
463
464 void
465 ignoresig(int signo, int vforked)
466 {
467 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
468 signal(signo, SIG_IGN);
469 }
470 if (!vforked)
471 sigmode[signo - 1] = S_HARD_IGN;
472 }
473
474
475 #ifdef mkinit
476 INCLUDE <signal.h>
477 INCLUDE "trap.h"
478
479 SHELLPROC {
480 char *sm;
481
482 clear_traps(0);
483 for (sm = sigmode ; sm < sigmode + NSIG ; sm++) {
484 if (*sm == S_IGN)
485 *sm = S_HARD_IGN;
486 }
487 }
488 #endif
489
490
491
492 /*
493 * Signal handler.
494 */
495
496 void
497 onsig(int signo)
498 {
499 CTRACE(DBG_SIG, ("Signal %d, had: pending %d, gotsig[%d]=%d\n",
500 signo, pendingsigs, signo, gotsig[signo]));
501
502 signal(signo, onsig);
503 if (signo == SIGINT && trap[SIGINT] == NULL) {
504 onint();
505 return;
506 }
507 gotsig[signo] = 1;
508 pendingsigs++;
509 }
510
511
512
513 /*
514 * Called to execute a trap. Perhaps we should avoid entering new trap
515 * handlers while we are executing a trap handler.
516 */
517
518 void
519 dotrap(void)
520 {
521 int i;
522 int savestatus;
523 char *tr;
524
525 for (;;) {
526 for (i = 1 ; ; i++) {
527 if (i >= NSIG) {
528 pendingsigs = 0;
529 return;
530 }
531 if (gotsig[i])
532 break;
533 }
534 gotsig[i] = 0;
535 savestatus=exitstatus;
536 CTRACE(DBG_TRAP|DBG_SIG, ("dotrap %d: \"%s\"\n", i,
537 trap[i] ? trap[i] : "-NULL-"));
538 if ((tr = trap[i]) != NULL) {
539 tr = savestr(tr); /* trap code may free trap[i] */
540 evalstring(tr, 0);
541 ckfree(tr);
542 }
543 exitstatus=savestatus;
544 }
545 }
546
547 int
548 lastsig(void)
549 {
550 int i;
551
552 for (i = NSIG; --i > 0; )
553 if (gotsig[i])
554 return i;
555 return SIGINT; /* XXX */
556 }
557
558 /*
559 * Controls whether the shell is interactive or not.
560 */
561
562
563 void
564 setinteractive(int on)
565 {
566 static int is_interactive;
567
568 if (on == is_interactive)
569 return;
570 setsignal(SIGINT, 0);
571 setsignal(SIGQUIT, 0);
572 setsignal(SIGTERM, 0);
573 is_interactive = on;
574 }
575
576
577
578 /*
579 * Called to exit the shell.
580 */
581
582 void
583 exitshell(int status)
584 {
585 struct jmploc loc1, loc2;
586 char *p;
587
588 CTRACE(DBG_ERRS|DBG_PROCS|DBG_CMDS|DBG_TRAP,
589 ("pid %d, exitshell(%d)\n", getpid(), status));
590
591 if (setjmp(loc1.loc)) {
592 goto l1;
593 }
594 if (setjmp(loc2.loc)) {
595 goto l2;
596 }
597 handler = &loc1;
598 if ((p = trap[0]) != NULL && *p != '\0') {
599 trap[0] = NULL;
600 VTRACE(DBG_TRAP, ("exit trap: \"%s\"\n", p));
601 evalstring(p, 0);
602 }
603 l1: handler = &loc2; /* probably unnecessary */
604 flushall();
605 #if JOBS
606 setjobctl(0);
607 #endif
608 l2: _exit(status);
609 /* NOTREACHED */
610 }
611