/** * @file main.c * @brief Options, startup and exit. */ #include #include #include #include #include #include #include "exec.h" #include "interact.h" #include "parser.h" #ifndef environ /* z/OS defines it as a macro */ extern char **environ; #endif /** * @brief Current option settings. */ options opt; /** * @brief `$0`. */ const char *arg0; /** * @brief Line of the command being executed, for messages and `$LINENO`. */ int cur_lineno; /** * @brief argv[0] as given. */ static const char *invoked_as; /**< argv[0] */ /** * @brief Working directory at startup, kept if argv[0] is a relative path. */ static char *start_dir; /**< cwd at startup, if invoked_as is relative */ /** * @brief The shell's own command line is being parsed. */ static bool startup; /**< parsing the shell's own command line */ /** * @brief `-c` was given. */ static bool opt_command; /**< -c */ /** * @brief `-l` was given, or argv[0] starts with `-`. */ static bool opt_login; /**< -l */ /* ---- options --------------------------------------------------------- */ /** * @brief The options: letter, long name and where the value lives. */ static const struct { char letter; /**< '\0' if the option only has a name */ const char *name; bool *value; bool startup_only; } option_table[] = { {'a', "allexport", &opt.allexport, false}, {'C', "noclobber", &opt.noclobber, false}, {'e', "errexit", &opt.errexit, false}, {'f', "noglob", &opt.noglob, false}, {'i', "interactive", &opt.interactive, true}, {'m', "monitor", &opt.monitor, false}, {'n', "noexec", &opt.noexec, false}, {'s', "stdin", &opt.stdin_cmds, true}, {'u', "nounset", &opt.nounset, false}, {'v', "verbose", &opt.verbose, false}, {'x', "xtrace", &opt.xtrace, false}, {'\0', "pipefail", &opt.pipefail, false}, {'\0', "jobnames", &opt.jobnames, false}, {'\0', "shareas", &opt.shareas, false}, {'\0', "msgid", &opt.msgid, false}, {'\0', "pipetag", &opt.pipetag, false}, {'b', "notify", &opt.notify, false}, {'h', "trackall", &opt.trackall, false}, {'\0', "ignoreeof", &opt.ignoreeof, false}, {'\0', "nolog", &opt.nolog, false}, {'E', "emacs", &opt.emacs, false}, {'V', "vi", &opt.vi, false}, }; /** * @brief `-m` or `+m` appeared on the command line. */ static bool monitor_given; /**< -m or +m appeared on the command line */ /** * @brief Apply the side effects of changing one option. * @param value The option's storage. * @param on Its new value. */ static void option_changed(const bool *value, bool on) { /* The two editing modes exclude each other. */ if (value == &opt.emacs && on) opt.vi = false; else if (value == &opt.vi && on) opt.emacs = false; else if (value == &opt.monitor && startup) monitor_given = true; } /** * @brief Set or clear an option by its letter. * @return false if there is no such option. */ bool option_set_letter(int letter, bool on) { if (startup && letter == 'c') { opt_command = on; return true; } if (startup && letter == 'l') { opt_login = on; return true; } for (size_t i = 0; i < ARRAY_LEN(option_table); i++) { if (option_table[i].letter == letter && (startup || !option_table[i].startup_only)) { *option_table[i].value = on; option_changed(option_table[i].value, on); return true; } } return false; } /** * @brief Set or clear an option by its `-o` name. * @return false if there is no such option. */ bool option_set_name(const char *name, bool on) { for (size_t i = 0; i < ARRAY_LEN(option_table); i++) { if (!strcmp(option_table[i].name, name) && (startup || !option_table[i].startup_only)) { *option_table[i].value = on; option_changed(option_table[i].value, on); return true; } } return false; } /** * @brief Is a shell option on? (`[[ -o name ]]`.) * @param name The option's long name. * @return 1 if it is on, 0 if off, -1 if there is no such option. */ int option_is_set(const char *name) { for (size_t i = 0; i < ARRAY_LEN(option_table); i++) { if (!strcmp(option_table[i].name, name)) return *option_table[i].value; } return -1; } /** * @brief Print every option (`set -o`), or as commands that restore them * (`set +o`). */ void options_print(bool as_commands) { for (size_t i = 0; i < ARRAY_LEN(option_table); i++) { bool on = *option_table[i].value; if (as_commands) out_printf(&out1, "set %co %s\n", on ? '-' : '+', option_table[i].name); else out_printf(&out1, "%-12s %s\n", option_table[i].name, on ? "on" : "off"); } } /** * @brief The value of `$-`. */ const char *option_letters(void) { static char buf[ARRAY_LEN(option_table) + 1]; size_t n = 0; for (size_t i = 0; i < ARRAY_LEN(option_table); i++) { if (option_table[i].letter && *option_table[i].value) buf[n++] = option_table[i].letter; } buf[n] = '\0'; return buf; } /** * @brief Process option arguments as `set` does. * @param argc Argument count. * @param argv Arguments. Argv[0] is skipped. * @param set_params Set when the operands (even if there are none) are * meant to replace the positional parameters. * @return Index of the first operand. */ int parse_set_options(int argc, char **argv, bool *set_params) { int i = 1; for (; i < argc; i++) { const char *a = argv[i]; if (!strcmp(a, "--") || !strcmp(a, "-")) { i++; *set_params = true; break; } if ((a[0] != '-' && a[0] != '+') || !a[1]) break; bool on = a[0] == '-'; for (const char *p = a + 1; *p; p++) { if (*p == 'o') { if (i + 1 >= argc) { options_print(!on); continue; } if (!option_set_name(argv[++i], on)) sh_error("%s: bad option name", argv[i]); } else if (!option_set_letter(*p, on)) { sh_error("%c%c: bad option", a[0], *p); } } } if (i < argc) *set_params = true; return i; } /* ---- identity -------------------------------------------------------- */ /** * @brief `$$`: process ID of the original shell, also in subshells. */ pid_t shell_pid(void) { static pid_t pid; if (!pid) pid = getpid(); return pid; } /** * @brief The path of this shell, for running scripts that have no `#!` line. * * Worked out the first time it is needed. */ const char *shell_path(void) { static const char *path; if (path) return path; const char *name = invoked_as; if (name[0] == '-') name++; if (name[0] == '/') { path = name; } else if (strchr(name, '/')) { size_t len = strlen(start_dir) + strlen(name) + 2; char *full = xmalloc(len); snprintf(full, len, "%s/%s", start_dir, name); path = full; } else { const char *search = var_get("PATH"); char *found = search ? path_search(name, search, true) : nullptr; path = found ? xstrdup(found) : "/bin/sh"; } return path; } /* ---- exit ------------------------------------------------------------ */ /** * @brief Leave the shell: run the EXIT trap, save history, hand back the * terminal, flush output. * @param status Exit status (the EXIT trap may change it by calling exit). */ void exit_shell(int status) { static bool exiting; volatile int code = status; /* survives the longjmp below */ if (!exiting) { exiting = true; exitstatus = status; jmploc jl; if (perf_ablate() & 16) { /* experiment: skip the EXIT trap */ } else if (setjmp(jl.buf) == 0) { exc_handler = &jl; trap_run_exit(); } else if (exc_code == EXC_EXIT) { code = exitstatus; /* the trap called exit itself */ } } exc_handler = nullptr; if (!in_subshell) { interact_exit(); jc_exit(); } if (!in_subshell && var_get("ZASH_PROCSTAT")) out_printf(&out2, "zash: spawns=%ld forks=%ld\n", stat_spawns, stat_forks); if (!(perf_ablate() & 32)) flush_all(); _exit(code); } /* ---- startup --------------------------------------------------------- */ /** * @brief Open a script on a descriptor above the ones scripts can name. */ static int open_script(const char *path) { int fd = sys_open(path, O_RDONLY, 0); if (fd < 0) return -1; int high = sys_dupfd(fd, SYS_NFD); close(fd); return high; } /** * @brief Run the commands in a file, if it exists (profile and ENV files). * * A failure in a startup file is reported and the shell carries on: these * files are only read by an interactive shell, and an interactive shell * does not exit for a command that fails (a `.kshrc` full of another * shell's builtins must not lock the user out). `exit` in the file still * exits. Parsing errors do not produce a prompt line, because there is * no interactive input here. */ static void source_file(const char *path) { int fd = open_script(path); if (fd < 0) return; input_push_fd(fd, false); run_input(RI_RECOVER); input_pop(); } /** * @brief A login shell reads /etc/profile and ~/.profile. */ static void read_profiles(void) { source_file("/etc/profile"); const char *home = var_get("HOME"); if (home) { char path[PATH_MAX]; int n = snprintf(path, sizeof path, "%s/.profile", home); if (n > 0 && (size_t)n < sizeof path) /* truncated: another file */ source_file(path); } } /** * @brief Print the command-line synopsis. * * The option letters come from option_table, so the synopsis cannot fall * out of step with what the shell accepts. * * @param o Where to write it. * @param full Also list the `-o` option names (for `--help`). */ static void usage_print(output *o, bool full) { /* Every table letter but s, plus l; sorted. c and s get their own synopsis lines. */ char letters[ARRAY_LEN(option_table) + 2]; size_t n = 0; for (size_t i = 0; i < ARRAY_LEN(option_table); i++) { if (option_table[i].letter && option_table[i].letter != 's') letters[n++] = option_table[i].letter; } letters[n++] = 'l'; for (size_t i = 1; i < n; i++) { /* insertion sort, ~15 letters */ char c = letters[i]; size_t j = i; for (; j > 0 && letters[j - 1] > c; j--) letters[j] = letters[j - 1]; letters[j] = c; } letters[n] = '\0'; const char *name = arg0 ? arg0 : "zash"; out_printf(o, "usage: %s [-+%s] [-+o option]... [script [arg...]]\n", name, letters); out_printf(o, " %s [-+%s] [-+o option]... -c command [name [arg...]]\n", name, letters); out_printf(o, " %s [-+%s] [-+o option]... -s [arg...]\n", name, letters); if (!full) return; out_puts(o, "options:"); size_t col = 8; for (size_t i = 0; i < ARRAY_LEN(option_table); i++) { size_t len = strlen(option_table[i].name); if (col + 1 + len > 72) { out_puts(o, "\n "); col = 7; } out_putc(o, ' '); out_puts(o, option_table[i].name); col += 1 + len; } out_putc(o, '\n'); } /** * @brief Start the shell. * * Order: stack guard, variables, command table, options, signals, job * control, profiles and ENV, then commands from `-c`, a script, or stdin. */ int main(int argc, char **argv) { jmploc jl; const char *volatile script = nullptr; const char *volatile command = nullptr; volatile bool in_args = false; /* read after longjmp: must be volatile */ bool ignored = false; stack_init(); invoked_as = argv[0] ? argv[0] : "zash"; arg0 = invoked_as[0] == '-' ? invoked_as + 1 : invoked_as; if (arg0[0] != '/' && strchr(arg0, '/')) { char buf[PATH_MAX]; start_dir = xstrdup(getcwd(buf, sizeof buf) ? buf : "."); } if (invoked_as[0] == '-') opt_login = true; var_init(environ); /* POSIX: the shell sets and exports PWD even when the parent had none. */ char cwd[PATH_MAX]; if (!var_get("PWD") && getcwd(cwd, sizeof cwd)) var_set("PWD", cwd, V_EXPORT); exec_init(); fd_open_mask = sys_init(); if (setjmp(jl.buf)) { if (in_args) /* the error was in the command line */ usage_print(&out2, false); exit_shell(exitstatus); } exc_handler = &jl; /* Only as the first argument, so that it cannot be an operand. */ if (argc > 1 && !strcmp(argv[1], "--help")) { usage_print(&out1, true); exit_shell(0); } in_args = true; startup = true; int i = parse_set_options(argc, argv, &ignored); startup = false; if (opt_command) { if (i >= argc) sh_error("-c requires an argument"); command = argv[i++]; if (i < argc) arg0 = argv[i++]; } else if (i < argc && !opt.stdin_cmds) { script = argv[i++]; arg0 = script; } in_args = false; shellparam = (shparam){argc - i, argv + i, nullptr}; if (!command && !script) { opt.stdin_cmds = true; if (isatty(0) && isatty(2)) opt.interactive = true; } trap_init(); if (opt.interactive && !monitor_given) opt.monitor = true; /* job control is the interactive default */ jc_sync(); if (opt.interactive) interact_init(); if (opt_login) read_profiles(); /* * POSIX: ENV is parameter-expanded, and is not used when the real * and effective user or group IDs differ (a set-ID shell must not * run a file the invoking user chose). */ if (opt.interactive && getuid() == geteuid() && getgid() == getegid()) { const char *env = var_get("ENV"); if (env && *env) { arena_marker mark = arena_mark(&scratch); const char *path = expand_quietly(env, false); if (*path) source_file(path); arena_release(&scratch, mark); } } if (command) { input_push_string(command, strlen(command)); run_input(RI_TOP | RI_EXEC_LAST); } else if (script) { int fd = open_script(script); if (fd < 0) { sh_warn("cannot open %s", script); exit_shell(127); } input_push_fd(fd, false); run_input(RI_TOP); } else { input_push_fd(0, true); run_input(RI_TOP); } exit_shell(exitstatus); }