/** * @file builtin_ext.c * @brief Builtins that are extensions to POSIX `sh`. * * From the Korn shell (and so familiar to users of the z/OS `/bin/sh`): * `print`, `whence`, `typeset`, `integer` and `let`. From FreeBSD `sh`: * `setvar` and `ulimit`. * * Each of these is only a row in the builtin table. A script that does * not call them is unaffected by their existence. */ #include #include #include #include #include #include #include #include "exec.h" #include "var.h" #include "expand.h" #include "sys.h" /* ---- print ----------------------------------------------------------- */ /** * @brief The `print` builtin: `print [-nrR] [-u[fd]] [--] [arg ...]`. * * Writes its arguments separated by spaces and followed by a newline. * Backslash escapes are interpreted as by `echo` unless `-r` (or `-R`) * is given. `-n` suppresses the newline. `-u` selects a descriptor other * than standard output. The co-process (`-p`) and history (`-s`) forms * of the Korn shell are not provided. * * @return 0, 1 on a write error, 2 for a bad option or descriptor. */ int builtin_print(int argc, char **argv) { bool newline = true; bool raw = false; long fd = 1; int i = 1; for (; i < argc && argv[i][0] == '-'; i++) { const char *a = argv[i]; if (!a[1] || !strcmp(a, "--")) { i++; break; } bool stop = false; for (const char *p = a + 1; *p; p++) { if (*p == 'n') { newline = false; } else if (*p == 'r') { raw = true; } else if (*p == 'R') { raw = stop = true; } else if (*p == 'u') { const char *num = p[1] ? p + 1 : i + 1 < argc ? argv[++i] : ""; if (!parse_long(num, &fd) || fd < 0 || fd >= SYS_NFD) { sh_warn("print: -u: bad file descriptor"); return 2; } break; } else { sh_warn("print: -%c: bad option", *p); return 2; } } if (stop) { /* after -R only -n is still an option */ i++; while (i < argc && !strcmp(argv[i], "-n")) { newline = false; i++; } break; } } char buf[256]; output other = {buf, 0, sizeof buf, (int)fd, 0}; output *o = fd == 1 ? &out1 : fd == 2 ? &out2 : &other; if (o == &other && fcntl((int)fd, F_GETFD) == -1) { sh_warn("print: -u: bad file descriptor"); return 2; } for (int first = i; i < argc; i++) { if (i > first) out_putc(o, ' '); if (raw) { out_puts(o, argv[i]); } else if (!out_escaped(o, argv[i], true)) { newline = false; /* \c */ break; } } if (newline) out_putc(o, '\n'); if (o != &out1) { out_flush(o); if (o->err && o->err != EPIPE) { sh_warn("print: write error: %s", strerror(o->err)); o->err = 0; return 1; } o->err = 0; } return 0; } /* ---- whence ---------------------------------------------------------- */ /** * @brief The `whence` builtin: `whence [-pv] name ...`. * * Without options it prints what `command -v` prints. `-v` gives the * descriptive form that `type` gives. `-p` searches PATH only, ignoring * aliases, functions and builtins. * * @return 0 if every name was found, otherwise non-zero. */ int builtin_whence(int argc, char **argv) { bool verbose = false; bool path_only = false; 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 == 'v') { verbose = true; } else if (*p == 'p') { path_only = true; } else { sh_warn("whence: -%c: bad option", *p); return 2; } } } int status = 0; for (; i < argc; i++) { if (!path_only) { status |= describe_command(argv[i], verbose); continue; } const char *path = var_get("PATH"); const char *full = nullptr; if (strchr(argv[i], '/')) { struct stat st; if (stat(argv[i], &st) == 0 && S_ISREG(st.st_mode) && access(argv[i], X_OK) == 0) full = argv[i]; } else { full = path_search(argv[i], path ? path : "", true); } if (full) out_printf(&out1, "%s\n", full); else status = 1; } return status; } /* ---- setvar ---------------------------------------------------------- */ /** * @brief The `setvar` builtin (FreeBSD): `setvar name value`. * * Assigns to the variable whose name is the first argument. This is the * safe replacement for `eval "$1=\$2"`: the name is checked, the value is * never parsed as shell text, and no parsing happens at all. * * @return 0, 2 for wrong usage or a bad name. */ int builtin_setvar(int argc, char **argv) { if (argc != 3) { sh_warn("setvar: usage: setvar name value"); return 2; } if (!is_name(argv[1])) { sh_warn("setvar: %s: bad variable name", argv[1]); return 2; } var_set(argv[1], argv[2], 0); return 0; } /* ---- typeset --------------------------------------------------------- */ /** * @brief The `typeset` builtin: `typeset [-irx] [+ix] [name[=value] ...]`. * * Gives variables attributes: `-x` exported, `-r` read-only, `-i` * integer (every value assigned is evaluated as an arithmetic * expression). `+x` and `+i` remove an attribute. Inside a function the * named variables become local to it, as with `local`. With no names, * the variables that have the given attributes are listed. * * `integer` is `typeset -i`. * * @return 0, 1 for a bad name, 2 for a bad option. */ int builtin_typeset(int argc, char **argv) { unsigned on = !strcmp(argv[0], "integer") ? V_INTEGER : 0; unsigned off = 0; int i = 1; for (; i < argc && (argv[i][0] == '-' || argv[i][0] == '+') && argv[i][1]; i++) { if (!strcmp(argv[i], "--")) { i++; break; } bool plus = argv[i][0] == '+'; for (const char *p = argv[i] + 1; *p; p++) { unsigned f = *p == 'x' ? V_EXPORT : *p == 'i' ? V_INTEGER : *p == 'r' ? V_READONLY : 0; if (!f || (plus && f == V_READONLY)) { sh_warn("%s: %c%c: bad option", argv[0], argv[i][0], *p); return 2; } if (plus) off |= f; else on |= f; } } if (i >= argc) { var_print_all(on, on & V_EXPORT ? "export " : on & V_READONLY ? "readonly " : on & V_INTEGER ? "integer " : ""); return 0; } for (; i < argc; i++) { const char *arg = argv[i]; size_t nlen = name_len(arg); if (!nlen || (arg[nlen] && arg[nlen] != '=')) { sh_warn("%s: %s: bad variable name", argv[0], arg); return 1; } const char *name = arena_strndup(&scratch, arg, nlen); if (func_depth) var_make_local(name); /* Attributes first, so that -i applies to this very value; but * read-only last, or the value could not be assigned. */ if (on & ~V_READONLY) var_set_flags(name, on & ~V_READONLY); if (off) var_clear_flags(name, off); if (arg[nlen]) var_set_n(arg, nlen, arg + nlen + 1, 0); if (on & V_READONLY) var_set_flags(name, V_READONLY); } return 0; } /* ---- let ------------------------------------------------------------- */ /** * @brief The `let` builtin: `let expression ...`. * * Evaluates each argument as an arithmetic expression. * * @return 0 if the last expression is non-zero, 1 if it is zero, 2 if * there are no arguments. */ int builtin_let(int argc, char **argv) { if (argc < 2) { sh_warn("let: expression expected"); return 2; } intmax_t v = 0; for (int i = 1; i < argc; i++) v = arith_eval(argv[i]); return v == 0; } /* ---- ulimit ---------------------------------------------------------- */ /** @brief One resource `ulimit` knows about. */ typedef struct limit { char opt; /**< Option letter. */ int resource; /**< RLIMIT_* value. */ const char *name; /**< Description for `ulimit -a`. */ const char *unit; /**< Unit name for `ulimit -a`, or nullptr. */ unsigned scale; /**< Bytes (or items) per unit shown to the user. */ } limit; static const limit limits[] = { #ifdef RLIMIT_CORE {'c', RLIMIT_CORE, "core file size", "512-blocks", 512}, #endif #ifdef RLIMIT_DATA {'d', RLIMIT_DATA, "data seg size", "kbytes", 1024}, #endif {'f', RLIMIT_FSIZE, "file size", "512-blocks", 512}, #ifdef RLIMIT_MEMLOCK {'l', RLIMIT_MEMLOCK, "locked memory", "kbytes", 1024}, #endif #ifdef RLIMIT_RSS {'m', RLIMIT_RSS, "max memory size", "kbytes", 1024}, #endif #ifdef RLIMIT_NOFILE {'n', RLIMIT_NOFILE, "open files", nullptr, 1}, #endif #ifdef RLIMIT_STACK {'s', RLIMIT_STACK, "stack size", "kbytes", 1024}, #endif #ifdef RLIMIT_CPU {'t', RLIMIT_CPU, "cpu time", "seconds", 1}, #endif #ifdef RLIMIT_NPROC {'u', RLIMIT_NPROC, "max user processes", nullptr, 1}, #endif #ifdef RLIMIT_AS {'v', RLIMIT_AS, "virtual memory", "kbytes", 1024}, #endif #ifdef RLIMIT_MEMLIMIT /* z/OS: storage above the 2 GB bar (MEMLIMIT) */ {'M', RLIMIT_MEMLIMIT, "memory above the bar", "mbytes", 1048576}, #endif }; /** * @brief Print one limit value, or "unlimited". * @param l The resource. * @param hard Whether to show the hard limit rather than the soft one. */ static void limit_print(const limit *l, bool hard) { struct rlimit rl; if (getrlimit(l->resource, &rl) < 0) { out_puts(&out1, "unknown\n"); return; } rlim_t v = hard ? rl.rlim_max : rl.rlim_cur; if (v == RLIM_INFINITY) out_puts(&out1, "unlimited\n"); else out_printf(&out1, "%llu\n", (unsigned long long)(v / l->scale)); } /** * @brief The `ulimit` builtin: `ulimit [-HSa] [-cdflmnstuv] [limit]`. * * Shows or sets a resource limit of the shell (inherited by the commands * it runs). The default resource is the file size limit, `-f`. `limit` * is a number in the resource's unit or the word `unlimited`. Setting * changes both the hard and the soft limit unless `-H` or `-S` chooses * one. A query reports the soft limit unless `-H` is given. * * @return 0, 1 if the limit could not be set, 2 for wrong usage. */ int builtin_ulimit(int argc, char **argv) { bool hard = false; bool soft = false; bool all = false; const limit *l = nullptr; int i = 1; for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) { for (const char *p = argv[i] + 1; *p; p++) { if (*p == 'H') { hard = true; } else if (*p == 'S') { soft = true; } else if (*p == 'a') { all = true; } else { const limit *found = nullptr; for (size_t k = 0; k < ARRAY_LEN(limits); k++) { if (limits[k].opt == *p) found = &limits[k]; } if (!found) { sh_warn("ulimit: -%c: bad option", *p); return 2; } l = found; } } } if (all) { for (size_t k = 0; k < ARRAY_LEN(limits); k++) { const limit *e = &limits[k]; if (e->unit) out_printf(&out1, "%-20s (%s, -%c) ", e->name, e->unit, e->opt); else out_printf(&out1, "%-20s (-%c) ", e->name, e->opt); limit_print(e, hard && !soft); } return 0; } if (!l) { for (size_t k = 0; k < ARRAY_LEN(limits); k++) { if (limits[k].opt == 'f') l = &limits[k]; } } if (!l) { /* Built without RLIMIT_FSIZE: there is no default resource. */ sh_warn("ulimit: -f: not supported here"); return 1; } if (i >= argc) { limit_print(l, hard && !soft); return 0; } struct rlimit rl; if (getrlimit(l->resource, &rl) < 0) { sh_warn("ulimit: %s", strerror(errno)); return 1; } rlim_t v; if (!strcmp(argv[i], "unlimited")) { v = RLIM_INFINITY; } else { char *end; errno = 0; unsigned long long n = strtoull(argv[i], &end, 10); if (errno || *end || end == argv[i] || argv[i][0] == '-') { sh_warn("ulimit: %s: bad limit", argv[i]); return 2; } /* n * scale may not wrap, and may not quietly mean "unlimited". */ if (n > RLIM_INFINITY / l->scale || n * l->scale == RLIM_INFINITY) { sh_warn("ulimit: %s: limit out of range", argv[i]); return 1; } v = (rlim_t)n * (rlim_t)l->scale; } if (hard || !soft) rl.rlim_max = v; if (soft || !hard) rl.rlim_cur = v; if (setrlimit(l->resource, &rl) < 0) { sh_warn("ulimit: %s", strerror(errno)); return 1; } return 0; } /* ---- z/OS builtins: tag, alloc, free ---------------------------------- */ /** * @brief Print one file's tag in `chtag -p` style. * * Four fields: `t` (text), `b` (binary), `m` (mixed: a CCSID without the * text flag) or `-` (untagged). The code set, `binary` or `untagged`; * `T=on` or `T=off`. The file name. * * @return 0, or 1 if the file cannot be examined. */ static int tag_print(const char *path) { sys_tag t; if (sys_tag_get(path, &t) < 0) { sh_warn("tag: %s: %s", path, strerror(errno)); return 1; } char kind = t.ccsid == 0 ? '-' : t.ccsid == 65535 ? 'b' : t.text ? 't' : 'm'; const char *cs = t.ccsid == 0 ? "untagged" : t.ccsid == 65535 ? "binary" : t.codeset[0] ? t.codeset : "?"; if (!t.codeset[0] && t.ccsid && t.ccsid != 65535) out_printf(&out1, "%c %-14d T=%s %s\n", kind, t.ccsid, t.text ? "on " : "off", path); else out_printf(&out1, "%c %-14s T=%s %s\n", kind, cs, t.text ? "on " : "off", path); return 0; } /** * @brief The `tag` builtin: show or change file tags without spawning * `chtag` (z/OS only). * * tag [-p] file... show, as chtag -p * tag -t -c codeset file... tag as text in codeset * tag -m -c codeset file... tag mixed (codeset, text flag off) * tag -b file... tag as binary * tag -r file... remove the tag * * @return 0, 1 if any file failed, 2 for wrong usage. */ int builtin_tag(int argc, char **argv) { char mode = 'p'; const char *codeset = nullptr; 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 (strchr("ptmbr", *p)) { mode = *p; } else if (*p == 'c') { codeset = p[1] ? p + 1 : (i + 1 < argc ? argv[++i] : nullptr); if (!codeset) { sh_warn("tag: -c: code set required"); return 2; } break; } else { sh_warn("tag: -%c: bad option", *p); return 2; } } } if (i == argc || ((mode == 't' || mode == 'm') && !codeset)) { sh_warn("usage: tag [-p | -t -c codeset | -m -c codeset | -b | -r] " "file..."); return 2; } int status = 0; for (; i < argc; i++) { if (mode == 'p') { status |= tag_print(argv[i]); continue; } int rc = mode == 'r' ? sys_tag_set(argv[i], nullptr, 0) : mode == 'b' ? sys_tag_set(argv[i], "BINARY", 0) : sys_tag_set(argv[i], codeset, mode == 't'); if (rc < 0) { sh_warn("tag: %s: %s", argv[i], errno == EINVAL ? "unknown code set" : strerror(errno)); status = 1; } } return status; } /** * @brief Run one BPXWDYN request built from a keyword and the arguments. * @param verb "alloc" or "free". * @param argc Argument count. * @param argv Arguments. argv[1..] are the request's keywords. * @return 0, or 1 if BPXWDYN failed (its message is printed). */ static int dynalloc(const char *verb, int argc, char **argv) { if (argc < 2) { sh_warn("usage: %s keyword... (BPXWDYN syntax, e.g. %s)", verb, verb[0] == 'a' ? "alloc dd(in) da('sys1.maclib') shr" : "free dd(in)"); return 2; } strbuf sb; arena_marker mark = arena_mark(&scratch); sb_init(&sb, &scratch); sb_puts(&sb, verb); for (int i = 1; i < argc; i++) { sb_putc(&sb, ' '); sb_puts(&sb, argv[i]); } char msg[128]; int rc = sys_dynalloc(sb_cstr(&sb), msg, sizeof msg); arena_release(&scratch, mark); if (rc) { sh_warn("%s: %s", verb, msg); return 1; } return 0; } /** * @brief The `alloc` builtin: dynamic allocation through BPXWDYN, so a * DD exists in the shell's address space (z/OS only). * * `alloc dd(sysut1) da('my.data') shr msg(2)`. A DD allocated here is * visible to commands that run in the same address space: builtins, and * external commands only with `_BPX_SHAREAS=YES` (`set -o shareas`). */ int builtin_alloc(int argc, char **argv) { return dynalloc("alloc", argc, argv); } /** * @brief The `free` builtin: release a dynamic allocation (z/OS only). */ int builtin_free(int argc, char **argv) { return dynalloc("free", argc, argv); }