1 /* $OpenBSD: var.c,v 1.38 2013/12/20 17:53:09 zhuk 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.183.2.2 2015/03/01 15:43:07 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, base;
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 if (arith && s[0] == '0' && (s[1] | 0x20) == 'x') {
505 if (Flag(FPOSIX) && arith && s[0] == '0' && ksh_isdigit(s[1]) &&
506 !(vp->flag & ZEROFIL)) {
507 /* interpret as octal (deprecated) */
511 while ((c = (unsigned char)*s++)) {
515 } else if (c == '#') {
516 if (have_base || num < 1 || num > 36)
518 if ((base = num) == 1) {
522 wc = *(const unsigned char *)s;
523 else if (utf_mbtowc(&wc, s) == (size_t)-1)
524 /* OPTU-8 -> OPTU-16 */
526 * (with a twist: 1#\uEF80 converts
527 * the same as 1#\x80 does, thus is
528 * not round-tripping correctly XXX)
530 wc = 0xEF00 + *(const unsigned char *)s;
531 nump->u = (mksh_uari_t)wc;
537 } else if (ksh_isdigit(c))
539 else if (ksh_islower(c))
541 else if (ksh_isupper(c))
547 num = num * base + c;
556 * convert variable vq to integer variable, setting its value from vp
557 * (vq and vp may be the same)
560 setint_v(struct tbl *vq, struct tbl *vp, bool arith)
565 if ((base = getint(vp, &num, arith)) == -1)
567 setint_n(vq, num.i, 0);
574 /* convert variable vq to integer variable, setting its value to num */
576 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
578 if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
581 afree(vq->val.s, vq->areap);
586 vq->flag |= ISSET|INTEGER;
587 if (vq->flag&SPECIAL)
592 formatstr(struct tbl *vp, const char *s)
598 olen = (int)utf_mbswidth(s);
600 if (vp->flag & (RJUST|LJUST)) {
602 /* default field width */
608 p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
609 if (vp->flag & (RJUST|LJUST)) {
610 int slen = olen, i = 0;
612 if (vp->flag & RJUST) {
617 i += utf_widthadj(qq, &qq);
618 /* strip trailing spaces (AT&T uses qq[-1] == ' ') */
619 while (qq > s && ksh_isspace(qq[-1])) {
623 if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
628 else if (s[2] == '#')
631 if (vp->u2.field <= n)
638 while (slen > vp->u2.field)
639 slen -= utf_widthadj(s, &s);
640 if (vp->u2.field - slen)
641 memset(p + n, (vp->flag & ZEROFIL) ? '0' : ' ',
642 vp->u2.field - slen);
644 shf_snprintf(p + vp->u2.field - slen,
645 psiz - (vp->u2.field - slen),
648 /* strip leading spaces/zeros */
649 while (ksh_isspace(*s))
651 if (vp->flag & ZEROFIL)
654 shf_snprintf(p, nlen + 1, "%-*.*s",
655 vp->u2.field, vp->u2.field, s);
658 memcpy(p, s, strlen(s) + 1);
660 if (vp->flag & UCASEV_AL) {
662 *q = ksh_toupper(*q);
663 } else if (vp->flag & LCASEV) {
665 *q = ksh_tolower(*q);
672 * make vp->val.s be "name=value" for quick exporting.
675 exportprep(struct tbl *vp, const char *val)
678 char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
679 size_t namelen, vallen;
681 namelen = strlen(vp->name);
682 vallen = strlen(val) + 1;
685 /* since name+val are both in memory this can go unchecked */
686 xp = alloc(namelen + 1 + vallen, vp->areap);
687 memcpy(vp->val.s = xp, vp->name, namelen);
690 /* offset to value */
691 vp->type = xp - vp->val.s;
692 memcpy(xp, val, vallen);
694 afree(op, vp->areap);
698 * lookup variable (according to (set&LOCAL)), set its attributes
699 * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV,
700 * UCASEV_AL), and optionally set its value if an assignment.
703 typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
706 struct tbl *vpbase, *t;
710 bool vappend = false;
711 enum namerefflag new_refflag = SRF_NOP;
713 if ((set & (ARRAY | ASSOC)) == ASSOC) {
714 new_refflag = SRF_ENABLE;
715 set &= ~(ARRAY | ASSOC);
717 if ((clr & (ARRAY | ASSOC)) == ASSOC) {
718 new_refflag = SRF_DISABLE;
719 clr &= ~(ARRAY | ASSOC);
722 /* check for valid variable name, search for value */
723 val = skip_varname(var, false);
725 /* no variable name given */
729 if (new_refflag != SRF_NOP)
730 errorf("%s: %s", var,
731 "reference variable can't be an array");
732 len = array_ref_len(val);
736 * IMPORT is only used when the shell starts up and is
737 * setting up its environment. Allow only simple array
738 * references at this time since parameter/command
739 * substitution is performed on the [expression] which
740 * would be a major security hole.
745 for (i = 1; i < len - 1; i++)
746 if (!ksh_isdigit(val[i]))
752 strndupx(tvar, var, val - var, ATEMP);
754 } else if (set & IMPORT) {
755 /* environment invalid variable name or no assignment */
757 } else if (val[0] == '+' && val[1] == '=') {
758 strndupx(tvar, var, val - var, ATEMP);
761 } else if (val[0] != '\0') {
762 /* other invalid variable names (not from environment) */
765 /* just varname with no value part nor equals sign */
766 strdupx(tvar, var, ATEMP);
768 /* handle foo[*] => foo (whole array) mapping for R39b */
770 if (len > 3 && tvar[len - 3] == '[' && tvar[len - 2] == '*' &&
771 tvar[len - 1] == ']')
772 tvar[len - 3] = '\0';
775 if (new_refflag == SRF_ENABLE) {
776 const char *qval, *ccp;
778 /* bail out on 'nameref foo+=bar' */
780 errorf("appending not allowed for nameref");
781 /* find value if variable already exists */
782 if ((qval = val) == NULL) {
783 varsearch(e->loc, &vp, tvar, hash(tvar));
788 /* check target value for being a valid variable name */
789 ccp = skip_varname(qval, false);
791 if (ksh_isdigit(qval[0])) {
795 goto nameref_rhs_checked;
796 } else if (qval[1] == '\0') switch (qval[0]) {
802 goto nameref_rhs_checked;
805 errorf("%s: %s", var, "empty nameref target");
807 len = (*ccp == '[') ? array_ref_len(ccp) : 0;
810 * works for cases "no array", "valid array with
811 * junk after it" and "invalid array"; in the
812 * latter case, len is also 0 and points to '['
814 errorf("%s: %s", qval,
815 "nameref target not a valid parameter name");
818 /* prevent nameref loops */
820 if (!strcmp(qval, tvar))
821 errorf("%s: %s", qval,
822 "expression recurses on parameter");
823 varsearch(e->loc, &vp, qval, hash(qval));
825 if (vp && ((vp->flag & (ARRAY | ASSOC)) == ASSOC))
830 /* prevent typeset from creating a local PATH/ENV/SHELL */
831 if (Flag(FRESTRICTED) && (strcmp(tvar, "PATH") == 0 ||
832 strcmp(tvar, "ENV") == 0 || strcmp(tvar, "SHELL") == 0))
833 errorf("%s: %s", tvar, "restricted");
835 innermost_refflag = new_refflag;
836 vp = (set & LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
838 if (new_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
840 else if (new_refflag == SRF_ENABLE) {
841 if (vp->flag & ARRAY) {
844 /* free up entire array */
845 for (a = vp->u.array; a; ) {
848 if (tmp->flag & ALLOC)
849 afree(tmp->val.s, tmp->areap);
850 afree(tmp, tmp->areap);
858 set &= ~(LOCAL|LOCAL_COPY);
860 vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
863 * only allow export flag to be set; AT&T ksh allows any
864 * attribute to be changed which means it can be truncated or
865 * modified (-L/-R/-Z/-i)
867 if ((vpbase->flag & RDONLY) &&
868 (val || clr || (set & ~EXPORT)))
869 /* XXX check calls - is error here ok by POSIX? */
870 errorfx(2, "read-only: %s", tvar);
873 /* most calls are with set/clr == 0 */
878 * XXX if x[0] isn't set, there will be problems: need
879 * to have one copy of attributes for arrays...
881 for (t = vpbase; t; t = t->u.array) {
884 char *free_me = NULL;
886 fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
887 ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
888 ((t->flag & INTEGER) && (clr & INTEGER)) ||
889 (!(t->flag & INTEGER) && (set & INTEGER)));
891 if (t->flag & INTEGER) {
895 s = t->val.s + t->type;
896 free_me = (t->flag & ALLOC) ? t->val.s :
901 if (!(t->flag & INTEGER) && (set & INTEGER)) {
905 t->flag = (t->flag | set) & ~clr;
907 * Don't change base if assignment is to be
908 * done, in case assignment fails.
910 if ((set & INTEGER) && base > 0 && (!val || t != vp))
912 if (set & (LJUST|RJUST|ZEROFIL))
915 if (!setstr(t, s, KSH_RETURN_ERROR)) {
917 * Somewhat arbitrary action
918 * here: zap contents of
919 * variable, but keep the flag
923 if (t->flag & INTEGER)
927 afree(t->val.s, t->areap);
928 t->flag &= ~(ISSET|ALLOC);
933 afree(free_me, t->areap);
944 tval = shf_smprintf("%s%s", str_val(vp), val);
949 if (vp->flag&INTEGER) {
950 /* do not zero base before assignment */
951 setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
952 /* done after assignment to override default */
956 /* setstr can't fail (readonly check already done) */
957 setstr(vp, val, KSH_RETURN_ERROR | 0x4);
963 /* only x[0] is ever exported, so use vpbase */
964 if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
966 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
972 * Unset a variable. The flags can be:
973 * |1 = tear down entire array
974 * |2 = keep attributes, only unset content
977 unset(struct tbl *vp, int flags)
979 if (vp->flag & ALLOC)
980 afree(vp->val.s, vp->areap);
981 if ((vp->flag & ARRAY) && (flags & 1)) {
984 /* free up entire array */
985 for (a = vp->u.array; a; ) {
988 if (tmp->flag & ALLOC)
989 afree(tmp->val.s, tmp->areap);
990 afree(tmp, tmp->areap);
995 vp->flag &= ~(ALLOC|ISSET);
998 /* if foo[0] is being unset, the remainder of the array is kept... */
999 vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
1000 if (vp->flag & SPECIAL)
1001 /* responsible for 'unspecial'ing var */
1006 * Return a pointer to the first char past a legal variable name
1007 * (returns the argument if there is no legal name, returns a pointer to
1008 * the terminating NUL if whole string is legal).
1011 skip_varname(const char *s, bool aok)
1015 if (s && ksh_isalphx(*s)) {
1016 while (*++s && ksh_isalnux(*s))
1018 if (aok && *s == '[' && (alen = array_ref_len(s)))
1024 /* Return a pointer to the first character past any legal variable name */
1026 skip_wdvarname(const char *s,
1027 /* skip array de-reference? */
1030 if (s[0] == CHAR && ksh_isalphx(s[1])) {
1033 } while (s[0] == CHAR && ksh_isalnux(s[1]));
1034 if (aok && s[0] == CHAR && s[1] == '[') {
1035 /* skip possible array de-reference */
1040 while (/* CONSTCOND */ 1) {
1047 else if (c == ']' && --depth == 0) {
1057 /* Check if coded string s is a variable name */
1059 is_wdvarname(const char *s, bool aok)
1061 const char *p = skip_wdvarname(s, aok);
1063 return (p != s && p[0] == EOS);
1066 /* Check if coded string s is a variable assignment */
1068 is_wdvarassign(const char *s)
1070 const char *p = skip_wdvarname(s, true);
1072 return (p != s && p[0] == CHAR &&
1073 (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1077 * Make the exported environment from the exported names in the dictionary.
1085 struct tbl *vp, **vpp;
1088 for (l = e->loc; l != NULL; l = l->next) {
1090 i = 1 << (l->vars.tshift);
1092 if ((vp = *vpp++) != NULL &&
1093 (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1096 uint32_t h = hash(vp->name);
1098 /* unexport any redefined instances */
1099 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1100 vp2 = ktsearch(&l2->vars, vp->name, h);
1102 vp2->flag &= ~EXPORT;
1104 if ((vp->flag&INTEGER)) {
1105 /* integer to string */
1108 vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1109 /* setstr can't fail here */
1110 setstr(vp, val, KSH_RETURN_ERROR);
1112 XPput(denv, vp->val.s);
1114 if (l->flags & BF_STOPENV)
1118 return ((char **)XPclose(denv));
1122 * handle special variables with side effects - PATH, SECONDS.
1125 /* Test if name is a special parameter */
1127 special(const char *name)
1131 tp = ktsearch(&specials, name, hash(name));
1132 return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1135 /* Make a variable non-special */
1137 unspecial(const char *name)
1141 tp = ktsearch(&specials, name, hash(name));
1146 static time_t seconds; /* time SECONDS last set */
1147 static int user_lineno; /* what user set $LINENO to */
1150 getspec(struct tbl *vp)
1156 switch ((st = special(vp->name))) {
1160 * Do NOT export COLUMNS/LINES. Many applications
1161 * check COLUMNS/LINES before checking ws.ws_col/row,
1162 * so if the app is started with C/L in the environ
1163 * and the window is then resized, the app won't
1164 * see the change cause the environ doesn't change.
1172 num.u = (mksh_uari_t)procpid;
1181 num.i = current_lineno + user_lineno;
1186 case V_EPOCHREALTIME: {
1187 /* 10(%u) + 1(.) + 6 + NUL */
1190 vp->flag &= ~SPECIAL;
1192 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1193 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1194 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1195 vp->flag |= SPECIAL;
1199 num.i = user_opt.uoptind;
1206 * On start up the value of SECONDS is used before
1207 * it has been set - don't do anything in this case
1208 * (see initcoms[] in main.c).
1210 if (vp->flag & ISSET) {
1212 num.i = tv.tv_sec - seconds;
1217 /* do nothing, do not touch vp at all */
1220 vp->flag &= ~SPECIAL;
1221 setint_n(vp, num.i, 0);
1222 vp->flag |= SPECIAL;
1226 setspec(struct tbl *vp)
1232 switch ((st = special(vp->name))) {
1233 #if HAVE_PERSISTENT_HISTORY
1235 sethistfile(str_val(vp));
1239 setctypes(s = str_val(vp), C_IFS);
1246 strdupx(path, s, APERM);
1247 /* clear tracked aliases */
1252 afree(tmpdir, APERM);
1256 * Use tmpdir iff it is an absolute path, is writable
1257 * and searchable and is a directory...
1263 /* LINTED use of access */
1264 if (s[0] == '/' && access(s, W_OK|X_OK) == 0 &&
1265 stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1266 strdupx(tmpdir, s, APERM);
1269 /* common sub-cases */
1272 if (vp->flag & IMPORT) {
1274 unspecial(vp->name);
1275 vp->flag &= ~SPECIAL;
1285 vp->flag &= ~SPECIAL;
1286 if (getint(vp, &num, false) == -1) {
1289 errorf("%s: %s: %s", vp->name, "bad number", s);
1292 vp->flag |= SPECIAL;
1295 /* do nothing, do not touch vp at all */
1299 /* process the singular parts of the common cases */
1303 if (num.i >= MIN_COLS)
1310 /* The -1 is because line numbering starts at 1. */
1311 user_lineno = num.u - current_lineno - 1;
1314 if (num.i >= MIN_LINS)
1318 getopts_reset((int)num.i);
1322 * mksh R39d+ no longer has the traditional repeatability
1323 * of $RANDOM sequences, but always retains state
1325 rndset((unsigned long)num.u);
1332 seconds = tv.tv_sec - num.i;
1336 ksh_tmout = num.i >= 0 ? num.i : 0;
1342 unsetspec(struct tbl *vp)
1345 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1346 * meaning, but OPTARG does not (still set by getopts) and _ is
1347 * also still set in various places. Don't know what AT&T does
1348 * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1349 * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1352 switch (special(vp->name)) {
1354 setctypes(TC_IFSWS, C_IFS);
1360 strdupx(path, def_path, APERM);
1361 /* clear tracked aliases */
1365 /* should not become unspecial */
1367 afree(tmpdir, APERM);
1375 /* AT&T ksh leaves previous value in place */
1376 unspecial(vp->name);
1382 * Search for (and possibly create) a table entry starting with
1383 * vp, indexed by val.
1386 arraysearch(struct tbl *vp, uint32_t val)
1388 struct tbl *prev, *curr, *news;
1391 vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
1392 /* the table entry is always [0] */
1397 while (curr && curr->ua.index < val) {
1399 curr = curr->u.array;
1401 if (curr && curr->ua.index == val) {
1402 if (curr->flag&ISSET)
1408 len = strlen(vp->name);
1409 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1410 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1411 memcpy(news->name, vp->name, len);
1413 news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1414 news->type = vp->type;
1415 news->areap = vp->areap;
1416 news->u2.field = vp->u2.field;
1417 news->ua.index = val;
1420 /* not reusing old array entry */
1421 prev->u.array = news;
1422 news->u.array = curr;
1428 * Return the length of an array reference (eg, [1+2]) - cp is assumed
1429 * to point to the open bracket. Returns 0 if there is no matching
1432 * XXX this should parse the actual arithmetic syntax
1435 array_ref_len(const char *cp)
1441 while ((c = *s++) && (c != ']' || --depth))
1450 * Make a copy of the base of an array name
1453 arrayname(const char *str)
1458 if ((p = cstrchr(str, '[')) == 0)
1459 /* Shouldn't happen, but why worry? */
1460 strdupx(rv, str, ATEMP);
1462 strndupx(rv, str, p - str, ATEMP);
1467 /* set (or overwrite, if reset) the array variable var to the values in vals */
1469 set_array(const char *var, bool reset, const char **vals)
1471 struct tbl *vp, *vq;
1472 mksh_uari_t i = 0, j = 0;
1473 const char *ccp = var;
1477 /* to get local array, use "local foo; set -A foo" */
1479 if (n > 0 && var[n - 1] == '+') {
1482 strndupx(cp, var, n - 1, ATEMP);
1487 /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1488 if ((vp->flag&RDONLY))
1489 errorfx(2, "read-only: %s", ccp);
1490 /* This code is quite non-optimal */
1492 /* trash existing values and attributes */
1494 /* allocate-by-access the [0] element to keep in scope */
1498 * TODO: would be nice for assignment to completely succeed or
1499 * completely fail. Only really effects integer arrays:
1500 * evaluation of some of vals[] may fail...
1503 /* find out where to set when appending */
1504 for (vq = vp; vq; vq = vq->u.array) {
1505 if (!(vq->flag & ISSET))
1507 if (arrayindex(vq) >= j)
1508 j = arrayindex(vq) + 1;
1512 while ((ccp = vals[i])) {
1513 #if 0 /* temporarily taken out due to regression */
1518 if (*ccp == ']' && --level == 0)
1524 if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1525 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1527 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1528 KSH_UNWIND_ERROR, true);
1536 vq = arraysearch(vp, j);
1537 /* would be nice to deal with errors here... (see above) */
1538 setstr(vq, ccp, KSH_RETURN_ERROR);
1552 BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
1555 /* check if window size has changed */
1556 if (tty_init_fd() < 2) {
1559 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1568 /* bounds check for sane values, use defaults otherwise */
1569 if (x_cols < MIN_COLS)
1571 if (x_lins < MIN_LINS)
1582 register uint32_t h;
1585 BAFHUpdateStr_reg(h, s);
1591 chvt_rndsetup(const void *bp, size_t sz)
1593 register uint32_t h;
1595 /* use LCG as seed but try to get them to deviate immediately */
1599 /* variation through pid, ppid, and the works */
1600 BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
1601 /* some variation, some possibly entropy, depending on OE */
1602 BAFHUpdateMem_reg(h, bp, sz);
1603 /* mix them all up */
1613 * this is the same Linear Congruential PRNG as Borland
1614 * C/C++ allegedly uses in its built-in rand() function
1616 return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1620 rndset(unsigned long v)
1622 register uint32_t h;
1623 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1624 register uint32_t t;
1635 /* clear the allocated space, for valgrind */
1636 memset(&z, 0, sizeof(z));
1641 BAFHUpdateMem_reg(h, &v, sizeof(v));
1646 z.r = (short)rndget();
1648 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1651 z.qh = (t & 0xFFFF8000) | rndget();
1652 lcg_state = (t << 15) | rndget();
1654 * either we have very chap entropy get and push available,
1655 * with malloc() pulling in this code already anyway, or the
1656 * user requested us to use the old functions
1659 BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
1662 #if defined(arc4random_pushb_fast)
1663 arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1664 lcg_state = arc4random();
1666 lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1668 BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
1673 BAFHUpdateMem_reg(h, &z, sizeof(z));
1679 rndpush(const void *s)
1681 register uint32_t h = qh_state;
1683 BAFHUpdateStr_reg(h, s);
1684 BAFHUpdateOctet_reg(h, 0);