summaryrefslogtreecommitdiffhomepage
path: root/src/trap.c
blob: 589038d1cc87e84f194a44e39320bfc3935753eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/**
 * @file trap.c
 * @brief Signals, and the `trap` and `kill` builtins.
 *
 * Handlers only record that a signal arrived.  Trap actions run from
 * trap_poll(), which the evaluator calls between commands.
 */
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

#include "exec.h"

/**
 * @brief Highest signal number the shell handles.
 */
#define MAXSIG 64

/**
 * @brief Signal names and numbers.
 */
static const struct {
    const char *name;
    int sig;
} signames[] = {
    {"HUP", SIGHUP},       {"INT", SIGINT},   {"QUIT", SIGQUIT},
    {"ILL", SIGILL},       {"ABRT", SIGABRT}, {"FPE", SIGFPE},
    {"KILL", SIGKILL},     {"SEGV", SIGSEGV}, {"PIPE", SIGPIPE},
    {"ALRM", SIGALRM},     {"TERM", SIGTERM}, {"USR1", SIGUSR1},
    {"USR2", SIGUSR2},     {"CHLD", SIGCHLD}, {"CONT", SIGCONT},
    {"STOP", SIGSTOP},     {"TSTP", SIGTSTP}, {"TTIN", SIGTTIN},
    {"TTOU", SIGTTOU},
#ifdef SIGBUS
    {"BUS", SIGBUS},
#endif
#ifdef SIGTRAP
    {"TRAP", SIGTRAP},
#endif
#ifdef SIGURG
    {"URG", SIGURG},
#endif
#ifdef SIGXCPU
    {"XCPU", SIGXCPU},
#endif
#ifdef SIGXFSZ
    {"XFSZ", SIGXFSZ},
#endif
#ifdef SIGVTALRM
    {"VTALRM", SIGVTALRM},
#endif
#ifdef SIGPROF
    {"PROF", SIGPROF},
#endif
#ifdef SIGWINCH
    {"WINCH", SIGWINCH},
#endif
};

/** @brief Pseudo-signal number of the Korn shell ERR trap. */
#define TRAP_ERR (MAXSIG + 1)

/**
 * @brief Trap actions.  Index 0 is the EXIT trap and TRAP_ERR the ERR trap.
 * nullptr means default, an empty string means ignore.
 */
static char *trap_action[MAXSIG + 2];

/**
 * @brief In a subshell: the traps of the shell that started it, kept for
 * printing only.
 *
 * POSIX wants `$(trap)` to print the invoking shell's traps even though
 * the subshell's own traps have been reset.
 */
static char *parent_action[MAXSIG + 2];
/**
 * @brief parent_action is what `trap` should print (no trap has been set in
 * this subshell yet).
 */
static bool show_parent;

/** @brief An ERR trap is set. eval_node() tests this after a failure. */
bool trap_err_set;
/**
 * @brief Job control is on: the terminal stop signals are ignored.
 */
static bool jobctl; /**< job control is on: the tty stop signals are ignored */
/**
 * @brief Set by the handler when signal N has arrived.
 */
static volatile sig_atomic_t got_signal[MAXSIG + 1];
/**
 * @brief Number of the latest signal that arrived, or 0.
 */
volatile sig_atomic_t trap_pending; /* number of the latest signal, or 0 */

/**
 * @brief Whether entry_ignored[N] has been worked out.
 */
static bool entry_checked[MAXSIG + 1];
/**
 * @brief Signal N was ignored when the shell started.
 */
static bool entry_ignored[MAXSIG + 1];
/**
 * @brief Signals the shell ignores for its own sake. Children get them reset.
 */
static sigset_t shell_ignored; /**< ignored for the shell's own sake */
/**
 * @brief shell_ignored is not empty.
 */
static bool have_shell_ignored;

/**
 * @brief The signal handler: just record the signal.
 */
static void on_signal(int sig) {
    got_signal[sig] = 1;
    trap_pending = sig;
}

