diff options
| author | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-13 02:24:39 +0000 |
|---|---|---|
| committer | Sean Kurtz <seankurtz75@gmail.com> | 2026-11-13 02:24:39 +0000 |
| commit | 8cb846c0ad784c4ce249958113d59a331dd207e8 (patch) | |
| tree | 328f83d7e19710fcb52c7659962a1363492cb907 /src/exec.c | |
| parent | c3b270f82dd62a56e9d75cdd652c55a694a2da64 (diff) | |
| download | zash-8cb846c0ad784c4ce249958113d59a331dd207e8.tar.gz | |
Add extensions, job control and the interactive layer; convert to C11
Language: $'...', aliases, function keyword, (( )) and let, typeset and
integer, print, whence, setvar, ulimit, read -t, RANDOM, SECONDS, the
ERR trap, trap -p, chdir, and more set -o names.
Job control: a job table, process groups, terminal hand-over through
the spawn layer, jobs/fg/bg, wait %n and kill %n.
Interactive: prompt expansion, a built-in line editor with emacs and vi
modes, completion, history with fc and HISTFILE, and libedit as a
compile-time alternative (make EDIT=libedit LDLIBS=-ledit).
The source is now C11 (was C23), uses typedef'd structs and enums, and
has Doxygen comments throughout. Adds .clang-tidy, .clangd and a
Doxyfile.
Diffstat (limited to 'src/exec.c')
| -rw-r--r-- | src/exec.c | 986 |
1 files changed, 638 insertions, 348 deletions
@@ -1,5 +1,6 @@ -/* - * exec.c: the evaluator. +/** + * @file exec.c + * @brief The evaluator. * * The guiding rule (see DESIGN.md, "Process creation"): do the work in the * shell when the language allows it, create a process with spawn() when @@ -19,86 +20,145 @@ #include <unistd.h> #include "expand.h" +#include "interact.h" #include "parser.h" -enum skip skip_kind; +/** + * @brief A `break`, `continue` or `return` is in progress. + */ +skip_type skip_kind; +/** + * @brief Loop levels a pending `break` or `continue` still has to leave. + */ int skip_count; +/** + * @brief Number of enclosing loops. + */ int loop_depth; +/** + * @brief Number of function calls in progress. + */ int func_depth; +/** + * @brief Number of `.` files being read. + */ int dot_depth; -pid_t last_bg_pid; +/** + * @brief Processes created with spawn (reported by ZASH_PROCSTAT). + */ long stat_spawns; +/** + * @brief Processes created with fork (reported by ZASH_PROCSTAT). + */ long stat_forks; +/** + * @brief This process is a forked copy of the shell. + */ bool in_subshell; -/* Exit status of the last command substitution in the current command. */ +/** + * @brief A command substitution ran while the current command was expanded. + */ static bool cmdsub_ran; +/** + * @brief Its exit status: the status of a command that is only assignments. + */ static int cmdsub_status; /* ---- command table --------------------------------------------------- */ -/* - * One hash table answers "what is this command name?": it holds builtins, - * functions and the paths of external commands already found in PATH. +/** + * @brief Number of buckets in the command table. + */ +#define CTAB_SIZE ((size_t)256) +/** + * @brief PATH used by `command -p` and when PATH is unset. */ -constexpr size_t CTAB_SIZE = 256; static const char default_path[] = "/bin:/usr/bin"; -struct cmdent { +/** + * @brief One name in the command table. + * + * One hash table answers "what is this command name?": it holds builtins, + * functions and the paths of external commands already found in PATH. + */ +typedef struct cmdent { struct cmdent *next; - const struct builtin *bi; - struct func *fn; + const builtin *bi; + func *fn; char *path; + unsigned hash; /**< full hash of name: rules out collisions cheaply */ char name[]; -}; +} cmdent; -static struct cmdent *ctab[CTAB_SIZE]; +/** + * @brief The command table. + */ +static cmdent *ctab[CTAB_SIZE]; -static struct cmdent *cmd_lookup(const char *name, bool create) { +/** + * @brief Find a name in the command table. + * @param name Command name. + * @param create Add an empty entry if it is not there. + * @return The entry, or NULL. + */ +static cmdent *cmd_lookup(const char *name, bool create) { unsigned h = 5381; for (const char *p = name; *p; p++) h = h * 33 + (unsigned char)*p; - struct cmdent **bucket = &ctab[h % CTAB_SIZE]; - for (struct cmdent *e = *bucket; e; e = e->next) { - if (!strcmp(e->name, name)) + cmdent **bucket = &ctab[h % CTAB_SIZE]; + for (cmdent *e = *bucket; e; e = e->next) { + if (e->hash == h && !strcmp(e->name, name)) return e; } if (!create) - return nullptr; + return NULL; size_t len = strlen(name) + 1; - struct cmdent *e = xmalloc(sizeof *e + len); - *e = (struct cmdent){.next = *bucket}; + cmdent *e = xmalloc(sizeof *e + len); + *e = (cmdent){.next = *bucket, .hash = h}; memcpy(e->name, name, len); *bucket = e; return e; } +/** + * @brief Forget every remembered command path (`hash -r`, or PATH changed). + */ void hash_clear(void) { for (size_t i = 0; i < CTAB_SIZE; i++) { - for (struct cmdent *e = ctab[i]; e; e = e->next) { + for (cmdent *e = ctab[i]; e; e = e->next) { free(e->path); - e->path = nullptr; + e->path = NULL; } } } +/** + * @brief Print the remembered command paths (`hash`). + */ void hash_print(void) { for (size_t i = 0; i < CTAB_SIZE; i++) { - for (const struct cmdent *e = ctab[i]; e; e = e->next) { + for (const cmdent *e = ctab[i]; e; e = e->next) { if (e->path) out_printf(&out1, "%s\n", e->path); } } } +/** + * @brief PATH hook: remembered paths are no longer valid. + */ static void path_changed(const char *value) { (void)value; hash_clear(); } -/* - * Look for `name` in the colon-separated `path`. Returns the full path - * (in scratch) of the first regular file found, or nullptr. +/** + * @brief Search a path list for a file. + * @param name File name without a slash. + * @param path Colon-separated directories. + * @param executable Require a regular file with execute permission. + * @return The full path in scratch memory, or NULL. */ char *path_search(const char *name, const char *path, bool executable) { size_t nlen = strlen(name); @@ -118,25 +178,35 @@ char *path_search(const char *name, const char *path, bool executable) { (!executable || (st.st_mode & 0111))) return full; if (!colon) - return nullptr; + return NULL; p = colon + 1; } } -/* - * "PATH=dir cmd": the search path for this one lookup. The result is not - * remembered, and remembered paths are not trusted. +/** + * @brief PATH from a `PATH=... command` prefix, used for that one lookup. */ static const char *path_override; -void find_command(const char *name, struct cmdinfo *ci, unsigned flags) { - *ci = (struct cmdinfo){.kind = C_NOTFOUND}; +/** + * @brief Work out what a command name refers to. + * + * Order: special builtins, functions, regular builtins, then PATH. A path + * found in PATH is remembered for next time. + * + * @param name The command name. + * @param ci Receives the answer. + * @param flags FC_NOFUNC to skip functions, FC_DEFPATH to search the + * default PATH. + */ +void find_command(const char *name, cmdinfo *ci, unsigned flags) { + *ci = (cmdinfo){.kind = C_NOTFOUND}; if (strchr(name, '/')) { ci->kind = C_EXTERNAL; ci->path = name; return; } - struct cmdent *e = cmd_lookup(name, false); + cmdent *e = cmd_lookup(name, false); if (e) { if (e->bi && (e->bi->flags & BI_SPECIAL)) { ci->kind = C_BUILTIN; @@ -174,31 +244,61 @@ void find_command(const char *name, struct cmdinfo *ci, unsigned flags) { } } -static void func_unref(struct func *fn) { +/** + * @brief Drop a reference to a function body, freeing it with the last one. + */ +static void func_unref(func *fn) { if (--fn->refs == 0) { arena_unref(fn->arena); free(fn); } } -void func_define(const char *name, struct node *body, struct arena *arena) { - struct cmdent *e = cmd_lookup(name, true); +/** + * @brief Define (or redefine) a function. + * @param name Its name. + * @param body Its body. + * @param owner Arena that owns the body; a reference is taken. + */ +void func_define(const char *name, node *body, arena *owner) { + cmdent *e = cmd_lookup(name, true); if (e->fn) func_unref(e->fn); e->fn = xmalloc(sizeof *e->fn); - *e->fn = (struct func){body, arena, 1}; - arena->refs++; + *e->fn = (func){body, owner, 1}; + owner->refs++; } +/** + * @brief Call a function for the name of every shell function. + * @param fn Callback. + * @param arg Passed through to the callback. + */ +void func_each(void (*fn)(const char *name, void *arg), void *arg) { + for (size_t i = 0; i < CTAB_SIZE; i++) { + for (const cmdent *e = ctab[i]; e; e = e->next) { + if (e->fn) + fn(e->name, arg); + } + } +} + +/** + * @brief Remove a function. + * @return false if there was none. + */ bool func_unset(const char *name) { - struct cmdent *e = cmd_lookup(name, false); + cmdent *e = cmd_lookup(name, false); if (!e || !e->fn) return false; func_unref(e->fn); - e->fn = nullptr; + e->fn = NULL; return true; } +/** + * @brief Fill the command table with the builtins and attach variable hooks. + */ void exec_init(void) { for (size_t i = 0; i < nbuiltins; i++) cmd_lookup(builtins[i].name, true)->bi = &builtins[i]; @@ -208,13 +308,19 @@ void exec_init(void) { /* ---- unwinding ------------------------------------------------------- */ -void unwind_save(struct unwind *u) { +/** + * @brief Record the state an exception handler must put back. + */ +void unwind_save(unwind *u) { u->scope = var_scope; u->redir = redir_top; u->input = input; } -void unwind_restore(const struct unwind *u) { +/** + * @brief Undo redirections, variable scopes and inputs back to a saved state. + */ +void unwind_restore(const unwind *u) { redir_unwind(u->redir); scope_unwind(u->scope); input_unwind(u->input); @@ -222,110 +328,15 @@ void unwind_restore(const struct unwind *u) { /* ---- processes ------------------------------------------------------- */ -struct bgjob { - struct bgjob *next; - pid_t pid; - int status; - bool done; -}; - -static struct bgjob *bgjobs; - -static int status_of(int wstatus) { - if (WIFEXITED(wstatus)) - return WEXITSTATUS(wstatus); - if (WIFSIGNALED(wstatus)) - return 128 + WTERMSIG(wstatus); - return 1; -} - -/* Wait for a foreground child and report death by signal. */ -int wait_fg(pid_t pid) { - int wstatus; - while (waitpid(pid, &wstatus, 0) < 0) { - if (errno != EINTR) - return 127; - } - if (WIFSIGNALED(wstatus)) { - int sig = WTERMSIG(wstatus); - if (sig != SIGINT && sig != SIGPIPE) { - out_printf(&out2, "%s\n", strsignal(sig)); - out_flush(&out2); - } - } - return status_of(wstatus); -} - -void jobs_add(pid_t pid) { - struct bgjob *j = xmalloc(sizeof *j); - *j = (struct bgjob){bgjobs, pid, 0, false}; - bgjobs = j; - last_bg_pid = pid; -} - -/* Collect finished background children; forget all but the latest. */ -void jobs_reap(void) { - for (struct bgjob **pj = &bgjobs; *pj;) { - struct bgjob *j = *pj; - int wstatus; - if (!j->done && waitpid(j->pid, &wstatus, WNOHANG) == j->pid) { - j->done = true; - j->status = status_of(wstatus); - } - if (j->done && j->pid != last_bg_pid) { - *pj = j->next; - free(j); - } else { - pj = &j->next; - } - } -} - -/* The `wait` builtin for one pid: 127 if it is not a child of ours. */ -int jobs_wait(pid_t pid) { - int status = 127; - bool done = false; - for (struct bgjob **pj = &bgjobs; *pj; pj = &(*pj)->next) { - struct bgjob *j = *pj; - if (j->pid != pid) - continue; - done = j->done; - status = j->status; - *pj = j->next; - free(j); - break; - } - if (done) - return status; - int wstatus; - while (waitpid(pid, &wstatus, 0) < 0) { - if (errno != EINTR) - return 127; - if (trap_pending) - return 128 + (int)trap_pending; - } - return status_of(wstatus); -} - -int jobs_wait_all(void) { - int wstatus; - for (;;) { - if (wait(&wstatus) < 0) { - if (errno != EINTR) - break; - if (trap_pending) - return 128 + (int)trap_pending; - } - } - while (bgjobs) { - struct bgjob *j = bgjobs; - bgjobs = j->next; - free(j); - } - return 0; -} - -/* fork() a copy of the shell. The child is a subshell. */ +/** + * @brief fork() a copy of the shell. + * + * The child is a subshell: it forgets the parent's jobs and traps, and + * under job control joins the process group of the job being launched. + * + * @return 0 in the child, the child's pid in the parent. A failed fork + * raises an error. + */ pid_t fork_shell(void) { flush_all(); (void)shell_pid(); /* fix $$ before the pid changes */ @@ -335,17 +346,23 @@ pid_t fork_shell(void) { if (pid == 0) { in_subshell = true; stat_spawns = stat_forks = 0; - bgjobs = nullptr; + if (job_launching) + job_child_setup(); /* while SIGTTOU is still ignored */ + jobs_forget(); trap_reset_child(); } else { stat_forks++; + if (job_launching) + job_add_proc(job_launching, pid); } return pid; } -/* Run `n` as the whole remaining life of this (forked) process. */ -[[noreturn]] static void child_eval(struct node *n) { - struct jmploc jl; +/** + * @brief Run a command as the whole remaining life of this (forked) process. + */ +static _Noreturn void child_eval(node *n) { + jmploc jl; if (setjmp(jl.buf) == 0) { exc_handler = &jl; eval_node(n, EV_EXIT); @@ -355,22 +372,26 @@ pid_t fork_shell(void) { /* ---- running external programs --------------------------------------- */ -/* - * Build the argument vector for a file the system refused to execute - * (ENOEXEC): the interpreter named on its "#!" line, or this shell. +/** + * @brief Build the argument vector for a file the system refused to execute + * (ENOEXEC): the interpreter named on its `#!` line, or this shell. + * @param path The file. + * @param argv The arguments it was to be run with. + * @return The new vector in scratch memory, or NULL if the file is not + * a script. */ static char **script_argv(const char *path, char **argv) { char head[256]; int fd = open(path, O_RDONLY); if (fd < 0) - return nullptr; + return NULL; ssize_t n = read(fd, head, sizeof head - 1); close(fd); if (n < 0) - return nullptr; + return NULL; if (memchr(head, '\0', (size_t)n)) { errno = ENOEXEC; /* a binary we cannot run, not a script */ - return nullptr; + return NULL; } head[n] = '\0'; @@ -394,7 +415,7 @@ static char **script_argv(const char *path, char **argv) { alen--; if (!*interp) { errno = ENOEXEC; - return nullptr; + return NULL; } nv[k++] = arena_strndup(&scratch, interp, strlen(interp)); if (alen) @@ -405,18 +426,24 @@ static char **script_argv(const char *path, char **argv) { nv[k++] = (char *)path; for (int i = 1; i < argc; i++) nv[k++] = argv[i]; - nv[k] = nullptr; + nv[k] = NULL; return nv; } +/** + * @brief Report that a command could not be run. + * @return 127 if it does not exist, otherwise 126. + */ static int exec_error(const char *name, int err) { bool missing = err == ENOENT || err == ENOTDIR; sh_warn("%s: %s", name, missing ? "not found" : strerror(err)); return missing ? 127 : 126; } -/* Replace the shell with a program. Does not return. */ -[[noreturn]] static void exec_path(const char *path, char **argv, char **envp) { +/** + * @brief Replace the shell with a program. Does not return. + */ +static _Noreturn void exec_path(const char *path, char **argv, char **envp) { flush_all(); trap_reset_child(); execve(path, argv, envp); @@ -430,10 +457,13 @@ static int exec_error(const char *name, int err) { _exit(status); } +/** + * @brief The `exec` builtin with a command: find it and replace the shell. + */ void shell_exec(char **argv, char **envp) { - struct cmdinfo ci; + cmdinfo ci; find_command(argv[0], &ci, FC_NOFUNC); - const char *path = ci.kind == C_EXTERNAL ? ci.path : nullptr; + const char *path = ci.kind == C_EXTERNAL ? ci.path : NULL; if (!path && !strchr(argv[0], '/')) { const char *search = var_get("PATH"); path = path_search(argv[0], search ? search : default_path, true); @@ -446,16 +476,30 @@ void shell_exec(char **argv, char **envp) { exec_path(path, argv, envp); } -/* spawn() a program. Returns its pid, or -1 with *status set. */ +/** + * @brief spawn() a program. + * + * On failure the message goes where the command's own stderr would have + * gone, so `cmd 2>/dev/null` silences it. + * + * @param path Program file. + * @param argv Arguments. + * @param envp Environment. + * @param plan The child's descriptors. + * @param status Receives the exit status to report if the spawn fails. + * @return The child's pid, or -1. + */ static pid_t spawn_command(const char *path, char **argv, char **envp, - const struct fdplan *plan, int *status) { - struct spawn_req rq = { + const fdplan *plan, int *status) { + spawn_req rq = { .path = path, .argv = argv, .envp = envp, .fdmap = plan->map, .open_mask = fd_open_mask, .sigdfl = trap_spawn_defaults(), + .pgroup = job_launch_pgid(), + .tty_fd = job_launching ? job_tty() : -1, }; flush_all(); pid_t pid = sys_spawn(&rq); @@ -480,22 +524,30 @@ static pid_t spawn_command(const char *path, char **argv, char **envp, return -1; } stat_spawns++; + if (job_launching) + job_add_proc(job_launching, pid); return pid; } /* ---- simple commands ------------------------------------------------- */ -struct simple { - struct node *n; +/** + * @brief A simple command that has been expanded and looked up. + */ +typedef struct simple_cmd { + node *n; int argc; char **argv; - struct cmdinfo cmd; - bool via_command; /* reached through the `command` builtin */ - char **atext; /* the expanded "name=value" of each assignment */ + cmdinfo cmd; + bool via_command; /**< reached through the `command` builtin */ + char **atext; /**< the expanded "name=value" of each assignment */ int nassign; -}; +} simple_cmd; -static void xtrace(const struct simple *sc) { +/** + * @brief Print a command for `set -x`. + */ +static void xtrace(const simple_cmd *sc) { const char *ps4 = var_get("PS4"); out_puts(&out2, ps4 ? ps4 : "+ "); for (int i = 0; i < sc->argc; i++) { @@ -507,27 +559,35 @@ static void xtrace(const struct simple *sc) { out_flush(&out2); } -/* Expand the command's words and find out what it names. */ -static void simple_prep(struct node *n, struct simple *sc) { +/** + * @brief Expand a simple command's words and find out what it names. + * + * The words are expanded first and the assignments after them (the POSIX + * order). `command name ...` is resolved here to the command it names. + * + * @param n The N_SIMPLE node. + * @param sc Receives the prepared command. + */ +static void simple_prep(node *n, simple_cmd *sc) { sc->n = n; sc->via_command = false; - sc->cmd = (struct cmdinfo){}; + sc->cmd = (cmdinfo){0}; cmdsub_ran = false; cur_lineno = n->lineno; - sc->atext = nullptr; + sc->atext = NULL; sc->nassign = 0; sc->argv = expand_words(n->u.simple.args, &sc->argc); if (!sc->argc) return; - path_override = nullptr; + path_override = NULL; if (n->u.simple.assigns) { /* Expanded once, here, after the words (POSIX order). */ - for (const struct word *w = n->u.simple.assigns; w; w = w->next) + for (const word *w = n->u.simple.assigns; w; w = w->next) sc->nassign++; sc->atext = arena_alloc(&scratch, (size_t)sc->nassign * sizeof *sc->atext); int k = 0; - for (const struct word *w = n->u.simple.assigns; w; w = w->next) { + for (const word *w = n->u.simple.assigns; w; w = w->next) { sc->atext[k] = expand_assign(w); if (w->assign_len == 4 && !memcmp(sc->atext[k], "PATH", 4)) path_override = sc->atext[k] + 5; @@ -540,7 +600,7 @@ static void simple_prep(struct node *n, struct simple *sc) { for (;;) { find_command(sc->argv[0], &sc->cmd, flags); if (sc->cmd.kind != C_BUILTIN || sc->cmd.bi->fn != builtin_command) { - path_override = nullptr; + path_override = NULL; return; } /* "command [-p] name ...": look `name` up afresh, minus functions. */ @@ -553,7 +613,7 @@ static void simple_prep(struct node *n, struct simple *sc) { if (i < sc->argc && !strcmp(sc->argv[i], "--")) i++; if (i >= sc->argc || sc->argv[i][0] == '-') { - path_override = nullptr; + path_override = NULL; return; /* -v, -V or nothing: the builtin handles it */ } sc->argv += i; @@ -563,11 +623,15 @@ static void simple_prep(struct node *n, struct simple *sc) { } } -/* simple_prep on behalf of a child: an error is the child's, not ours. */ -static bool guarded_prep(struct node *n, struct simple *sc) { - struct jmploc jl; - struct jmploc *prev = exc_handler; - struct unwind u; +/** + * @brief simple_prep() on behalf of a child: an expansion error is the child's + * failure, not the shell's. + * @return false if expansion failed; `$?` holds the status. + */ +static bool guarded_prep(node *n, simple_cmd *sc) { + jmploc jl; + jmploc *prev = exc_handler; + unwind u; bool ok = true; unwind_save(&u); if (setjmp(jl.buf) == 0) { @@ -581,25 +645,36 @@ static bool guarded_prep(struct node *n, struct simple *sc) { return ok; } -/* The NAME part of an expanded assignment is everything before the '='. */ +/** + * @brief Perform one expanded `name=value` assignment. + */ static void assign_text(const char *text, unsigned flags) { size_t nlen = (size_t)(strchr(text, '=') - text); var_set_n(text, nlen, text + nlen + 1, flags); } -/* Assignments with no command: each sees the ones before it. */ -static void assign_words(const struct word *assigns) { - for (const struct word *w = assigns; w; w = w->next) +/** + * @brief Perform assignments that stand alone, each seeing the ones before it. + */ +static void assign_words(const word *assigns) { + for (const word *w = assigns; w; w = w->next) assign_text(expand_assign(w), 0); } -static void assign_all(const struct simple *sc) { +/** + * @brief Perform a prepared command's assignments permanently (special + * builtins). + */ +static void assign_all(const simple_cmd *sc) { for (int i = 0; i < sc->nassign; i++) assign_text(sc->atext[i], 0); } -/* Assignments that last only as long as the current scope. */ -static void assign_temp(const struct simple *sc) { +/** + * @brief Perform a prepared command's assignments for the current scope only, + * exported, as for `X=1 builtin` and `X=1 function`. + */ +static void assign_temp(const simple_cmd *sc) { for (int i = 0; i < sc->nassign; i++) { const char *text = sc->atext[i]; size_t nlen = (size_t)(strchr(text, '=') - text); @@ -608,18 +683,24 @@ static void assign_temp(const struct simple *sc) { } } -/* - * Run an external command. `in` and `out`, when not -1, are descriptors - * for its stdin and stdout (a pipeline or command substitution). With - * `async`, the pid is stored there and the command is not waited for. +/** + * @brief Run an external command. + * + * @param sc The prepared command. + * @param flags EV_EXIT allows replacing the shell with exec. + * @param in Descriptor for its stdin, or -1. + * @param out Descriptor for its stdout, or -1. + * @param async When not NULL, receives the pid and the command is not + * waited for (pipeline stages, `&`, command substitution). + * @return The exit status; 0 for an async launch. */ -static int run_external(struct simple *sc, unsigned flags, int in, int out, +static int run_external(simple_cmd *sc, unsigned flags, int in, int out, pid_t *async) { - const struct node *n = sc->n; + const node *n = sc->n; char **envp = sc->nassign ? var_environ_with(sc->atext, sc->nassign) : var_environ(); - struct fdplan plan; + fdplan plan; plan_init(&plan, in, out); if (!plan_redirs(&plan, n->redirs)) { plan_close(&plan); @@ -630,18 +711,32 @@ static int run_external(struct simple *sc, unsigned flags, int in, int out, plan_apply(&plan); exec_path(sc->cmd.path, sc->argv, envp); } + /* Under job control a foreground command is a job of its own. */ + job *jb = + !async && jc_active() && !job_launching ? job_begin(n, true) : NULL; int status = 0; pid_t pid = spawn_command(sc->cmd.path, sc->argv, envp, &plan, &status); plan_close(&plan); - if (pid < 0) + if (pid < 0) { + if (jb) + job_release(jb); return status; + } if (async) { *async = pid; return 0; } + if (jb) { + status = job_wait_fg(jb); + job_release(jb); + return status; + } return wait_fg(pid); } +/** + * @brief Flush a builtin's output and turn a write error into a failure. + */ static int finish_builtin(int status) { out_flush(&out1); if (out1.err) { @@ -654,13 +749,19 @@ static int finish_builtin(int status) { return status; } -static int run_builtin(struct simple *sc) { - const struct node *n = sc->n; - const struct builtin *bi = sc->cmd.bi; +/** + * @brief Run a builtin with its assignments and redirections. + * + * Assignments before a special builtin persist; before a regular builtin + * they last only for the call. + */ +static int run_builtin(simple_cmd *sc) { + const node *n = sc->n; + const builtin *bi = sc->cmd.bi; bool special = (bi->flags & BI_SPECIAL) && !sc->via_command; bool scoped = !special && n->u.simple.assigns; - struct varscope vs; - struct redirsave rs; + varscope vs; + redirsave rs; int status; if (scoped) { @@ -685,19 +786,27 @@ static int run_builtin(struct simple *sc) { return status; } -int call_function(struct func *fn, int argc, char **argv, unsigned flags) { +/** + * @brief Call a shell function. + * @param fn The function. + * @param argc Argument count, including the name. + * @param argv Arguments; argv[0] is the name. + * @param flags EV_TESTED if the status is being tested. + * @return The function's exit status. + */ +int call_function(func *fn, int argc, char **argv, unsigned flags) { if (stack_low()) sh_error("%s: functions nested too deeply", argv[0]); - struct shparam saved_param = shellparam; + shparam saved_param = shellparam; int saved_loop = loop_depth; - struct jmploc jl; - struct jmploc *prev = exc_handler; + jmploc jl; + jmploc *prev = exc_handler; bool raised = false; fn->refs++; func_depth++; loop_depth = 0; - shellparam = (struct shparam){argc - 1, argv + 1, nullptr}; + shellparam = (shparam){argc - 1, argv + 1, NULL}; if (setjmp(jl.buf) == 0) { exc_handler = &jl; eval_node(fn->body, flags & EV_TESTED); @@ -717,10 +826,13 @@ int call_function(struct func *fn, int argc, char **argv, unsigned flags) { return exitstatus; } -static int run_function(struct simple *sc, unsigned flags) { - const struct node *n = sc->n; - struct varscope vs; - struct redirsave rs; +/** + * @brief Run a function with its temporary assignments and redirections. + */ +static int run_function(simple_cmd *sc, unsigned flags) { + const node *n = sc->n; + varscope vs; + redirsave rs; int status = 2; scope_push(&vs, false, true); @@ -734,9 +846,14 @@ static int run_function(struct simple *sc, unsigned flags) { return status; } -static int run_assignments(struct simple *sc) { - const struct node *n = sc->n; - struct redirsave rs; +/** + * @brief Run a command that has no command word: assignments and redirections + * only. + * @return The status of the last command substitution, else 0. + */ +static int run_assignments(simple_cmd *sc) { + const node *n = sc->n; + redirsave rs; if (n->redirs) { /* "> file" alone still creates the file */ if (!redir_push(n->redirs, &rs)) return 2; @@ -746,7 +863,10 @@ static int run_assignments(struct simple *sc) { return cmdsub_ran ? cmdsub_status : 0; } -static int simple_run(struct simple *sc, unsigned flags) { +/** + * @brief Run a prepared simple command, whatever it turned out to be. + */ +static int simple_run(simple_cmd *sc, unsigned flags) { if (!sc->argc) return run_assignments(sc); switch (sc->cmd.kind) { @@ -755,10 +875,10 @@ static int simple_run(struct simple *sc, unsigned flags) { case C_FUNC: return run_function(sc, flags); case C_EXTERNAL: - return run_external(sc, flags, -1, -1, nullptr); + return run_external(sc, flags, -1, -1, NULL); case C_NOTFOUND: { /* The message belongs on the command's stderr, not ours. */ - struct redirsave rs; + redirsave rs; if (sc->n->redirs && !redir_push(sc->n->redirs, &rs)) return 2; sh_warn("%s: not found", sc->argv[0]); @@ -767,11 +887,14 @@ static int simple_run(struct simple *sc, unsigned flags) { return 127; } } - unreachable(); + UNREACHABLE(); } -[[noreturn]] static void child_simple(struct simple *sc) { - struct jmploc jl; +/** + * @brief Run a prepared simple command as the rest of a forked child's life. + */ +static _Noreturn void child_simple(simple_cmd *sc) { + jmploc jl; if (setjmp(jl.buf) == 0) { exc_handler = &jl; exitstatus = simple_run(sc, EV_EXIT); @@ -779,23 +902,27 @@ static int simple_run(struct simple *sc, unsigned flags) { exit_shell(exitstatus); } -/* - * Can this command stand in for a subshell without a process? Only a - * builtin that does nothing but write to out1/out2, with no redirections - * or assignments of its own. +/** + * @brief Can this command stand in for a subshell without a process? + * + * Only a builtin that does nothing but write to out1/out2, with no + * redirections or assignments of its own. */ -static bool is_pure(const struct simple *sc) { +static bool is_pure(const simple_cmd *sc) { return sc->argc && sc->cmd.kind == C_BUILTIN && (sc->cmd.bi->flags & BI_PURE) && !sc->n->redirs && !sc->n->u.simple.assigns; } -/* Run a pure builtin with its standard output going to `o`. */ -static int run_pure(struct simple *sc, struct output *o) { - struct output saved = out1; - struct jmploc jl; - struct jmploc *prev = exc_handler; - struct unwind u; +/** + * @brief Run a pure builtin with its standard output going to `o`. + * @return Its exit status. + */ +static int run_pure(simple_cmd *sc, output *o) { + output saved = out1; + jmploc jl; + jmploc *prev = exc_handler; + unwind u; int status; unwind_save(&u); @@ -816,16 +943,22 @@ static int run_pure(struct simple *sc, struct output *o) { /* ---- pipelines ------------------------------------------------------- */ -struct stage { - int in; /* read end feeding this stage, or -1 */ - int out; /* write end this stage feeds, or -1 */ +/** + * @brief One command of a pipeline. + */ +typedef struct stage { + int in; /**< read end feeding this stage, or -1 */ + int out; /**< write end this stage feeds, or -1 */ pid_t pid; int status; - bool deferred; /* a pure builtin to run in the shell */ - struct simple sc; -}; + bool deferred; /**< a pure builtin to run in the shell */ + simple_cmd sc; +} stage; -static void close_stage(struct stage *s) { +/** + * @brief Close the pipe ends a stage still holds. + */ +static void close_stage(stage *s) { if (s->in >= 0) close(s->in); if (s->out >= 0) @@ -833,9 +966,20 @@ static void close_stage(struct stage *s) { s->in = s->out = -1; } -/* Start a stage that is not the last one. */ -static void launch_stage(struct stage *st, int nc, int i, struct node *c) { - struct stage *s = &st[i]; +/** + * @brief Start one stage of a pipeline. + * + * An external command is spawned with the pipe ends in its fd plan. A + * pure builtin is deferred, to run in the shell once its reader exists. + * Anything else needs a copy of the shell and is forked. + * + * @param st The stages. + * @param nc Number of stages (for closing pipes in a forked child). + * @param i Which stage. + * @param c Its command. + */ +static void launch_stage(stage *st, int nc, int i, node *c) { + stage *s = &st[i]; bool prepped = false; if (c->kind == N_SIMPLE) { if (!guarded_prep(c, &s->sc)) { @@ -849,7 +993,7 @@ static void launch_stage(struct stage *st, int nc, int i, struct node *c) { close_stage(s); return; } - if (is_pure(&s->sc)) { + if (is_pure(&s->sc) && s->out >= 0) { s->deferred = true; /* run once its reader exists */ return; } @@ -875,31 +1019,36 @@ static void launch_stage(struct stage *st, int nc, int i, struct node *c) { close_stage(s); } -/* - * Run a deferred pure builtin, sending its output down the pipe. +/** + * @brief Run a deferred pure builtin, sending its output down the pipe. * * If the reader is already a process, the builtin writes straight into * the pipe. If the reader is this shell (the last stage, or another * deferred stage) nobody would drain the pipe while we write, so the * output is collected in memory first: up to PIPE_BUF bytes are certain * to fit in an empty pipe and cost no process at all; anything larger is - * handed to a forked writer. `stream` is false when the far end of the - * whole pipeline is the shell (command substitution): then even a writer - * with a live reader could fill every pipe in the chain and block. + * handed to a forked writer. + * + * @param st The stages. + * @param nc Number of stages. + * @param i Which stage. + * @param stream false when the far end of the whole pipeline is the shell + * (command substitution): then even a writer with a live + * reader could fill every pipe in the chain and block. */ -static void run_deferred(struct stage *st, int nc, int i, bool stream) { - struct stage *s = &st[i]; +static void run_deferred(stage *st, int nc, int i, bool stream) { + stage *s = &st[i]; if (stream && st[i + 1].pid > 0) { char buf[1024]; - struct output o = {buf, 0, sizeof buf, s->out, 0}; + output o = {buf, 0, sizeof buf, s->out, 0}; s->status = run_pure(&s->sc, &o); close_stage(s); return; } - struct output o = {.fd = OUT_MEM}; + output o = {.fd = OUT_MEM}; s->status = run_pure(&s->sc, &o); if (o.len <= PIPE_BUF) { - struct output direct = {o.buf, o.len, o.len, s->out, 0}; + output direct = {o.buf, o.len, o.len, s->out, 0}; out_flush(&direct); } else { pid_t pid = fork_shell(); @@ -909,7 +1058,7 @@ static void run_deferred(struct stage *st, int nc, int i, bool stream) { for (int j = 0; j < nc; j++) close_stage(&st[j]); /* or we would never see EPIPE */ signal(SIGPIPE, SIG_DFL); - struct output direct = {o.buf, o.len, o.len, out, 0}; + output direct = {o.buf, o.len, o.len, out, 0}; out_flush(&direct); _exit(0); } @@ -919,17 +1068,36 @@ static void run_deferred(struct stage *st, int nc, int i, bool stream) { close_stage(s); } -static void read_all(int fd, struct strbuf *sb); +static void read_all(int fd, strbuf *sb); -/* Close what is left, reap every child, and work out the status. */ -static int pipe_finish(struct stage *st, int nc, int total) { +/** + * @brief Close what is left of a pipeline, reap every child, and work out the + * status. + * @param st The stages. + * @param nc Number of commands. + * @param total Number of stage slots (one more when capturing). + * @param jb The job, under job control; else NULL. + * @return Status of the last command, or with `pipefail` of the last one + * that failed. + */ +static int pipe_finish(stage *st, int nc, int total, job *jb) { for (int i = 0; i < total; i++) close_stage(&st[i]); - for (int i = 0; i < nc; i++) { - if (st[i].pid > 0) - st[i].status = wait_fg(st[i].pid); - else if (st[i].pid < 0) - wait_fg(-st[i].pid); + if (jb) { + /* Job control: the job is waited for (and may stop) as a unit. */ + job_wait_fg(jb); + for (int i = 0; i < nc; i++) { + if (st[i].pid > 0) + st[i].status = job_status_of(jb, st[i].pid); + } + job_release(jb); + } else { + for (int i = 0; i < nc; i++) { + if (st[i].pid > 0) + st[i].status = wait_fg(st[i].pid); + else if (st[i].pid < 0) + wait_fg(-st[i].pid); + } } int status = st[nc - 1].status; if (opt.pipefail && !status) { @@ -941,22 +1109,29 @@ static int pipe_finish(struct stage *st, int nc, int total) { return status; } -/* - * Run a pipeline. With `cap`, the pipeline is the body of a command - * substitution: every stage is launched as a child (spawned if it is an - * external command, run in place if it is a pure builtin, forked - * otherwise), the last one writing to a pipe that is collected into - * `cap`. "$(grep x f | cut -f1)" therefore costs two spawns and no fork. +/** + * @brief Run a pipeline. + * + * Normally the last stage runs in this shell unless it is an external + * command. With `cap`, the pipeline is the body of a command + * substitution: every stage is launched as a child, the last one writing + * to a pipe that is collected into `cap`, so `$(grep x f | cut -f1)` + * costs two spawns and no fork. + * + * @param n The N_PIPE node. + * @param flags Evaluation flags. + * @param cap Where to collect the output, or NULL. + * @return The pipeline's exit status. */ -static int eval_pipe(struct node *n, unsigned flags, struct strbuf *cap) { +static int eval_pipe(node *n, unsigned flags, strbuf *cap) { int nc = n->u.pipe.n; int total = cap ? nc + 1 : nc; /* slot nc holds the capture pipe */ - struct node **cmds = n->u.pipe.cmds; - struct stage *st = arena_alloc(&scratch, (size_t)total * sizeof *st); - struct stage *last = &st[nc - 1]; - struct node *lc = cmds[nc - 1]; + node **cmds = n->u.pipe.cmds; + stage *st = arena_alloc(&scratch, (size_t)total * sizeof *st); + stage *last = &st[nc - 1]; + node *lc = cmds[nc - 1]; for (int i = 0; i < total; i++) - st[i] = (struct stage){.in = -1, .out = -1}; + st[i] = (stage){.in = -1, .out = -1}; for (int i = 0; i < total - 1; i++) { int p[2]; @@ -974,38 +1149,45 @@ static int eval_pipe(struct node *n, unsigned flags, struct strbuf *cap) { * Whatever preparing the earlier stages does to shell variables must * not outlive them: they are, notionally, subshells. */ - struct varscope vs; + /* + * Under job control the pipeline is one job in one process group, and + * every stage is a process, the last included: a stage running inside + * the shell could not be stopped with the rest of the job. + */ + job *jb = !cap && jc_active() && !job_launching ? job_begin(n, true) : NULL; + varscope vs; scope_push(&vs, true, false); bool any_deferred = false; - int nlaunch = cap ? nc : nc - 1; + int nlaunch = cap || jb ? nc : nc - 1; for (int i = 0; i < nlaunch; i++) { launch_stage(st, total, i, cmds[i]); any_deferred |= st[i].deferred; } scope_pop(); - if (cap) { + if (cap || jb) { if (any_deferred) { struct sigaction ignore = {.sa_handler = SIG_IGN}; struct sigaction old; sigaction(SIGPIPE, &ignore, &old); for (int i = nc - 1; i >= 0; i--) { if (st[i].deferred) - run_deferred(st, total, i, false); + run_deferred(st, total, i, !cap); } - sigaction(SIGPIPE, &old, nullptr); + sigaction(SIGPIPE, &old, NULL); } - read_all(st[nc].in, cap); - return pipe_finish(st, nc, total); + if (cap) + read_all(st[nc].in, cap); + return pipe_finish(st, nc, total, jb); } /* * The last stage runs in this shell unless it is an external command. * An error from here on must not strand the pipes or the children. */ - struct jmploc jl; - struct jmploc *prev = exc_handler; - struct unwind u; + jmploc jl; + jmploc *prev = exc_handler; + unwind u; volatile bool raised = false; unwind_save(&u); if (setjmp(jl.buf) == 0) { @@ -1030,10 +1212,10 @@ static int eval_pipe(struct node *n, unsigned flags, struct strbuf *cap) { if (st[i].deferred) run_deferred(st, nc, i, true); } - sigaction(SIGPIPE, &old, nullptr); + sigaction(SIGPIPE, &old, NULL); } if (!last_started) { - struct redirsave rs; + redirsave rs; redir_push_fd(&rs, 0, last->in); last->in = -1; if (lc->kind == N_SIMPLE) @@ -1049,20 +1231,26 @@ static int eval_pipe(struct node *n, unsigned flags, struct strbuf *cap) { exc_handler = prev; if (raised) { - pipe_finish(st, nc, total); + pipe_finish(st, nc, total, NULL); exc_raise(exc_code); } - return pipe_finish(st, nc, total); + return pipe_finish(st, nc, total, NULL); } /* ---- background commands --------------------------------------------- */ -static int eval_background(struct node *body) { - struct simple sc; +/** + * @brief Run a command in the background (`command &`). + * + * An external command is spawned; anything else is forked. Without job + * control the child ignores SIGINT and SIGQUIT and reads /dev/null. + */ +static int eval_background(node *body) { + simple_cmd sc; bool prepped = false; pid_t pid = 0; struct sigaction ignore = {.sa_handler = SIG_IGN}; - struct varscope vs; + varscope vs; scope_push(&vs, true, false); if (body->kind == N_SIMPLE) { @@ -1071,7 +1259,17 @@ static int eval_background(struct node *body) { return exitstatus; } prepped = true; - if (sc.argc && sc.cmd.kind == C_EXTERNAL) { + } + /* + * With job control the command gets a process group of its own and + * keeps its stdin and signal settings: it is the group, not ignored + * signals, that protects it from the keyboard. + */ + job *jb = jc_active() ? job_begin(body, false) : NULL; + if (prepped && sc.argc && sc.cmd.kind == C_EXTERNAL) { + if (jb) { + run_external(&sc, 0, -1, -1, &pid); + } else { /* The child inherits "ignored", which spawn cannot set. */ struct sigaction old_int; struct sigaction old_quit; @@ -1079,37 +1277,47 @@ static int eval_background(struct node *body) { sigaction(SIGINT, &ignore, &old_int); sigaction(SIGQUIT, &ignore, &old_quit); run_external(&sc, 0, null, -1, &pid); - sigaction(SIGINT, &old_int, nullptr); - sigaction(SIGQUIT, &old_quit, nullptr); + sigaction(SIGINT, &old_int, NULL); + sigaction(SIGQUIT, &old_quit, NULL); if (null >= 0) close(null); - scope_pop(); - if (pid > 0) - jobs_add(pid); - return 0; } + scope_pop(); + if (jb) + job_end_bg(jb); + else if (pid > 0) + jobs_add(pid, body); + return 0; } pid = fork_shell(); if (pid == 0) { - sigaction(SIGINT, &ignore, nullptr); - sigaction(SIGQUIT, &ignore, nullptr); - int null = open("/dev/null", O_RDONLY); - if (null >= 0) { - dup2(null, 0); - close(null); + if (!jb) { + sigaction(SIGINT, &ignore, NULL); + sigaction(SIGQUIT, &ignore, NULL); + int null = open("/dev/null", O_RDONLY); + if (null >= 0) { + dup2(null, 0); + close(null); + } } if (prepped) child_simple(&sc); child_eval(body); } scope_pop(); - jobs_add(pid); + if (jb) + job_end_bg(jb); + else + jobs_add(pid, body); return 0; } /* ---- command substitution -------------------------------------------- */ -static void read_all(int fd, struct strbuf *sb) { +/** + * @brief Read a descriptor to end of file into a string builder. + */ +static void read_all(int fd, strbuf *sb) { for (;;) { sb_reserve(sb, 4096); ssize_t n = read(fd, sb->s + sb->len, 4096); @@ -1121,7 +1329,14 @@ static void read_all(int fd, struct strbuf *sb) { } } -static int cmdsub_fork(struct node *n, struct simple *sc, struct strbuf *sb) { +/** + * @brief Run a command substitution in a forked subshell (the general case). + * @param n The command. + * @param sc Its prepared form if it is a simple command, else NULL. + * @param sb Receives the output. + * @return The exit status. + */ +static int cmdsub_fork(node *n, simple_cmd *sc, strbuf *sb) { int p[2]; if (sys_pipe(p) < 0) sh_error("cannot create pipe: %s", strerror(errno)); @@ -1140,14 +1355,21 @@ static int cmdsub_fork(struct node *n, struct simple *sc, struct strbuf *sb) { return wait_fg(pid); } -/* Pick the cheapest way to run `n` and collect its output. */ -static int cmdsub_collect(struct node *n, struct strbuf *sb) { +/** + * @brief Pick the cheapest way to run a command substitution and collect its + * output. + * + * `$(<file)` is read directly; a pure builtin runs in the shell; an + * external command is spawned; a pipeline spawns its stages; only the + * rest forks. + */ +static int cmdsub_collect(node *n, strbuf *sb) { if (n->kind == N_PIPE) return eval_pipe(n, 0, sb); if (n->kind != N_SIMPLE) - return cmdsub_fork(n, nullptr, sb); + return cmdsub_fork(n, NULL, sb); - const struct redir *r = n->redirs; + const redir *r = n->redirs; if (!n->u.simple.args && !n->u.simple.assigns && r && !r->next && r->op == R_IN) { /* $(<file): read the file ourselves. */ @@ -1162,7 +1384,7 @@ static int cmdsub_collect(struct node *n, struct strbuf *sb) { return 0; } - struct simple sc; + simple_cmd sc; if (!guarded_prep(n, &sc)) return exitstatus; if (sc.argc && sc.cmd.kind == C_EXTERNAL) { @@ -1180,7 +1402,7 @@ static int cmdsub_collect(struct node *n, struct strbuf *sb) { return status; } if (is_pure(&sc)) { - struct output o = {.fd = OUT_MEM}; + output o = {.fd = OUT_MEM}; int status = run_pure(&sc, &o); sb_put(sb, o.buf, o.len); free(o.buf); @@ -1191,15 +1413,26 @@ static int cmdsub_collect(struct node *n, struct strbuf *sb) { return cmdsub_fork(n, &sc, sb); } -char *cmdsub_run(struct node *n, size_t *lenp) { - struct strbuf sb; +/** + * @brief Run a command substitution. + * @param n The command, or NULL for an empty `$()`. + * @param lenp Receives the length of the output. + * @return The output with trailing newlines removed, in scratch memory. + */ +char *cmdsub_run(node *n, size_t *lenp) { + strbuf sb; sb_init(&sb, &scratch); int status = 0; if (n) { - struct varscope vs; + /* Its processes are the shell's own, never part of a job that + * happens to be half launched (a pipeline stage's arguments). */ + job *launching = job_launching; + varscope vs; + job_launching = NULL; scope_push(&vs, true, false); status = cmdsub_collect(n, &sb); scope_pop(); + job_launching = launching; } while (sb.len && sb.s[sb.len - 1] == '\n') sb.len--; @@ -1212,9 +1445,10 @@ char *cmdsub_run(struct node *n, size_t *lenp) { /* ---- compound commands ----------------------------------------------- */ -/* - * After a loop body: returns true if the loop must stop. A `continue` - * for this loop is absorbed and the loop carries on. +/** + * @brief After a loop body: must the loop stop? + * + * A `continue` for this loop is absorbed and the loop carries on. */ static bool loop_should_stop(void) { if (skip_kind == SKIP_NONE) @@ -1228,7 +1462,10 @@ static bool loop_should_stop(void) { return is_break; } -static int eval_loop(struct node *n, unsigned flags) { +/** + * @brief Run a `while` or `until` loop. + */ +static int eval_loop(node *n, unsigned flags) { int status = 0; loop_depth++; for (;;) { @@ -1248,7 +1485,10 @@ static int eval_loop(struct node *n, unsigned flags) { return status; } -static int eval_for(struct node *n, unsigned flags) { +/** + * @brief Run a `for` loop. + */ +static int eval_for(node *n, unsigned flags) { int count; char **words; if (n->u.for_.has_in) { @@ -1270,11 +1510,14 @@ static int eval_for(struct node *n, unsigned flags) { return status; } -static int eval_case(struct node *n, unsigned flags) { +/** + * @brief Run a `case` command. + */ +static int eval_case(node *n, unsigned flags) { const char *subject = expand_string(n->u.case_.subject->parts, XS_TILDE); const char *end = subject + strlen(subject); - for (struct caseitem *it = n->u.case_.items; it; it = it->next) { - for (const struct word *w = it->patterns; w; w = w->next) { + for (caseitem *it = n->u.case_.items; it; it = it->next) { + for (const word *w = it->patterns; w; w = w->next) { if (pat_match(expand_pattern(w->parts), subject, end)) return it->body ? eval_node(it->body, flags) : 0; } @@ -1282,29 +1525,51 @@ static int eval_case(struct node *n, unsigned flags) { return 0; } -static int eval_subshell(struct node *n, unsigned flags) { +/** + * @brief Run `( list )` in a forked copy of the shell, or in this process if + * the shell was about to exit anyway. + */ +static int eval_subshell(node *n, unsigned flags) { if (!(flags & EV_EXIT) || trap_has_exit()) { + job *jb = jc_active() && !job_launching ? job_begin(n, true) : NULL; pid_t pid = fork_shell(); - if (pid) - return wait_fg(pid); + if (pid) { + if (!jb) + return wait_fg(pid); + int status = job_wait_fg(jb); + job_release(jb); + return status; + } } else { trap_reset_child(); /* already the last thing this shell does */ in_subshell = true; } - struct redirsave rs; + redirsave rs; if (n->redirs && !redir_push(n->redirs, &rs)) exit_shell(1); child_eval(n->u.body); } -int eval_node(struct node *n, unsigned flags) { +/** + * @brief Evaluate a command tree. + * + * Scratch memory used by the command is released when it finishes. After + * a failing command the ERR trap and `errexit` are applied, and pending + * trap actions run. + * + * @param n The command, or NULL for an empty one. + * @param flags EV_EXIT if nothing follows the command, EV_TESTED if its + * status is being tested. + * @return The exit status, also left in `$?`. + */ +int eval_node(node *n, unsigned flags) { if (!n) return exitstatus = 0; if (opt.noexec && !opt.interactive) return exitstatus; - struct arena_mark mark = arena_mark(&scratch); - struct redirsave rs; + arena_marker mark = arena_mark(&scratch); + redirsave rs; bool redirected = false; bool leaf = false; /* a command whose failure triggers errexit */ int status = 0; @@ -1320,14 +1585,14 @@ int eval_node(struct node *n, unsigned flags) { switch (n->kind) { case N_SIMPLE: { - struct simple sc; + simple_cmd sc; simple_prep(n, &sc); status = simple_run(&sc, flags); leaf = true; break; } case N_PIPE: - status = eval_pipe(n, flags, nullptr); + status = eval_pipe(n, flags, NULL); leaf = true; break; case N_SUBSHELL: @@ -1382,15 +1647,26 @@ int eval_node(struct node *n, unsigned flags) { case N_FUNC: func_define(n->u.func.name, n->u.func.body, n->u.func.arena); break; + case N_ARITH: + /* (( expr )): true when the value is not zero. */ + cur_lineno = n->lineno; + status = !strcmp(expand_string(n->u.arith, 0), "0"); + leaf = true; + break; } if (redirected) redir_pop(false); arena_release(&scratch, mark); exitstatus = status; - if (leaf && status && opt.errexit && !(flags & EV_TESTED) && - skip_kind == SKIP_NONE) - exc_raise(EXC_EXIT); + if (leaf && status && !(flags & EV_TESTED) && skip_kind == SKIP_NONE) { + /* Only reached when a command has failed: the ERR trap and + * errexit cost a successful command nothing. */ + if (trap_err_set) + trap_run_err(); + if (opt.errexit) + exc_raise(EXC_EXIT); + } if (trap_pending) trap_poll(); return status; @@ -1398,13 +1674,19 @@ int eval_node(struct node *n, unsigned flags) { /* ---- the read-eval loop ---------------------------------------------- */ -/* Read commands from the current input and run them until it ends. */ +/** + * @brief Read commands from the current input and run them until it ends. + * @param flags RI_TOP for the main loop (recover from errors at a + * terminal), RI_EXEC_LAST if the last command may replace + * the shell. + * @return The status of the last command. + */ int run_input(unsigned flags) { - struct arena *volatile pa = arena_new(); - struct arena_mark mark = arena_mark(&scratch); - struct jmploc jl; - struct jmploc *prev = exc_handler; - struct unwind u; + arena *volatile pa = arena_new(); + arena_marker mark = arena_mark(&scratch); + jmploc jl; + jmploc *prev = exc_handler; + unwind u; int saved_loop = loop_depth; bool recover = (flags & RI_TOP) && opt.interactive; @@ -1428,17 +1710,18 @@ int run_input(unsigned flags) { skip_kind = SKIP_NONE; loop_depth = saved_loop; dot_depth = 0; + job_launching = NULL; } exc_handler = &jl; prompt_state = 1; } bool eof = false; - struct node *n = parse_command(pa, &eof); + node *n = parse_command(pa, &eof); if (n && (!opt.noexec || opt.interactive)) { input_sync(); bool last = (flags & RI_EXEC_LAST) && (eof || input_at_end()); eval_node(n, last ? EV_EXIT : 0); - if (bgjobs) + if (job_list && !opt.interactive) jobs_reap(); } arena_release(&scratch, mark); @@ -1448,6 +1731,10 @@ int run_input(unsigned flags) { } else { arena_reset(pa); } + if (eof && recover && input->tty && interact_refuse_eof()) { + input->eof = false; /* ^D ignored: prompt again */ + continue; + } if (eof || skip_kind == SKIP_RETURN) break; } @@ -1456,6 +1743,9 @@ int run_input(unsigned flags) { return exitstatus; } +/** + * @brief Run the commands in a string (`eval`, trap actions, `-c`). + */ int eval_string(const char *s, unsigned flags) { input_push_string(s, strlen(s)); run_input(flags); |
