/** * @file var.c * @brief Shell variables. */ #include "var.h" #include #include #include #include #include #include "expand.h" #include "sys.h" /** * @brief Number of hash buckets for variables. */ #define VTAB_SIZE ((size_t)128) /** * @brief The saved state of one variable, to be restored when a scope ends. */ typedef struct varsave { struct varsave *next; var *v; char *text; unsigned flags; int prev_depth; } varsave; /** * @brief The variable hash table. */ static var *vtab[VTAB_SIZE]; /** * @brief Storage for `struct var`. Variables are never freed, only emptied. */ static arena var_arena; /**< struct var is never freed */ /** * @brief The environment vector last built by var_environ(). */ static char **env_cache; /** * @brief Allocated slots in env_cache. */ static size_t env_cap; /** * @brief An exported variable changed: env_cache must be rebuilt. */ static bool env_dirty = true; /** * @brief The innermost active scope, or NULL. */ varscope *var_scope; /** * @brief The positional parameters. */ shparam shellparam; /** * @brief Field-splitting class of every byte value, rebuilt when IFS changes. */ unsigned char ifs_class[256]; /** * @brief First character of IFS: the separator for `"$*"`. */ char ifs_first = ' '; /** * @brief Hash a variable name to a bucket. */ static unsigned hash_name(const char *s, size_t n) { unsigned h = 5381; while (n--) h = h * 33 + (unsigned char)*s++; return h % VTAB_SIZE; } /** * @brief Create a variable record and put it in the table. * @param text Its `name=value` string. * @param nlen Length of the name. * @param flags Initial flags. */ static var *var_link(char *text, size_t nlen, unsigned flags) { var *v = arena_alloc(&var_arena, sizeof *v); *v = (var){.text = text, .nlen = nlen, .flags = flags}; var **bucket = &vtab[hash_name(text, nlen)]; v->next = *bucket; *bucket = v; return v; } /** * @brief Build a heap `name=value` string. */ static char *make_text(const char *name, size_t nlen, const char *value) { size_t vlen = strlen(value); char *t = xmalloc(nlen + vlen + 2); memcpy(t, name, nlen); t[nlen] = '='; memcpy(t + nlen + 1, value, vlen + 1); return t; } /** * @brief Look up a variable. * @param name Name (not NUL-terminated). * @param nlen Its length. * @param create Make an unset variable if there is none. * @return The variable, or NULL. */ var *var_find(const char *name, size_t nlen, bool create) { for (var *v = vtab[hash_name(name, nlen)]; v; v = v->next) { if (v->nlen == nlen && !memcmp(v->text, name, nlen)) return v; } if (!create) return NULL; return var_link(make_text(name, nlen, ""), nlen, V_UNSET); } /** * @brief Value of a variable. * @param name Name (not NUL-terminated). * @param nlen Its length. * @return The value, or NULL if the variable is unset. */ const char *var_get_n(const char *name, size_t nlen) { const var *v = var_find(name, nlen, false); if (!v || (v->flags & V_UNSET)) return NULL; if (v->flags & V_DYNAMIC) return v->get(); return v->text + nlen + 1; } /** * @brief Value of a variable named by a NUL-terminated string. */ const char *var_get(const char *name) { return var_get_n(name, strlen(name)); } /** * @brief Note that a variable changed: mark the environment stale if it is (or * was) exported and run its hook. */ static void var_changed(var *v, unsigned old_flags) { if ((v->flags | old_flags) & V_EXPORT) env_dirty = true; if (v->hook) v->hook((v->flags & V_UNSET) ? NULL : v->text + v->nlen + 1); } /** * @brief Replace a variable's text, freeing the old one if the table owns it. */ static void var_replace(var *v, char *text, unsigned flags) { unsigned old = v->flags; if (!(old & V_NOFREE)) free(v->text); v->text = text; v->flags = flags; var_changed(v, old); } /** * @brief Record a variable's current state in a scope, once per scope. * * The save record takes over ownership of the old text. */ void var_save(var *v, varscope *s) { if (v->save_depth == s->depth) return; varsave *r = xmalloc(sizeof *r); *r = (varsave){s->saved, v, v->text, v->flags, v->save_depth}; s->saved = r; v->flags |= V_NOFREE; /* the save record owns the old text now */ v->save_depth = s->depth; } /** * @brief Assign to a variable. * * Fails with an error for a read-only variable. An integer variable gets * the value of the expression. A dynamic one is handed the value. While * a capturing scope is active the old value is saved first. * * @param name Name (not NUL-terminated). * @param nlen Its length. * @param value New value. * @param flags Flags to add (V_EXPORT, V_READONLY). */ void var_set_n(const char *name, size_t nlen, const char *value, unsigned flags) { var *v = var_find(name, nlen, true); char num[INT_BUFSZ]; /* One test covers every unusual kind of variable. */ if (v->flags & (V_READONLY | V_INTEGER | V_DYNAMIC)) { if (v->flags & V_READONLY) sh_error("%.*s: is read only", (int)nlen, name); if ((v->flags & V_DYNAMIC) && v->set) { v->set(value); return; } if (v->flags & V_INTEGER) value = fmt_int(arith_eval(value), num); } if (var_scope && var_scope->capture) var_save(v, var_scope); unsigned keep = v->flags & ~(V_UNSET | V_NOFREE | V_DYNAMIC); if (opt.allexport) flags |= V_EXPORT; char *text = make_text(name, nlen, value); var_replace(v, text, keep | flags | (v->flags & V_NOFREE)); v->flags &= ~V_NOFREE; } /** * @brief Assign to a variable named by a NUL-terminated string. */ void var_set(const char *name, const char *value, unsigned flags) { var_set_n(name, strlen(name), value, flags); } /** * @brief Assign a number to a variable. */ void var_set_long(const char *name, long value) { char buf[32]; snprintf(buf, sizeof buf, "%ld", value); var_set(name, buf, 0); } /** * @brief Unset a variable. * @return false if it is read-only. */ bool var_unset(const char *name) { size_t nlen = strlen(name); var *v = var_find(name, nlen, false); if (!v || (v->flags & V_UNSET && !(v->flags & V_EXPORT))) return true; if (v->flags & V_READONLY) { sh_warn("%s: is read only", name); return false; } if (var_scope && var_scope->capture) var_save(v, var_scope); char *text = make_text(name, nlen, ""); var_replace(v, text, V_UNSET | (v->flags & V_NOFREE)); v->flags &= ~V_NOFREE; return true; } /** * @brief Add attributes (export, read-only, integer) to a variable, creating it * unset if necessary. */ void var_set_flags(const char *name, unsigned flags) { var *v = var_find(name, strlen(name), true); if (var_scope && var_scope->capture) var_save(v, var_scope); v->flags |= flags; if (flags & V_EXPORT) env_dirty = true; } /** * @brief Remove attributes from a variable (`typeset +x`, `typeset +i`). * @param name Variable name. * @param flags V_EXPORT and/or V_INTEGER. */ void var_clear_flags(const char *name, unsigned flags) { var *v = var_find(name, strlen(name), false); if (!v) return; if (var_scope && var_scope->capture) var_save(v, var_scope); if (v->flags & flags & V_EXPORT) env_dirty = true; v->flags &= ~flags; } /** * @brief Call a function for the name of every variable that is set. * @param fn Callback. Receives a NUL-terminated copy of the name. * @param arg Passed through to the callback. */ void var_each(void (*fn)(const char *name, void *arg), void *arg) { for (size_t i = 0; i < VTAB_SIZE; i++) { for (const var *v = vtab[i]; v; v = v->next) { if (v->flags & V_UNSET) continue; arena_marker mark = arena_mark(&scratch); fn(arena_strndup(&scratch, v->text, v->nlen), arg); arena_release(&scratch, mark); } } } /* ---- scopes ---------------------------------------------------------- */ /** * @brief Enter a variable scope. * @param s Caller-provided scope record. * @param capture Save every variable that changes while it is active. * @param is_func It is the scope of a function call (target of `local`). */ void scope_push(varscope *s, bool capture, bool is_func) { s->prev = var_scope; s->saved = NULL; s->depth = var_scope ? var_scope->depth + 1 : 1; s->capture = capture; s->func = is_func; var_scope = s; } /** * @brief Leave the innermost scope, restoring every variable it saved. */ void scope_pop(void) { varscope *s = var_scope; while (s->saved) { varsave *r = s->saved; var *v = r->v; unsigned old = v->flags; s->saved = r->next; if (v->text != r->text && !(v->flags & V_NOFREE)) free(v->text); v->text = r->text; v->flags = r->flags; v->save_depth = r->prev_depth; var_changed(v, old); free(r); } var_scope = s->prev; } /** * @brief Pop scopes until `to` is innermost again (after an error). */ void scope_unwind(varscope *to) { while (var_scope != to) scope_pop(); } /** * @brief Make a variable local to the innermost function call. * @return false if no function is running. */ bool var_make_local(const char *name) { varscope *s = var_scope; while (s && !s->func) s = s->prev; if (!s) return false; var_save(var_find(name, strlen(name), true), s); return true; } /* ---- environment ----------------------------------------------------- */ /** * @brief The environment for a child: every exported variable. * * The vector points straight at the variables' `name=value` strings and * is rebuilt only after an exported variable has changed. */ char **var_environ(void) { if (!env_dirty) return env_cache; size_t n = 0; for (size_t i = 0; i < VTAB_SIZE; i++) { for (var *v = vtab[i]; v; v = v->next) { if ((v->flags & (V_EXPORT | V_UNSET)) != V_EXPORT) continue; if (n + 1 >= env_cap) { env_cap = env_cap ? env_cap * 2 : 64; env_cache = xrealloc(env_cache, env_cap * sizeof *env_cache); } env_cache[n++] = v->text; } } if (!env_cache) env_cache = xmalloc(sizeof *env_cache); env_cache[n] = NULL; env_dirty = false; return env_cache; } /** * @brief The environment plus extra `name=value` strings, which take priority * (the assignments in `X=1 command`). * @param extra The extra strings. * @param nextra How many. * @return A vector in scratch memory. */ char **var_environ_with(char **extra, int nextra) { char **base = var_environ(); size_t n = 0; while (base[n]) n++; char **env = arena_alloc(&scratch, (n + (size_t)nextra + 1) * sizeof *env); size_t k = 0; for (int i = 0; i < nextra; i++) env[k++] = extra[i]; for (size_t i = 0; i < n; i++) { size_t nlen = (size_t)(strchr(base[i], '=') - base[i]) + 1; bool shadowed = false; for (int j = 0; j < nextra && !shadowed; j++) shadowed = !strncmp(base[i], extra[j], nlen); if (!shadowed) env[k++] = base[i]; } env[k] = NULL; return env; } /** * @brief qsort() comparison of two variables by their text. */ static int cmp_text(const void *a, const void *b) { const var *const *va = a; const var *const *vb = b; return strcmp((*va)->text, (*vb)->text); } /** * @brief Print variables in a form the shell can read back. * @param flag Only variables with this flag. 0 for every set variable. * @param prefix Printed before each (`export `, `readonly `, ...). */ void var_print_all(unsigned flag, const char *prefix) { size_t n = 0; size_t cap = 64; var **list = xmalloc(cap * sizeof *list); for (size_t i = 0; i < VTAB_SIZE; i++) { for (var *v = vtab[i]; v; v = v->next) { if (flag ? !(v->flags & flag) : (v->flags & V_UNSET) != 0) continue; if (n == cap) list = xrealloc(list, (cap *= 2) * sizeof *list); list[n++] = v; } } qsort(list, n, sizeof *list, cmp_text); for (size_t i = 0; i < n; i++) { const var *v = list[i]; out_puts(&out1, prefix); out_write(&out1, v->text, v->nlen); if (!(v->flags & V_UNSET)) { const char *value = v->flags & V_DYNAMIC ? v->get() : v->text + v->nlen + 1; out_putc(&out1, '='); out_quote(&out1, value); } out_putc(&out1, '\n'); } free(list); } /* ---- special variables ----------------------------------------------- */ /** * @brief IFS hook: rebuild the splitting table. */ static void ifs_changed(const char *value) { if (!value) value = " \t\n"; memset(ifs_class, IFS_NONE, sizeof ifs_class); for (const char *p = value; *p; p++) { bool space = *p == ' ' || *p == '\t' || *p == '\n'; ifs_class[(unsigned char)*p] = space ? IFS_SPACE : IFS_HARD; } ifs_first = value[0]; } /** * @brief Value of `$LINENO`. */ static const char *get_lineno(void) { static char buf[16]; snprintf(buf, sizeof buf, "%d", cur_lineno); return buf; } /** * @brief Value of `$PPID`. */ static const char *get_ppid(void) { static char buf[24]; snprintf(buf, sizeof buf, "%ld", (long)getppid()); return buf; } /** * @brief State of the RANDOM generator. */ static unsigned random_state; /** * @brief RANDOM has been seeded. */ static bool random_seeded; /** @brief Value of `$RANDOM`: a new number in 0..32767 on each read. */ static const char *get_random(void) { static char buf[INT_BUFSZ]; if (!random_seeded) { random_state = (unsigned)time(NULL) ^ ((unsigned)getpid() << 8); random_seeded = true; } random_state = random_state * 1103515245u + 12345u; return fmt_int((random_state >> 16) & 0x7fff, buf); } /** @brief Assignment to `RANDOM` seeds the generator. */ static void set_random(const char *value) { random_state = (unsigned)strtoul(value, NULL, 10); random_seeded = true; } /** * @brief The moment SECONDS counts from. */ static time_t seconds_base; /** @brief Value of `$SECONDS`. */ static const char *get_seconds(void) { static char buf[INT_BUFSZ]; return fmt_int((intmax_t)(time(NULL) - seconds_base), buf); } /** @brief Assignment to `SECONDS` restarts the count from that value. */ static void set_seconds(const char *value) { seconds_base = time(NULL) - (time_t)strtol(value, NULL, 10); } /** * @brief Give a variable a default value unless the environment supplied one. */ /** * @brief Decode the value of a `_TAG_REDIR_*` variable. */ tag_mode tag_value(const char *v) { if (v && !strcmp(v, "TXT")) return TAG_TXT; if (v && !strcmp(v, "BIN")) return TAG_BIN; return TAG_UNSET; } /** @brief `_TAG_REDIR_IN` hook: cache the setting for redir.c. */ static void tag_in_changed(const char *v) { tag_redir[TAG_IN] = tag_value(v); } /** @brief `_TAG_REDIR_OUT` hook. */ static void tag_out_changed(const char *v) { tag_redir[TAG_OUT] = tag_value(v); } /** @brief `_TAG_REDIR_ERR` hook. */ static void tag_err_changed(const char *v) { tag_redir[TAG_ERR] = tag_value(v); } /** * @brief Attach a hook to a variable and run it for the current value * (which may have come from the environment). */ static void watch(const char *name, void (*hook)(const char *value)) { var *v = var_find(name, strlen(name), true); v->hook = hook; hook((v->flags & V_UNSET) ? NULL : v->text + v->nlen + 1); } /** * @brief A system fact for a ZOS_* variable. Never NULL (a dynamic * variable's getter must return a string). */ static const char *zos_info(sys_info_kind kind) { const char *s = sys_info(kind); return s ? s : ""; } /** @brief Value of `$ZOS_SYSNAME`: the system (LPAR) name. */ static const char *get_zos_sysname(void) { return zos_info(SI_SYSNAME); } /** @brief Value of `$ZOS_SYSPLEX`: the sysplex name. */ static const char *get_zos_sysplex(void) { return zos_info(SI_SYSPLEX); } /** @brief Value of `$ZOS_RELEASE`: version and release, "03.02.00". */ static const char *get_zos_release(void) { return zos_info(SI_RELEASE); } /** @brief Value of `$ZOS_ASID`: the shell's address space ID, in hex. */ static const char *get_zos_asid(void) { return zos_info(SI_ASID); } /** @brief Value of `$ZOS_JOBNAME`: the shell's job name. */ static const char *get_zos_jobname(void) { return zos_info(SI_JOBNAME); } static void set_default(char *text) { size_t nlen = (size_t)(strchr(text, '=') - text); if (!var_find(text, nlen, false)) var_link(text, nlen, V_NOFREE); } /** * @brief Define a variable whose value is computed when it is read. * @param text Static `NAME=` string. * @param get Function producing the value. */ static void set_dynamic(char *text, const char *(*get)(void)) { size_t nlen = strlen(text) - 1; var *v = var_find(text, nlen, false); if (!v) v = var_link(text, nlen, 0); v->flags |= V_NOFREE | V_DYNAMIC; v->flags &= ~(V_UNSET | V_EXPORT); v->get = get; } /** * @brief Set up the variable table from the environment and add the shell's own * variables. * * Imported strings are used where they are. Nothing is copied. */ void var_init(char **envp) { static char ifs[] = "IFS= \t\n"; static char ps1[] = "PS1=$ "; static char ps2[] = "PS2=> "; static char ps4[] = "PS4=+ "; static char optind1[] = "OPTIND=1"; static char lineno[] = "LINENO="; static char ppid[] = "PPID="; static char random[] = "RANDOM="; static char seconds[] = "SECONDS="; /* Imported strings are used where they are; nothing is copied. */ for (; envp && *envp; envp++) { size_t nlen = name_len(*envp); if (nlen && (*envp)[nlen] == '=' && !var_find(*envp, nlen, false)) var_link(*envp, nlen, V_EXPORT | V_NOFREE); } /* IFS is never taken from the environment. */ var *v = var_find("IFS", 3, false); if (v) { v->text = ifs; v->flags |= V_NOFREE; } else { v = var_link(ifs, 3, V_NOFREE); } v->hook = ifs_changed; ifs_changed(NULL); set_default(ps1); set_default(ps2); set_default(ps4); set_default(optind1); set_dynamic(lineno, get_lineno); set_dynamic(ppid, get_ppid); /* Computed when read, so they cost nothing until a script asks. */ seconds_base = time(NULL); set_dynamic(random, get_random); var_find("RANDOM", 6, false)->set = set_random; set_dynamic(seconds, get_seconds); var_find("SECONDS", 7, false)->set = set_seconds; if (SYS_MVS) { static char sysname[] = "ZOS_SYSNAME="; static char sysplex[] = "ZOS_SYSPLEX="; static char release[] = "ZOS_RELEASE="; static char asid[] = "ZOS_ASID="; static char jobname[] = "ZOS_JOBNAME="; /* Read from control blocks only when a script asks. */ set_dynamic(sysname, get_zos_sysname); set_dynamic(sysplex, get_zos_sysplex); set_dynamic(release, get_zos_release); set_dynamic(asid, get_zos_asid); set_dynamic(jobname, get_zos_jobname); watch("_TAG_REDIR_IN", tag_in_changed); watch("_TAG_REDIR_OUT", tag_out_changed); watch("_TAG_REDIR_ERR", tag_err_changed); } } /* ---- positional parameters ------------------------------------------- */ /** * @brief Free a heap copy of positional parameters. */ void params_free(shparam *sp) { free(sp->base); sp->base = NULL; } /** * @brief Replace the positional parameters with a private copy of argv[0..n). */ void params_set(char **argv, int n) { size_t bytes = ((size_t)n + 1) * sizeof(char *); size_t total = bytes; for (int i = 0; i < n; i++) total += strlen(argv[i]) + 1; char **p = xmalloc(total); char *s = (char *)p + bytes; for (int i = 0; i < n; i++) { size_t len = strlen(argv[i]) + 1; p[i] = memcpy(s, argv[i], len); s += len; } p[n] = NULL; params_free(&shellparam); shellparam = (shparam){n, p, p}; }