/**
 * @brief Install a handler (or SIG_IGN / SIG_DFL) for a signal.
 */
static void set_handler(int sig, void (*handler)(int)) {
    struct sigaction sa = {.sa_handler = handler};
    sigemptyset(&sa.sa_mask);
    sigaction(sig, &sa, nullptr);
}

/**
 * @brief Put a signal back to SIG_DFL.
 *
 * For the two places that must not inherit or keep a handler: a parent's
 * ignored SIGCHLD (waitpid then fails with ECHILD for every child) and a
 * pipeline child that must die on SIGPIPE.
 *
 * @param sig The signal.
 */
void trap_sig_default(int sig) {
    set_handler(sig, SIG_DFL);
}

/**
 * @brief What a signal does in this shell when no trap is set for it.
 */
static void (*default_handler(int sig))(int) {
    if (jobctl && (sig == SIGTSTP || sig == SIGTTIN || sig == SIGTTOU))
        return SIG_IGN;
    if (opt.interactive) {
        if (sig == SIGINT)
            return on_signal;
        if (sig == SIGQUIT || sig == SIGTERM)
            return SIG_IGN;
    }
    return SIG_DFL;
}

/**
 * @brief Set up signals at startup: an interactive shell survives `^C`, `^\`
 * and a stray SIGTERM.
 */
void trap_init(void) {
    sigemptyset(&shell_ignored);
    if (!opt.interactive)
        return;
    set_handler(SIGINT, on_signal);
    set_handler(SIGQUIT, SIG_IGN);
    set_handler(SIGTERM, SIG_IGN);
    sigaddset(&shell_ignored, SIGQUIT);
    sigaddset(&shell_ignored, SIGTERM);
    have_shell_ignored = true;
}

/**
 * @brief Ignore, or stop ignoring, the terminal stop signals.
 *
 * A shell doing job control must not be stopped by `^Z` (SIGTSTP) or by
 * touching the terminal while a job owns it (SIGTTIN, SIGTTOU).  The
 * signals are remembered in the set that children get reset to default.
 *
 * @param on true when job control is being switched on.
 */
void trap_jobctl(bool on) {
    static const int sigs[] = {SIGTSTP, SIGTTIN, SIGTTOU};
    jobctl = on;
    for (size_t i = 0; i < ARRAY_LEN(sigs); i++) {
        if (trap_action[sigs[i]])
            continue; /* the user's trap stays in charge */
        set_handler(sigs[i], on ? SIG_IGN : SIG_DFL);
        if (on)
            sigaddset(&shell_ignored, sigs[i]);
        else
            sigdelset(&shell_ignored, sigs[i]);
    }
    if (on)
        have_shell_ignored = true;
}

/**
 * @brief Record a signal as if the shell had received it.
 *
 * Under job control `^C` is delivered to the foreground job only. The
 * shell calls this when it sees that the job died of SIGINT so that the
 * rest of the command line is abandoned in the usual way.
 *
 * @param sig Signal number.
 */
void trap_note(int sig) {
    on_signal(sig);
}

/**
 * @brief Signals a spawned child must have reset to their default action.
 * @return The set, or nullptr if there are none.
 */
const sigset_t *trap_spawn_defaults(void) {
    return have_shell_ignored ? &shell_ignored : nullptr;
}

/**
 * @brief Was this signal ignored when a non-interactive shell started?
 *
 * POSIX: such a signal stays ignored and cannot be trapped.
 */
static bool ignored_on_entry(int sig) {
    if (opt.interactive)
        return false;
    if (!entry_checked[sig]) {
        struct sigaction sa;
        entry_checked[sig] = true;
        entry_ignored[sig] =
            sigaction(sig, nullptr, &sa) == 0 && sa.sa_handler == SIG_IGN;
    }
    return entry_ignored[sig];
}

