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
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.182 2014/10/03 17:20:03 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);
313 if (!ksh_isalphx(*n)) {
315 vp->flag = DEFINED|RDONLY;
320 vp = ktenter(&l->vars, n, h);
321 if (copy && !(vp->flag & DEFINED)) {
324 varsearch(l->next, &vq, n, h);
326 vp->flag |= vq->flag &
327 (EXPORT | INTEGER | RDONLY | LJUST | RJUST |
328 ZEROFIL | LCASEV | UCASEV_AL | INT_U | INT_L);
329 if (vq->flag & INTEGER)
331 vp->u2.field = vq->u2.field;
335 vp = arraysearch(vp, val);
342 /* get variable string value */
344 str_val(struct tbl *vp)
348 if ((vp->flag&SPECIAL))
350 if (!(vp->flag&ISSET))
351 /* special to dollar() */
353 else if (!(vp->flag&INTEGER))
355 s = vp->val.s + vp->type;
361 * worst case number length is when base == 2:
362 * 1 (minus) + 2 (base, up to 36) + 1 ('#') +
363 * number of bits in the mksh_uari_t + 1 (NUL)
365 char strbuf[1 + 2 + 1 + 8 * sizeof(mksh_uari_t) + 1];
366 const char *digits = (vp->flag & UCASEV_AL) ?
367 digits_uc : digits_lc;
369 s = strbuf + sizeof(strbuf);
370 if (vp->flag & INT_U)
373 n = (vp->val.i < 0) ? -vp->val.u : vp->val.u;
374 base = (vp->type == 0) ? 10U : (unsigned int)vp->type;
376 if (base == 1 && n == 0)
383 if (!UTFMODE || ((n & 0xFF80) == 0xEF80))
384 /* OPTU-16 -> raw octet */
387 sz = utf_wctomb(s + 2, n);
392 *--s = digits[n % base];
397 *--s = digits[base % 10];
399 *--s = digits[base / 10];
401 if (!(vp->flag & INT_U) && vp->val.i < 0)
404 if (vp->flag & (RJUST|LJUST))
405 /* case already dealt with */
406 s = formatstr(vp, s);
408 strdupx(s, s, ATEMP);
413 /* set variable to string value */
415 setstr(struct tbl *vq, const char *s, int error_ok)
418 bool no_ro_check = tobool(error_ok & 0x4);
421 if ((vq->flag & RDONLY) && !no_ro_check) {
422 warningf(true, "read-only: %s", vq->name);
427 if (!(vq->flag&INTEGER)) {
429 if ((vq->flag&ALLOC)) {
432 if (s >= vq->val.s &&
433 s <= vq->val.s + strlen(vq->val.s)) {
435 "setstr: %s=%s: assigning to self",
439 afree(vq->val.s, vq->areap);
441 vq->flag &= ~(ISSET|ALLOC);
443 if (s && (vq->flag & (UCASEV_AL|LCASEV|LJUST|RJUST)))
444 s = salloc = formatstr(vq, s);
445 if ((vq->flag&EXPORT))
448 strdupx(vq->val.s, s, vq->areap);
453 if (!v_evaluate(vq, s, error_ok, true))
457 if ((vq->flag&SPECIAL))
459 afree(salloc, ATEMP);
463 /* set variable to integer */
465 setint(struct tbl *vq, mksh_ari_t n)
467 if (!(vq->flag&INTEGER)) {
468 struct tbl *vp = &vtemp;
469 vp->flag = (ISSET|INTEGER);
473 /* setstr can't fail here */
474 setstr(vq, str_val(vp), KSH_RETURN_ERROR);
478 if ((vq->flag&SPECIAL))
483 getint(struct tbl *vp, mksh_ari_u *nump, bool arith)
485 mksh_uari_t c, num, base;
487 bool have_base = false, neg = false;
489 if (vp->flag&SPECIAL)
491 /* XXX is it possible for ISSET to be set and val.s to be NULL? */
492 if (!(vp->flag&ISSET) || (!(vp->flag&INTEGER) && vp->val.s == NULL))
494 if (vp->flag&INTEGER) {
498 s = vp->val.s + vp->type;
501 if (arith && s[0] == '0' && (s[1] | 0x20) == 'x') {
506 if (Flag(FPOSIX) && arith && s[0] == '0' && ksh_isdigit(s[1]) &&
507 !(vp->flag & ZEROFIL)) {
508 /* interpret as octal (deprecated) */
512 while ((c = (unsigned char)*s++)) {
516 } else if (c == '#') {
517 if (have_base || num < 1 || num > 36)
519 if ((base = num) == 1) {
523 wc = *(const unsigned char *)s;
524 else if (utf_mbtowc(&wc, s) == (size_t)-1)
525 /* OPTU-8 -> OPTU-16 */
527 * (with a twist: 1#\uEF80 converts
528 * the same as 1#\x80 does, thus is
529 * not round-tripping correctly XXX)
531 wc = 0xEF00 + *(const unsigned char *)s;
532 nump->u = (mksh_uari_t)wc;
538 } else if (ksh_isdigit(c))
540 else if (ksh_islower(c))
542 else if (ksh_isupper(c))
548 num = num * base + c;
557 * convert variable vq to integer variable, setting its value from vp
558 * (vq and vp may be the same)
561 setint_v(struct tbl *vq, struct tbl *vp, bool arith)
566 if ((base = getint(vp, &num, arith)) == -1)
568 setint_n(vq, num.i, 0);
575 /* convert variable vq to integer variable, setting its value to num */
577 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
579 if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
582 afree(vq->val.s, vq->areap);
587 vq->flag |= ISSET|INTEGER;
588 if (vq->flag&SPECIAL)
593 formatstr(struct tbl *vp, const char *s)
599 olen = (int)utf_mbswidth(s);
601 if (vp->flag & (RJUST|LJUST)) {
603 /* default field width */
609 p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
610 if (vp->flag & (RJUST|LJUST)) {
611 int slen = olen, i = 0;
613 if (vp->flag & RJUST) {
618 i += utf_widthadj(qq, &qq);
619 /* strip trailing spaces (AT&T uses qq[-1] == ' ') */
620 while (qq > s && ksh_isspace(qq[-1])) {
624 if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
629 else if (s[2] == '#')
632 if (vp->u2.field <= n)
639 while (slen > vp->u2.field)
640 slen -= utf_widthadj(s, &s);
641 if (vp->u2.field - slen)
642 memset(p + n, (vp->flag & ZEROFIL) ? '0' : ' ',
643 vp->u2.field - slen);
645 shf_snprintf(p + vp->u2.field - slen,
646 psiz - (vp->u2.field - slen),
649 /* strip leading spaces/zeros */
650 while (ksh_isspace(*s))
652 if (vp->flag & ZEROFIL)
655 shf_snprintf(p, nlen + 1, "%-*.*s",
656 vp->u2.field, vp->u2.field, s);
659 memcpy(p, s, strlen(s) + 1);
661 if (vp->flag & UCASEV_AL) {
663 *q = ksh_toupper(*q);
664 } else if (vp->flag & LCASEV) {
666 *q = ksh_tolower(*q);
673 * make vp->val.s be "name=value" for quick exporting.
676 exportprep(struct tbl *vp, const char *val)
679 char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
680 size_t namelen, vallen;
682 mkssert(val != NULL);
684 namelen = strlen(vp->name);
685 vallen = strlen(val) + 1;
688 /* since name+val are both in memory this can go unchecked */
689 xp = alloc(namelen + 1 + vallen, vp->areap);
690 memcpy(vp->val.s = xp, vp->name, namelen);
693 /* offset to value */
694 vp->type = xp - vp->val.s;
695 memcpy(xp, val, vallen);
697 afree(op, vp->areap);
701 * lookup variable (according to (set&LOCAL)), set its attributes
702 * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV,
703 * UCASEV_AL), and optionally set its value if an assignment.
706 typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
709 struct tbl *vpbase, *t;
713 bool vappend = false;
714 enum namerefflag new_refflag = SRF_NOP;
716 if ((set & (ARRAY | ASSOC)) == ASSOC) {
717 new_refflag = SRF_ENABLE;
718 set &= ~(ARRAY | ASSOC);
720 if ((clr & (ARRAY | ASSOC)) == ASSOC) {
721 new_refflag = SRF_DISABLE;
722 clr &= ~(ARRAY | ASSOC);
725 /* check for valid variable name, search for value */
726 val = skip_varname(var, false);
728 /* no variable name given */
732 if (new_refflag != SRF_NOP)
733 errorf("%s: %s", var,
734 "reference variable can't be an array");
735 len = array_ref_len(val);
739 * IMPORT is only used when the shell starts up and is
740 * setting up its environment. Allow only simple array
741 * references at this time since parameter/command
742 * substitution is performed on the [expression] which
743 * would be a major security hole.
748 for (i = 1; i < len - 1; i++)
749 if (!ksh_isdigit(val[i]))
755 strndupx(tvar, var, val - var, ATEMP);
757 } else if (set & IMPORT) {
758 /* environment invalid variable name or no assignment */
760 } else if (val[0] == '+' && val[1] == '=') {
761 strndupx(tvar, var, val - var, ATEMP);
764 } else if (val[0] != '\0') {
765 /* other invalid variable names (not from environment) */
768 /* just varname with no value part nor equals sign */
769 strdupx(tvar, var, ATEMP);
771 /* handle foo[*] => foo (whole array) mapping for R39b */
773 if (len > 3 && tvar[len - 3] == '[' && tvar[len - 2] == '*' &&
774 tvar[len - 1] == ']')
775 tvar[len - 3] = '\0';
778 if (new_refflag == SRF_ENABLE) {
779 const char *qval, *ccp;
781 /* bail out on 'nameref foo+=bar' */
783 errorf("appending not allowed for nameref");
784 /* find value if variable already exists */
785 if ((qval = val) == NULL) {
786 varsearch(e->loc, &vp, tvar, hash(tvar));
790 /* check target value for being a valid variable name */
791 ccp = skip_varname(qval, false);
793 if (ksh_isdigit(qval[0])) {
797 goto nameref_rhs_checked;
798 } else if (qval[1] == '\0') switch (qval[0]) {
804 goto nameref_rhs_checked;
806 errorf("%s: %s", var, "empty nameref target");
808 len = (*ccp == '[') ? array_ref_len(ccp) : 0;
811 * works for cases "no array", "valid array with
812 * junk after it" and "invalid array"; in the
813 * latter case, len is also 0 and points to '['
815 errorf("%s: %s", qval,
816 "nameref target not a valid parameter name");
819 /* prevent nameref loops */
821 if (!strcmp(qval, tvar))
822 errorf("%s: %s", qval,
823 "expression recurses on parameter");
824 varsearch(e->loc, &vp, qval, hash(qval));
826 if (vp && ((vp->flag & (ARRAY | ASSOC)) == ASSOC))
831 /* prevent typeset from creating a local PATH/ENV/SHELL */
832 if (Flag(FRESTRICTED) && (strcmp(tvar, "PATH") == 0 ||
833 strcmp(tvar, "ENV") == 0 || strcmp(tvar, "SHELL") == 0))
834 errorf("%s: %s", tvar, "restricted");
836 innermost_refflag = new_refflag;
837 vp = (set & LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
839 if (new_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
841 else if (new_refflag == SRF_ENABLE) {
842 if (vp->flag & ARRAY) {
845 /* free up entire array */
846 for (a = vp->u.array; a; ) {
849 if (tmp->flag & ALLOC)
850 afree(tmp->val.s, tmp->areap);
851 afree(tmp, tmp->areap);
859 set &= ~(LOCAL|LOCAL_COPY);
861 vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
864 * only allow export flag to be set; AT&T ksh allows any
865 * attribute to be changed which means it can be truncated or
866 * modified (-L/-R/-Z/-i)
868 if ((vpbase->flag & RDONLY) &&
869 (val || clr || (set & ~EXPORT)))
870 /* XXX check calls - is error here ok by POSIX? */
871 errorfx(2, "read-only: %s", tvar);
874 /* most calls are with set/clr == 0 */
879 * XXX if x[0] isn't set, there will be problems: need
880 * to have one copy of attributes for arrays...
882 for (t = vpbase; t; t = t->u.array) {
885 char *free_me = NULL;
887 fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
888 ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
889 ((t->flag & INTEGER) && (clr & INTEGER)) ||
890 (!(t->flag & INTEGER) && (set & INTEGER)));
892 if (t->flag & INTEGER) {
896 s = t->val.s + t->type;
897 free_me = (t->flag & ALLOC) ? t->val.s :
902 if (!(t->flag & INTEGER) && (set & INTEGER)) {
906 t->flag = (t->flag | set) & ~clr;
908 * Don't change base if assignment is to be
909 * done, in case assignment fails.
911 if ((set & INTEGER) && base > 0 && (!val || t != vp))
913 if (set & (LJUST|RJUST|ZEROFIL))
916 if (!setstr(t, s, KSH_RETURN_ERROR)) {
918 * Somewhat arbitrary action
919 * here: zap contents of
920 * variable, but keep the flag
924 if (t->flag & INTEGER)
928 afree(t->val.s, t->areap);
929 t->flag &= ~(ISSET|ALLOC);
934 afree(free_me, t->areap);
945 tval = shf_smprintf("%s%s", str_val(vp), val);
950 if (vp->flag&INTEGER) {
951 /* do not zero base before assignment */
952 setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
953 /* done after assignment to override default */
957 /* setstr can't fail (readonly check already done) */
958 setstr(vp, val, KSH_RETURN_ERROR | 0x4);
964 /* only x[0] is ever exported, so use vpbase */
965 if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
967 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
973 * Unset a variable. The flags can be:
974 * |1 = tear down entire array
975 * |2 = keep attributes, only unset content
978 unset(struct tbl *vp, int flags)
980 if (vp->flag & ALLOC)
981 afree(vp->val.s, vp->areap);
982 if ((vp->flag & ARRAY) && (flags & 1)) {
985 /* free up entire array */
986 for (a = vp->u.array; a; ) {
989 if (tmp->flag & ALLOC)
990 afree(tmp->val.s, tmp->areap);
991 afree(tmp, tmp->areap);
996 vp->flag &= ~(ALLOC|ISSET);
999 /* if foo[0] is being unset, the remainder of the array is kept... */
1000 vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
1001 if (vp->flag & SPECIAL)
1002 /* responsible for 'unspecial'ing var */
1007 * Return a pointer to the first char past a legal variable name
1008 * (returns the argument if there is no legal name, returns a pointer to
1009 * the terminating NUL if whole string is legal).
1012 skip_varname(const char *s, bool aok)
1016 if (s && ksh_isalphx(*s)) {
1017 while (*++s && ksh_isalnux(*s))
1019 if (aok && *s == '[' && (alen = array_ref_len(s)))
1025 /* Return a pointer to the first character past any legal variable name */
1027 skip_wdvarname(const char *s,
1028 /* skip array de-reference? */
1031 if (s[0] == CHAR && ksh_isalphx(s[1])) {
1034 } while (s[0] == CHAR && ksh_isalnux(s[1]));
1035 if (aok && s[0] == CHAR && s[1] == '[') {
1036 /* skip possible array de-reference */
1041 while (/* CONSTCOND */ 1) {
1048 else if (c == ']' && --depth == 0) {
1058 /* Check if coded string s is a variable name */
1060 is_wdvarname(const char *s, bool aok)
1062 const char *p = skip_wdvarname(s, aok);
1064 return (p != s && p[0] == EOS);
1067 /* Check if coded string s is a variable assignment */
1069 is_wdvarassign(const char *s)
1071 const char *p = skip_wdvarname(s, true);
1073 return (p != s && p[0] == CHAR &&
1074 (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1078 * Make the exported environment from the exported names in the dictionary.
1086 struct tbl *vp, **vpp;
1089 for (l = e->loc; l != NULL; l = l->next) {
1091 i = 1 << (l->vars.tshift);
1093 if ((vp = *vpp++) != NULL &&
1094 (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1097 uint32_t h = hash(vp->name);
1099 /* unexport any redefined instances */
1100 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1101 vp2 = ktsearch(&l2->vars, vp->name, h);
1103 vp2->flag &= ~EXPORT;
1105 if ((vp->flag&INTEGER)) {
1106 /* integer to string */
1109 vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1110 /* setstr can't fail here */
1111 setstr(vp, val, KSH_RETURN_ERROR);
1113 XPput(denv, vp->val.s);
1117 return ((char **)XPclose(denv));
1121 * handle special variables with side effects - PATH, SECONDS.
1124 /* Test if name is a special parameter */
1126 special(const char *name)
1130 tp = ktsearch(&specials, name, hash(name));
1131 return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1134 /* Make a variable non-special */
1136 unspecial(const char *name)
1140 tp = ktsearch(&specials, name, hash(name));
1145 static time_t seconds; /* time SECONDS last set */
1146 static int user_lineno; /* what user set $LINENO to */
1149 getspec(struct tbl *vp)
1155 switch ((st = special(vp->name))) {
1159 * Do NOT export COLUMNS/LINES. Many applications
1160 * check COLUMNS/LINES before checking ws.ws_col/row,
1161 * so if the app is started with C/L in the environ
1162 * and the window is then resized, the app won't
1163 * see the change cause the environ doesn't change.
1171 num.u = (mksh_uari_t)procpid;
1180 num.i = current_lineno + user_lineno;
1185 case V_EPOCHREALTIME: {
1186 /* 10(%u) + 1(.) + 6 + NUL */
1189 vp->flag &= ~SPECIAL;
1191 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1192 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1193 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1194 vp->flag |= SPECIAL;
1198 num.i = user_opt.uoptind;
1205 * On start up the value of SECONDS is used before
1206 * it has been set - don't do anything in this case
1207 * (see initcoms[] in main.c).
1209 if (vp->flag & ISSET) {
1211 num.i = tv.tv_sec - seconds;
1216 /* do nothing, do not touch vp at all */
1219 vp->flag &= ~SPECIAL;
1220 setint_n(vp, num.i, 0);
1221 vp->flag |= SPECIAL;
1225 setspec(struct tbl *vp)
1231 switch ((st = special(vp->name))) {
1232 #if HAVE_PERSISTENT_HISTORY
1234 sethistfile(str_val(vp));
1238 setctypes(s = str_val(vp), C_IFS);
1245 strdupx(path, s, APERM);
1246 /* clear tracked aliases */
1251 afree(tmpdir, APERM);
1255 * Use tmpdir iff it is an absolute path, is writable
1256 * and searchable and is a directory...
1262 /* LINTED use of access */
1263 if (s[0] == '/' && access(s, W_OK|X_OK) == 0 &&
1264 stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1265 strdupx(tmpdir, s, APERM);
1268 /* common sub-cases */
1271 if (vp->flag & IMPORT) {
1273 unspecial(vp->name);
1274 vp->flag &= ~SPECIAL;
1284 vp->flag &= ~SPECIAL;
1285 if (getint(vp, &num, false) == -1) {
1288 errorf("%s: %s: %s", vp->name, "bad number", s);
1291 vp->flag |= SPECIAL;
1294 /* do nothing, do not touch vp at all */
1298 /* process the singular parts of the common cases */
1302 if (num.i >= MIN_COLS)
1309 /* The -1 is because line numbering starts at 1. */
1310 user_lineno = num.u - current_lineno - 1;
1313 if (num.i >= MIN_LINS)
1317 getopts_reset((int)num.i);
1321 * mksh R39d+ no longer has the traditional repeatability
1322 * of $RANDOM sequences, but always retains state
1324 rndset((unsigned long)num.u);
1331 seconds = tv.tv_sec - num.i;
1335 ksh_tmout = num.i >= 0 ? num.i : 0;
1341 unsetspec(struct tbl *vp)
1344 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1345 * meaning, but OPTARG does not (still set by getopts) and _ is
1346 * also still set in various places. Don't know what AT&T does
1347 * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1348 * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1351 switch (special(vp->name)) {
1353 setctypes(TC_IFSWS, C_IFS);
1359 strdupx(path, def_path, APERM);
1360 /* clear tracked aliases */
1364 /* should not become unspecial */
1366 afree(tmpdir, APERM);
1374 /* AT&T ksh leaves previous value in place */
1375 unspecial(vp->name);
1381 * Search for (and possibly create) a table entry starting with
1382 * vp, indexed by val.
1385 arraysearch(struct tbl *vp, uint32_t val)
1387 struct tbl *prev, *curr, *news;
1390 vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
1391 /* the table entry is always [0] */
1396 while (curr && curr->ua.index < val) {
1398 curr = curr->u.array;
1400 if (curr && curr->ua.index == val) {
1401 if (curr->flag&ISSET)
1407 len = strlen(vp->name);
1408 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1409 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1410 memcpy(news->name, vp->name, len);
1412 news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1413 news->type = vp->type;
1414 news->areap = vp->areap;
1415 news->u2.field = vp->u2.field;
1416 news->ua.index = val;
1419 /* not reusing old array entry */
1420 prev->u.array = news;
1421 news->u.array = curr;
1427 * Return the length of an array reference (eg, [1+2]) - cp is assumed
1428 * to point to the open bracket. Returns 0 if there is no matching
1431 * XXX this should parse the actual arithmetic syntax
1434 array_ref_len(const char *cp)
1440 while ((c = *s++) && (c != ']' || --depth))
1449 * Make a copy of the base of an array name
1452 arrayname(const char *str)
1457 if ((p = cstrchr(str, '[')) == 0)
1458 /* Shouldn't happen, but why worry? */
1459 strdupx(rv, str, ATEMP);
1461 strndupx(rv, str, p - str, ATEMP);
1466 /* set (or overwrite, if reset) the array variable var to the values in vals */
1468 set_array(const char *var, bool reset, const char **vals)
1470 struct tbl *vp, *vq;
1471 mksh_uari_t i = 0, j = 0;
1472 const char *ccp = var;
1476 /* to get local array, use "local foo; set -A foo" */
1478 if (n > 0 && var[n - 1] == '+') {
1481 strndupx(cp, var, n - 1, ATEMP);
1486 /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1487 if ((vp->flag&RDONLY))
1488 errorfx(2, "read-only: %s", ccp);
1489 /* This code is quite non-optimal */
1491 /* trash existing values and attributes */
1493 /* allocate-by-access the [0] element to keep in scope */
1497 * TODO: would be nice for assignment to completely succeed or
1498 * completely fail. Only really effects integer arrays:
1499 * evaluation of some of vals[] may fail...
1502 /* find out where to set when appending */
1503 for (vq = vp; vq; vq = vq->u.array) {
1504 if (!(vq->flag & ISSET))
1506 if (arrayindex(vq) >= j)
1507 j = arrayindex(vq) + 1;
1511 while ((ccp = vals[i])) {
1512 #if 0 /* temporarily taken out due to regression */
1517 if (*ccp == ']' && --level == 0)
1523 if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1524 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1526 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1527 KSH_UNWIND_ERROR, true);
1535 vq = arraysearch(vp, j);
1536 /* would be nice to deal with errors here... (see above) */
1537 setstr(vq, ccp, KSH_RETURN_ERROR);
1551 BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
1554 /* check if window size has changed */
1555 if (tty_init_fd() < 2) {
1558 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1567 /* bounds check for sane values, use defaults otherwise */
1568 if (x_cols < MIN_COLS)
1570 if (x_lins < MIN_LINS)
1581 register uint32_t h;
1584 BAFHUpdateStr_reg(h, s);
1590 chvt_rndsetup(const void *bp, size_t sz)
1592 register uint32_t h;
1594 /* use LCG as seed but try to get them to deviate immediately */
1598 /* variation through pid, ppid, and the works */
1599 BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
1600 /* some variation, some possibly entropy, depending on OE */
1601 BAFHUpdateMem_reg(h, bp, sz);
1602 /* mix them all up */
1612 * this is the same Linear Congruential PRNG as Borland
1613 * C/C++ allegedly uses in its built-in rand() function
1615 return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1619 rndset(unsigned long v)
1621 register uint32_t h;
1622 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1623 register uint32_t t;
1634 /* clear the allocated space, for valgrind */
1635 memset(&z, 0, sizeof(z));
1640 BAFHUpdateMem_reg(h, &v, sizeof(v));
1645 z.r = (short)rndget();
1647 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1650 z.qh = (t & 0xFFFF8000) | rndget();
1651 lcg_state = (t << 15) | rndget();
1653 * either we have very chap entropy get and push available,
1654 * with malloc() pulling in this code already anyway, or the
1655 * user requested us to use the old functions
1658 BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
1661 #if defined(arc4random_pushb_fast)
1662 arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1663 lcg_state = arc4random();
1665 lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1667 BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
1672 BAFHUpdateMem_reg(h, &z, sizeof(z));
1678 rndpush(const void *s)
1680 register uint32_t h = qh_state;
1682 BAFHUpdateStr_reg(h, s);
1683 BAFHUpdateOctet_reg(h, 0);