1 /* $OpenBSD: var.c,v 1.41 2015/04/17 17:20:41 deraadt Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5 * 2011, 2012, 2013, 2014, 2015
6 * Thorsten Glaser <tg@mirbsd.org>
8 * Provided that these terms and disclaimer and all copyright notices
9 * are retained or reproduced in an accompanying document, permission
10 * is granted to deal in this work without restriction, including un-
11 * limited rights to use, publicly perform, distribute, sell, modify,
12 * merge, give away, or sublicence.
14 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15 * the utmost extent permitted by applicable law, neither express nor
16 * implied; without malicious intent or gross negligence. In no event
17 * may a licensor, author or contributor be held liable for indirect,
18 * direct, other damage, loss, or other issues arising in any way out
19 * of dealing in the work, even if advised of the possibility of such
20 * damage or existence of a defect, except proven that it results out
21 * of said person's immediate fault when using the work as intended.
27 #if defined(__OpenBSD__)
28 #include <sys/sysctl.h>
31 __RCSID("$MirOS: src/bin/mksh/var.c,v 1.193 2015/07/10 19:36:38 tg Exp $");
36 * WARNING: unreadable code, needs a rewrite
38 * if (flag&INTEGER), val.i contains integer value, and type contains base.
39 * otherwise, (val.s + type) contains string value.
40 * if (flag&EXPORT), val.s contains "name=value" for E-Z exporting.
43 static struct table specials;
44 static uint32_t lcg_state = 5381, qh_state = 4711;
45 /* may only be set by typeset() just before call to array_index_calc() */
46 static enum namerefflag innermost_refflag = SRF_NOP;
48 static char *formatstr(struct tbl *, const char *);
49 static void exportprep(struct tbl *, const char *);
50 static int special(const char *);
51 static void unspecial(const char *);
52 static void getspec(struct tbl *);
53 static void setspec(struct tbl *);
54 static void unsetspec(struct tbl *);
55 static int getint(struct tbl *, mksh_ari_u *, bool);
56 static const char *array_index_calc(const char *, bool *, uint32_t *);
59 * create a new block for function calls and simple commands
60 * assume caller has allocated and set up e->loc
66 static const char *empty[] = { null };
68 l = alloc(sizeof(struct block), ATEMP);
70 /* TODO: could use e->area (l->area => l->areap) */
76 l->argc = e->loc->argc;
77 l->argv = e->loc->argv;
79 l->exit = l->error = NULL;
80 ktinit(&l->area, &l->vars, 0);
81 ktinit(&l->area, &l->funs, 0);
87 * pop a block handling special variables
93 struct block *l = e->loc;
94 struct tbl *vp, **vpp = l->vars.tbls, *vq;
99 i = 1 << (l->vars.tshift);
101 if ((vp = *vpp++) != NULL && (vp->flag&SPECIAL)) {
102 if ((vq = global(vp->name))->flag & ISSET)
107 if (l->flags & BF_DOGETOPTS)
108 user_opt = l->getopts_state;
113 /* called by main() to initialise variable data structures */
114 #define VARSPEC_DEFNS
115 #include "var_spec.h"
118 #define VARSPEC_ENUMS
119 #include "var_spec.h"
123 /* this is biased with -1 relative to VARSPEC_ENUMS */
124 static const char * const initvar_names[] = {
125 #define VARSPEC_ITEMS
126 #include "var_spec.h"
135 ktinit(APERM, &specials,
136 /* currently 14 specials: 75% of 32 = 2^5 */
138 while (i < V_MAX - 1) {
139 tp = ktenter(&specials, initvar_names[i],
140 hash(initvar_names[i]));
141 tp->flag = DEFINED|ISSET;
146 /* common code for several functions below and c_typeset() */
148 varsearch(struct block *l, struct tbl **vpp, const char *vn, uint32_t h)
150 register struct tbl *vp;
154 if ((vp = ktsearch(&l->vars, vn, h)) != NULL)
156 if (l->next != NULL) {
168 * Used to calculate an array index for global()/local(). Sets *arrayp
169 * to true if this is an array, sets *valp to the array index, returns
170 * the basename of the array. May only be called from global()/local()
171 * and must be their first callee.
174 array_index_calc(const char *n, bool *arrayp, uint32_t *valp)
182 p = skip_varname(n, false);
183 if (innermost_refflag == SRF_NOP && (p != n) && ksh_isalphx(n[0])) {
187 strndupx(vn, n, p - n, ATEMP);
188 /* check if this is a reference */
189 varsearch(e->loc, &vp, vn, hash(vn));
191 if (vp && (vp->flag & (DEFINED | ASSOC | ARRAY)) ==
196 cp = shf_smprintf("%s%s", str_val(vp), p);
202 innermost_refflag = SRF_NOP;
204 if (p != n && *p == '[' && (len = array_ref_len(p))) {
208 /* calculate the value of the subscript */
210 strndupx(tmp, p + 1, len - 2, ATEMP);
211 sub = substitute(tmp, 0);
213 strndupx(n, n, p - n, ATEMP);
214 evaluate(sub, &rval, KSH_UNWIND_ERROR, true);
215 *valp = (uint32_t)rval;
222 * Search for variable, if not found create globally.
225 global(const char *n)
227 struct block *l = e->loc;
234 * check to see if this is an array;
235 * dereference namerefs; must come first
237 n = array_index_calc(n, &array, &val);
239 c = (unsigned char)n[0];
240 if (!ksh_isalphx(c)) {
242 errorf("bad substitution");
248 if (ksh_isdigit(c)) {
249 if (getn(n, &c) && (c <= l->argc))
250 /* setstr can't fail here */
251 setstr(vp, l->argv[c], KSH_RETURN_ERROR);
258 vp->flag |= ISSET|INTEGER;
264 /* if no job, expand to nothing */
265 if ((vp->val.i = j_async()) == 0)
266 vp->flag &= ~(ISSET|INTEGER);
269 vp->val.i = exstat & 0xFF;
275 vp->flag &= ~INTEGER;
276 vp->val.s = getoptions();
279 vp->flag &= ~(ISSET|INTEGER);
283 l = varsearch(e->loc, &vp, n, h);
285 return (array ? arraysearch(vp, val) : vp);
286 vp = ktenter(&l->vars, n, h);
288 vp = arraysearch(vp, val);
296 * Search for local variable, if not found create locally.
299 local(const char *n, bool copy)
301 struct block *l = e->loc;
307 * check to see if this is an array;
308 * dereference namerefs; must come first
310 n = array_index_calc(n, &array, &val);
312 if (!ksh_isalphx(*n)) {
314 vp->flag = DEFINED|RDONLY;
319 vp = ktenter(&l->vars, n, h);
320 if (copy && !(vp->flag & DEFINED)) {
323 varsearch(l->next, &vq, n, h);
325 vp->flag |= vq->flag &
326 (EXPORT | INTEGER | RDONLY | LJUST | RJUST |
327 ZEROFIL | LCASEV | UCASEV_AL | INT_U | INT_L);
328 if (vq->flag & INTEGER)
330 vp->u2.field = vq->u2.field;
334 vp = arraysearch(vp, val);
341 /* get variable string value */
343 str_val(struct tbl *vp)
347 if ((vp->flag&SPECIAL))
349 if (!(vp->flag&ISSET))
350 /* special to dollar() */
352 else if (!(vp->flag&INTEGER))
354 s = vp->val.s + vp->type;
360 * worst case number length is when base == 2:
361 * 1 (minus) + 2 (base, up to 36) + 1 ('#') +
362 * number of bits in the mksh_uari_t + 1 (NUL)
364 char strbuf[1 + 2 + 1 + 8 * sizeof(mksh_uari_t) + 1];
365 const char *digits = (vp->flag & UCASEV_AL) ?
366 digits_uc : digits_lc;
368 s = strbuf + sizeof(strbuf);
369 if (vp->flag & INT_U)
372 n = (vp->val.i < 0) ? -vp->val.u : vp->val.u;
373 base = (vp->type == 0) ? 10U : (unsigned int)vp->type;
375 if (base == 1 && n == 0)
382 if (!UTFMODE || ((n & 0xFF80) == 0xEF80))
383 /* OPTU-16 -> raw octet */
386 sz = utf_wctomb(s + 2, n);
391 *--s = digits[n % base];
396 *--s = digits[base % 10];
398 *--s = digits[base / 10];
400 if (!(vp->flag & INT_U) && vp->val.i < 0)
403 if (vp->flag & (RJUST|LJUST))
404 /* case already dealt with */
405 s = formatstr(vp, s);
407 strdupx(s, s, ATEMP);
412 /* set variable to string value */
414 setstr(struct tbl *vq, const char *s, int error_ok)
417 bool no_ro_check = tobool(error_ok & 0x4);
420 if ((vq->flag & RDONLY) && !no_ro_check) {
421 warningf(true, "read-only: %s", vq->name);
426 if (!(vq->flag&INTEGER)) {
428 if ((vq->flag&ALLOC)) {
431 if (s >= vq->val.s &&
432 s <= vq->val.s + strlen(vq->val.s)) {
434 "setstr: %s=%s: assigning to self",
438 afree(vq->val.s, vq->areap);
440 vq->flag &= ~(ISSET|ALLOC);
442 if (s && (vq->flag & (UCASEV_AL|LCASEV|LJUST|RJUST)))
443 s = salloc = formatstr(vq, s);
444 if ((vq->flag&EXPORT))
447 strdupx(vq->val.s, s, vq->areap);
452 if (!v_evaluate(vq, s, error_ok, true))
456 if ((vq->flag&SPECIAL))
458 afree(salloc, ATEMP);
462 /* set variable to integer */
464 setint(struct tbl *vq, mksh_ari_t n)
466 if (!(vq->flag&INTEGER)) {
467 struct tbl *vp = &vtemp;
468 vp->flag = (ISSET|INTEGER);
472 /* setstr can't fail here */
473 setstr(vq, str_val(vp), KSH_RETURN_ERROR);
477 if ((vq->flag&SPECIAL))
482 getint(struct tbl *vp, mksh_ari_u *nump, bool arith)
484 mksh_uari_t c, num = 0, base = 10;
486 bool have_base = false, neg = false;
488 if (vp->flag & SPECIAL)
490 /* XXX is it possible for ISSET to be set and val.s to be NULL? */
491 if (!(vp->flag & ISSET) || (!(vp->flag & INTEGER) && vp->val.s == NULL))
493 if (vp->flag & INTEGER) {
497 s = vp->val.s + vp->type;
500 c = (unsigned char)*s++;
501 } while (ksh_isspace(c));
508 c = (unsigned char)*s++;
512 if (c == '0' && arith) {
513 if (ksh_eq(s[0], 'X', 'x')) {
514 /* interpret as hexadecimal */
517 goto getint_c_style_base;
518 } else if (Flag(FPOSIX) && ksh_isdigit(s[0]) &&
519 !(vp->flag & ZEROFIL)) {
520 /* interpret as octal (deprecated) */
524 c = (unsigned char)*s++;
530 /* ksh-style base determination */
531 if (have_base || num < 1)
533 if ((base = num) == 1) {
534 /* mksh-specific extension */
538 wc = *(const unsigned char *)s;
539 else if (utf_mbtowc(&wc, s) == (size_t)-1)
540 /* OPTU-8 -> OPTU-16 */
542 * (with a twist: 1#\uEF80 converts
543 * the same as 1#\x80 does, thus is
544 * not round-tripping correctly XXX)
546 wc = 0xEF00 + *(const unsigned char *)s;
547 nump->u = (mksh_uari_t)wc;
549 } else if (base > 36)
557 else if (ksh_isupper(c))
558 c = ksh_numuc(c) + 10;
559 else if (ksh_islower(c))
560 c = ksh_numlc(c) + 10;
565 /* handle overflow as truncation */
566 num = num * base + c;
567 } while ((c = (unsigned char)*s++));
576 * convert variable vq to integer variable, setting its value from vp
577 * (vq and vp may be the same)
580 setint_v(struct tbl *vq, struct tbl *vp, bool arith)
585 if ((base = getint(vp, &num, arith)) == -1)
587 setint_n(vq, num.i, 0);
594 /* convert variable vq to integer variable, setting its value to num */
596 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
598 if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
601 afree(vq->val.s, vq->areap);
606 vq->flag |= ISSET|INTEGER;
607 if (vq->flag&SPECIAL)
612 formatstr(struct tbl *vp, const char *s)
618 olen = (int)utf_mbswidth(s);
620 if (vp->flag & (RJUST|LJUST)) {
622 /* default field width */
628 p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
629 if (vp->flag & (RJUST|LJUST)) {
630 int slen = olen, i = 0;
632 if (vp->flag & RJUST) {
637 i += utf_widthadj(qq, &qq);
638 /* strip trailing spaces (AT&T uses qq[-1] == ' ') */
639 while (qq > s && ksh_isspace(qq[-1])) {
643 if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
648 else if (s[2] == '#')
651 if (vp->u2.field <= n)
658 while (slen > vp->u2.field)
659 slen -= utf_widthadj(s, &s);
660 if (vp->u2.field - slen)
661 memset(p + n, (vp->flag & ZEROFIL) ? '0' : ' ',
662 vp->u2.field - slen);
664 shf_snprintf(p + vp->u2.field - slen,
665 psiz - (vp->u2.field - slen),
668 /* strip leading spaces/zeros */
669 while (ksh_isspace(*s))
671 if (vp->flag & ZEROFIL)
674 shf_snprintf(p, nlen + 1, "%-*.*s",
675 vp->u2.field, vp->u2.field, s);
678 memcpy(p, s, strlen(s) + 1);
680 if (vp->flag & UCASEV_AL) {
682 *q = ksh_toupper(*q);
683 } else if (vp->flag & LCASEV) {
685 *q = ksh_tolower(*q);
692 * make vp->val.s be "name=value" for quick exporting.
695 exportprep(struct tbl *vp, const char *val)
698 char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
699 size_t namelen, vallen;
701 namelen = strlen(vp->name);
702 vallen = strlen(val) + 1;
705 /* since name+val are both in memory this can go unchecked */
706 xp = alloc(namelen + 1 + vallen, vp->areap);
707 memcpy(vp->val.s = xp, vp->name, namelen);
710 /* offset to value */
711 vp->type = xp - vp->val.s;
712 memcpy(xp, val, vallen);
714 afree(op, vp->areap);
718 * lookup variable (according to (set&LOCAL)), set its attributes
719 * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV,
720 * UCASEV_AL), and optionally set its value if an assignment.
723 typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
726 struct tbl *vpbase, *t;
730 bool vappend = false;
731 enum namerefflag new_refflag = SRF_NOP;
733 if ((set & (ARRAY | ASSOC)) == ASSOC) {
734 new_refflag = SRF_ENABLE;
735 set &= ~(ARRAY | ASSOC);
737 if ((clr & (ARRAY | ASSOC)) == ASSOC) {
738 new_refflag = SRF_DISABLE;
739 clr &= ~(ARRAY | ASSOC);
742 /* check for valid variable name, search for value */
743 val = skip_varname(var, false);
745 /* no variable name given */
749 if (new_refflag != SRF_NOP)
750 errorf("%s: %s", var,
751 "reference variable can't be an array");
752 len = array_ref_len(val);
756 * IMPORT is only used when the shell starts up and is
757 * setting up its environment. Allow only simple array
758 * references at this time since parameter/command
759 * substitution is performed on the [expression] which
760 * would be a major security hole.
765 for (i = 1; i < len - 1; i++)
766 if (!ksh_isdigit(val[i]))
772 strndupx(tvar, var, val - var, ATEMP);
774 } else if (set & IMPORT) {
775 /* environment invalid variable name or no assignment */
777 } else if (val[0] == '+' && val[1] == '=') {
778 strndupx(tvar, var, val - var, ATEMP);
781 } else if (val[0] != '\0') {
782 /* other invalid variable names (not from environment) */
785 /* just varname with no value part nor equals sign */
786 strdupx(tvar, var, ATEMP);
788 /* handle foo[*] => foo (whole array) mapping for R39b */
790 if (len > 3 && tvar[len - 3] == '[' && tvar[len - 2] == '*' &&
791 tvar[len - 1] == ']')
792 tvar[len - 3] = '\0';
795 if (new_refflag == SRF_ENABLE) {
796 const char *qval, *ccp;
798 /* bail out on 'nameref foo+=bar' */
800 errorf("appending not allowed for nameref");
801 /* find value if variable already exists */
802 if ((qval = val) == NULL) {
803 varsearch(e->loc, &vp, tvar, hash(tvar));
808 /* check target value for being a valid variable name */
809 ccp = skip_varname(qval, false);
811 if (ksh_isdigit(qval[0])) {
815 goto nameref_rhs_checked;
816 } else if (qval[1] == '\0') switch (qval[0]) {
822 goto nameref_rhs_checked;
825 errorf("%s: %s", var, "empty nameref target");
827 len = (*ccp == '[') ? array_ref_len(ccp) : 0;
830 * works for cases "no array", "valid array with
831 * junk after it" and "invalid array"; in the
832 * latter case, len is also 0 and points to '['
834 errorf("%s: %s", qval,
835 "nameref target not a valid parameter name");
838 /* prevent nameref loops */
840 if (!strcmp(qval, tvar))
841 errorf("%s: %s", qval,
842 "expression recurses on parameter");
843 varsearch(e->loc, &vp, qval, hash(qval));
845 if (vp && ((vp->flag & (ARRAY | ASSOC)) == ASSOC))
850 /* prevent typeset from creating a local PATH/ENV/SHELL */
851 if (Flag(FRESTRICTED) && (strcmp(tvar, "PATH") == 0 ||
852 strcmp(tvar, "ENV") == 0 || strcmp(tvar, "SHELL") == 0))
853 errorf("%s: %s", tvar, "restricted");
855 innermost_refflag = new_refflag;
856 vp = (set & LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
858 if (new_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
860 else if (new_refflag == SRF_ENABLE) {
861 if (vp->flag & ARRAY) {
864 /* free up entire array */
865 for (a = vp->u.array; a; ) {
868 if (tmp->flag & ALLOC)
869 afree(tmp->val.s, tmp->areap);
870 afree(tmp, tmp->areap);
878 set &= ~(LOCAL|LOCAL_COPY);
880 vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
883 * only allow export flag to be set; AT&T ksh allows any
884 * attribute to be changed which means it can be truncated or
885 * modified (-L/-R/-Z/-i)
887 if ((vpbase->flag & RDONLY) &&
888 (val || clr || (set & ~EXPORT)))
889 /* XXX check calls - is error here ok by POSIX? */
890 errorfx(2, "read-only: %s", tvar);
893 /* most calls are with set/clr == 0 */
898 * XXX if x[0] isn't set, there will be problems: need
899 * to have one copy of attributes for arrays...
901 for (t = vpbase; t; t = t->u.array) {
904 char *free_me = NULL;
906 fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
907 ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
908 ((t->flag & INTEGER) && (clr & INTEGER)) ||
909 (!(t->flag & INTEGER) && (set & INTEGER)));
911 if (t->flag & INTEGER) {
915 s = t->val.s + t->type;
916 free_me = (t->flag & ALLOC) ? t->val.s :
921 if (!(t->flag & INTEGER) && (set & INTEGER)) {
925 t->flag = (t->flag | set) & ~clr;
927 * Don't change base if assignment is to be
928 * done, in case assignment fails.
930 if ((set & INTEGER) && base > 0 && (!val || t != vp))
932 if (set & (LJUST|RJUST|ZEROFIL))
935 if (!setstr(t, s, KSH_RETURN_ERROR)) {
937 * Somewhat arbitrary action
938 * here: zap contents of
939 * variable, but keep the flag
943 if (t->flag & INTEGER)
947 afree(t->val.s, t->areap);
948 t->flag &= ~(ISSET|ALLOC);
953 afree(free_me, t->areap);
964 tval = shf_smprintf("%s%s", str_val(vp), val);
969 if (vp->flag&INTEGER) {
970 /* do not zero base before assignment */
971 setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
972 /* done after assignment to override default */
976 /* setstr can't fail (readonly check already done) */
977 setstr(vp, val, KSH_RETURN_ERROR | 0x4);
983 /* only x[0] is ever exported, so use vpbase */
984 if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
986 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
992 * Unset a variable. The flags can be:
993 * |1 = tear down entire array
994 * |2 = keep attributes, only unset content
997 unset(struct tbl *vp, int flags)
999 if (vp->flag & ALLOC)
1000 afree(vp->val.s, vp->areap);
1001 if ((vp->flag & ARRAY) && (flags & 1)) {
1002 struct tbl *a, *tmp;
1004 /* free up entire array */
1005 for (a = vp->u.array; a; ) {
1008 if (tmp->flag & ALLOC)
1009 afree(tmp->val.s, tmp->areap);
1010 afree(tmp, tmp->areap);
1015 vp->flag &= ~(ALLOC|ISSET);
1018 /* if foo[0] is being unset, the remainder of the array is kept... */
1019 vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
1020 if (vp->flag & SPECIAL)
1021 /* responsible for 'unspecial'ing var */
1026 * Return a pointer to the first char past a legal variable name
1027 * (returns the argument if there is no legal name, returns a pointer to
1028 * the terminating NUL if whole string is legal).
1031 skip_varname(const char *s, bool aok)
1035 if (s && ksh_isalphx(*s)) {
1036 while (*++s && ksh_isalnux(*s))
1038 if (aok && *s == '[' && (alen = array_ref_len(s)))
1044 /* Return a pointer to the first character past any legal variable name */
1046 skip_wdvarname(const char *s,
1047 /* skip array de-reference? */
1050 if (s[0] == CHAR && ksh_isalphx(s[1])) {
1053 } while (s[0] == CHAR && ksh_isalnux(s[1]));
1054 if (aok && s[0] == CHAR && s[1] == '[') {
1055 /* skip possible array de-reference */
1060 while (/* CONSTCOND */ 1) {
1067 else if (c == ']' && --depth == 0) {
1077 /* Check if coded string s is a variable name */
1079 is_wdvarname(const char *s, bool aok)
1081 const char *p = skip_wdvarname(s, aok);
1083 return (p != s && p[0] == EOS);
1086 /* Check if coded string s is a variable assignment */
1088 is_wdvarassign(const char *s)
1090 const char *p = skip_wdvarname(s, true);
1092 return (p != s && p[0] == CHAR &&
1093 (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1097 * Make the exported environment from the exported names in the dictionary.
1105 struct tbl *vp, **vpp;
1108 for (l = e->loc; l != NULL; l = l->next) {
1110 i = 1 << (l->vars.tshift);
1112 if ((vp = *vpp++) != NULL &&
1113 (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1116 uint32_t h = hash(vp->name);
1118 /* unexport any redefined instances */
1119 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1120 vp2 = ktsearch(&l2->vars, vp->name, h);
1122 vp2->flag &= ~EXPORT;
1124 if ((vp->flag&INTEGER)) {
1125 /* integer to string */
1128 vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1129 /* setstr can't fail here */
1130 setstr(vp, val, KSH_RETURN_ERROR);
1132 XPput(denv, vp->val.s);
1134 if (l->flags & BF_STOPENV)
1138 return ((char **)XPclose(denv));
1142 * handle special variables with side effects - PATH, SECONDS.
1145 /* Test if name is a special parameter */
1147 special(const char *name)
1151 tp = ktsearch(&specials, name, hash(name));
1152 return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1155 /* Make a variable non-special */
1157 unspecial(const char *name)
1161 tp = ktsearch(&specials, name, hash(name));
1166 static time_t seconds; /* time SECONDS last set */
1167 static mksh_uari_t user_lineno; /* what user set $LINENO to */
1170 getspec(struct tbl *vp)
1176 switch ((st = special(vp->name))) {
1180 * Do NOT export COLUMNS/LINES. Many applications
1181 * check COLUMNS/LINES before checking ws.ws_col/row,
1182 * so if the app is started with C/L in the environ
1183 * and the window is then resized, the app won't
1184 * see the change cause the environ doesn't change.
1192 num.u = (mksh_uari_t)procpid;
1201 num.u = (mksh_uari_t)current_lineno + user_lineno;
1206 case V_EPOCHREALTIME: {
1207 /* 10(%u) + 1(.) + 6 + NUL */
1210 vp->flag &= ~SPECIAL;
1212 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1213 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1214 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1215 vp->flag |= SPECIAL;
1219 num.i = user_opt.uoptind;
1226 * On start up the value of SECONDS is used before
1227 * it has been set - don't do anything in this case
1228 * (see initcoms[] in main.c).
1230 if (vp->flag & ISSET) {
1232 num.i = tv.tv_sec - seconds;
1237 /* do nothing, do not touch vp at all */
1240 vp->flag &= ~SPECIAL;
1241 setint_n(vp, num.i, 0);
1242 vp->flag |= SPECIAL;
1246 setspec(struct tbl *vp)
1252 switch ((st = special(vp->name))) {
1253 #if HAVE_PERSISTENT_HISTORY
1255 sethistfile(str_val(vp));
1259 setctypes(s = str_val(vp), C_IFS);
1266 strdupx(path, s, APERM);
1267 /* clear tracked aliases */
1272 afree(tmpdir, APERM);
1276 * Use tmpdir iff it is an absolute path, is writable
1277 * and searchable and is a directory...
1283 /* LINTED use of access */
1284 if (mksh_abspath(s) && access(s, W_OK|X_OK) == 0 &&
1285 stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1286 strdupx(tmpdir, s, APERM);
1289 /* common sub-cases */
1292 if (vp->flag & IMPORT) {
1294 unspecial(vp->name);
1295 vp->flag &= ~SPECIAL;
1305 vp->flag &= ~SPECIAL;
1306 if (getint(vp, &num, false) == -1) {
1309 errorf("%s: %s: %s", vp->name, "bad number", s);
1312 vp->flag |= SPECIAL;
1315 /* do nothing, do not touch vp at all */
1319 /* process the singular parts of the common cases */
1323 if (num.i >= MIN_COLS)
1330 /* The -1 is because line numbering starts at 1. */
1331 user_lineno = num.u - (mksh_uari_t)current_lineno - 1;
1334 if (num.i >= MIN_LINS)
1338 getopts_reset((int)num.i);
1342 * mksh R39d+ no longer has the traditional repeatability
1343 * of $RANDOM sequences, but always retains state
1345 rndset((unsigned long)num.u);
1352 seconds = tv.tv_sec - num.i;
1356 ksh_tmout = num.i >= 0 ? num.i : 0;
1362 unsetspec(struct tbl *vp)
1365 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1366 * meaning, but OPTARG does not (still set by getopts) and _ is
1367 * also still set in various places. Don't know what AT&T does
1368 * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1369 * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1372 switch (special(vp->name)) {
1373 #if HAVE_PERSISTENT_HISTORY
1379 setctypes(TC_IFSWS, C_IFS);
1385 strdupx(path, def_path, APERM);
1386 /* clear tracked aliases */
1390 /* should not become unspecial */
1392 afree(tmpdir, APERM);
1400 /* AT&T ksh leaves previous value in place */
1401 unspecial(vp->name);
1407 * Search for (and possibly create) a table entry starting with
1408 * vp, indexed by val.
1411 arraysearch(struct tbl *vp, uint32_t val)
1413 struct tbl *prev, *curr, *news;
1416 vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
1417 /* the table entry is always [0] */
1422 while (curr && curr->ua.index < val) {
1424 curr = curr->u.array;
1426 if (curr && curr->ua.index == val) {
1427 if (curr->flag&ISSET)
1433 len = strlen(vp->name);
1434 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1435 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1436 memcpy(news->name, vp->name, len);
1438 news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1439 news->type = vp->type;
1440 news->areap = vp->areap;
1441 news->u2.field = vp->u2.field;
1442 news->ua.index = val;
1445 /* not reusing old array entry */
1446 prev->u.array = news;
1447 news->u.array = curr;
1453 * Return the length of an array reference (eg, [1+2]) - cp is assumed
1454 * to point to the open bracket. Returns 0 if there is no matching
1457 * XXX this should parse the actual arithmetic syntax
1460 array_ref_len(const char *cp)
1466 while ((c = *s++) && (c != ']' || --depth))
1475 * Make a copy of the base of an array name
1478 arrayname(const char *str)
1483 if ((p = cstrchr(str, '[')) == 0)
1484 /* Shouldn't happen, but why worry? */
1485 strdupx(rv, str, ATEMP);
1487 strndupx(rv, str, p - str, ATEMP);
1492 /* set (or overwrite, if reset) the array variable var to the values in vals */
1494 set_array(const char *var, bool reset, const char **vals)
1496 struct tbl *vp, *vq;
1497 mksh_uari_t i = 0, j = 0;
1498 const char *ccp = var;
1502 /* to get local array, use "local foo; set -A foo" */
1504 if (n > 0 && var[n - 1] == '+') {
1507 strndupx(cp, var, n - 1, ATEMP);
1512 /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1513 if ((vp->flag&RDONLY))
1514 errorfx(2, "read-only: %s", ccp);
1515 /* This code is quite non-optimal */
1517 /* trash existing values and attributes */
1519 /* allocate-by-access the [0] element to keep in scope */
1523 * TODO: would be nice for assignment to completely succeed or
1524 * completely fail. Only really effects integer arrays:
1525 * evaluation of some of vals[] may fail...
1528 /* find out where to set when appending */
1529 for (vq = vp; vq; vq = vq->u.array) {
1530 if (!(vq->flag & ISSET))
1532 if (arrayindex(vq) >= j)
1533 j = arrayindex(vq) + 1;
1537 while ((ccp = vals[i])) {
1538 #if 0 /* temporarily taken out due to regression */
1543 if (*ccp == ']' && --level == 0)
1549 if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1550 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1552 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1553 KSH_UNWIND_ERROR, true);
1561 vq = arraysearch(vp, j);
1562 /* would be nice to deal with errors here... (see above) */
1563 setstr(vq, ccp, KSH_RETURN_ERROR);
1577 BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
1580 /* check if window size has changed */
1581 if (tty_init_fd() < 2) {
1584 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1593 /* bounds check for sane values, use defaults otherwise */
1594 if (x_cols < MIN_COLS)
1596 if (x_lins < MIN_LINS)
1607 register uint32_t h;
1610 BAFHUpdateStr_reg(h, s);
1616 chvt_rndsetup(const void *bp, size_t sz)
1618 register uint32_t h;
1620 /* use LCG as seed but try to get them to deviate immediately */
1624 /* variation through pid, ppid, and the works */
1625 BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
1626 /* some variation, some possibly entropy, depending on OE */
1627 BAFHUpdateMem_reg(h, bp, sz);
1628 /* mix them all up */
1638 * this is the same Linear Congruential PRNG as Borland
1639 * C/C++ allegedly uses in its built-in rand() function
1641 return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1645 rndset(unsigned long v)
1647 register uint32_t h;
1648 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1649 register uint32_t t;
1660 /* clear the allocated space, for valgrind */
1661 memset(&z, 0, sizeof(z));
1666 BAFHUpdateMem_reg(h, &v, sizeof(v));
1671 z.r = (short)rndget();
1673 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1676 z.qh = (t & 0xFFFF8000) | rndget();
1677 lcg_state = (t << 15) | rndget();
1679 * either we have very chap entropy get and push available,
1680 * with malloc() pulling in this code already anyway, or the
1681 * user requested us to use the old functions
1684 BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
1687 #if defined(arc4random_pushb_fast)
1688 arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1689 lcg_state = arc4random();
1691 lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1693 BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
1698 BAFHUpdateMem_reg(h, &z, sizeof(z));
1704 rndpush(const void *s)
1706 register uint32_t h = qh_state;
1708 BAFHUpdateStr_reg(h, s);
1709 BAFHUpdateOctet_reg(h, 0);