/** * @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 * 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 #include #include #include #include #include #include #include #include #include #include #include "expand.h" #include "interact.h" #include "parser.h" #include "sys.h" /* POSIX may leave PIPE_BUF undefined when the limit varies by file (z/OS does); _POSIX_PIPE_BUF is the guaranteed minimum. */ #ifndef PIPE_BUF #define PIPE_BUF _POSIX_PIPE_BUF #endif /** * @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; /** * @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; /** * @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 --------------------------------------------------- */ /** * @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. */ static const char default_path[] = "/bin:/usr/bin"; /** * @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 builtin *bi; func *fn; char *path; unsigned hash; /**< full hash of name: rules out collisions cheaply */ char name[]; } cmdent; /** * @brief The command table. */ static cmdent *ctab[CTAB_SIZE]; /** * @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 nullptr. */ 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; 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; size_t len = strlen(name) + 1; 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 (cmdent *e = ctab[i]; e; e = e->next) { free(e->path); e->path = nullptr; } } } /** * @brief Print the remembered command paths (`hash`). */ void hash_print(void) { for (size_t i = 0; i < CTAB_SIZE; i++) { for (const cmdent *e = ctab[i]; e; e = e->next) { if (e->path) out_printf(&out1, "%s\n", e->path); } } } /** * @brief Add a difference of two timevals, in microseconds, to a total. */ static long long tv_diff(struct timeval a, struct timeval b) { return (long long)(b.tv_sec - a.tv_sec) * 1000000 + (long long)(b.tv_usec - a.tv_usec); } /** * @brief Print one line of `time` output. * @param label "real", "user" or "sys". * @param us The time in microseconds. * @param posix `-p`: seconds with two decimals. Else `0m0.000s`. */ static void put_time(const char *label, long long us, bool posix) { if (us < 0) us = 0; if (posix) out_printf(&out2, "%s %lld.%02lld", label, us / 1000000, us % 1000000 / 10000); else out_printf(&out2, "%s\t%lldm%lld.%03llds", label, us / 60000000, us / 1000000 % 60, us % 1000000 / 1000); } /** * @brief Run `time pipeline` and report where the time went. * * The report goes to standard error after the pipeline finishes: * * real 0m1.204s * user 0m0.310s (shell 0m0.010s, children 0m0.300s) * sys 0m0.052s (shell 0m0.002s, children 0m0.050s) * * The split is what an external `time` cannot give: CPU the shell itself * used (builtins, expansion, loops) against CPU used by the processes it * ran, which is the first question when a script costs too much. With * `-p` the three POSIX lines are printed and nothing else. * * @param n The N_TIME node. * @param flags Evaluation flags for the pipeline. `EV_EXIT` is dropped * because the shell must survive to print the report. * @return Status of the pipeline (0 if there is none). */ static int eval_time(const node *n, unsigned flags) { struct rusage s0; struct rusage c0; struct rusage s1; struct rusage c1; struct timeval t0; struct timeval t1; getrusage(RUSAGE_SELF, &s0); getrusage(RUSAGE_CHILDREN, &c0); gettimeofday(&t0, nullptr); int status = n->u.time.body ? eval_node(n->u.time.body, flags & ~EV_EXIT) : 0; gettimeofday(&t1, nullptr); getrusage(RUSAGE_SELF, &s1); getrusage(RUSAGE_CHILDREN, &c1); bool posix = n->u.time.posix; long long self[2] = { tv_diff(s0.ru_utime, s1.ru_utime), tv_diff(s0.ru_stime, s1.ru_stime), }; long long kids[2] = { tv_diff(c0.ru_utime, c1.ru_utime), tv_diff(c0.ru_stime, c1.ru_stime), }; static const char *const label[2] = {"user", "sys"}; out_flush(&out1); put_time("real", tv_diff(t0, t1), posix); out_putc(&out2, '\n'); for (int i = 0; i < 2; i++) { put_time(label[i], self[i] + kids[i], posix); if (!posix) { put_time(" (shell", self[i], true); put_time("s, children", kids[i], true); out_puts(&out2, "s)"); } out_putc(&out2, '\n'); } out_flush(&out2); return status; } /** * @brief Is this byte allowed in an MVS job name? */ static bool jobname_char(char c) { return (c >= 'A' && c <= 'I') || (c >= 'J' && c <= 'R') || (c >= 'S' && c <= 'Z') || (c >= '0' && c <= '9') || c == '@' || c == '#' || c == '$'; } /** * @brief Does an environment vector define a variable? * @param envp The vector. * @param name The name followed by `=`. */ static bool env_has(char **envp, const char *name) { size_t n = strlen(name); for (; *envp; envp++) { if (!strncmp(*envp, name, n)) return true; } return false; } /** * @brief Add the z/OS per-command variables to a command's environment. * * Called only when `set -o jobnames` or `set -o shareas` is on, so a * shell that uses neither pays two byte tests per external command. * * - **jobnames:** `_BPX_JOBNAME` is set to the command's name in upper * case (up to 8 characters valid in a job name), so that each command * is visible under its own name in SDSF, SMF type 30 records and WLM * classification, instead of as `USERID1` to `USERID9`. z/OS honours * it only for a process that gets its own address space and only if * the user may read `BPX.JOBNAME` in FACILITY (or is a superuser). * - **shareas:** `_BPX_SHAREAS=YES` for a foreground command, which then * runs in the shell's address space: no address space creation, which * is most of the cost of starting a command on z/OS. Background * commands and pipeline stages are left alone: they outlive or run * beside the shell, and a shared address space serialises storage * and is torn down with its owner. * * A variable the user has exported, or given on the command itself, is * never overridden. * * @param envp The command's environment. * @param name argv[0]. * @param foreground The shell waits for this command alone. * @return The environment to use, in scratch memory. */ static char **zos_environ(char **envp, const char *name, bool foreground) { char *add[2]; int nadd = 0; if (opt.jobnames && !env_has(envp, "_BPX_JOBNAME=")) { const char *base = strrchr(name, '/'); base = base ? base + 1 : name; char *text = arena_alloc(&scratch, sizeof "_BPX_JOBNAME=" + 8); memcpy(text, "_BPX_JOBNAME=", sizeof "_BPX_JOBNAME=" - 1); char *p = text + sizeof "_BPX_JOBNAME=" - 1; /* no stpcpy on z/OS */ char *start = p; for (; *base && p - start < 8; base++) { char c = (char)toupper((unsigned char)*base); if (!jobname_char(c) || (p == start && c >= '0' && c <= '9')) continue; *p++ = c; } *p = '\0'; if (p > start) add[nadd++] = text; } if (opt.shareas && foreground && !env_has(envp, "_BPX_SHAREAS=")) { static char shareas[] = "_BPX_SHAREAS=YES"; add[nadd++] = shareas; } if (!nadd) return envp; size_t n = 0; while (envp[n]) n++; char **env = arena_alloc(&scratch, (n + (size_t)nadd + 1) * sizeof *env); memcpy(env, envp, n * sizeof *env); for (int i = 0; i < nadd; i++) env[n + (size_t)i] = add[i]; env[n + (size_t)nadd] = nullptr; return env; } /** * @brief PATH hook: remembered paths are no longer valid. */ static void path_changed(const char *value) { (void)value; hash_clear(); } /** * @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 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; } } /** * @brief PATH from a `PATH=... command` prefix, used for that one lookup. */ static const char *path_override; /** * @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; } 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; } } /** * @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); } } /** * @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 = (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) { cmdent *e = cmd_lookup(name, false); if (!e || !e->fn) return false; func_unref(e->fn); e->fn = nullptr; 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]; var_find("PATH", 4, true)->hook = path_changed; var_find("OPTIND", 6, true)->hook = getopts_reset; } /* ---- unwinding ------------------------------------------------------- */ /** * @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; } /** * @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); } /* ---- processes ------------------------------------------------------- */ /** * @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 */ 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; 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; } /** * @brief Run a command as the whole remaining life of this (forked) process. */ [[noreturn]] static void child_eval(node *n) { jmploc jl; if (setjmp(jl.buf) == 0) { exc_handler = &jl; eval_node(n, EV_EXIT); } exit_shell(exitstatus); } /* ---- running external programs --------------------------------------- */ /** * @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 nullptr 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; 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; } /** * @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; } /** * @brief 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(); COVERAGE_FLUSH(); 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); } /** * @brief The `exec` builtin with a command: find it and replace the shell. */ void shell_exec(char **argv, char **envp) { 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); } /** * @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 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); 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++; if (job_launching) job_add_proc(job_launching, pid); return pid; } /* ---- simple commands ------------------------------------------------- */ /** * @brief A simple command that has been expanded and looked up. */ typedef struct simple_cmd { node *n; int argc; char **argv; cmdinfo cmd; bool via_command; /**< reached through the `command` builtin */ char **atext; /**< the expanded "name=value" of each assignment */ int nassign; } simple_cmd; /** * @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++) { if (i) out_putc(&out2, ' '); out_quote(&out2, sc->argv[i]); } out_putc(&out2, '\n'); out_flush(&out2); } /** * @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 = (cmdinfo){0}; 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 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 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); } } /** * @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) { exc_handler = &jl; simple_prep(n, sc); } else { unwind_restore(&u); ok = false; } exc_handler = prev; return ok; } /** * @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); } /** * @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); } /** * @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); } /** * @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); var_save(var_find(text, nlen, true), var_scope); var_set_n(text, nlen, text + nlen + 1, V_EXPORT); } } /** * @brief Apply `_TAG_REDIR_*` assignments given on an external command. * * Assignments before an external command go only into its environment, * never into the shell's variables, so the hooks that keep #tag_redir * current do not see `_TAG_REDIR_OUT=TXT cmd >f`. This sets #tag_redir * from them for the duration of the redirections, and applies them to * the pipe ends the command gets in a pipeline, as /bin/sh does. * * @param sc The command. * @param saved Receives #tag_redir as it was. * @return true if anything changed (call tag_prefix_end()). */ static bool tag_prefix_begin(const simple_cmd *sc, tag_mode saved[3]) { static const char *const name[3] = { "_TAG_REDIR_IN=", "_TAG_REDIR_OUT=", "_TAG_REDIR_ERR=", }; bool any = false; memcpy(saved, tag_redir, sizeof tag_redir); for (int i = 0; i < sc->nassign; i++) { const char *a = sc->atext[i]; if (strncmp(a, "_TAG_REDIR_", 11)) continue; for (int k = 0; k < 3; k++) { size_t n = strlen(name[k]); if (!strncmp(a, name[k], n)) { tag_redir[k] = tag_value(a + n); any = true; } } } return any; } /** * @brief Tag the pipe ends of a pipeline stage per its prefix, then put * #tag_redir back. */ static void tag_prefix_end(const tag_mode saved[3], int in, int out) { if (out >= 0 && tag_redir[TAG_OUT] != saved[TAG_OUT]) sys_redir_tag(out, TAG_OUT, tag_redir[TAG_OUT], true); if (in >= 0 && tag_redir[TAG_IN] != saved[TAG_IN]) sys_redir_tag(in, TAG_IN, tag_redir[TAG_IN], false); memcpy(tag_redir, saved, sizeof tag_redir); } /** * @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 nullptr, 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(simple_cmd *sc, unsigned flags, int in, int out, pid_t *async) { const node *n = sc->n; char **envp = sc->nassign ? var_environ_with(sc->atext, sc->nassign) : var_environ(); if (opt.jobnames || opt.shareas) envp = zos_environ(envp, sc->argv[0], !async && in < 0 && out < 0); fdplan plan; plan_init(&plan, in, out); tag_mode saved_tags[3]; bool tags = SYS_MVS && sc->nassign && tag_prefix_begin(sc, saved_tags); bool planned = plan_redirs(&plan, n->redirs); if (tags) tag_prefix_end(saved_tags, in, out); if (!planned) { 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); } /* Under job control a foreground command is a job of its own. */ job *jb = !async && jc_active() && !job_launching ? job_begin(n, true) : nullptr; int status = 0; pid_t pid = spawn_command(sc->cmd.path, sc->argv, envp, &plan, &status); plan_close(&plan); 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) { if (out1.err != EPIPE) sh_warn("write error: %s", strerror(out1.err)); out1.err = 0; if (!status) status = 1; } return status; } /** * @brief Run a special builtin reached through `command`. * * `command` takes away the special properties, and one of them is that * an error in a special builtin exits a non-interactive shell. So an * error raised inside it (a syntax error in `command eval`, a missing * file or syntax error in `command .`, an arithmetic error) is caught * here and becomes the builtin's status, as in dash, bash and ksh93. * `exit` still exits. Only this rare path pays for the setjmp(). * * @param bi The builtin. * @param sc The command. * @return Its status, or that of the error. */ static int run_special_guarded(const builtin *bi, simple_cmd *sc) { jmploc jl; jmploc *prev = exc_handler; unwind u; unwind_save(&u); arena_marker mark = arena_mark(&scratch); int saved_loop = loop_depth; int saved_dot = dot_depth; int saved_func = func_depth; if (setjmp(jl.buf)) { exc_handler = prev; if (exc_code == EXC_EXIT) exc_raise(EXC_EXIT); unwind_restore(&u); arena_release(&scratch, mark); loop_depth = saved_loop; dot_depth = saved_dot; func_depth = saved_func; skip_kind = SKIP_NONE; return exitstatus ? exitstatus : 2; } exc_handler = &jl; int status = bi->fn(sc->argc, sc->argv); exc_handler = prev; return status; } /** * @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; varscope vs; 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(sc->via_command && (bi->flags & BI_SPECIAL) ? run_special_guarded(bi, sc) : bi->fn(sc->argc, sc->argv)); if (n->redirs) redir_pop(bi->fn == builtin_exec); } if (scoped) scope_pop(); return status; } /** * @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]); shparam saved_param = shellparam; int saved_loop = loop_depth; jmploc jl; jmploc *prev = exc_handler; bool raised = false; fn->refs++; func_depth++; loop_depth = 0; shellparam = (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; } /** * @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); 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; } /** * @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; redir_pop(false); } assign_words(n->u.simple.assigns); return cmdsub_ran ? cmdsub_status : 0; } /** * @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) { 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. */ 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(); } /** * @brief Run a prepared simple command as the rest of a forked child's life. */ [[noreturn]] static void child_simple(simple_cmd *sc) { jmploc jl; if (setjmp(jl.buf) == 0) { exc_handler = &jl; exitstatus = simple_run(sc, EV_EXIT); } exit_shell(exitstatus); } /** * @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 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; } /** * @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); 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; } /** * @brief Can a subshell run without a process of its own? * * Its body has to be one command whose name is written literally, that * name has to be a builtin which only writes output or changes directory * state that can be restored, and neither the subshell nor the command may * redirect or assign. Then nothing the parent can see can change. A * `fork()` copies the address space on z/OS, 4.7 ms against 0.3 ms for a * `spawn()`, and ksh88 does not pay it for `( : )` either. */ static bool subshell_in_process(const node *n) { const node *b = n->u.body; if (n->redirs || !b || b->kind != N_SIMPLE || b->redirs || b->u.simple.assigns || !b->u.simple.args || !b->u.simple.args->plain) return false; cmdinfo ci; find_command(b->u.simple.args->plain, &ci, 0); if (ci.kind != C_BUILTIN) return false; if (ci.bi->flags & BI_CD) return var_is_plain("PWD") && var_is_plain("OLDPWD"); return (ci.bi->flags & BI_PURE) != 0; } /* ---- pipelines ------------------------------------------------------- */ /** * @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 */ simple_cmd sc; } stage; /** * @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) close(s->out); s->in = s->out = -1; } /** * @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)) { 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->out >= 0) { 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); } /** * @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. * * @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(stage *st, int nc, int i, bool stream) { stage *s = &st[i]; if (stream && st[i + 1].pid > 0) { char buf[1024]; output o = {buf, 0, sizeof buf, s->out, 0}; s->status = run_pure(&s->sc, &o); close_stage(s); return; } output o = {.fd = OUT_MEM}; s->status = run_pure(&s->sc, &o); if (o.len <= PIPE_BUF) { 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); 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, strbuf *sb); /** * @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 nullptr. * @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]); 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) { for (int i = 0; i < nc; i++) { if (st[i].status) status = st[i].status; } } return status; } /** * @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 nullptr. * @return The pipeline's exit status. */ 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 */ 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] = (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. */ /* * 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) : nullptr; varscope vs; scope_push(&vs, true, false); bool any_deferred = false; 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 || 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, !cap); } sigaction(SIGPIPE, &old, nullptr); } 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. */ jmploc jl; jmploc *prev = exc_handler; 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) { 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, nullptr); exc_raise(exc_code); } return pipe_finish(st, nc, total, nullptr); } /* ---- background commands --------------------------------------------- */ /** * @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}; varscope vs; scope_push(&vs, true, false); if (body->kind == N_SIMPLE) { if (!guarded_prep(body, &sc)) { scope_pop(); return exitstatus; } prepped = true; } /* * 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) : nullptr; 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; 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 (jb) job_end_bg(jb); else if (pid > 0) jobs_add(pid, body); return 0; } pid = fork_shell(); if (pid == 0) { if (!jb) { 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(); if (jb) job_end_bg(jb); else jobs_add(pid, body); return 0; } /* ---- command substitution -------------------------------------------- */ /** * @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); if (n < 0 && errno == EINTR) continue; if (n <= 0) return; sb->len += (size_t)n; } } /** * @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 nullptr. * @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)); 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); } /** * @brief Pick the cheapest way to run a command substitution and collect its * output. * * `$(kind == N_PIPE) return eval_pipe(n, 0, sb); if (n->kind != N_SIMPLE) return cmdsub_fork(n, nullptr, sb); const redir *r = n->redirs; if (!n->u.simple.args && !n->u.simple.assigns && r && !r->next && r->op == R_IN) { /* $(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; } simple_cmd 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)) { 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); } /** * @brief Run a command substitution. * @param n The command, or nullptr 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) { /* 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 = nullptr; 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--; exitstatus = status; cmdsub_ran = true; cmdsub_status = status; *lenp = sb.len; return sb_cstr(&sb); } /* ---- compound commands ----------------------------------------------- */ /** * @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) 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; } /** * @brief Run a `while` or `until` loop. */ static int eval_loop(node *n, unsigned flags) { int status = 0; loop_depth++; for (;;) { int test = eval_node(n->u.loop.cond, EV_TESTED); if (skip_kind != SKIP_NONE) { if (loop_should_stop()) break; continue; } if ((test == 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; } /** * @brief Run a `for` loop. */ static int eval_for(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; } /** * @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 (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; } } return 0; } /** * @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()) { if (!job_launching && !opt.errexit && subshell_in_process(n)) { simple_cmd sc; varscope vs; /* Expansion may assign (${x=1}), so undo it on the way out. */ scope_push(&vs, true, false); bool ok = guarded_prep(n->u.body, &sc); if (ok && is_pure(&sc)) { int status = run_pure(&sc, &out1); scope_pop(); return status; } if (ok && (sc.cmd.bi->flags & BI_CD)) { int status; builtin_cd_isolated(sc.argc, sc.argv, &status); scope_pop(); return status; } scope_pop(); if (!ok) return exitstatus; } job *jb = jc_active() && !job_launching ? job_begin(n, true) : nullptr; pid_t pid = fork_shell(); 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; } /* `( false; echo x ) || y`: errexit is ignored inside, too. */ if (flags & EV_TESTED) opt.errexit = false; redirsave rs; if (n->redirs && !redir_push(n->redirs, &rs)) exit_shell(1); child_eval(n->u.body); } /** * @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 nullptr 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; arena_marker mark = arena_mark(&scratch); 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: { simple_cmd 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_TIME: status = eval_time(n, flags); 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; case N_COND: cur_lineno = n->lineno; if (opt.xtrace) { char *text = node_text(n); out_printf(&out2, "%s%s\n", var_get("PS4") ? var_get("PS4") : "+ ", text); out_flush(&out2); free(text); } status = eval_cond(n->u.cond); leaf = true; 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 && !(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; } /* ---- the read-eval loop ---------------------------------------------- */ /** * @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) { 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) || (flags & RI_RECOVER); unwind_save(&u); if (stack_low()) { arena_unref(pa); sh_error("eval nested too deeply"); } if (!recover) { /* * An error or exit unwinding through here drops this level's * parse arena. Without this it leaks once per error that an * outer handler (command, a subshell, the prompt) catches. * One setjmp() per eval, `.` or script, not per command. */ if (setjmp(jl.buf)) { exc_handler = prev; arena_unref(pa); exc_raise(exc_code); } exc_handler = &jl; } 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; arena_unref(pa); 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; job_launching = nullptr; } exc_handler = &jl; if (flags & RI_TOP) prompt_state = 1; } bool eof = false; 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 (job_list && !opt.interactive) 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 && recover && input->tty && interact_refuse_eof()) { input->eof = false; /* ^D ignored: prompt again */ continue; } if (eof || skip_kind == SKIP_RETURN) break; } exc_handler = prev; arena_unref(pa); 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); input_pop(); return exitstatus; }