/**
 * @brief Set, clear or ignore the trap for a signal (or EXIT, or ERR).
 * @param sig    Signal number, 0 for EXIT, TRAP_ERR for ERR.
 * @param action Command text. "" to ignore. nullptr for the default.
 */
static void set_trap(int sig, const char *action) {
    if (sig && sig != TRAP_ERR && ignored_on_entry(sig))
        return;
    free(trap_action[sig]);
    trap_action[sig] = action ? xstrdup(action) : nullptr;
    show_parent = false;
    if (sig == TRAP_ERR)
        trap_err_set = action && *action;
    if (!sig || sig == TRAP_ERR)
        return;
    if (!action)
        set_handler(sig, default_handler(sig));
    else if (!*action)
        set_handler(sig, SIG_IGN);
    else
        set_handler(sig, on_signal);
}

/**
 * @brief Run the actions of any signals that have arrived.
 *
 * An interactive shell with no INT trap abandons the current command line
 * here by raising EXC_ERROR.
 */
void trap_poll(void) {
    static bool running;
    if (running)
        return;
    running = true;
    while (trap_pending) {
        trap_pending = 0;
        for (int sig = 1; sig <= MAXSIG; sig++) {
            if (!got_signal[sig])
                continue;
            got_signal[sig] = 0;
            const char *action = trap_action[sig];
            if (action && *action) {
                /* Run a copy: the action may replace its own trap.  An error
                 * in the action raises after the state is back, so the next
                 * poll runs the remaining signals instead of skipping them. */
                int saved = exitstatus;
                arena_marker mark = arena_mark(&scratch);
                jmploc jl;
                jmploc *prev = exc_handler;
                if (setjmp(jl.buf) == 0) {
                    exc_catch(&jl);
                    eval_string(arena_strndup(&scratch, action, strlen(action)),
                                0);
                } else {
                    exc_handler = prev;
                    running = false;
                    for (int s = 1; s <= MAXSIG; s++)
                        if (got_signal[s]) {
                            trap_pending = (sig_atomic_t)s;
                            break;
                        }
                    exc_raise(exc_code); /* exitstatus is the shell's now */
                }
                exc_handler = prev;
                arena_release(&scratch, mark);
                exitstatus = saved;
            } else if (sig == SIGINT && opt.interactive) {
                running = false;
                out_putc(&out2, '\n');
                out_flush(&out2);
                exitstatus = 128 + SIGINT;
                exc_raise(EXC_ERROR);
            }
        }
    }
    running = false;
}

/**
 * @brief Reset signals in a new subshell: traps are forgotten, ignored signals
 * stay ignored, and signals the shell ignored for itself go back to
 * default.
 */
void trap_reset_child(void) {
    for (int sig = 0; sig <= TRAP_ERR; sig++) {
        if (!show_parent) {
            free(parent_action[sig]);
            parent_action[sig] = nullptr;
        }
        if (!trap_action[sig] || !*trap_action[sig])
            continue;
        if (!show_parent)
            parent_action[sig] = trap_action[sig];
        else
            free(trap_action[sig]);
        trap_action[sig] = nullptr;
        if (sig && sig != TRAP_ERR)
            set_handler(sig, SIG_DFL);
    }
    show_parent = true;
    trap_err_set = false;
    if (have_shell_ignored) {
        if (!trap_action[SIGINT])
            set_handler(SIGINT, SIG_DFL);
        for (int sig = 1; sig <= MAXSIG; sig++) {
            if (sigismember(&shell_ignored, sig) == 1 && !trap_action[sig])
                set_handler(sig, SIG_DFL);
        }
        sigemptyset(&shell_ignored);
        have_shell_ignored = false;
        jobctl = false;
    }
}

/**
 * @brief Give up the signals the shell ignored for itself, before `exec`.
 *
 * A trapped signal's handler is reset by the kernel when the image is
 * replaced, so only SIG_IGN needs undoing here.  The trap text is left
 * alone: a failed `exec` leaves the shell running, and its EXIT trap still
 * has to run.  Nothing else calls this after a failure, so the shell_ignored
 * bookkeeping is simply cleared.
 */
