summaryrefslogtreecommitdiffhomepage
path: root/src/exec.c
diff options
context:
space:
mode:
authorSean Kurtz <seankurtz75@gmail.com>2026-11-12 17:42:49 +0000
committerSean Kurtz <seankurtz75@gmail.com>2026-11-12 17:42:49 +0000
commitc3b270f82dd62a56e9d75cdd652c55a694a2da64 (patch)
tree0e97654333e4cc6245d632156275c3d4f2301ae5 /src/exec.c
downloadzash-c3b270f82dd62a56e9d75cdd652c55a694a2da64.tar.gz
zash: scripting core, test suite and benchmarks
A clean-slate POSIX shell for z/OS UNIX in the Almquist tradition, written in C23 for Clang (Linux) and IBM Open XL C/C++ (z/OS). - Parser, expansion, arithmetic, redirection, traps and builtins. - Spawn-first execution: fd plans instead of fork+dup2, in-shell pure builtins for pipelines and command substitution, $(a | b) without a subshell. - Flat .POSIX Makefile; asan, valgrind, bench, compdb and z/OS targets. - Tests: posix (dash-generated), zash, process accounting, linux, zos. Nothing has been compiled or run on z/OS yet.
Diffstat (limited to 'src/exec.c')
-rw-r--r--src/exec.c1464
1 files changed, 1464 insertions, 0 deletions
diff --git a/src/exec.c b/src/exec.c
new file mode 100644
index 0000000..eae9246
--- /dev/null
+++ b/src/exec.c
@@ -0,0 +1,1464 @@
+/*
+ * exec.c: 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
+ * one is needed, and fork() only when a copy of the shell itself is
+ * required. Everything a spawned child needs is prepared here in the
+ * parent: its arguments, its environment and a plan for its descriptors.
+ */
+#include "exec.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "expand.h"
+#include "parser.h"
+
+enum skip skip_kind;
+int skip_count;
+int loop_depth;
+int func_depth;
+int dot_depth;
+pid_t last_bg_pid;
+long stat_spawns;
+long stat_forks;
+bool in_subshell;
+
+/* Exit status of the last command substitution in the current command. */
+static bool cmdsub_ran;
+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.
+ */
+constexpr size_t CTAB_SIZE = 256;
+static const char default_path[] = "/bin:/usr/bin";
+
+struct cmdent {
+ struct cmdent *next;
+ const struct builtin *bi;
+ struct func *fn;
+ char *path;
+ char name[];
+};
+
+static struct cmdent *ctab[CTAB_SIZE];
+
+static struct 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))
+ return e;
+ }
+ if (!create)
+ return nullptr;
+ size_t len = strlen(name) + 1;
+ struct cmdent *e = xmalloc(sizeof *e + len);
+ *e = (struct cmdent){.next = *bucket};
+ memcpy(e->name, name, len);
+ *bucket = e;
+ return e;
+}
+
+void hash_clear(void) {
+ for (size_t i = 0; i < CTAB_SIZE; i++) {
+ for (struct cmdent *e = ctab[i]; e; e = e->next) {
+ free(e->path);
+ e->path = nullptr;
+ }
+ }
+}
+
+void hash_print(void) {
+ for (size_t i = 0; i < CTAB_SIZE; i++) {
+ for (const struct cmdent *e = ctab[i]; e; e = e->next) {
+ if (e->path)
+ out_printf(&out1, "%s\n", e->path);
+ }
+ }
+}
+
+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.
+ */
+char *path_search(const char *name, const char *path, bool executable) {
+ size_t nlen = strlen(name);
+ for (const char *p = path;;) {
+ const char *colon = strchr(p, ':');
+ size_t dlen = colon ? (size_t)(colon - p) : strlen(p);
+ char *full = arena_alloc(&scratch, dlen + nlen + 2);
+ if (dlen) {
+ memcpy(full, p, dlen);
+ full[dlen] = '/';
+ memcpy(full + dlen + 1, name, nlen + 1);
+ } else {
+ memcpy(full, name, nlen + 1);
+ }
+ struct stat st;
+ if (stat(full, &st) == 0 && S_ISREG(st.st_mode) &&
+ (!executable || (st.st_mode & 0111)))
+ return full;
+ if (!colon)
+ return nullptr;
+ p = colon + 1;
+ }
+}
+
+/*
+ * "PATH=dir cmd": the search path for this one lookup. The result is not
+ * remembered, and remembered paths are not trusted.
+ */
+static const char *path_override;
+
+void find_command(const char *name, struct cmdinfo *ci, unsigned flags) {
+ *ci = (struct cmdinfo){.kind = C_NOTFOUND};
+ if (strchr(name, '/')) {
+ ci->kind = C_EXTERNAL;
+ ci->path = name;
+ return;
+ }
+ struct cmdent *e = cmd_lookup(name, false);
+ if (e) {
+ if (e->bi && (e->bi->flags & BI_SPECIAL)) {
+ ci->kind = C_BUILTIN;
+ ci->bi = e->bi;
+ return;
+ }
+ if (e->fn && !(flags & FC_NOFUNC)) {
+ ci->kind = C_FUNC;
+ ci->fn = e->fn;
+ return;
+ }
+ if (e->bi) {
+ ci->kind = C_BUILTIN;
+ ci->bi = e->bi;
+ return;
+ }
+ if (e->path && !(flags & FC_DEFPATH) && !path_override) {
+ ci->kind = C_EXTERNAL;
+ ci->path = e->path;
+ return;
+ }
+ }
+ const char *path = (flags & FC_DEFPATH) ? default_path
+ : path_override ? path_override
+ : var_get("PATH");
+ char *full = path_search(name, path ? path : default_path, true);
+ if (!full)
+ return;
+ ci->kind = C_EXTERNAL;
+ ci->path = full;
+ if (!(flags & FC_DEFPATH) && !path_override) {
+ e = cmd_lookup(name, true);
+ e->path = xstrdup(full);
+ ci->path = e->path;
+ }
+}
+
+static void func_unref(struct 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);
+ if (e->fn)
+ func_unref(e->fn);
+ e->fn = xmalloc(sizeof *e->fn);
+ *e->fn = (struct func){body, arena, 1};
+ arena->refs++;
+}
+
+bool func_unset(const char *name) {
+ struct cmdent *e = cmd_lookup(name, false);
+ if (!e || !e->fn)
+ return false;
+ func_unref(e->fn);
+ e->fn = nullptr;
+ return true;
+}
+
+void exec_init(void) {
+ for (size_t i = 0; i < nbuiltins; i++)
+ cmd_lookup(builtins[i].name, true)->bi = &builtins[i];
+ var_find("PATH", 4, true)->hook = path_changed;
+ var_find("OPTIND", 6, true)->hook = getopts_reset;
+}
+
+/* ---- unwinding ------------------------------------------------------- */
+
+void unwind_save(struct unwind *u) {
+ u->scope = var_scope;
+ u->redir = redir_top;
+ u->input = input;
+}
+
+void unwind_restore(const struct unwind *u) {
+ redir_unwind(u->redir);
+ scope_unwind(u->scope);
+ input_unwind(u->input);
+}
+
+/* ---- 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. */
+pid_t fork_shell(void) {
+ flush_all();
+ (void)shell_pid(); /* fix $$ before the pid changes */
+ pid_t pid = fork();
+ if (pid < 0)
+ sh_error("cannot fork: %s", strerror(errno));
+ if (pid == 0) {
+ in_subshell = true;
+ stat_spawns = stat_forks = 0;
+ bgjobs = nullptr;
+ trap_reset_child();
+ } else {
+ stat_forks++;
+ }
+ return pid;
+}
+
+/* Run `n` as the whole remaining life of this (forked) process. */
+[[noreturn]] static void child_eval(struct node *n) {
+ struct jmploc jl;
+ if (setjmp(jl.buf) == 0) {
+ exc_handler = &jl;
+ eval_node(n, EV_EXIT);
+ }
+ exit_shell(exitstatus);
+}
+
+/* ---- 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.
+ */
+static char **script_argv(const char *path, char **argv) {
+ char head[256];
+ int fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return nullptr;
+ ssize_t n = read(fd, head, sizeof head - 1);
+ close(fd);
+ if (n < 0)
+ return nullptr;
+ if (memchr(head, '\0', (size_t)n)) {
+ errno = ENOEXEC; /* a binary we cannot run, not a script */
+ return nullptr;
+ }
+ head[n] = '\0';
+
+ int argc = 0;
+ while (argv[argc])
+ argc++;
+ char **nv = arena_alloc(&scratch, ((size_t)argc + 4) * sizeof *nv);
+ int k = 0;
+ if (head[0] == '#' && head[1] == '!') {
+ char *p = head + 2;
+ p[strcspn(p, "\n")] = '\0';
+ p += strspn(p, " \t");
+ char *interp = p;
+ p += strcspn(p, " \t");
+ if (*p) {
+ *p++ = '\0';
+ p += strspn(p, " \t");
+ }
+ size_t alen = strlen(p);
+ while (alen && (p[alen - 1] == ' ' || p[alen - 1] == '\t'))
+ alen--;
+ if (!*interp) {
+ errno = ENOEXEC;
+ return nullptr;
+ }
+ nv[k++] = arena_strndup(&scratch, interp, strlen(interp));
+ if (alen)
+ nv[k++] = arena_strndup(&scratch, p, alen);
+ } else {
+ nv[k++] = (char *)shell_path();
+ }
+ nv[k++] = (char *)path;
+ for (int i = 1; i < argc; i++)
+ nv[k++] = argv[i];
+ nv[k] = nullptr;
+ return nv;
+}
+
+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) {
+ flush_all();
+ trap_reset_child();
+ execve(path, argv, envp);
+ if (errno == ENOEXEC) {
+ char **nv = script_argv(path, argv);
+ if (nv)
+ execve(nv[0], nv, envp);
+ }
+ int status = exec_error(argv[0], errno);
+ flush_all();
+ _exit(status);
+}
+
+void shell_exec(char **argv, char **envp) {
+ struct cmdinfo ci;
+ find_command(argv[0], &ci, FC_NOFUNC);
+ const char *path = ci.kind == C_EXTERNAL ? ci.path : nullptr;
+ if (!path && !strchr(argv[0], '/')) {
+ const char *search = var_get("PATH");
+ path = path_search(argv[0], search ? search : default_path, true);
+ }
+ if (!path) {
+ int status = exec_error(argv[0], ENOENT);
+ flush_all();
+ _exit(status);
+ }
+ exec_path(path, argv, envp);
+}
+
+/* spawn() a program. Returns its pid, or -1 with *status set. */
+static pid_t spawn_command(const char *path, char **argv, char **envp,
+ const struct fdplan *plan, int *status) {
+ struct spawn_req rq = {
+ .path = path,
+ .argv = argv,
+ .envp = envp,
+ .fdmap = plan->map,
+ .open_mask = fd_open_mask,
+ .sigdfl = trap_spawn_defaults(),
+ };
+ flush_all();
+ pid_t pid = sys_spawn(&rq);
+ if (pid < 0 && errno == ENOEXEC) {
+ char **nv = script_argv(path, argv);
+ if (nv) {
+ rq.path = nv[0];
+ rq.argv = nv;
+ pid = sys_spawn(&rq);
+ }
+ }
+ if (pid < 0) {
+ /* Report it where the command's own stderr would have gone. */
+ int err = errno;
+ int saved = out2.fd;
+ out_flush(&out2);
+ if (plan->map[2] != FD_CLOSED)
+ out2.fd = plan->map[2];
+ *status = exec_error(argv[0], err);
+ out_flush(&out2);
+ out2.fd = saved;
+ return -1;
+ }
+ stat_spawns++;
+ return pid;
+}
+
+/* ---- simple commands ------------------------------------------------- */
+
+struct simple {
+ struct 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 */
+ int nassign;
+};
+
+static void xtrace(const struct simple *sc) {
+ const char *ps4 = var_get("PS4");
+ out_puts(&out2, ps4 ? ps4 : "+ ");
+ for (int i = 0; i < sc->argc; i++) {
+ if (i)
+ out_putc(&out2, ' ');
+ out_quote(&out2, sc->argv[i]);
+ }
+ out_putc(&out2, '\n');
+ out_flush(&out2);
+}
+
+/* Expand the command's words and find out what it names. */
+static void simple_prep(struct node *n, struct simple *sc) {
+ sc->n = n;
+ sc->via_command = false;
+ sc->cmd = (struct cmdinfo){};
+ cmdsub_ran = false;
+ cur_lineno = n->lineno;
+ sc->atext = nullptr;
+ sc->nassign = 0;
+ sc->argv = expand_words(n->u.simple.args, &sc->argc);
+ if (!sc->argc)
+ return;
+ path_override = nullptr;
+ 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)
+ 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) {
+ sc->atext[k] = expand_assign(w);
+ if (w->assign_len == 4 && !memcmp(sc->atext[k], "PATH", 4))
+ path_override = sc->atext[k] + 5;
+ k++;
+ }
+ }
+ if (opt.xtrace)
+ xtrace(sc);
+ unsigned flags = 0;
+ for (;;) {
+ find_command(sc->argv[0], &sc->cmd, flags);
+ if (sc->cmd.kind != C_BUILTIN || sc->cmd.bi->fn != builtin_command) {
+ path_override = nullptr;
+ return;
+ }
+ /* "command [-p] name ...": look `name` up afresh, minus functions. */
+ int i = 1;
+ bool defpath = false;
+ if (i < sc->argc && !strcmp(sc->argv[i], "-p")) {
+ defpath = true;
+ i++;
+ }
+ if (i < sc->argc && !strcmp(sc->argv[i], "--"))
+ i++;
+ if (i >= sc->argc || sc->argv[i][0] == '-') {
+ path_override = nullptr;
+ return; /* -v, -V or nothing: the builtin handles it */
+ }
+ sc->argv += i;
+ sc->argc -= i;
+ sc->via_command = true;
+ flags = FC_NOFUNC | (defpath ? FC_DEFPATH : 0);
+ }
+}
+
+/* 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;
+ bool ok = true;
+ unwind_save(&u);
+ if (setjmp(jl.buf) == 0) {
+ exc_handler = &jl;
+ simple_prep(n, sc);
+ } else {
+ unwind_restore(&u);
+ ok = false;
+ }
+ exc_handler = prev;
+ return ok;
+}
+
+/* The NAME part of an expanded assignment is everything before the '='. */
+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)
+ assign_text(expand_assign(w), 0);
+}
+
+static void assign_all(const struct simple *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) {
+ for (int i = 0; i < sc->nassign; i++) {
+ const char *text = sc->atext[i];
+ size_t nlen = (size_t)(strchr(text, '=') - text);
+ var_save(var_find(text, nlen, true), var_scope);
+ var_set_n(text, nlen, text + nlen + 1, V_EXPORT);
+ }
+}
+
+/*
+ * 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.
+ */
+static int run_external(struct simple *sc, unsigned flags, int in, int out,
+ pid_t *async) {
+ const struct node *n = sc->n;
+ char **envp =
+ sc->nassign ? var_environ_with(sc->atext, sc->nassign) : var_environ();
+
+ struct fdplan plan;
+ plan_init(&plan, in, out);
+ if (!plan_redirs(&plan, n->redirs)) {
+ plan_close(&plan);
+ return 2;
+ }
+ if ((flags & EV_EXIT) && !async && !trap_has_exit()) {
+ /* Nothing comes after this command: become it. */
+ plan_apply(&plan);
+ exec_path(sc->cmd.path, sc->argv, envp);
+ }
+ int status = 0;
+ pid_t pid = spawn_command(sc->cmd.path, sc->argv, envp, &plan, &status);
+ plan_close(&plan);
+ if (pid < 0)
+ return status;
+ if (async) {
+ *async = pid;
+ return 0;
+ }
+ return wait_fg(pid);
+}
+
+static int finish_builtin(int status) {
+ out_flush(&out1);
+ if (out1.err) {
+ if (out1.err != EPIPE)
+ sh_warn("write error: %s", strerror(out1.err));
+ out1.err = 0;
+ if (!status)
+ status = 1;
+ }
+ return status;
+}
+
+static int run_builtin(struct simple *sc) {
+ const struct node *n = sc->n;
+ const struct 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;
+ int status;
+
+ if (scoped) {
+ scope_push(&vs, false, false);
+ assign_temp(sc);
+ } else {
+ assign_all(sc);
+ }
+ if (n->redirs && !redir_push(n->redirs, &rs)) {
+ if (special) { /* POSIX: a failed redirection here is fatal */
+ exitstatus = 2;
+ exc_raise(EXC_ERROR);
+ }
+ status = 2;
+ } else {
+ status = finish_builtin(bi->fn(sc->argc, sc->argv));
+ if (n->redirs)
+ redir_pop(bi->fn == builtin_exec);
+ }
+ if (scoped)
+ scope_pop();
+ return status;
+}
+
+int call_function(struct 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;
+ int saved_loop = loop_depth;
+ struct jmploc jl;
+ struct jmploc *prev = exc_handler;
+ bool raised = false;
+
+ fn->refs++;
+ func_depth++;
+ loop_depth = 0;
+ shellparam = (struct shparam){argc - 1, argv + 1, nullptr};
+ if (setjmp(jl.buf) == 0) {
+ exc_handler = &jl;
+ eval_node(fn->body, flags & EV_TESTED);
+ } else {
+ raised = true;
+ }
+ exc_handler = prev;
+ params_free(&shellparam);
+ shellparam = saved_param;
+ loop_depth = saved_loop;
+ func_depth--;
+ func_unref(fn);
+ if (raised)
+ exc_raise(exc_code);
+ if (skip_kind == SKIP_RETURN)
+ skip_kind = SKIP_NONE;
+ return exitstatus;
+}
+
+static int run_function(struct simple *sc, unsigned flags) {
+ const struct node *n = sc->n;
+ struct varscope vs;
+ struct redirsave rs;
+ int status = 2;
+
+ scope_push(&vs, false, true);
+ assign_temp(sc);
+ if (!n->redirs || redir_push(n->redirs, &rs)) {
+ status = call_function(sc->cmd.fn, sc->argc, sc->argv, flags);
+ if (n->redirs)
+ redir_pop(false);
+ }
+ scope_pop();
+ return status;
+}
+
+static int run_assignments(struct simple *sc) {
+ const struct node *n = sc->n;
+ struct redirsave rs;
+ if (n->redirs) { /* "> file" alone still creates the file */
+ if (!redir_push(n->redirs, &rs))
+ return 2;
+ redir_pop(false);
+ }
+ assign_words(n->u.simple.assigns);
+ return cmdsub_ran ? cmdsub_status : 0;
+}
+
+static int simple_run(struct simple *sc, unsigned flags) {
+ if (!sc->argc)
+ return run_assignments(sc);
+ switch (sc->cmd.kind) {
+ case C_BUILTIN:
+ return run_builtin(sc);
+ case C_FUNC:
+ return run_function(sc, flags);
+ case C_EXTERNAL:
+ return run_external(sc, flags, -1, -1, nullptr);
+ case C_NOTFOUND: {
+ /* The message belongs on the command's stderr, not ours. */
+ struct redirsave rs;
+ if (sc->n->redirs && !redir_push(sc->n->redirs, &rs))
+ return 2;
+ sh_warn("%s: not found", sc->argv[0]);
+ if (sc->n->redirs)
+ redir_pop(false);
+ return 127;
+ }
+ }
+ unreachable();
+}
+
+[[noreturn]] static void child_simple(struct simple *sc) {
+ struct jmploc jl;
+ if (setjmp(jl.buf) == 0) {
+ exc_handler = &jl;
+ exitstatus = simple_run(sc, EV_EXIT);
+ }
+ 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.
+ */
+static bool is_pure(const struct simple *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;
+ int status;
+
+ unwind_save(&u);
+ out1 = *o;
+ if (setjmp(jl.buf) == 0) {
+ exc_handler = &jl;
+ status = sc->cmd.bi->fn(sc->argc, sc->argv);
+ } else {
+ unwind_restore(&u);
+ status = exitstatus ? exitstatus : 2;
+ }
+ exc_handler = prev;
+ out_flush(&out1);
+ *o = out1;
+ out1 = saved;
+ return status;
+}
+
+/* ---- pipelines ------------------------------------------------------- */
+
+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;
+};
+
+static void close_stage(struct stage *s) {
+ if (s->in >= 0)
+ close(s->in);
+ if (s->out >= 0)
+ close(s->out);
+ 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];
+ bool prepped = false;
+ if (c->kind == N_SIMPLE) {
+ if (!guarded_prep(c, &s->sc)) {
+ s->status = exitstatus;
+ close_stage(s);
+ return;
+ }
+ prepped = true;
+ if (s->sc.argc && s->sc.cmd.kind == C_EXTERNAL) {
+ s->status = run_external(&s->sc, 0, s->in, s->out, &s->pid);
+ close_stage(s);
+ return;
+ }
+ if (is_pure(&s->sc)) {
+ s->deferred = true; /* run once its reader exists */
+ return;
+ }
+ if (s->sc.argc && s->sc.cmd.kind == C_NOTFOUND) {
+ s->status = simple_run(&s->sc, 0); /* only complains */
+ close_stage(s);
+ return;
+ }
+ }
+ pid_t pid = fork_shell();
+ if (pid == 0) {
+ if (s->in >= 0)
+ dup2(s->in, 0);
+ if (s->out >= 0)
+ dup2(s->out, 1);
+ for (int j = 0; j < nc; j++)
+ close_stage(&st[j]);
+ if (prepped)
+ child_simple(&s->sc);
+ child_eval(c);
+ }
+ s->pid = pid;
+ close_stage(s);
+}
+
+/*
+ * 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.
+ */
+static void run_deferred(struct stage *st, int nc, int i, bool stream) {
+ struct stage *s = &st[i];
+ if (stream && st[i + 1].pid > 0) {
+ char buf[1024];
+ struct 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};
+ s->status = run_pure(&s->sc, &o);
+ if (o.len <= PIPE_BUF) {
+ struct output direct = {o.buf, o.len, o.len, s->out, 0};
+ out_flush(&direct);
+ } else {
+ pid_t pid = fork_shell();
+ if (pid == 0) {
+ int out = s->out;
+ s->out = -1;
+ 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};
+ out_flush(&direct);
+ _exit(0);
+ }
+ s->pid = -pid; /* reap it, but keep the builtin's own status */
+ }
+ free(o.buf);
+ close_stage(s);
+}
+
+static void read_all(int fd, struct 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) {
+ 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);
+ }
+ int status = st[nc - 1].status;
+ if (opt.pipefail && !status) {
+ for (int i = 0; i < nc; i++) {
+ if (st[i].status)
+ status = st[i].status;
+ }
+ }
+ 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.
+ */
+static int eval_pipe(struct node *n, unsigned flags, struct 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];
+ for (int i = 0; i < total; i++)
+ st[i] = (struct stage){.in = -1, .out = -1};
+
+ for (int i = 0; i < total - 1; i++) {
+ int p[2];
+ if (sys_pipe(p) < 0) {
+ int err = errno;
+ for (int j = 0; j < total; j++)
+ close_stage(&st[j]);
+ sh_error("cannot create pipe: %s", strerror(err));
+ }
+ st[i].out = p[1];
+ st[i + 1].in = p[0];
+ }
+
+ /*
+ * Whatever preparing the earlier stages does to shell variables must
+ * not outlive them: they are, notionally, subshells.
+ */
+ struct varscope vs;
+ scope_push(&vs, true, false);
+ bool any_deferred = false;
+ int nlaunch = cap ? 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 (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);
+ }
+ sigaction(SIGPIPE, &old, nullptr);
+ }
+ read_all(st[nc].in, cap);
+ return pipe_finish(st, nc, total);
+ }
+
+ /*
+ * 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;
+ volatile bool raised = false;
+ unwind_save(&u);
+ if (setjmp(jl.buf) == 0) {
+ exc_handler = &jl;
+ bool last_started = false;
+ if (lc->kind == N_SIMPLE) {
+ simple_prep(lc, &last->sc);
+ if (last->sc.argc && last->sc.cmd.kind == C_EXTERNAL) {
+ /* Start the reader before any in-shell writer runs. */
+ last->status =
+ run_external(&last->sc, 0, last->in, -1, &last->pid);
+ close_stage(last);
+ last_started = true;
+ }
+ }
+ if (any_deferred) {
+ /* A reader that has gone away must not kill the shell. */
+ struct sigaction ignore = {.sa_handler = SIG_IGN};
+ struct sigaction old;
+ sigaction(SIGPIPE, &ignore, &old);
+ for (int i = nc - 2; i >= 0; i--) {
+ if (st[i].deferred)
+ run_deferred(st, nc, i, true);
+ }
+ sigaction(SIGPIPE, &old, nullptr);
+ }
+ if (!last_started) {
+ struct redirsave rs;
+ redir_push_fd(&rs, 0, last->in);
+ last->in = -1;
+ if (lc->kind == N_SIMPLE)
+ last->status = simple_run(&last->sc, flags & EV_TESTED);
+ else
+ last->status = eval_node(lc, flags & EV_TESTED);
+ redir_pop(false);
+ }
+ } else {
+ unwind_restore(&u);
+ raised = true;
+ }
+ exc_handler = prev;
+
+ if (raised) {
+ pipe_finish(st, nc, total);
+ exc_raise(exc_code);
+ }
+ return pipe_finish(st, nc, total);
+}
+
+/* ---- background commands --------------------------------------------- */
+
+static int eval_background(struct node *body) {
+ struct simple sc;
+ bool prepped = false;
+ pid_t pid = 0;
+ struct sigaction ignore = {.sa_handler = SIG_IGN};
+ struct varscope vs;
+
+ scope_push(&vs, true, false);
+ if (body->kind == N_SIMPLE) {
+ if (!guarded_prep(body, &sc)) {
+ scope_pop();
+ return exitstatus;
+ }
+ prepped = true;
+ if (sc.argc && sc.cmd.kind == C_EXTERNAL) {
+ /* The child inherits "ignored", which spawn cannot set. */
+ struct sigaction old_int;
+ struct sigaction old_quit;
+ int null = sys_open("/dev/null", O_RDONLY, 0);
+ 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);
+ if (null >= 0)
+ close(null);
+ scope_pop();
+ if (pid > 0)
+ jobs_add(pid);
+ 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 (prepped)
+ child_simple(&sc);
+ child_eval(body);
+ }
+ scope_pop();
+ jobs_add(pid);
+ return 0;
+}
+
+/* ---- command substitution -------------------------------------------- */
+
+static void read_all(int fd, struct strbuf *sb) {
+ for (;;) {
+ sb_reserve(sb, 4096);
+ ssize_t n = read(fd, sb->s + sb->len, 4096);
+ if (n < 0 && errno == EINTR)
+ continue;
+ if (n <= 0)
+ return;
+ sb->len += (size_t)n;
+ }
+}
+
+static int cmdsub_fork(struct node *n, struct simple *sc, struct strbuf *sb) {
+ int p[2];
+ if (sys_pipe(p) < 0)
+ sh_error("cannot create pipe: %s", strerror(errno));
+ pid_t pid = fork_shell();
+ if (pid == 0) {
+ dup2(p[1], 1);
+ close(p[0]);
+ close(p[1]);
+ if (sc)
+ child_simple(sc);
+ child_eval(n);
+ }
+ close(p[1]);
+ read_all(p[0], sb);
+ close(p[0]);
+ 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) {
+ if (n->kind == N_PIPE)
+ return eval_pipe(n, 0, sb);
+ if (n->kind != N_SIMPLE)
+ return cmdsub_fork(n, nullptr, sb);
+
+ const struct 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. */
+ const char *path = expand_string(r->target->parts, XS_TILDE);
+ int fd = sys_open(path, O_RDONLY, 0);
+ if (fd < 0) {
+ sh_warn("cannot open %s: %s", path, strerror(errno));
+ return 1;
+ }
+ read_all(fd, sb);
+ close(fd);
+ return 0;
+ }
+
+ struct simple sc;
+ if (!guarded_prep(n, &sc))
+ return exitstatus;
+ if (sc.argc && sc.cmd.kind == C_EXTERNAL) {
+ int p[2];
+ pid_t pid = 0;
+ if (sys_pipe(p) < 0)
+ sh_error("cannot create pipe: %s", strerror(errno));
+ int status = run_external(&sc, 0, -1, p[1], &pid);
+ close(p[1]);
+ if (pid > 0) {
+ read_all(p[0], sb);
+ status = wait_fg(pid);
+ }
+ close(p[0]);
+ return status;
+ }
+ if (is_pure(&sc)) {
+ struct output o = {.fd = OUT_MEM};
+ int status = run_pure(&sc, &o);
+ sb_put(sb, o.buf, o.len);
+ free(o.buf);
+ return status;
+ }
+ if (sc.argc && sc.cmd.kind == C_NOTFOUND)
+ return simple_run(&sc, 0); /* only complains: no process needed */
+ return cmdsub_fork(n, &sc, sb);
+}
+
+char *cmdsub_run(struct node *n, size_t *lenp) {
+ struct strbuf sb;
+ sb_init(&sb, &scratch);
+ int status = 0;
+ if (n) {
+ struct varscope vs;
+ scope_push(&vs, true, false);
+ status = cmdsub_collect(n, &sb);
+ scope_pop();
+ }
+ while (sb.len && sb.s[sb.len - 1] == '\n')
+ sb.len--;
+ exitstatus = status;
+ cmdsub_ran = true;
+ cmdsub_status = status;
+ *lenp = sb.len;
+ return sb_cstr(&sb);
+}
+
+/* ---- 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.
+ */
+static bool loop_should_stop(void) {
+ if (skip_kind == SKIP_NONE)
+ return false;
+ if (skip_kind == SKIP_RETURN)
+ return true;
+ if (--skip_count > 0)
+ return true; /* aimed at an enclosing loop */
+ bool is_break = skip_kind == SKIP_BREAK;
+ skip_kind = SKIP_NONE;
+ return is_break;
+}
+
+static int eval_loop(struct node *n, unsigned flags) {
+ int status = 0;
+ loop_depth++;
+ for (;;) {
+ int cond = eval_node(n->u.loop.cond, EV_TESTED);
+ if (skip_kind != SKIP_NONE) {
+ if (loop_should_stop())
+ break;
+ continue;
+ }
+ if ((cond == 0) != (n->kind == N_WHILE))
+ break;
+ status = eval_node(n->u.loop.body, flags & EV_TESTED);
+ if (loop_should_stop())
+ break;
+ }
+ loop_depth--;
+ return status;
+}
+
+static int eval_for(struct node *n, unsigned flags) {
+ int count;
+ char **words;
+ if (n->u.for_.has_in) {
+ words = expand_words(n->u.for_.words, &count);
+ } else {
+ count = shellparam.n;
+ words = arena_alloc(&scratch, ((size_t)count + 1) * sizeof *words);
+ memcpy(words, shellparam.p, (size_t)count * sizeof *words);
+ }
+ int status = 0;
+ loop_depth++;
+ for (int i = 0; i < count; i++) {
+ var_set(n->u.for_.var, words[i], 0);
+ status = eval_node(n->u.for_.body, flags & EV_TESTED);
+ if (loop_should_stop())
+ break;
+ }
+ loop_depth--;
+ return status;
+}
+
+static int eval_case(struct 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) {
+ if (pat_match(expand_pattern(w->parts), subject, end))
+ return it->body ? eval_node(it->body, flags) : 0;
+ }
+ }
+ return 0;
+}
+
+static int eval_subshell(struct node *n, unsigned flags) {
+ if (!(flags & EV_EXIT) || trap_has_exit()) {
+ pid_t pid = fork_shell();
+ if (pid)
+ return wait_fg(pid);
+ } else {
+ trap_reset_child(); /* already the last thing this shell does */
+ in_subshell = true;
+ }
+ struct 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) {
+ if (!n)
+ return exitstatus = 0;
+ if (opt.noexec && !opt.interactive)
+ return exitstatus;
+
+ struct arena_mark mark = arena_mark(&scratch);
+ struct redirsave rs;
+ bool redirected = false;
+ bool leaf = false; /* a command whose failure triggers errexit */
+ int status = 0;
+
+ if (n->redirs && n->kind != N_SIMPLE && n->kind != N_SUBSHELL) {
+ if (!redir_push(n->redirs, &rs)) {
+ arena_release(&scratch, mark);
+ return exitstatus = 2;
+ }
+ redirected = true;
+ flags &= ~EV_EXIT;
+ }
+
+ switch (n->kind) {
+ case N_SIMPLE: {
+ struct simple sc;
+ simple_prep(n, &sc);
+ status = simple_run(&sc, flags);
+ leaf = true;
+ break;
+ }
+ case N_PIPE:
+ status = eval_pipe(n, flags, nullptr);
+ leaf = true;
+ break;
+ case N_SUBSHELL:
+ status = eval_subshell(n, flags);
+ leaf = true;
+ break;
+ case N_SEQ:
+ /* Walk the right-leaning chain without recursing on it. */
+ for (;;) {
+ eval_node(n->u.bin.left, flags & EV_TESTED);
+ status = exitstatus;
+ if (skip_kind != SKIP_NONE)
+ break;
+ n = n->u.bin.right;
+ if (n->kind != N_SEQ) {
+ status = eval_node(n, flags);
+ break;
+ }
+ }
+ break;
+ case N_AND:
+ case N_OR:
+ status = eval_node(n->u.bin.left, EV_TESTED);
+ if (skip_kind == SKIP_NONE && (status == 0) == (n->kind == N_AND))
+ status = eval_node(n->u.bin.right, flags);
+ break;
+ case N_NOT:
+ status = !eval_node(n->u.body, EV_TESTED);
+ break;
+ case N_BG:
+ status = eval_background(n->u.body);
+ break;
+ case N_GROUP:
+ status = eval_node(n->u.body, flags);
+ break;
+ case N_IF:
+ if (eval_node(n->u.if_.cond, EV_TESTED) == 0 && skip_kind == SKIP_NONE)
+ status = eval_node(n->u.if_.then_part, flags);
+ else if (skip_kind == SKIP_NONE)
+ status = eval_node(n->u.if_.else_part, flags);
+ break;
+ case N_WHILE:
+ case N_UNTIL:
+ status = eval_loop(n, flags);
+ break;
+ case N_FOR:
+ status = eval_for(n, flags);
+ break;
+ case N_CASE:
+ status = eval_case(n, flags);
+ break;
+ case N_FUNC:
+ func_define(n->u.func.name, n->u.func.body, n->u.func.arena);
+ 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 (trap_pending)
+ trap_poll();
+ return status;
+}
+
+/* ---- the read-eval loop ---------------------------------------------- */
+
+/* Read commands from the current input and run them until it ends. */
+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;
+ int saved_loop = loop_depth;
+ bool recover = (flags & RI_TOP) && opt.interactive;
+
+ unwind_save(&u);
+ if (stack_low()) {
+ arena_unref(pa);
+ sh_error("eval nested too deeply");
+ }
+ for (;;) {
+ if (recover) {
+ if (setjmp(jl.buf)) {
+ /* An error at the prompt: tidy up and prompt again. */
+ if (exc_code == EXC_EXIT) {
+ exc_handler = prev;
+ exc_raise(EXC_EXIT);
+ }
+ unwind_restore(&u);
+ arena_release(&scratch, mark);
+ parser_reset();
+ input_discard_line();
+ skip_kind = SKIP_NONE;
+ loop_depth = saved_loop;
+ dot_depth = 0;
+ }
+ exc_handler = &jl;
+ prompt_state = 1;
+ }
+ bool eof = false;
+ struct 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)
+ jobs_reap();
+ }
+ arena_release(&scratch, mark);
+ if (pa->refs > 1) { /* a function now owns this arena */
+ arena_unref(pa);
+ pa = arena_new();
+ } else {
+ arena_reset(pa);
+ }
+ if (eof || skip_kind == SKIP_RETURN)
+ break;
+ }
+ exc_handler = prev;
+ arena_unref(pa);
+ return exitstatus;
+}
+
+int eval_string(const char *s, unsigned flags) {
+ input_push_string(s, strlen(s));
+ run_input(flags);
+ input_pop();
+ return exitstatus;
+}