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.183 2014/10/04 11:47:19 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));
791 /* check target value for being a valid variable name */
792 ccp = skip_varname(qval, false);
794 if (ksh_isdigit(qval[0])) {
798 goto nameref_rhs_checked;
799 } else if (qval[1] == '\0') switch (qval[0]) {
805 goto nameref_rhs_checked;
808 errorf("%s: %s", var, "empty nameref target");
810 len = (*ccp == '[') ? array_ref_len(ccp) : 0;
813 * works for cases "no array", "valid array with
814 * junk after it" and "invalid array"; in the
815 * latter case, len is also 0 and points to '['
817 errorf("%s: %s", qval,
818 "nameref target not a valid parameter name");
821 /* prevent nameref loops */
823 if (!strcmp(qval, tvar))
824 errorf("%s: %s", qval,
825 "expression recurses on parameter");
826 varsearch(e->loc, &vp, qval, hash(qval));
828 if (vp && ((vp->flag & (ARRAY | ASSOC)) == ASSOC))
833 /* prevent typeset from creating a local PATH/ENV/SHELL */
834 if (Flag(FRESTRICTED) && (strcmp(tvar, "PATH") == 0 ||
835 strcmp(tvar, "ENV") == 0 || strcmp(tvar, "SHELL") == 0))
836 errorf("%s: %s", tvar, "restricted");
838 innermost_refflag = new_refflag;
839 vp = (set & LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
841 if (new_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
843 else if (new_refflag == SRF_ENABLE) {
844 if (vp->flag & ARRAY) {
847 /* free up entire array */
848 for (a = vp->u.array; a; ) {
851 if (tmp->flag & ALLOC)
852 afree(tmp->val.s, tmp->areap);
853 afree(tmp, tmp->areap);
861 set &= ~(LOCAL|LOCAL_COPY);
863 vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
866 * only allow export flag to be set; AT&T ksh allows any
867 * attribute to be changed which means it can be truncated or
868 * modified (-L/-R/-Z/-i)
870 if ((vpbase->flag & RDONLY) &&
871 (val || clr || (set & ~EXPORT)))
872 /* XXX check calls - is error here ok by POSIX? */
873 errorfx(2, "read-only: %s", tvar);
876 /* most calls are with set/clr == 0 */
881 * XXX if x[0] isn't set, there will be problems: need
882 * to have one copy of attributes for arrays...
884 for (t = vpbase; t; t = t->u.array) {
887 char *free_me = NULL;
889 fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
890 ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
891 ((t->flag & INTEGER) && (clr & INTEGER)) ||
892 (!(t->flag & INTEGER) && (set & INTEGER)));
894 if (t->flag & INTEGER) {
898 s = t->val.s + t->type;
899 free_me = (t->flag & ALLOC) ? t->val.s :
904 if (!(t->flag & INTEGER) && (set & INTEGER)) {
908 t->flag = (t->flag | set) & ~clr;
910 * Don't change base if assignment is to be
911 * done, in case assignment fails.
913 if ((set & INTEGER) && base > 0 && (!val || t != vp))
915 if (set & (LJUST|RJUST|ZEROFIL))
918 if (!setstr(t, s, KSH_RETURN_ERROR)) {
920 * Somewhat arbitrary action
921 * here: zap contents of
922 * variable, but keep the flag
926 if (t->flag & INTEGER)
930 afree(t->val.s, t->areap);
931 t->flag &= ~(ISSET|ALLOC);
936 afree(free_me, t->areap);
947 tval = shf_smprintf("%s%s", str_val(vp), val);
952 if (vp->flag&INTEGER) {
953 /* do not zero base before assignment */
954 setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
955 /* done after assignment to override default */
959 /* setstr can't fail (readonly check already done) */
960 setstr(vp, val, KSH_RETURN_ERROR | 0x4);
966 /* only x[0] is ever exported, so use vpbase */
967 if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
969 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
975 * Unset a variable. The flags can be:
976 * |1 = tear down entire array
977 * |2 = keep attributes, only unset content
980 unset(struct tbl *vp, int flags)
982 if (vp->flag & ALLOC)
983 afree(vp->val.s, vp->areap);
984 if ((vp->flag & ARRAY) && (flags & 1)) {
987 /* free up entire array */
988 for (a = vp->u.array; a; ) {
991 if (tmp->flag & ALLOC)
992 afree(tmp->val.s, tmp->areap);
993 afree(tmp, tmp->areap);
998 vp->flag &= ~(ALLOC|ISSET);
1001 /* if foo[0] is being unset, the remainder of the array is kept... */
1002 vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
1003 if (vp->flag & SPECIAL)
1004 /* responsible for 'unspecial'ing var */
1009 * Return a pointer to the first char past a legal variable name
1010 * (returns the argument if there is no legal name, returns a pointer to
1011 * the terminating NUL if whole string is legal).
1014 skip_varname(const char *s, bool aok)
1018 if (s && ksh_isalphx(*s)) {
1019 while (*++s && ksh_isalnux(*s))
1021 if (aok && *s == '[' && (alen = array_ref_len(s)))
1027 /* Return a pointer to the first character past any legal variable name */
1029 skip_wdvarname(const char *s,
1030 /* skip array de-reference? */
1033 if (s[0] == CHAR && ksh_isalphx(s[1])) {
1036 } while (s[0] == CHAR && ksh_isalnux(s[1]));
1037 if (aok && s[0] == CHAR && s[1] == '[') {
1038 /* skip possible array de-reference */
1043 while (/* CONSTCOND */ 1) {
1050 else if (c == ']' && --depth == 0) {
1060 /* Check if coded string s is a variable name */
1062 is_wdvarname(const char *s, bool aok)
1064 const char *p = skip_wdvarname(s, aok);
1066 return (p != s && p[0] == EOS);
1069 /* Check if coded string s is a variable assignment */
1071 is_wdvarassign(const char *s)
1073 const char *p = skip_wdvarname(s, true);
1075 return (p != s && p[0] == CHAR &&
1076 (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1080 * Make the exported environment from the exported names in the dictionary.
1088 struct tbl *vp, **vpp;
1091 for (l = e->loc; l != NULL; l = l->next) {
1093 i = 1 << (l->vars.tshift);
1095 if ((vp = *vpp++) != NULL &&
1096 (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1099 uint32_t h = hash(vp->name);
1101 /* unexport any redefined instances */
1102 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1103 vp2 = ktsearch(&l2->vars, vp->name, h);
1105 vp2->flag &= ~EXPORT;
1107 if ((vp->flag&INTEGER)) {
1108 /* integer to string */
1111 vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1112 /* setstr can't fail here */
1113 setstr(vp, val, KSH_RETURN_ERROR);
1115 XPput(denv, vp->val.s);
1119 return ((char **)XPclose(denv));
1123 * handle special variables with side effects - PATH, SECONDS.
1126 /* Test if name is a special parameter */
1128 special(const char *name)
1132 tp = ktsearch(&specials, name, hash(name));
1133 return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1136 /* Make a variable non-special */
1138 unspecial(const char *name)
1142 tp = ktsearch(&specials, name, hash(name));
1147 static time_t seconds; /* time SECONDS last set */
1148 static int user_lineno; /* what user set $LINENO to */
1151 getspec(struct tbl *vp)
1157 switch ((st = special(vp->name))) {
1161 * Do NOT export COLUMNS/LINES. Many applications
1162 * check COLUMNS/LINES before checking ws.ws_col/row,
1163 * so if the app is started with C/L in the environ
1164 * and the window is then resized, the app won't
1165 * see the change cause the environ doesn't change.
1173 num.u = (mksh_uari_t)procpid;
1182 num.i = current_lineno + user_lineno;
1187 case V_EPOCHREALTIME: {
1188 /* 10(%u) + 1(.) + 6 + NUL */
1191 vp->flag &= ~SPECIAL;
1193 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1194 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1195 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1196 vp->flag |= SPECIAL;
1200 num.i = user_opt.uoptind;
1207 * On start up the value of SECONDS is used before
1208 * it has been set - don't do anything in this case
1209 * (see initcoms[] in main.c).
1211 if (vp->flag & ISSET) {
1213 num.i = tv.tv_sec - seconds;
1218 /* do nothing, do not touch vp at all */
1221 vp->flag &= ~SPECIAL;
1222 setint_n(vp, num.i, 0);
1223 vp->flag |= SPECIAL;
1227 setspec(struct tbl *vp)
1233 switch ((st = special(vp->name))) {
1234 #if HAVE_PERSISTENT_HISTORY
1236 sethistfile(str_val(vp));
1240 setctypes(s = str_val(vp), C_IFS);
1247 strdupx(path, s, APERM);
1248 /* clear tracked aliases */
1253 afree(tmpdir, APERM);
1257 * Use tmpdir iff it is an absolute path, is writable
1258 * and searchable and is a directory...
1264 /* LINTED use of access */
1265 if (s[0] == '/' && access(s, W_OK|X_OK) == 0 &&
1266 stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1267 strdupx(tmpdir, s, APERM);
1270 /* common sub-cases */
1273 if (vp->flag & IMPORT) {
1275 unspecial(vp->name);
1276 vp->flag &= ~SPECIAL;
1286 vp->flag &= ~SPECIAL;
1287 if (getint(vp, &num, false) == -1) {
1290 errorf("%s: %s: %s", vp->name, "bad number", s);
1293 vp->flag |= SPECIAL;
1296 /* do nothing, do not touch vp at all */
1300 /* process the singular parts of the common cases */
1304 if (num.i >= MIN_COLS)
1311 /* The -1 is because line numbering starts at 1. */
1312 user_lineno = num.u - current_lineno - 1;
1315 if (num.i >= MIN_LINS)
1319 getopts_reset((int)num.i);
1323 * mksh R39d+ no longer has the traditional repeatability
1324 * of $RANDOM sequences, but always retains state
1326 rndset((unsigned long)num.u);
1333 seconds = tv.tv_sec - num.i;
1337 ksh_tmout = num.i >= 0 ? num.i : 0;
1343 unsetspec(struct tbl *vp)
1346 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1347 * meaning, but OPTARG does not (still set by getopts) and _ is
1348 * also still set in various places. Don't know what AT&T does
1349 * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1350 * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1353 switch (special(vp->name)) {
1355 setctypes(TC_IFSWS, C_IFS);
1361 strdupx(path, def_path, APERM);
1362 /* clear tracked aliases */
1366 /* should not become unspecial */
1368 afree(tmpdir, APERM);
1376 /* AT&T ksh leaves previous value in place */
1377 unspecial(vp->name);
1383 * Search for (and possibly create) a table entry starting with
1384 * vp, indexed by val.
1387 arraysearch(struct tbl *vp, uint32_t val)
1389 struct tbl *prev, *curr, *news;
1392 vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
1393 /* the table entry is always [0] */
1398 while (curr && curr->ua.index < val) {
1400 curr = curr->u.array;
1402 if (curr && curr->ua.index == val) {
1403 if (curr->flag&ISSET)
1409 len = strlen(vp->name);
1410 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1411 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1412 memcpy(news->name, vp->name, len);
1414 news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1415 news->type = vp->type;
1416 news->areap = vp->areap;
1417 news->u2.field = vp->u2.field;
1418 news->ua.index = val;
1421 /* not reusing old array entry */
1422 prev->u.array = news;
1423 news->u.array = curr;
1429 * Return the length of an array reference (eg, [1+2]) - cp is assumed
1430 * to point to the open bracket. Returns 0 if there is no matching
1433 * XXX this should parse the actual arithmetic syntax
1436 array_ref_len(const char *cp)
1442 while ((c = *s++) && (c != ']' || --depth))
1451 * Make a copy of the base of an array name
1454 arrayname(const char *str)
1459 if ((p = cstrchr(str, '[')) == 0)
1460 /* Shouldn't happen, but why worry? */
1461 strdupx(rv, str, ATEMP);
1463 strndupx(rv, str, p - str, ATEMP);
1468 /* set (or overwrite, if reset) the array variable var to the values in vals */
1470 set_array(const char *var, bool reset, const char **vals)
1472 struct tbl *vp, *vq;
1473 mksh_uari_t i = 0, j = 0;
1474 const char *ccp = var;
1478 /* to get local array, use "local foo; set -A foo" */
1480 if (n > 0 && var[n - 1] == '+') {
1483 strndupx(cp, var, n - 1, ATEMP);
1488 /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1489 if ((vp->flag&RDONLY))
1490 errorfx(2, "read-only: %s", ccp);
1491 /* This code is quite non-optimal */
1493 /* trash existing values and attributes */
1495 /* allocate-by-access the [0] element to keep in scope */
1499 * TODO: would be nice for assignment to completely succeed or
1500 * completely fail. Only really effects integer arrays:
1501 * evaluation of some of vals[] may fail...
1504 /* find out where to set when appending */
1505 for (vq = vp; vq; vq = vq->u.array) {
1506 if (!(vq->flag & ISSET))
1508 if (arrayindex(vq) >= j)
1509 j = arrayindex(vq) + 1;
1513 while ((ccp = vals[i])) {
1514 #if 0 /* temporarily taken out due to regression */
1519 if (*ccp == ']' && --level == 0)
1525 if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1526 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1528 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1529 KSH_UNWIND_ERROR, true);
1537 vq = arraysearch(vp, j);
1538 /* would be nice to deal with errors here... (see above) */
1539 setstr(vq, ccp, KSH_RETURN_ERROR);
1553 BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
1556 /* check if window size has changed */
1557 if (tty_init_fd() < 2) {
1560 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1569 /* bounds check for sane values, use defaults otherwise */
1570 if (x_cols < MIN_COLS)
1572 if (x_lins < MIN_LINS)
1583 register uint32_t h;
1586 BAFHUpdateStr_reg(h, s);
1592 chvt_rndsetup(const void *bp, size_t sz)
1594 register uint32_t h;
1596 /* use LCG as seed but try to get them to deviate immediately */
1600 /* variation through pid, ppid, and the works */
1601 BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
1602 /* some variation, some possibly entropy, depending on OE */
1603 BAFHUpdateMem_reg(h, bp, sz);
1604 /* mix them all up */
1614 * this is the same Linear Congruential PRNG as Borland
1615 * C/C++ allegedly uses in its built-in rand() function
1617 return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1621 rndset(unsigned long v)
1623 register uint32_t h;
1624 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1625 register uint32_t t;
1636 /* clear the allocated space, for valgrind */
1637 memset(&z, 0, sizeof(z));
1642 BAFHUpdateMem_reg(h, &v, sizeof(v));
1647 z.r = (short)rndget();
1649 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1652 z.qh = (t & 0xFFFF8000) | rndget();
1653 lcg_state = (t << 15) | rndget();
1655 * either we have very chap entropy get and push available,
1656 * with malloc() pulling in this code already anyway, or the
1657 * user requested us to use the old functions
1660 BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
1663 #if defined(arc4random_pushb_fast)
1664 arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1665 lcg_state = arc4random();
1667 lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1669 BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
1674 BAFHUpdateMem_reg(h, &z, sizeof(z));
1680 rndpush(const void *s)
1682 register uint32_t h = qh_state;
1684 BAFHUpdateStr_reg(h, s);
1685 BAFHUpdateOctet_reg(h, 0);