void trap_reset_exec(void) {
    if (!have_shell_ignored)
        return;
    if (!trap_action[SIGINT])
        set_handler(SIGINT, SIG_DFL);
    for (int sig = 1; sig <= MAXSIG; sig++) {
        if (sigismember(&shell_ignored, sig) == 1 && !trap_action[sig])
            set_handler(sig, SIG_DFL);
    }
    sigemptyset(&shell_ignored);
    have_shell_ignored = false;
}

/**
 * @brief Run the ERR trap after a command has failed.
 *
 * The action sees the failing status in `$?`, and that status is still
 * the command's status afterwards.  A failure inside the action does not
 * run the trap again.
 */
void trap_run_err(void) {
    static bool running;
    const char *action = trap_action[TRAP_ERR];
    if (running || !action || !*action)
        return;
    running = true;
    int saved = exitstatus;
    arena_marker mark = arena_mark(&scratch);
    jmploc jl;
    jmploc *prev = exc_handler;
    if (setjmp(jl.buf) == 0) {
        exc_catch(&jl);
        eval_string(arena_strndup(&scratch, action, strlen(action)), 0);
    } else {
        exc_handler = prev;
        running = false;
        exc_raise(exc_code);
    }
    exc_handler = prev;
    arena_release(&scratch, mark);
    exitstatus = saved;
    running = false;
}

/**
 * @brief Is an EXIT trap set?
 */
bool trap_has_exit(void) {
    return trap_action[0] && *trap_action[0];
}

/**
 * @brief Must something run after the last command?
 *
 * The EXIT trap and the ERR trap both run after the command that ends the
 * shell, so when either is set the last command may not replace the
 * shell: the process would be gone before the trap could run.
 *
 * @return true if the EXIT or the ERR trap is set.
 */
bool trap_after_last(void) {
    return trap_has_exit() || trap_err_set;
}

/**
 * @brief Run the EXIT trap, once.
 */
void trap_run_exit(void) {
    char *action = trap_action[0];
    if (!action)
        return;
    trap_action[0] = nullptr;
    if (*action)
        eval_string(action, 0);
    free(action);
}

/* ---- signal names ---------------------------------------------------- */

/**
 * @brief Name of a signal, without "SIG".
 * @return The name, or nullptr if the number has none.
 */
static const char *signal_name(int sig) {
    if (sig == 0)
        return "EXIT";
    if (sig == TRAP_ERR)
        return "ERR";
    for (size_t i = 0; i < ARRAY_LEN(signames); i++) {
        if (signames[i].sig == sig)
            return signames[i].name;
    }
    return nullptr;
}

/**
 * @brief Parse a signal number or name (with or without "SIG").
 * @return The number. 0 for EXIT. -1 if unknown.
 */
static int signal_number(const char *s) {
    long n;
    if (isdigit((unsigned char)*s))
        return parse_long(s, &n) && n >= 0 && n <= MAXSIG ? (int)n : -1;
    if (!strcasecmp(s, "EXIT"))
        return 0;
    if (!strcasecmp(s, "ERR"))
        return TRAP_ERR;
    if (!strncasecmp(s, "SIG", 3))
        s += 3;
    for (size_t i = 0; i < ARRAY_LEN(signames); i++) {
        if (!strcasecmp(signames[i].name, s))
            return signames[i].sig;
    }
    return -1;
}

/**
 * @brief Print a signal's name, or its number if it has no name.
 */
static void print_signal(int sig) {
    const char *name = signal_name(sig);
    if (name)
        out_puts(&out1, name);
    else
        out_printf(&out1, "%d", sig);
}

/* ---- builtins -------------------------------------------------------- */

/**
 * @brief The `trap` builtin: `trap [-p]`, `trap action signal...`,
 * `trap - signal...`.
 */
