/** * @file builtin.c * @brief The builtin commands of POSIX `sh`, and the builtin table. * * A builtin writes to #out1 and #out2 and never to a file descriptor, so * that its output can be captured or piped without a process. It reports * problems with sh_warn() and returns a status. Only the special builtins * raise errors. */ #include #include #include #include #include #include #include #include #include #include #include #include "exec.h" #include "sys.h" #include "parser.h" #include "interact.h" /* ---- trivial ones ---------------------------------------------------- */ /** * @brief The `:` and `true` builtins. * * `:` stays a special builtin. Neither writes anything at all, which is * the strongest form of output-only, so `( : )` needs no process of its * own. That is the shape of `while ... ; do ( : ); done`, the subshell row * that cost 4.7 ms a turn on z/OS against ksh88's zero. */ static int b_true(int argc, char **argv) { (void)argc; (void)argv; return 0; } /** * @brief The `false` builtin. */ static int b_false(int argc, char **argv) { (void)argc; (void)argv; return 1; } /** * @brief The `echo` builtin. * * XSI behaviour: backslash escapes are interpreted and `-n` suppresses * the newline. Use `printf` or `print -r` for exact output. */ static int b_echo(int argc, char **argv) { int i = 1; bool newline = true; if (i < argc && !strcmp(argv[i], "-n")) { newline = false; i++; } for (int first = i; i < argc; i++) { if (i > first) out_putc(&out1, ' '); if (!out_escaped(&out1, argv[i], true)) return 0; /* \c: stop, no newline */ } if (newline) out_putc(&out1, '\n'); return 0; } /* ---- control flow ---------------------------------------------------- */ /** * @brief Parse the optional count of `break`, `continue`, `shift` and friends. * @param argc Argument count. * @param argv Arguments. * @param dflt Value when no count is given. * @return The count. A bad or negative one raises an error. */ static long count_arg(int argc, char **argv, long dflt) { if (argc < 2) return dflt; long n; if (!parse_long(argv[1], &n) || n < 0) sh_error("%s: %s: bad number", argv[0], argv[1]); return n; } /** * @brief The `exit` builtin: `exit [n]`. * * An interactive shell with stopped jobs refuses once. */ static int b_exit(int argc, char **argv) { /* Leaving would orphan stopped jobs: say so once, then let it happen. */ static bool warned; if (opt.interactive && !in_subshell && !warned && jobs_stopped()) { warned = true; sh_warn("there are stopped jobs"); return 1; } exitstatus = (int)(count_arg(argc, argv, exitstatus) & 0xff); exc_raise(EXC_EXIT); } /** * @brief The `return` builtin: `return [n]`, valid in a function or `.` file. */ static int b_return(int argc, char **argv) { int status = (int)(count_arg(argc, argv, exitstatus) & 0xff); if (!func_depth && !dot_depth) { exitstatus = status; exc_raise(EXC_EXIT); } skip_kind = SKIP_RETURN; return status; } /** * @brief Common part of `break` and `continue`: start leaving `n` loop levels. */ static int loop_skip(int argc, char **argv, skip_type kind) { long n = count_arg(argc, argv, 1); if (n < 1) sh_error("%s: %s: bad number", argv[0], argv[1]); if (loop_depth) { skip_kind = kind; skip_count = n > loop_depth ? loop_depth : (int)n; } return 0; } /** * @brief The `break` builtin. */ static int b_break(int argc, char **argv) { return loop_skip(argc, argv, SKIP_BREAK); } /** * @brief The `continue` builtin. */ static int b_continue(int argc, char **argv) { return loop_skip(argc, argv, SKIP_CONTINUE); } /** * @brief The `eval` builtin: join the arguments with spaces and run the result. */ static int b_eval(int argc, char **argv) { if (argc < 2) return 0; strbuf sb; sb_init(&sb, &scratch); for (int i = 1; i < argc; i++) { if (i > 1) sb_putc(&sb, ' '); sb_puts(&sb, argv[i]); } exitstatus = 0; return eval_string(sb_cstr(&sb), 0); } /** * @brief The `.` builtin: run a file in the current shell. * * A name without a slash is looked up in PATH (it need not be * executable). */ static int b_dot(int argc, char **argv) { if (argc < 2) sh_error(".: file name required"); const char *file = argv[1]; if (!strchr(file, '/')) { const char *path = var_get("PATH"); file = path_search(file, path ? path : "", false); } int fd = file ? sys_open(file, O_RDONLY, 0) : -1; if (fd < 0) sh_error(".: %s: not found", argv[1]); int high = sys_dupfd(fd, SYS_NFD); close(fd); input_push_fd(high, false); dot_depth++; exitstatus = 0; run_input(0); dot_depth--; input_pop(); if (skip_kind == SKIP_RETURN) skip_kind = SKIP_NONE; return exitstatus; } /** * @brief The `exec` builtin. * * With a command, replaces the shell. With only redirections, makes them * permanent. */ int builtin_exec(int argc, char **argv) { int i = 1; if (i < argc && !strcmp(argv[i], "--")) i++; if (i >= argc) return 0; /* redirections only: the caller makes them permanent */ shell_exec(argv + i, var_environ()); } /* ---- variables ------------------------------------------------------- */ /** * @brief Common part of `export` and `readonly`. * @param argc Argument count. * @param argv Arguments. * @param flag V_EXPORT or V_READONLY. */ static int export_or_readonly(int argc, char **argv, unsigned flag) { int i = 1; if (i < argc && !strcmp(argv[i], "-p")) i++; if (i >= argc) { var_print_all(flag, flag == V_EXPORT ? "export " : "readonly "); return 0; } for (; i < argc; i++) { const char *arg = argv[i]; size_t nlen = name_len(arg); if (!nlen || (arg[nlen] && arg[nlen] != '=')) sh_error("%s: %s: bad variable name", argv[0], arg); if (arg[nlen]) var_set_n(arg, nlen, arg + nlen + 1, flag); else var_set_flags(arg, flag); } return 0; } /** * @brief The `export` builtin. */ static int b_export(int argc, char **argv) { return export_or_readonly(argc, argv, V_EXPORT); } /** * @brief The `readonly` builtin. */ static int b_readonly(int argc, char **argv) { return export_or_readonly(argc, argv, V_READONLY); } /** * @brief The `unset` builtin: `unset [-fv] name...`. */ static int b_unset(int argc, char **argv) { int i = 1; bool functions = false; for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) { if (!strcmp(argv[i], "-f")) functions = true; else if (!strcmp(argv[i], "-v")) functions = false; else if (!strcmp(argv[i], "--")) { i++; break; } else sh_error("unset: %s: bad option", argv[i]); } int status = 0; for (; i < argc; i++) { if (functions) func_unset(argv[i]); else if (!var_unset(argv[i])) status = 1; } return status; } /** * @brief The `local` builtin: make variables local to the current function. */ static int b_local(int argc, char **argv) { if (!func_depth) { sh_warn("local: not in a function"); return 1; } for (int i = 1; i < argc; i++) { const char *arg = argv[i]; size_t nlen = name_len(arg); if (!nlen || (arg[nlen] && arg[nlen] != '=')) { sh_warn("local: %s: bad variable name", arg); return 1; } var_make_local(arena_strndup(&scratch, arg, nlen)); if (arg[nlen]) var_set_n(arg, nlen, arg + nlen + 1, 0); } return 0; } /** * @brief The `set` builtin: options, positional parameters, or a listing of * every variable. */ static int b_set(int argc, char **argv) { if (argc == 1) { var_print_all(0, ""); return 0; } bool set_params = false; int i = parse_set_options(argc, argv, &set_params); if (set_params) params_set(argv + i, argc - i); jc_sync(); /* "set -m" and "set +m" take effect at once */ return 0; } /** * @brief The `shift` builtin. */ static int b_shift(int argc, char **argv) { long n = count_arg(argc, argv, 1); if (n > shellparam.n) sh_error("shift: cannot shift %ld", n); shellparam.p += n; shellparam.n -= (int)n; return 0; } /** * @brief The `read` builtin: `read [-r] [-t seconds] [name...]`. * * The shell must not consume input beyond the line it returns, because * the next command may read the same descriptor. On a seekable input the * line is read in blocks and the excess given back with lseek(). On a * pipe or terminal it is read a byte at a time. * * @return 0, 1 at end of input, over 128 if `-t` timed out or a trapped * signal arrived. */ static int b_read(int argc, char **argv) { static char *default_vars[] = {"REPLY", NULL}; bool raw = false; double timeout = -1; /* seconds; negative: wait for ever */ int i = 1; for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) { if (!strcmp(argv[i], "--")) { i++; break; } for (const char *p = argv[i] + 1; *p; p++) { if (*p == 'r') { raw = true; } else if (*p == 't') { const char *num = p[1] ? p + 1 : i + 1 < argc ? argv[++i] : ""; char *end; timeout = strtod(num, &end); if (end == num || *end || timeout < 0) { sh_warn("read: -t: bad timeout"); return 2; } break; } else { sh_warn("read: -%c: bad option", *p); return 2; } } } struct timeval deadline = {0}; if (timeout >= 0) { gettimeofday(&deadline, NULL); deadline.tv_sec += (time_t)timeout; deadline.tv_usec += (suseconds_t)((timeout - (double)(time_t)timeout) * 1e6); if (deadline.tv_usec >= 1000000) { deadline.tv_sec++; deadline.tv_usec -= 1000000; } } char **vars = i < argc ? argv + i : default_vars; for (char **v = vars; *v; v++) { if (!is_name(*v)) { sh_warn("read: %s: bad variable name", *v); return 2; } } /* * Read exactly one line and nothing after it. From a seekable file a * block is read and the surplus given back. From a pipe or terminal * there is no way to give bytes back, so they are read one at a time. */ input_sync(); strbuf line; strbuf esc; /* 1 where the byte was backslash-escaped */ sb_init(&line, &scratch); sb_init(&esc, &scratch); bool seekable = lseek(0, 0, SEEK_CUR) != (off_t)-1; /* * A descriptor that cannot block is read without waiting for poll(). * z/OS never reports /dev/null as readable, so `read -t 1 v = 0) { /* -t: give up (status > 128) if no input arrives in time. */ struct timeval now; gettimeofday(&now, NULL); long ms = (long)(deadline.tv_sec - now.tv_sec) * 1000 + (long)(deadline.tv_usec - now.tv_usec) / 1000; struct pollfd pfd = {.fd = 0, .events = POLLIN}; int ready = 1; if (!always_ready) ready = ms > 0 ? poll(&pfd, 1, (int)ms) : 0; if (ready == 0) return 128 + SIGALRM; if (ready < 0 && errno == EINTR) { if (trap_pending) return 128 + (int)trap_pending; continue; } } have = read(0, buf, seekable ? sizeof buf : 1); if (have < 0 && errno == EINTR) { have = pos = 0; if (trap_pending) return 128 + (int)trap_pending; continue; } if (have <= 0) { eof = true; have = pos = 0; break; } pos = 0; } char c = buf[pos++]; if (backslash) { backslash = false; if (c != '\n') { sb_putc(&line, c); sb_putc(&esc, 1); } } else if (c == '\\' && !raw) { backslash = true; } else if (c == '\n') { break; } else if (c) { sb_putc(&line, c); sb_putc(&esc, 0); } } if (seekable && pos < have) lseek(0, -(off_t)(have - pos), SEEK_CUR); /* Split into the variables; the last one takes the rest of the line. */ const char *s = sb_cstr(&line); const char *e = sb_cstr(&esc); size_t n = line.len; size_t p = 0; /** * @brief Splitting class of byte k of the line being split by `read` (an * escaped byte is never a separator). */ #define IFS_AT(k) (e[k] ? IFS_NONE : ifs_class[(unsigned char)s[k]]) while (p < n && IFS_AT(p) == IFS_SPACE) p++; for (char **v = vars; *v; v++) { size_t start = p; size_t end; if (!v[1]) { end = n; while (end > start && IFS_AT(end - 1) == IFS_SPACE) end--; p = n; } else { while (p < n && IFS_AT(p) == IFS_NONE) p++; end = p; while (p < n && IFS_AT(p) == IFS_SPACE) p++; if (p < n && IFS_AT(p) == IFS_HARD) { p++; while (p < n && IFS_AT(p) == IFS_SPACE) p++; } } var_set(*v, arena_strndup(&scratch, s + start, end - start), 0); } #undef IFS_AT return eof ? 1 : 0; } /* ---- getopts --------------------------------------------------------- */ /** * @brief `getopts`: position inside the argument being scanned. */ static size_t getopts_off; /**< position inside the current argument */ /** * @brief `getopts` itself is assigning OPTIND, so the hook must not reset. */ static bool getopts_setting; /** * @brief OPTIND hook: an assignment by the script restarts the scan. */ void getopts_reset(const char *value) { (void)value; if (!getopts_setting) getopts_off = 0; } /** * @brief Assign OPTIND from inside `getopts` without triggering a reset. */ static void set_optind(long ind) { getopts_setting = true; var_set_long("OPTIND", ind); getopts_setting = false; } /** * @brief The `getopts` builtin: `getopts optstring name [arg...]`. */ static int b_getopts(int argc, char **argv) { if (argc < 3 || !is_name(argv[2])) { sh_warn("getopts: usage: getopts optstring name [arg ...]"); return 2; } const char *optstring = argv[1]; const char *name = argv[2]; char **args = argc > 3 ? argv + 3 : shellparam.p; int nargs = argc > 3 ? argc - 3 : shellparam.n; bool silent = optstring[0] == ':'; long ind = 1; const char *v = var_get("OPTIND"); if (v && (!parse_long(v, &ind) || ind < 1)) ind = 1; const char *arg = ind <= nargs ? args[ind - 1] : NULL; if (getopts_off && (!arg || getopts_off >= strlen(arg))) getopts_off = 0; /* the arguments changed under us: start afresh */ if (getopts_off == 0) { bool is_option = arg && arg[0] == '-' && arg[1]; if (is_option && !strcmp(arg, "--")) { ind++; is_option = false; } if (!is_option) { var_set(name, "?", 0); set_optind(ind); return 1; } getopts_off = 1; } char c = arg[getopts_off++]; char opt_name[2] = {c, '\0'}; const char *result = opt_name; const char *optval = NULL; const char *spec = c == ':' ? NULL : strchr(optstring, c); bool took_arg = false; if (!spec) { result = "?"; if (silent) optval = opt_name; else sh_warn("getopts: illegal option -- %c", c); } else if (spec[1] == ':') { took_arg = true; if (arg[getopts_off]) { optval = arg + getopts_off; ind++; } else if (ind < nargs) { optval = args[ind]; ind += 2; } else { ind++; if (silent) { result = ":"; optval = opt_name; } else { result = "?"; sh_warn("getopts: option requires an argument -- %c", c); } } } if (took_arg) { getopts_off = 0; } else if (!arg[getopts_off]) { ind++; getopts_off = 0; } /* Copy before assigning: the strings may live in a variable. */ const char *res = arena_strndup(&scratch, result, strlen(result)); if (optval) var_set("OPTARG", arena_strndup(&scratch, optval, strlen(optval)), 0); else var_unset("OPTARG"); var_set(name, res, 0); size_t off = getopts_off; set_optind(ind); getopts_off = off; return 0; } /* ---- directories ----------------------------------------------------- */ /** * @brief The logical working directory, found on first use. */ static char *curdir; /**< logical working directory, found on first use */ /** * @brief The logical working directory: `$PWD` if it is correct, else getcwd(). */ static const char *get_curdir(void) { if (curdir) return curdir; const char *pwd = var_get("PWD"); struct stat a; struct stat b; if (pwd && pwd[0] == '/' && stat(pwd, &a) == 0 && stat(".", &b) == 0 && a.st_dev == b.st_dev && a.st_ino == b.st_ino) { curdir = xstrdup(pwd); } else { char buf[PATH_MAX]; curdir = xstrdup(getcwd(buf, sizeof buf) ? buf : "."); } return curdir; } /** * @brief Remove `.`, `..` and repeated slashes from an absolute path, textually * (the logical view `cd -L` uses). * @return The cleaned path in scratch memory. */ static char *normalize_path(const char *path) { strbuf sb; sb_init(&sb, &scratch); for (const char *p = path; *p;) { while (*p == '/') p++; size_t len = strcspn(p, "/"); if (len == 2 && p[0] == '.' && p[1] == '.') { while (sb.len && sb.s[sb.len - 1] != '/') sb.len--; if (sb.len) sb.len--; } else if (len && !(len == 1 && p[0] == '.')) { sb_putc(&sb, '/'); sb_put(&sb, p, len); } p += len; } if (!sb.len) sb_putc(&sb, '/'); return sb_cstr(&sb); } /** * @brief Join a directory and a relative path. */ static char *join_path(const char *dir, const char *name) { strbuf sb; sb_init(&sb, &scratch); sb_puts(&sb, dir); if (sb.len && sb.s[sb.len - 1] != '/') sb_putc(&sb, '/'); sb_puts(&sb, name); return sb_cstr(&sb); } /** * @brief Is this path a directory? */ static bool is_directory(const char *path) { struct stat st; return stat(path, &st) == 0 && S_ISDIR(st.st_mode); } /** * @brief Find a relative directory through CDPATH. * @param dest The directory asked for. * @param print Set if the result came from a non-empty CDPATH entry, in * which case `cd` prints where it went. * @return The path to use, or NULL if CDPATH has no match. */ static const char *cdpath_search(const char *dest, bool *print) { const char *cdpath = var_get("CDPATH"); if (!cdpath || dest[0] == '/' || dest[0] == '.') return dest; for (const char *p = cdpath;;) { size_t len = strcspn(p, ":"); if (len) { char *dir = arena_strndup(&scratch, p, len); char *full = join_path(dir, dest); if (is_directory(full)) { *print = true; return full; } } else if (is_directory(dest)) { return dest; } if (!p[len]) return dest; p += len + 1; } } /** * @brief The `cd` and `chdir` builtins: `cd [-L | -P] [dir | -]`. * * Keeps PWD and OLDPWD up to date. */ static int b_cd(int argc, char **argv) { bool physical = false; bool print = false; int i = 1; for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) { if (!strcmp(argv[i], "-P")) physical = true; else if (!strcmp(argv[i], "-L")) physical = false; else break; } const char *dest = i < argc ? argv[i] : var_get("HOME"); if (!dest) { sh_warn("cd: HOME not set"); return 1; } if (!strcmp(dest, "-")) { dest = var_get("OLDPWD"); if (!dest) { sh_warn("cd: OLDPWD not set"); return 1; } print = true; } else { dest = cdpath_search(dest, &print); } const char *old = arena_strndup(&scratch, get_curdir(), strlen(get_curdir())); const char *target = dest[0] == '/' ? dest : join_path(old, dest); if (!physical) target = normalize_path(target); if (chdir(target) < 0 && chdir(dest) < 0) { sh_warn("cd: %s: %s", dest, strerror(errno)); return 1; } char buf[PATH_MAX]; if (physical && getcwd(buf, sizeof buf)) target = buf; var_set("OLDPWD", old, V_EXPORT); var_set("PWD", target, V_EXPORT); free(curdir); curdir = xstrdup(target); if (print) out_printf(&out1, "%s\n", target); return 0; } /** * @brief The `pwd` builtin: `pwd [-L | -P]`. */ static int b_pwd(int argc, char **argv) { char buf[PATH_MAX]; if (argc > 1 && !strcmp(argv[1], "-P")) { if (!getcwd(buf, sizeof buf)) { sh_warn("pwd: %s", strerror(errno)); return 1; } out_printf(&out1, "%s\n", buf); } else { out_printf(&out1, "%s\n", get_curdir()); } return 0; } /* ---- commands -------------------------------------------------------- */ /** * @brief Is this word a reserved word of the shell language? */ static bool is_keyword(const char *s) { static const char *const words[] = { "if", "then", "else", "elif", "fi", "do", "done", "case", "esac", "while", "until", "for", "in", "{", "}", "!", "function", "[[", "]]", }; for (size_t i = 0; i < ARRAY_LEN(words); i++) { if (!strcmp(s, words[i])) return true; } return false; } /** * @brief Say what a command name refers to. * @param name The name. * @param verbose The `type` / `command -V` form instead of the terse * `command -v` form. * @return 0 if found, 127 if not. */ int describe_command(const char *name, bool verbose) { cmdinfo ci; const char *what = NULL; const alias *al = alias_count ? alias_find(name) : NULL; if (al) { if (verbose) { out_printf(&out1, "%s is an alias for %s\n", name, al->value); } else { out_printf(&out1, "alias %s=", name); out_quote(&out1, al->value); out_putc(&out1, '\n'); } return 0; } if (is_keyword(name)) { what = "a shell keyword"; } else { find_command(name, &ci, 0); switch (ci.kind) { case C_BUILTIN: what = ci.bi->flags & BI_SPECIAL ? "a special shell builtin" : "a shell builtin"; break; case C_FUNC: what = "a shell function"; break; case C_EXTERNAL: if (access(ci.path, X_OK) == 0) { if (verbose) out_printf(&out1, "%s is %s\n", name, ci.path); else out_printf(&out1, "%s\n", ci.path); return 0; } FALLTHROUGH; case C_NOTFOUND: if (verbose) sh_warn("%s: not found", name); return 127; } } if (verbose) out_printf(&out1, "%s is %s\n", name, what); else out_printf(&out1, "%s\n", name); return 0; } /** * @brief The `command` builtin when it is only asked to describe (`-v`, `-V`). * * Running a command through `command` is handled in simple_prep(), which * strips the prefix before the command is looked up. */ int builtin_command(int argc, char **argv) { int i = 1; bool verbose = false; bool describe = false; for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) { if (!strcmp(argv[i], "-v")) { describe = true; } else if (!strcmp(argv[i], "-V")) { describe = verbose = true; } else if (strcmp(argv[i], "-p")) { sh_warn("command: %s: bad option", argv[i]); return 2; } } int status = 0; for (; describe && i < argc; i++) status |= describe_command(argv[i], verbose); return status; } /** * @brief The `type` builtin. */ static int b_type(int argc, char **argv) { int status = 0; for (int i = 1; i < argc; i++) status |= describe_command(argv[i], true); return status; } /** * @brief The `bind` builtin: `bind [-l] ['keys'=action ...]`. * * The notation is the BSD shells' (`bind '^[[A'=up-history`). The * defaults stay bash's. Macros (`-m`) are not supported. */ static int b_bind(int argc, char **argv) { bool list = false; int status = 0; for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-l") == 0) { list = true; continue; } if (strcmp(argv[i], "-m") == 0) { sh_warn("bind: -m: macros are not supported"); return 1; } if (edit_bind(argv[i]) < 0) status = 1; } if (list) edit_bind_list(); return status; } /** * @brief The `hash` builtin: `hash [-r] [name...]`. */ static int b_hash(int argc, char **argv) { if (argc == 1) { hash_print(); return 0; } int status = 0; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-r")) { hash_clear(); continue; } cmdinfo ci; find_command(argv[i], &ci, FC_NOFUNC); if (ci.kind == C_NOTFOUND) { sh_warn("hash: %s: not found", argv[i]); status = 1; } } return status; } /* ---- process attributes ---------------------------------------------- */ /** * @brief Print a file mode mask in the `u=rwx,g=rx,o=rx` form. */ static void print_umask_symbolic(mode_t mask) { static const char who[] = "ugo"; for (int i = 0; i < 3; i++) { unsigned bits = (~mask >> (6 - 3 * i)) & 7u; out_printf(&out1, "%s%c=%s%s%s", i ? "," : "", who[i], bits & 4 ? "r" : "", bits & 2 ? "w" : "", bits & 1 ? "x" : ""); } out_putc(&out1, '\n'); } /** * @brief Apply a symbolic mode such as `g-w,o=` to a mask. * @param s The mode text. * @param maskp The current mask. Updated. * @return false if the text is not a valid mode. */ static bool parse_symbolic_umask(const char *s, mode_t *maskp) { mode_t perms = ~*maskp & 0777; while (*s) { mode_t who = 0; for (; *s == 'u' || *s == 'g' || *s == 'o' || *s == 'a'; s++) { who |= *s == 'u' ? 0700u : *s == 'g' ? 0070u : *s == 'o' ? 0007u : 0777u; } if (!who) who = 0777; char op = *s++; if (op != '+' && op != '-' && op != '=') return false; mode_t bits = 0; for (; *s == 'r' || *s == 'w' || *s == 'x'; s++) bits |= *s == 'r' ? 0444u : *s == 'w' ? 0222u : 0111u; bits &= who; if (op == '+') perms |= bits; else if (op == '-') perms &= ~bits; else perms = (perms & ~who) | bits; if (*s == ',') s++; else if (*s) return false; } *maskp = ~perms & 0777; return true; } /** * @brief The `umask` builtin: `umask [-S] [mask]`. */ static int b_umask(int argc, char **argv) { int i = 1; bool symbolic = false; if (i < argc && !strcmp(argv[i], "-S")) { symbolic = true; i++; } mode_t mask = umask(0); umask(mask); if (i >= argc) { if (symbolic) print_umask_symbolic(mask); else out_printf(&out1, "%04o\n", (unsigned)mask); return 0; } const char *arg = argv[i]; if (arg[0] >= '0' && arg[0] <= '7') { char *end; unsigned long v = strtoul(arg, &end, 8); if (*end || v > 0777) { sh_warn("umask: %s: bad mask", arg); return 1; } mask = (mode_t)v; } else if (!parse_symbolic_umask(arg, &mask)) { sh_warn("umask: %s: bad mask", arg); return 1; } umask(mask); return 0; } /** * @brief The `times` builtin: CPU time used by the shell and by its children. */ static int b_times(int argc, char **argv) { (void)argc; (void)argv; struct tms t; long hz = sysconf(_SC_CLK_TCK); times(&t); const clock_t v[4] = {t.tms_utime, t.tms_stime, t.tms_cutime, t.tms_cstime}; for (int i = 0; i < 4; i++) { double secs = (double)v[i] / (double)hz; out_printf(&out1, "%dm%.2fs%c", (int)(secs / 60), secs - 60 * (int)(secs / 60), i % 2 ? '\n' : ' '); } return 0; } /* ---- the table ------------------------------------------------------- */ const builtin builtins[] = { #if SYS_MVS /* z/OS only: `free` in particular must not hide procps on Linux. */ {"alloc", builtin_alloc, 0}, {"free", builtin_free, 0}, {"tag", builtin_tag, 0}, #endif {".", b_dot, BI_SPECIAL}, {":", b_true, BI_SPECIAL | BI_PURE}, {"[", builtin_test, BI_PURE}, {"alias", builtin_alias, 0}, {"bg", builtin_bg, 0}, {"bind", b_bind, 0}, {"break", b_break, BI_SPECIAL}, {"cd", b_cd, 0}, {"chdir", b_cd, 0}, {"command", builtin_command, 0}, {"continue", b_continue, BI_SPECIAL}, {"echo", b_echo, BI_PURE}, {"eval", b_eval, BI_SPECIAL}, {"exec", builtin_exec, BI_SPECIAL}, {"exit", b_exit, BI_SPECIAL}, {"export", b_export, BI_SPECIAL}, {"false", b_false, BI_PURE}, {"fc", builtin_fc, 0}, {"fg", builtin_fg, 0}, {"getopts", b_getopts, 0}, {"hash", b_hash, 0}, {"integer", builtin_typeset, 0}, {"jobs", builtin_jobs, BI_PURE}, {"kill", builtin_kill, 0}, {"let", builtin_let, 0}, {"local", b_local, 0}, {"print", builtin_print, BI_PURE}, {"printf", builtin_printf, BI_PURE}, {"pwd", b_pwd, BI_PURE}, {"read", b_read, 0}, {"readonly", b_readonly, BI_SPECIAL}, {"return", b_return, BI_SPECIAL}, {"set", b_set, BI_SPECIAL}, {"setvar", builtin_setvar, 0}, {"shift", b_shift, BI_SPECIAL}, {"test", builtin_test, BI_PURE}, {"times", b_times, BI_SPECIAL}, {"trap", builtin_trap, BI_SPECIAL}, {"true", b_true, BI_PURE}, {"type", b_type, BI_PURE}, {"typeset", builtin_typeset, 0}, {"ulimit", builtin_ulimit, 0}, {"umask", b_umask, 0}, {"unalias", builtin_unalias, 0}, {"unset", b_unset, BI_SPECIAL}, {"wait", builtin_wait, 0}, {"whence", builtin_whence, BI_PURE}, }; /** * @brief Number of entries in #builtins. */ const size_t nbuiltins = ARRAY_LEN(builtins);