Merge branch 'vendor/AWK'
[dragonfly.git] / bin / sh / trap.c
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  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * @(#)trap.c   8.5 (Berkeley) 6/5/95
33  * $FreeBSD: head/bin/sh/trap.c 247720 2013-03-03 17:33:59Z jilles $
34  */
35
36 #include <signal.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39
40 #include "shell.h"
41 #include "main.h"
42 #include "nodes.h"      /* for other headers */
43 #include "eval.h"
44 #include "jobs.h"
45 #include "show.h"
46 #include "options.h"
47 #include "syntax.h"
48 #include "output.h"
49 #include "memalloc.h"
50 #include "error.h"
51 #include "trap.h"
52 #include "mystring.h"
53 #include "builtins.h"
54 #include "myhistedit.h"
55
56
57 /*
58  * Sigmode records the current value of the signal handlers for the various
59  * modes.  A value of zero means that the current handler is not known.
60  * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
61  */
62
63 #define S_DFL 1                 /* default signal handling (SIG_DFL) */
64 #define S_CATCH 2               /* signal is caught */
65 #define S_IGN 3                 /* signal is ignored (SIG_IGN) */
66 #define S_HARD_IGN 4            /* signal is ignored permanently */
67 #define S_RESET 5               /* temporary - to reset a hard ignored sig */
68
69
70 MKINIT char sigmode[NSIG];      /* current value of signal */
71 volatile sig_atomic_t pendingsig;       /* indicates some signal received */
72 int in_dotrap;                  /* do we execute in a trap handler? */
73 static char *volatile trap[NSIG];       /* trap handler commands */
74 static volatile sig_atomic_t gotsig[NSIG];
75                                 /* indicates specified signal received */
76 static int ignore_sigchld;      /* Used while handling SIGCHLD traps. */
77 volatile sig_atomic_t gotwinch;
78 static int last_trapsig;
79
80 static int exiting;             /* exitshell() has been called */
81 static int exiting_exitstatus;  /* value passed to exitshell() */
82
83 static int getsigaction(int, sig_t *);
84
85
86 /*
87  * Map a string to a signal number.
88  *
89  * Note: the signal number may exceed NSIG.
90  */
91 static int
92 sigstring_to_signum(char *sig)
93 {
94
95         if (is_number(sig)) {
96                 int signo;
97
98                 signo = atoi(sig);
99                 return ((signo >= 0 && signo < NSIG) ? signo : (-1));
100         } else if (strcasecmp(sig, "EXIT") == 0) {
101                 return (0);
102         } else {
103                 int n;
104
105                 if (strncasecmp(sig, "SIG", 3) == 0)
106                         sig += 3;
107                 for (n = 1; n < sys_nsig; n++)
108                         if (sys_signame[n] &&
109                             strcasecmp(sys_signame[n], sig) == 0)
110                                 return (n);
111         }
112         return (-1);
113 }
114
115
116 /*
117  * Print a list of valid signal names.
118  */
119 static void
120 printsignals(void)
121 {
122         int n, outlen;
123
124         outlen = 0;
125         for (n = 1; n < sys_nsig; n++) {
126                 if (sys_signame[n]) {
127                         out1fmt("%s", sys_signame[n]);
128                         outlen += strlen(sys_signame[n]);
129                 } else {
130                         out1fmt("%d", n);
131                         outlen += 3;    /* good enough */
132                 }
133                 ++outlen;
134                 if (outlen > 71 || n == sys_nsig - 1) {
135                         out1str("\n");
136                         outlen = 0;
137                 } else {
138                         out1c(' ');
139                 }
140         }
141 }
142
143
144 /*
145  * The trap builtin.
146  */
147 int
148 trapcmd(int argc __unused, char **argv)
149 {
150         char *action;
151         int signo;
152         int errors = 0;
153         int i;
154
155         while ((i = nextopt("l")) != '\0') {
156                 switch (i) {
157                 case 'l':
158                         printsignals();
159                         return (0);
160                 }
161         }
162         argv = argptr;
163
164         if (*argv == NULL) {
165                 for (signo = 0 ; signo < sys_nsig ; signo++) {
166                         if (signo < NSIG && trap[signo] != NULL) {
167                                 out1str("trap -- ");
168                                 out1qstr(trap[signo]);
169                                 if (signo == 0) {
170                                         out1str(" EXIT\n");
171                                 } else if (sys_signame[signo]) {
172                                         out1fmt(" %s\n", sys_signame[signo]);
173                                 } else {
174                                         out1fmt(" %d\n", signo);
175                                 }
176                         }
177                 }
178                 return 0;
179         }
180         action = NULL;
181         if (*argv && sigstring_to_signum(*argv) == -1) {
182                 if (strcmp(*argv, "-") == 0)
183                         argv++;
184                 else {
185                         action = *argv;
186                         argv++;
187                 }
188         }
189         for (; *argv; argv++) {
190                 if ((signo = sigstring_to_signum(*argv)) == -1) {
191                         warning("bad signal %s", *argv);
192                         errors = 1;
193                         continue;
194                 }
195                 INTOFF;
196                 if (action)
197                         action = savestr(action);
198                 if (trap[signo])
199                         ckfree(trap[signo]);
200                 trap[signo] = action;
201                 if (signo != 0)
202                         setsignal(signo);
203                 INTON;
204         }
205         return errors;
206 }
207
208
209 /*
210  * Clear traps on a fork.
211  */
212 void
213 clear_traps(void)
214 {
215         char *volatile *tp;
216
217         for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
218                 if (*tp && **tp) {      /* trap not NULL or SIG_IGN */
219                         INTOFF;
220                         ckfree(*tp);
221                         *tp = NULL;
222                         if (tp != &trap[0])
223                                 setsignal(tp - trap);
224                         INTON;
225                 }
226         }
227 }
228
229
230 /*
231  * Check if we have any traps enabled.
232  */
233 int
234 have_traps(void)
235 {
236         char *volatile *tp;
237
238         for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
239                 if (*tp && **tp)        /* trap not NULL or SIG_IGN */
240                         return 1;
241         }
242         return 0;
243 }
244
245 /*
246  * Set the signal handler for the specified signal.  The routine figures
247  * out what it should be set to.
248  */
249 void
250 setsignal(int signo)
251 {
252         int action;
253         sig_t sigact = SIG_DFL;
254         struct sigaction sa;
255         char *t;
256
257         if ((t = trap[signo]) == NULL)
258                 action = S_DFL;
259         else if (*t != '\0')
260                 action = S_CATCH;
261         else
262                 action = S_IGN;
263         if (action == S_DFL) {
264                 switch (signo) {
265                 case SIGINT:
266                         action = S_CATCH;
267                         break;
268                 case SIGQUIT:
269 #ifdef DEBUG
270                         {
271                         extern int debug;
272
273                         if (debug)
274                                 break;
275                         }
276 #endif
277                         action = S_CATCH;
278                         break;
279                 case SIGTERM:
280                         if (rootshell && iflag)
281                                 action = S_IGN;
282                         break;
283 #if JOBS
284                 case SIGTSTP:
285                 case SIGTTOU:
286                         if (rootshell && mflag)
287                                 action = S_IGN;
288                         break;
289 #endif
290 #ifndef NO_HISTORY
291                 case SIGWINCH:
292                         if (rootshell && iflag)
293                                 action = S_CATCH;
294                         break;
295 #endif
296                 }
297         }
298
299         t = &sigmode[signo];
300         if (*t == 0) {
301                 /*
302                  * current setting unknown
303                  */
304                 if (!getsigaction(signo, &sigact)) {
305                         /*
306                          * Pretend it worked; maybe we should give a warning
307                          * here, but other shells don't. We don't alter
308                          * sigmode, so that we retry every time.
309                          */
310                         return;
311                 }
312                 if (sigact == SIG_IGN) {
313                         if (mflag && (signo == SIGTSTP ||
314                              signo == SIGTTIN || signo == SIGTTOU)) {
315                                 *t = S_IGN;     /* don't hard ignore these */
316                         } else
317                                 *t = S_HARD_IGN;
318                 } else {
319                         *t = S_RESET;   /* force to be set */
320                 }
321         }
322         if (*t == S_HARD_IGN || *t == action)
323                 return;
324         switch (action) {
325                 case S_DFL:     sigact = SIG_DFL;       break;
326                 case S_CATCH:   sigact = onsig;         break;
327                 case S_IGN:     sigact = SIG_IGN;       break;
328         }
329         *t = action;
330         sa.sa_handler = sigact;
331         sa.sa_flags = 0;
332         sigemptyset(&sa.sa_mask);
333         sigaction(signo, &sa, NULL);
334 }
335
336
337 /*
338  * Return the current setting for sig w/o changing it.
339  */
340 static int
341 getsigaction(int signo, sig_t *sigact)
342 {
343         struct sigaction sa;
344
345         if (sigaction(signo, NULL, &sa) == -1)
346                 return 0;
347         *sigact = (sig_t) sa.sa_handler;
348         return 1;
349 }
350
351
352 /*
353  * Ignore a signal.
354  */
355 void
356 ignoresig(int signo)
357 {
358
359         if (sigmode[signo] != S_IGN && sigmode[signo] != S_HARD_IGN) {
360                 signal(signo, SIG_IGN);
361         }
362         sigmode[signo] = S_HARD_IGN;
363 }
364
365
366 int
367 issigchldtrapped(void)
368 {
369
370         return (trap[SIGCHLD] != NULL && *trap[SIGCHLD] != '\0');
371 }
372
373
374 /*
375  * Signal handler.
376  */
377 void
378 onsig(int signo)
379 {
380
381         if (signo == SIGINT && trap[SIGINT] == NULL) {
382                 onint();
383                 return;
384         }
385
386         /* If we are currently in a wait builtin, prepare to break it */
387         if ((signo == SIGINT || signo == SIGQUIT) && in_waitcmd != 0) {
388                 breakwaitcmd = 1;
389                 pendingsig = signo;
390         }
391
392         if (trap[signo] != NULL && trap[signo][0] != '\0' &&
393             (signo != SIGCHLD || !ignore_sigchld)) {
394                 gotsig[signo] = 1;
395                 pendingsig = signo;
396
397                 /*
398                  * If a trap is set, not ignored and not the null command, we
399                  * need to make sure traps are executed even when a child
400                  * blocks signals.
401                  */
402                 if (Tflag && !(trap[signo][0] == ':' && trap[signo][1] == '\0'))
403                         breakwaitcmd = 1;
404         }
405
406 #ifndef NO_HISTORY
407         if (signo == SIGWINCH)
408                 gotwinch = 1;
409 #endif
410 }
411
412
413 /*
414  * Called to execute a trap.  Perhaps we should avoid entering new trap
415  * handlers while we are executing a trap handler.
416  */
417 void
418 dotrap(void)
419 {
420         int i;
421         int savestatus, prev_evalskip, prev_skipcount;
422
423         in_dotrap++;
424         for (;;) {
425                 pendingsig = 0;
426                 for (i = 1; i < NSIG; i++) {
427                         if (gotsig[i]) {
428                                 gotsig[i] = 0;
429                                 if (trap[i]) {
430                                         /*
431                                          * Ignore SIGCHLD to avoid infinite
432                                          * recursion if the trap action does
433                                          * a fork.
434                                          */
435                                         if (i == SIGCHLD)
436                                                 ignore_sigchld++;
437
438                                         /*
439                                          * Backup current evalskip
440                                          * state and reset it before
441                                          * executing a trap, so that the
442                                          * trap is not disturbed by an
443                                          * ongoing break/continue/return
444                                          * statement.
445                                          */
446                                         prev_evalskip  = evalskip;
447                                         prev_skipcount = skipcount;
448                                         evalskip = 0;
449
450                                         last_trapsig = i;
451                                         savestatus = exitstatus;
452                                         evalstring(trap[i], 0);
453
454                                         /*
455                                          * If such a command was not
456                                          * already in progress, allow a
457                                          * break/continue/return in the
458                                          * trap action to have an effect
459                                          * outside of it.
460                                          */
461                                         if (evalskip == 0 ||
462                                             prev_evalskip != 0) {
463                                                 evalskip  = prev_evalskip;
464                                                 skipcount = prev_skipcount;
465                                                 exitstatus = savestatus;
466                                         }
467
468                                         if (i == SIGCHLD)
469                                                 ignore_sigchld--;
470                                 }
471                                 break;
472                         }
473                 }
474                 if (i >= NSIG)
475                         break;
476         }
477         in_dotrap--;
478 }
479
480
481 /*
482  * Controls whether the shell is interactive or not.
483  */
484 void
485 setinteractive(int on)
486 {
487         static int is_interactive = -1;
488
489         if (on == is_interactive)
490                 return;
491         setsignal(SIGINT);
492         setsignal(SIGQUIT);
493         setsignal(SIGTERM);
494 #ifndef NO_HISTORY
495         setsignal(SIGWINCH);
496 #endif
497         is_interactive = on;
498 }
499
500
501 /*
502  * Called to exit the shell.
503  */
504 void
505 exitshell(int status)
506 {
507         TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
508         exiting = 1;
509         exiting_exitstatus = status;
510         exitshell_savedstatus();
511 }
512
513 void
514 exitshell_savedstatus(void)
515 {
516         struct jmploc loc1, loc2;
517         char *p;
518         volatile int sig = 0;
519         sigset_t sigs;
520
521         if (!exiting) {
522                 if (in_dotrap && last_trapsig) {
523                         sig = last_trapsig;
524                         exiting_exitstatus = sig + 128;
525                 } else
526                         exiting_exitstatus = oexitstatus;
527         }
528         exitstatus = oexitstatus = exiting_exitstatus;
529         if (setjmp(loc1.loc)) {
530                 goto l1;
531         }
532         if (setjmp(loc2.loc)) {
533                 goto l2;
534         }
535         handler = &loc1;
536         if ((p = trap[0]) != NULL && *p != '\0') {
537                 /*
538                  * Reset evalskip, or the trap on EXIT could be
539                  * interrupted if the last command was a "return".
540                  */
541                 evalskip = 0;
542                 trap[0] = NULL;
543                 evalstring(p, 0);
544         }
545 l1:   handler = &loc2;                  /* probably unnecessary */
546         flushall();
547 #if JOBS
548         setjobctl(0);
549 #endif
550 l2:
551         if (sig != 0 && sig != SIGSTOP && sig != SIGTSTP && sig != SIGTTIN &&
552             sig != SIGTTOU) {
553                 signal(sig, SIG_DFL);
554                 sigemptyset(&sigs);
555                 sigaddset(&sigs, sig);
556                 sigprocmask(SIG_UNBLOCK, &sigs, NULL);
557                 kill(getpid(), sig);
558                 /* If the default action is to ignore, fall back to _exit(). */
559         }
560         _exit(exiting_exitstatus);
561 }