/**
 * @brief Print one signal's trap in the form that would set it.
 * @param sig Signal number, 0 for EXIT, TRAP_ERR for ERR.
 */
static void print_trap(int sig) {
    const char *shown = trap_action[sig];
    if (!shown && show_parent)
        shown = parent_action[sig];
    if (!shown)
        return;
    out_puts(&out1, "trap -- ");
    out_quote(&out1, shown);
    out_putc(&out1, ' ');
    print_signal(sig);
    out_putc(&out1, '\n');
}

int builtin_trap(int argc, char **argv) {
    bool print = false;
    int i = 1;
    if (i < argc && !strcmp(argv[i], "-p")) {
        print = true; /* "trap -p" prints, like "trap" alone */
        i++;
    }
    if (i < argc && !strcmp(argv[i], "--"))
        i++;
    if (i >= argc) {
        for (int sig = 0; sig <= TRAP_ERR; sig++)
            print_trap(sig);
        return 0;
    }
    if (print) {
        int status = 0;
        for (; i < argc; i++) {
            int sig = signal_number(argv[i]);
            if (sig < 0) {
                sh_warn("trap: %s: bad signal", argv[i]);
                status = 1;
                continue;
            }
            print_trap(sig);
        }
        return status;
    }
    const char *action = nullptr;
    if (!strcmp(argv[i], "-"))
        i++;
    else if (!isdigit((unsigned char)argv[i][0]))
        action = argv[i++];

    int status = 0;
    for (; i < argc; i++) {
        int sig = signal_number(argv[i]);
        if (sig < 0) {
            sh_warn("trap: %s: bad signal", argv[i]);
            status = 1;
            continue;
        }
        set_trap(sig, action);
    }
    return status;
}

/**
 * @brief The `kill` builtin: `kill [-s sig | -sig] pid|%job...`, `kill -l [n]`.
 */
int builtin_kill(int argc, char **argv) {
    int sig = SIGTERM;
    int i = 1;
    if (i < argc && !strcmp(argv[i], "-l")) {
        if (i + 1 < argc) {
            long n;
            if (!parse_long(argv[i + 1], &n))
                return 2;
            print_signal((int)(n > 128 ? n - 128 : n));
            out_putc(&out1, '\n');
            return 0;
        }
        for (size_t k = 0; k < ARRAY_LEN(signames); k++)
            out_printf(&out1, "%s%s", k ? " " : "", signames[k].name);
        out_putc(&out1, '\n');
        return 0;
    }
    if (i < argc && !strcmp(argv[i], "-s")) {
        sig = i + 1 < argc ? signal_number(argv[i + 1]) : -1;
        i += 2;
        if (i < argc && !strcmp(argv[i], "--"))
            i++;
    } else if (i < argc && !strcmp(argv[i], "--")) {
        i++;
    } else if (i < argc && argv[i][0] == '-' && argv[i][1]) {
        sig = signal_number(argv[i] + 1);
        i++;
        if (i < argc && !strcmp(argv[i], "--"))
            i++;
    }
    if (sig < 0 || sig > MAXSIG) {
        sh_warn("kill: bad signal");
        return 2;
    }
    if (i >= argc) {
        sh_warn("kill: usage: kill [-s signal | -signal] pid ...");
        return 2;
    }
    int status = 0;
    for (; i < argc; i++) {
        long pid;
        if (argv[i][0] == '%') {
            if (job_signal(argv[i], sig) < 0) {
                sh_warn("kill: %s: %s", argv[i],
                        errno == ESRCH ? "no such job" : strerror(errno));
                status = 1;
            }
        } else if (!parse_long(argv[i], &pid)) {
            sh_warn("kill: %s: bad process id", argv[i]);
            status = 1;
        } else if (kill((pid_t)pid, sig) < 0) {
            sh_warn("kill: %s: %s", argv[i], strerror(errno));
            status = 1;
        }
    }
    return status;
}