/** * @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 #include #include #include #include #include #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; }