1 /* $OpenBSD: var.c,v 1.44 2015/09/10 11:37:42 jca Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5 * 2011, 2012, 2013, 2014, 2015, 2016
6 * mirabilos <m@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.207 2016/08/01 21:38: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 15 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(Tf_ss, 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;
223 * Search for variable, if not found create globally.
226 global(const char *n)
229 union mksh_cchack vname;
230 struct block *l = e->loc;
236 * check to see if this is an array;
237 * dereference namerefs; must come first
239 vn = array_index_calc(n, &array, &val);
241 c = (unsigned char)vn[0];
242 if (!ksh_isalphx(c)) {
249 if (ksh_isdigit(c)) {
251 /* main.c:main_init() says 12 */
252 shf_snprintf(vp->name, 12, Tf_d, c);
254 /* setstr can't fail here */
255 setstr(vp, l->argv[c],
268 vp->flag |= ISSET|INTEGER;
274 /* if no job, expand to nothing */
275 if ((vp->val.i = j_async()) == 0)
276 vp->flag &= ~(ISSET|INTEGER);
279 vp->val.i = exstat & 0xFF;
285 vp->flag &= ~INTEGER;
286 vp->val.s = getoptions();
289 vp->flag &= ~(ISSET|INTEGER);
293 l = varsearch(e->loc, &vp, vn, h);
296 vp = arraysearch(vp, val);
299 vp = ktenter(&l->vars, vn, h);
301 vp = arraysearch(vp, val);
306 last_lookup_was_array = array;
308 afree(vname.rw, ATEMP);
313 * Search for local variable, if not found create locally.
316 local(const char *n, bool copy)
319 union mksh_cchack vname;
320 struct block *l = e->loc;
325 * check to see if this is an array;
326 * dereference namerefs; must come first
328 vn = array_index_calc(n, &array, &val);
330 if (!ksh_isalphx(*vn)) {
332 vp->flag = DEFINED|RDONLY;
337 vp = ktenter(&l->vars, vn, h);
338 if (copy && !(vp->flag & DEFINED)) {
341 varsearch(l->next, &vq, vn, h);
343 vp->flag |= vq->flag &
344 (EXPORT | INTEGER | RDONLY | LJUST | RJUST |
345 ZEROFIL | LCASEV | UCASEV_AL | INT_U | INT_L);
346 if (vq->flag & INTEGER)
348 vp->u2.field = vq->u2.field;
352 vp = arraysearch(vp, val);
357 last_lookup_was_array = array;
359 afree(vname.rw, ATEMP);
364 /* get variable string value */
366 str_val(struct tbl *vp)
370 if ((vp->flag&SPECIAL))
372 if (!(vp->flag&ISSET))
373 /* special to dollar() */
375 else if (!(vp->flag&INTEGER))
377 s = vp->val.s + vp->type;
383 * worst case number length is when base == 2:
384 * 1 (minus) + 2 (base, up to 36) + 1 ('#') +
385 * number of bits in the mksh_uari_t + 1 (NUL)
387 char strbuf[1 + 2 + 1 + 8 * sizeof(mksh_uari_t) + 1];
388 const char *digits = (vp->flag & UCASEV_AL) ?
389 digits_uc : digits_lc;
391 s = strbuf + sizeof(strbuf);
392 if (vp->flag & INT_U)
395 n = (vp->val.i < 0) ? -vp->val.u : vp->val.u;
396 base = (vp->type == 0) ? 10U : (unsigned int)vp->type;
398 if (base == 1 && n == 0)
405 if (!UTFMODE || ((n & 0xFF80) == 0xEF80))
406 /* OPTU-16 -> raw octet */
409 sz = utf_wctomb(s + 2, n);
414 *--s = digits[n % base];
419 *--s = digits[base % 10];
421 *--s = digits[base / 10];
423 if (!(vp->flag & INT_U) && vp->val.i < 0)
426 if (vp->flag & (RJUST|LJUST))
427 /* case already dealt with */
428 s = formatstr(vp, s);
430 strdupx(s, s, ATEMP);
435 /* set variable to string value */
437 setstr(struct tbl *vq, const char *s, int error_ok)
440 bool no_ro_check = tobool(error_ok & 0x4);
443 if ((vq->flag & RDONLY) && !no_ro_check) {
444 warningf(true, Tf_ro, vq->name);
449 if (!(vq->flag&INTEGER)) {
451 if ((vq->flag&ALLOC)) {
454 if (s >= vq->val.s &&
455 s <= vq->val.s + strlen(vq->val.s)) {
457 "setstr: %s=%s: assigning to self",
461 afree(vq->val.s, vq->areap);
463 vq->flag &= ~(ISSET|ALLOC);
465 if (s && (vq->flag & (UCASEV_AL|LCASEV|LJUST|RJUST)))
466 s = salloc = formatstr(vq, s);
467 if ((vq->flag&EXPORT))
470 strdupx(vq->val.s, s, vq->areap);
475 if (!v_evaluate(vq, s, error_ok, true))
479 if ((vq->flag&SPECIAL))
481 afree(salloc, ATEMP);
485 /* set variable to integer */
487 setint(struct tbl *vq, mksh_ari_t n)
489 if (!(vq->flag&INTEGER)) {
490 vtemp->flag = (ISSET|INTEGER);
492 vtemp->areap = ATEMP;
494 /* setstr can't fail here */
495 setstr(vq, str_val(vtemp), KSH_RETURN_ERROR);
499 if ((vq->flag&SPECIAL))
504 getint(struct tbl *vp, mksh_ari_u *nump, bool arith)
506 mksh_uari_t c, num = 0, base = 10;
508 bool have_base = false, neg = false;
510 if (vp->flag & SPECIAL)
512 /* XXX is it possible for ISSET to be set and val.s to be NULL? */
513 if (!(vp->flag & ISSET) || (!(vp->flag & INTEGER) && vp->val.s == NULL))
515 if (vp->flag & INTEGER) {
519 s = vp->val.s + vp->type;
522 c = (unsigned char)*s++;
523 } while (ksh_isspace(c));
530 c = (unsigned char)*s++;
534 if (c == '0' && arith) {
535 if (ksh_eq(s[0], 'X', 'x')) {
536 /* interpret as hexadecimal */
539 goto getint_c_style_base;
540 } else if (Flag(FPOSIX) && ksh_isdigit(s[0]) &&
541 !(vp->flag & ZEROFIL)) {
542 /* interpret as octal (deprecated) */
546 c = (unsigned char)*s++;
552 /* ksh-style base determination */
553 if (have_base || num < 1)
555 if ((base = num) == 1) {
556 /* mksh-specific extension */
560 wc = *(const unsigned char *)s;
561 else if (utf_mbtowc(&wc, s) == (size_t)-1)
562 /* OPTU-8 -> OPTU-16 */
564 * (with a twist: 1#\uEF80 converts
565 * the same as 1#\x80 does, thus is
566 * not round-tripping correctly XXX)
568 wc = 0xEF00 + *(const unsigned char *)s;
569 nump->u = (mksh_uari_t)wc;
571 } else if (base > 36)
579 else if (ksh_isupper(c))
580 c = ksh_numuc(c) + 10;
581 else if (ksh_islower(c))
582 c = ksh_numlc(c) + 10;
587 /* handle overflow as truncation */
588 num = num * base + c;
589 } while ((c = (unsigned char)*s++));
598 * convert variable vq to integer variable, setting its value from vp
599 * (vq and vp may be the same)
602 setint_v(struct tbl *vq, struct tbl *vp, bool arith)
607 if ((base = getint(vp, &num, arith)) == -1)
609 setint_n(vq, num.i, 0);
616 /* convert variable vq to integer variable, setting its value to num */
618 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
620 if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
623 afree(vq->val.s, vq->areap);
628 vq->flag |= ISSET|INTEGER;
629 if (vq->flag&SPECIAL)
634 formatstr(struct tbl *vp, const char *s)
640 olen = (int)utf_mbswidth(s);
642 if (vp->flag & (RJUST|LJUST)) {
644 /* default field width */
650 p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
651 if (vp->flag & (RJUST|LJUST)) {
654 if (vp->flag & RJUST) {
658 qq = utf_skipcols(s, slen, &slen);
660 /* strip trailing spaces (AT&T uses qq[-1] == ' ') */
661 while (qq > s && ksh_isspace(qq[-1])) {
665 if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
670 else if (s[2] == '#')
673 if (vp->u2.field <= n)
680 while (slen > vp->u2.field)
681 slen -= utf_widthadj(s, &s);
682 if (vp->u2.field - slen)
683 memset(p + n, (vp->flag & ZEROFIL) ? '0' : ' ',
684 vp->u2.field - slen);
686 shf_snprintf(p + vp->u2.field - slen,
687 psiz - (vp->u2.field - slen),
690 /* strip leading spaces/zeros */
691 while (ksh_isspace(*s))
693 if (vp->flag & ZEROFIL)
696 shf_snprintf(p, nlen + 1, "%-*.*s",
697 vp->u2.field, vp->u2.field, s);
700 memcpy(p, s, strlen(s) + 1);
702 if (vp->flag & UCASEV_AL) {
704 *q = ksh_toupper(*q);
705 } else if (vp->flag & LCASEV) {
707 *q = ksh_tolower(*q);
714 * make vp->val.s be "name=value" for quick exporting.
717 exportprep(struct tbl *vp, const char *val)
720 char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
721 size_t namelen, vallen;
723 namelen = strlen(vp->name);
724 vallen = strlen(val) + 1;
727 /* since name+val are both in memory this can go unchecked */
728 xp = alloc(namelen + 1 + vallen, vp->areap);
729 memcpy(vp->val.s = xp, vp->name, namelen);
732 /* offset to value */
733 vp->type = xp - vp->val.s;
734 memcpy(xp, val, vallen);
735 afree(op, vp->areap);
739 * lookup variable (according to (set&LOCAL)), set its attributes
740 * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV,
741 * UCASEV_AL), and optionally set its value if an assignment.
744 typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
747 struct tbl *vpbase, *t;
751 bool vappend = false;
752 enum namerefflag new_refflag = SRF_NOP;
754 if ((set & (ARRAY | ASSOC)) == ASSOC) {
755 new_refflag = SRF_ENABLE;
756 set &= ~(ARRAY | ASSOC);
758 if ((clr & (ARRAY | ASSOC)) == ASSOC) {
759 new_refflag = SRF_DISABLE;
760 clr &= ~(ARRAY | ASSOC);
763 /* check for valid variable name, search for value */
764 val = skip_varname(var, false);
766 /* no variable name given */
770 if (new_refflag != SRF_NOP)
772 "reference variable can't be an array");
773 len = array_ref_len(val);
777 * IMPORT is only used when the shell starts up and is
778 * setting up its environment. Allow only simple array
779 * references at this time since parameter/command
780 * substitution is performed on the [expression] which
781 * would be a major security hole.
786 for (i = 1; i < len - 1; i++)
787 if (!ksh_isdigit(val[i]))
793 strndupx(tvar, var, val - var, ATEMP);
795 } else if (set & IMPORT) {
796 /* environment invalid variable name or no assignment */
798 } else if (val[0] == '+' && val[1] == '=') {
799 strndupx(tvar, var, val - var, ATEMP);
802 } else if (val[0] != '\0') {
803 /* other invalid variable names (not from environment) */
806 /* just varname with no value part nor equals sign */
807 strdupx(tvar, var, ATEMP);
809 /* handle foo[*] => foo (whole array) mapping for R39b */
811 if (len > 3 && tvar[len - 3] == '[' && tvar[len - 2] == '*' &&
812 tvar[len - 1] == ']')
813 tvar[len - 3] = '\0';
816 if (new_refflag == SRF_ENABLE) {
817 const char *qval, *ccp;
819 /* bail out on 'nameref foo+=bar' */
821 errorf("appending not allowed for nameref");
822 /* find value if variable already exists */
823 if ((qval = val) == NULL) {
824 varsearch(e->loc, &vp, tvar, hash(tvar));
829 /* check target value for being a valid variable name */
830 ccp = skip_varname(qval, false);
834 if (!(c = (unsigned char)qval[0]))
836 else if (ksh_isdigit(c) && getn(qval, &c))
837 goto nameref_rhs_checked;
838 else if (qval[1] == '\0') switch (c) {
844 goto nameref_rhs_checked;
847 errorf(Tf_sD_s, var, "empty nameref target");
849 len = (*ccp == '[') ? array_ref_len(ccp) : 0;
852 * works for cases "no array", "valid array with
853 * junk after it" and "invalid array"; in the
854 * latter case, len is also 0 and points to '['
856 errorf(Tf_sD_s, qval,
857 "nameref target not a valid parameter name");
860 /* prevent nameref loops */
862 if (!strcmp(qval, tvar))
863 errorf(Tf_sD_s, qval,
864 "expression recurses on parameter");
865 varsearch(e->loc, &vp, qval, hash(qval));
867 if (vp && ((vp->flag & (ARRAY | ASSOC)) == ASSOC))
872 /* prevent typeset from creating a local PATH/ENV/SHELL */
873 if (Flag(FRESTRICTED) && (strcmp(tvar, TPATH) == 0 ||
874 strcmp(tvar, "ENV") == 0 || strcmp(tvar, TSHELL) == 0))
875 errorf(Tf_sD_s, tvar, "restricted");
877 innermost_refflag = new_refflag;
878 vp = (set & LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
880 if (new_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
882 else if (new_refflag == SRF_ENABLE) {
883 if (vp->flag & ARRAY) {
886 /* free up entire array */
887 for (a = vp->u.array; a; ) {
890 if (tmp->flag & ALLOC)
891 afree(tmp->val.s, tmp->areap);
892 afree(tmp, tmp->areap);
900 set &= ~(LOCAL|LOCAL_COPY);
902 vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
905 * only allow export flag to be set; AT&T ksh allows any
906 * attribute to be changed which means it can be truncated or
907 * modified (-L/-R/-Z/-i)
909 if ((vpbase->flag & RDONLY) &&
910 (val || clr || (set & ~EXPORT)))
911 /* XXX check calls - is error here ok by POSIX? */
912 errorfx(2, Tf_ro, tvar);
915 /* most calls are with set/clr == 0 */
920 * XXX if x[0] isn't set, there will be problems: need
921 * to have one copy of attributes for arrays...
923 for (t = vpbase; t; t = t->u.array) {
926 char *free_me = NULL;
928 fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
929 ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
930 ((t->flag & INTEGER) && (clr & INTEGER)) ||
931 (!(t->flag & INTEGER) && (set & INTEGER)));
933 if (t->flag & INTEGER) {
937 s = t->val.s + t->type;
938 free_me = (t->flag & ALLOC) ? t->val.s :
943 if (!(t->flag & INTEGER) && (set & INTEGER)) {
947 t->flag = (t->flag | set) & ~clr;
949 * Don't change base if assignment is to be
950 * done, in case assignment fails.
952 if ((set & INTEGER) && base > 0 && (!val || t != vp))
954 if (set & (LJUST|RJUST|ZEROFIL))
957 if (!setstr(t, s, KSH_RETURN_ERROR)) {
959 * Somewhat arbitrary action
960 * here: zap contents of
961 * variable, but keep the flag
965 if (t->flag & INTEGER)
969 afree(t->val.s, t->areap);
970 t->flag &= ~(ISSET|ALLOC);
974 afree(free_me, t->areap);
985 tval = shf_smprintf(Tf_ss, str_val(vp), val);
990 if (vp->flag&INTEGER) {
991 /* do not zero base before assignment */
992 setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
993 /* done after assignment to override default */
997 /* setstr can't fail (readonly check already done) */
998 setstr(vp, val, KSH_RETURN_ERROR | 0x4);
1003 /* only x[0] is ever exported, so use vpbase */
1004 if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
1006 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
1012 * Unset a variable. The flags can be:
1013 * |1 = tear down entire array
1014 * |2 = keep attributes, only unset content
1017 unset(struct tbl *vp, int flags)
1019 if (vp->flag & ALLOC)
1020 afree(vp->val.s, vp->areap);
1021 if ((vp->flag & ARRAY) && (flags & 1)) {
1022 struct tbl *a, *tmp;
1024 /* free up entire array */
1025 for (a = vp->u.array; a; ) {
1028 if (tmp->flag & ALLOC)
1029 afree(tmp->val.s, tmp->areap);
1030 afree(tmp, tmp->areap);
1035 vp->flag &= ~(ALLOC|ISSET);
1038 /* if foo[0] is being unset, the remainder of the array is kept... */
1039 vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
1040 if (vp->flag & SPECIAL)
1041 /* responsible for 'unspecial'ing var */
1046 * Return a pointer to the first char past a legal variable name
1047 * (returns the argument if there is no legal name, returns a pointer to
1048 * the terminating NUL if whole string is legal).
1051 skip_varname(const char *s, bool aok)
1055 if (s && ksh_isalphx(*s)) {
1056 while (*++s && ksh_isalnux(*s))
1058 if (aok && *s == '[' && (alen = array_ref_len(s)))
1064 /* Return a pointer to the first character past any legal variable name */
1066 skip_wdvarname(const char *s,
1067 /* skip array de-reference? */
1070 if (s[0] == CHAR && ksh_isalphx(s[1])) {
1073 } while (s[0] == CHAR && ksh_isalnux(s[1]));
1074 if (aok && s[0] == CHAR && s[1] == '[') {
1075 /* skip possible array de-reference */
1080 while (/* CONSTCOND */ 1) {
1087 else if (c == ']' && --depth == 0) {
1097 /* Check if coded string s is a variable name */
1099 is_wdvarname(const char *s, bool aok)
1101 const char *p = skip_wdvarname(s, aok);
1103 return (p != s && p[0] == EOS);
1106 /* Check if coded string s is a variable assignment */
1108 is_wdvarassign(const char *s)
1110 const char *p = skip_wdvarname(s, true);
1112 return (p != s && p[0] == CHAR &&
1113 (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1117 * Make the exported environment from the exported names in the dictionary.
1125 struct tbl *vp, **vpp;
1128 for (l = e->loc; l != NULL; l = l->next) {
1130 i = 1 << (l->vars.tshift);
1132 if ((vp = *vpp++) != NULL &&
1133 (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1136 uint32_t h = hash(vp->name);
1138 /* unexport any redefined instances */
1139 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1140 vp2 = ktsearch(&l2->vars, vp->name, h);
1142 vp2->flag &= ~EXPORT;
1144 if ((vp->flag&INTEGER)) {
1145 /* integer to string */
1148 vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1149 /* setstr can't fail here */
1150 setstr(vp, val, KSH_RETURN_ERROR);
1152 XPput(denv, vp->val.s);
1154 if (l->flags & BF_STOPENV)
1158 return ((char **)XPclose(denv));
1162 * handle special variables with side effects - PATH, SECONDS.
1165 /* Test if name is a special parameter */
1167 special(const char *name)
1171 tp = ktsearch(&specials, name, hash(name));
1172 return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1175 /* Make a variable non-special */
1177 unspecial(const char *name)
1181 tp = ktsearch(&specials, name, hash(name));
1186 static time_t seconds; /* time SECONDS last set */
1187 static mksh_uari_t user_lineno; /* what user set $LINENO to */
1189 /* minimum values from the OS we consider sane, lowered for R53 */
1194 getspec(struct tbl *vp)
1200 switch ((st = special(vp->name))) {
1204 * Do NOT export COLUMNS/LINES. Many applications
1205 * check COLUMNS/LINES before checking ws.ws_col/row,
1206 * so if the app is started with C/L in the environ
1207 * and the window is then resized, the app won't
1208 * see the change cause the environ doesn't change.
1216 num.u = (mksh_uari_t)procpid;
1225 num.u = (mksh_uari_t)current_lineno + user_lineno;
1230 case V_EPOCHREALTIME: {
1231 /* 10(%u) + 1(.) + 6 + NUL */
1234 vp->flag &= ~SPECIAL;
1236 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1237 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1238 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1239 vp->flag |= SPECIAL;
1243 num.i = user_opt.uoptind;
1250 * On start up the value of SECONDS is used before
1251 * it has been set - don't do anything in this case
1252 * (see initcoms[] in main.c).
1254 if (vp->flag & ISSET) {
1256 num.i = tv.tv_sec - seconds;
1261 /* do nothing, do not touch vp at all */
1264 vp->flag &= ~SPECIAL;
1265 setint_n(vp, num.i, 0);
1266 vp->flag |= SPECIAL;
1270 setspec(struct tbl *vp)
1276 switch ((st = special(vp->name))) {
1277 #if HAVE_PERSISTENT_HISTORY
1279 sethistfile(str_val(vp));
1283 setctypes(s = str_val(vp), C_IFS);
1289 strdupx(path, s, APERM);
1290 /* clear tracked aliases */
1293 #ifndef MKSH_NO_CMDLINE_EDITING
1295 x_initterm(str_val(vp));
1299 afree(tmpdir, APERM);
1302 * Use tmpdir iff it is an absolute path, is writable
1303 * and searchable and is a directory...
1309 /* LINTED use of access */
1310 if (mksh_abspath(s) && access(s, W_OK|X_OK) == 0 &&
1311 stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1312 strdupx(tmpdir, s, APERM);
1315 /* common sub-cases */
1318 if (vp->flag & IMPORT) {
1320 unspecial(vp->name);
1321 vp->flag &= ~SPECIAL;
1331 vp->flag &= ~SPECIAL;
1332 if (getint(vp, &num, false) == -1) {
1335 errorf(Tf_sD_sD_s, vp->name, "bad number", s);
1338 vp->flag |= SPECIAL;
1341 /* do nothing, do not touch vp at all */
1345 /* process the singular parts of the common cases */
1349 if (num.i >= MIN_COLS)
1356 /* The -1 is because line numbering starts at 1. */
1357 user_lineno = num.u - (mksh_uari_t)current_lineno - 1;
1360 if (num.i >= MIN_LINS)
1364 getopts_reset((int)num.i);
1368 * mksh R39d+ no longer has the traditional repeatability
1369 * of $RANDOM sequences, but always retains state
1371 rndset((unsigned long)num.u);
1378 seconds = tv.tv_sec - num.i;
1382 ksh_tmout = num.i >= 0 ? num.i : 0;
1388 unsetspec(struct tbl *vp)
1391 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1392 * meaning, but OPTARG does not (still set by getopts) and _ is
1393 * also still set in various places. Don't know what AT&T does
1394 * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1395 * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1398 switch (special(vp->name)) {
1399 #if HAVE_PERSISTENT_HISTORY
1405 setctypes(TC_IFSWS, C_IFS);
1410 strdupx(path, def_path, APERM);
1411 /* clear tracked aliases */
1414 #ifndef MKSH_NO_CMDLINE_EDITING
1420 /* should not become unspecial */
1422 afree(tmpdir, APERM);
1430 /* AT&T ksh leaves previous value in place */
1431 unspecial(vp->name);
1437 * Search for (and possibly create) a table entry starting with
1438 * vp, indexed by val.
1441 arraysearch(struct tbl *vp, uint32_t val)
1443 struct tbl *prev, *curr, *news;
1446 vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
1447 /* the table entry is always [0] */
1452 while (curr && curr->ua.index < val) {
1454 curr = curr->u.array;
1456 if (curr && curr->ua.index == val) {
1457 if (curr->flag&ISSET)
1463 len = strlen(vp->name);
1464 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1465 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1466 memcpy(news->name, vp->name, len);
1468 news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1469 news->type = vp->type;
1470 news->areap = vp->areap;
1471 news->u2.field = vp->u2.field;
1472 news->ua.index = val;
1475 /* not reusing old array entry */
1476 prev->u.array = news;
1477 news->u.array = curr;
1483 * Return the length of an array reference (eg, [1+2]) - cp is assumed
1484 * to point to the open bracket. Returns 0 if there is no matching
1487 * XXX this should parse the actual arithmetic syntax
1490 array_ref_len(const char *cp)
1496 while ((c = *s++) && (c != ']' || --depth))
1505 * Make a copy of the base of an array name
1508 arrayname(const char *str)
1513 if (!(p = cstrchr(str, '[')))
1514 /* Shouldn't happen, but why worry? */
1515 strdupx(rv, str, ATEMP);
1517 strndupx(rv, str, p - str, ATEMP);
1522 /* set (or overwrite, if reset) the array variable var to the values in vals */
1524 set_array(const char *var, bool reset, const char **vals)
1526 struct tbl *vp, *vq;
1527 mksh_uari_t i = 0, j = 0;
1528 const char *ccp = var;
1532 /* to get local array, use "local foo; set -A foo" */
1534 if (n > 0 && var[n - 1] == '+') {
1537 strndupx(cp, var, n - 1, ATEMP);
1542 /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1543 if ((vp->flag&RDONLY))
1544 errorfx(2, Tf_ro, ccp);
1545 /* This code is quite non-optimal */
1547 /* trash existing values and attributes */
1549 /* allocate-by-access the [0] element to keep in scope */
1553 * TODO: would be nice for assignment to completely succeed or
1554 * completely fail. Only really effects integer arrays:
1555 * evaluation of some of vals[] may fail...
1558 /* find out where to set when appending */
1559 for (vq = vp; vq; vq = vq->u.array) {
1560 if (!(vq->flag & ISSET))
1562 if (arrayindex(vq) >= j)
1563 j = arrayindex(vq) + 1;
1567 while ((ccp = vals[i])) {
1568 #if 0 /* temporarily taken out due to regression */
1573 if (*ccp == ']' && --level == 0)
1579 if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1580 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1582 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1583 KSH_UNWIND_ERROR, true);
1591 vq = arraysearch(vp, j);
1592 /* would be nice to deal with errors here... (see above) */
1593 setstr(vq, ccp, KSH_RETURN_ERROR);
1607 BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
1610 /* check if window size has changed */
1611 if (tty_init_fd() < 2) {
1614 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1623 /* bounds check for sane values, use defaults otherwise */
1624 if (x_cols < MIN_COLS)
1626 if (x_lins < MIN_LINS)
1637 register uint32_t h;
1640 BAFHUpdateStr_reg(h, s);
1646 chvt_rndsetup(const void *bp, size_t sz)
1648 register uint32_t h;
1650 /* use LCG as seed but try to get them to deviate immediately */
1654 /* variation through pid, ppid, and the works */
1655 BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
1656 /* some variation, some possibly entropy, depending on OE */
1657 BAFHUpdateMem_reg(h, bp, sz);
1658 /* mix them all up */
1668 * this is the same Linear Congruential PRNG as Borland
1669 * C/C++ allegedly uses in its built-in rand() function
1671 return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1675 rndset(unsigned long v)
1677 register uint32_t h;
1678 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1679 register uint32_t t;
1690 /* clear the allocated space, for valgrind */
1691 memset(&z, 0, sizeof(z));
1696 BAFHUpdateMem_reg(h, &v, sizeof(v));
1701 z.r = (short)rndget();
1703 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1706 z.qh = (t & 0xFFFF8000) | rndget();
1707 lcg_state = (t << 15) | rndget();
1709 * either we have very chap entropy get and push available,
1710 * with malloc() pulling in this code already anyway, or the
1711 * user requested us to use the old functions
1714 BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
1717 #if defined(arc4random_pushb_fast)
1718 arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1719 lcg_state = arc4random();
1721 lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1723 BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
1728 BAFHUpdateMem_reg(h, &z, sizeof(z));
1734 rndpush(const void *s)
1736 register uint32_t h = qh_state;
1738 BAFHUpdateStr_reg(h, s);
1739 BAFHUpdateOctet_reg(h, 0);
1743 /* record last glob match */
1745 record_match(const char *istr)
1749 vp = local("KSH_MATCH", false);
1751 vp->flag = DEFINED | RDONLY;
1752 setstr(vp, istr, 0x4);