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, 2017
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.214 2017/04/02 16:47:43 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 void c_typeset_vardump(struct tbl *, uint32_t, int, int, bool, bool);
49 static void c_typeset_vardump_recursive(struct block *, uint32_t, int, bool,
51 static char *formatstr(struct tbl *, const char *);
52 static void exportprep(struct tbl *, const char *);
53 static int special(const char *);
54 static void unspecial(const char *);
55 static void getspec(struct tbl *);
56 static void setspec(struct tbl *);
57 static void unsetspec(struct tbl *);
58 static int getint(struct tbl *, mksh_ari_u *, bool);
59 static const char *array_index_calc(const char *, bool *, uint32_t *);
62 * create a new block for function calls and simple commands
63 * assume caller has allocated and set up e->loc
69 static const char *empty[] = { null };
71 l = alloc(sizeof(struct block), ATEMP);
73 /* TODO: could use e->area (l->area => l->areap) */
79 l->argc = e->loc->argc;
80 l->argv = e->loc->argv;
82 l->exit = l->error = NULL;
83 ktinit(&l->area, &l->vars, 0);
84 ktinit(&l->area, &l->funs, 0);
90 * pop a block handling special variables
96 struct block *l = e->loc;
97 struct tbl *vp, **vpp = l->vars.tbls, *vq;
102 i = 1 << (l->vars.tshift);
104 if ((vp = *vpp++) != NULL && (vp->flag&SPECIAL)) {
105 if ((vq = global(vp->name))->flag & ISSET)
110 if (l->flags & BF_DOGETOPTS)
111 user_opt = l->getopts_state;
116 /* called by main() to initialise variable data structures */
117 #define VARSPEC_DEFNS
118 #include "var_spec.h"
121 #define VARSPEC_ENUMS
122 #include "var_spec.h"
126 /* this is biased with -1 relative to VARSPEC_ENUMS */
127 static const char * const initvar_names[] = {
128 #define VARSPEC_ITEMS
129 #include "var_spec.h"
138 ktinit(APERM, &specials,
139 /* currently 18 specials: 75% of 32 = 2^5 */
141 while (i < V_MAX - 1) {
142 tp = ktenter(&specials, initvar_names[i],
143 hash(initvar_names[i]));
144 tp->flag = DEFINED|ISSET;
149 /* common code for several functions below and c_typeset() */
151 varsearch(struct block *l, struct tbl **vpp, const char *vn, uint32_t h)
153 register struct tbl *vp;
157 if ((vp = ktsearch(&l->vars, vn, h)) != NULL)
159 if (l->next != NULL) {
171 * Used to calculate an array index for global()/local(). Sets *arrayp
172 * to true if this is an array, sets *valp to the array index, returns
173 * the basename of the array. May only be called from global()/local()
174 * and must be their first callee.
177 array_index_calc(const char *n, bool *arrayp, uint32_t *valp)
185 p = skip_varname(n, false);
186 if (innermost_refflag == SRF_NOP && (p != n) && ksh_isalphx(n[0])) {
190 strndupx(vn, n, p - n, ATEMP);
191 /* check if this is a reference */
192 varsearch(e->loc, &vp, vn, hash(vn));
194 if (vp && (vp->flag & (DEFINED | ASSOC | ARRAY)) ==
199 cp = shf_smprintf(Tf_ss, str_val(vp), p);
205 innermost_refflag = SRF_NOP;
207 if (p != n && *p == '[' && (len = array_ref_len(p))) {
211 /* calculate the value of the subscript */
213 strndupx(tmp, p + 1, len - 2, ATEMP);
214 sub = substitute(tmp, 0);
216 strndupx(n, n, p - n, ATEMP);
217 evaluate(sub, &rval, KSH_UNWIND_ERROR, true);
218 *valp = (uint32_t)rval;
226 * Search for variable, if not found create globally.
229 global(const char *n)
231 return (isglobal(n, true));
234 /* search for variable; if not found, return NULL or create globally */
236 isglobal(const char *n, bool docreate)
239 union mksh_cchack vname;
240 struct block *l = e->loc;
246 * check to see if this is an array;
247 * dereference namerefs; must come first
249 vn = array_index_calc(n, &array, &val);
251 c = (unsigned char)vn[0];
252 if (!ksh_isalphx(c)) {
259 if (ksh_isdigit(c)) {
261 /* main.c:main_init() says 12 */
262 shf_snprintf(vp->name, 12, Tf_d, c);
264 /* setstr can't fail here */
265 setstr(vp, l->argv[c],
278 vp->flag |= ISSET|INTEGER;
284 /* if no job, expand to nothing */
285 if ((vp->val.i = j_async()) == 0)
286 vp->flag &= ~(ISSET|INTEGER);
289 vp->val.i = exstat & 0xFF;
295 vp->flag &= ~INTEGER;
296 vp->val.s = getoptions();
299 vp->flag &= ~(ISSET|INTEGER);
303 l = varsearch(e->loc, &vp, vn, h);
304 if (vp == NULL && docreate)
305 vp = ktenter(&l->vars, vn, h);
310 vp = arraysearch(vp, val);
318 last_lookup_was_array = array;
320 afree(vname.rw, ATEMP);
325 * Search for local variable, if not found create locally.
328 local(const char *n, bool copy)
331 union mksh_cchack vname;
332 struct block *l = e->loc;
337 * check to see if this is an array;
338 * dereference namerefs; must come first
340 vn = array_index_calc(n, &array, &val);
342 if (!ksh_isalphx(*vn)) {
344 vp->flag = DEFINED|RDONLY;
349 vp = ktenter(&l->vars, vn, h);
350 if (copy && !(vp->flag & DEFINED)) {
353 varsearch(l->next, &vq, vn, h);
355 vp->flag |= vq->flag &
356 (EXPORT | INTEGER | RDONLY | LJUST | RJUST |
357 ZEROFIL | LCASEV | UCASEV_AL | INT_U | INT_L);
358 if (vq->flag & INTEGER)
360 vp->u2.field = vq->u2.field;
364 vp = arraysearch(vp, val);
369 last_lookup_was_array = array;
371 afree(vname.rw, ATEMP);
376 /* get variable string value */
378 str_val(struct tbl *vp)
382 if ((vp->flag&SPECIAL))
384 if (!(vp->flag&ISSET))
385 /* special to dollar() */
387 else if (!(vp->flag&INTEGER))
389 s = vp->val.s + vp->type;
395 * worst case number length is when base == 2:
396 * 1 (minus) + 2 (base, up to 36) + 1 ('#') +
397 * number of bits in the mksh_uari_t + 1 (NUL)
399 char strbuf[1 + 2 + 1 + 8 * sizeof(mksh_uari_t) + 1];
400 const char *digits = (vp->flag & UCASEV_AL) ?
401 digits_uc : digits_lc;
403 s = strbuf + sizeof(strbuf);
404 if (vp->flag & INT_U)
407 n = (vp->val.i < 0) ? -vp->val.u : vp->val.u;
408 base = (vp->type == 0) ? 10U : (unsigned int)vp->type;
410 if (base == 1 && n == 0)
417 if (!UTFMODE || ((n & 0xFF80) == 0xEF80))
418 /* OPTU-16 -> raw octet */
421 sz = utf_wctomb(s + 2, n);
426 *--s = digits[n % base];
431 *--s = digits[base % 10];
433 *--s = digits[base / 10];
435 if (!(vp->flag & INT_U) && vp->val.i < 0)
438 if (vp->flag & (RJUST|LJUST))
439 /* case already dealt with */
440 s = formatstr(vp, s);
442 strdupx(s, s, ATEMP);
447 /* set variable to string value */
449 setstr(struct tbl *vq, const char *s, int error_ok)
452 bool no_ro_check = tobool(error_ok & 0x4);
455 if ((vq->flag & RDONLY) && !no_ro_check) {
456 warningf(true, Tf_ro, vq->name);
461 if (!(vq->flag&INTEGER)) {
463 if ((vq->flag&ALLOC)) {
466 if (s >= vq->val.s &&
467 s <= vq->val.s + strlen(vq->val.s)) {
469 "setstr: %s=%s: assigning to self",
473 afree(vq->val.s, vq->areap);
475 vq->flag &= ~(ISSET|ALLOC);
477 if (s && (vq->flag & (UCASEV_AL|LCASEV|LJUST|RJUST)))
478 s = salloc = formatstr(vq, s);
479 if ((vq->flag&EXPORT))
482 strdupx(vq->val.s, s, vq->areap);
487 if (!v_evaluate(vq, s, error_ok, true))
491 if ((vq->flag&SPECIAL))
493 afree(salloc, ATEMP);
497 /* set variable to integer */
499 setint(struct tbl *vq, mksh_ari_t n)
501 if (!(vq->flag&INTEGER)) {
502 vtemp->flag = (ISSET|INTEGER);
504 vtemp->areap = ATEMP;
506 /* setstr can't fail here */
507 setstr(vq, str_val(vtemp), KSH_RETURN_ERROR);
511 if ((vq->flag&SPECIAL))
516 getint(struct tbl *vp, mksh_ari_u *nump, bool arith)
518 mksh_uari_t c, num = 0, base = 10;
520 bool have_base = false, neg = false;
522 if (vp->flag & SPECIAL)
524 /* XXX is it possible for ISSET to be set and val.s to be NULL? */
525 if (!(vp->flag & ISSET) || (!(vp->flag & INTEGER) && vp->val.s == NULL))
527 if (vp->flag & INTEGER) {
531 s = vp->val.s + vp->type;
534 c = (unsigned char)*s++;
535 } while (ksh_isspace(c));
542 c = (unsigned char)*s++;
546 if (c == '0' && arith) {
547 if (ksh_eq(s[0], 'X', 'x')) {
548 /* interpret as hexadecimal */
551 goto getint_c_style_base;
552 } else if (Flag(FPOSIX) && ksh_isdigit(s[0]) &&
553 !(vp->flag & ZEROFIL)) {
554 /* interpret as octal (deprecated) */
558 c = (unsigned char)*s++;
564 /* ksh-style base determination */
565 if (have_base || num < 1)
567 if ((base = num) == 1) {
568 /* mksh-specific extension */
572 wc = *(const unsigned char *)s;
573 else if (utf_mbtowc(&wc, s) == (size_t)-1)
574 /* OPTU-8 -> OPTU-16 */
576 * (with a twist: 1#\uEF80 converts
577 * the same as 1#\x80 does, thus is
578 * not round-tripping correctly XXX)
580 wc = 0xEF00 + *(const unsigned char *)s;
581 nump->u = (mksh_uari_t)wc;
583 } else if (base > 36)
591 else if (ksh_isupper(c))
592 c = ksh_numuc(c) + 10;
593 else if (ksh_islower(c))
594 c = ksh_numlc(c) + 10;
599 /* handle overflow as truncation */
600 num = num * base + c;
601 } while ((c = (unsigned char)*s++));
610 * convert variable vq to integer variable, setting its value from vp
611 * (vq and vp may be the same)
614 setint_v(struct tbl *vq, struct tbl *vp, bool arith)
619 if ((base = getint(vp, &num, arith)) == -1)
621 setint_n(vq, num.i, 0);
628 /* convert variable vq to integer variable, setting its value to num */
630 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
632 if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
635 afree(vq->val.s, vq->areap);
640 vq->flag |= ISSET|INTEGER;
641 if (vq->flag&SPECIAL)
646 formatstr(struct tbl *vp, const char *s)
652 olen = (int)utf_mbswidth(s);
654 if (vp->flag & (RJUST|LJUST)) {
656 /* default field width */
662 p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
663 if (vp->flag & (RJUST|LJUST)) {
666 if (vp->flag & RJUST) {
670 qq = utf_skipcols(s, slen, &slen);
672 /* strip trailing spaces (AT&T uses qq[-1] == ' ') */
673 while (qq > s && ksh_isspace(qq[-1])) {
677 if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
682 else if (s[2] == '#')
685 if (vp->u2.field <= n)
692 while (slen > vp->u2.field)
693 slen -= utf_widthadj(s, &s);
694 if (vp->u2.field - slen)
695 memset(p + n, (vp->flag & ZEROFIL) ? '0' : ' ',
696 vp->u2.field - slen);
698 shf_snprintf(p + vp->u2.field - slen,
699 psiz - (vp->u2.field - slen),
702 /* strip leading spaces/zeros */
703 while (ksh_isspace(*s))
705 if (vp->flag & ZEROFIL)
708 shf_snprintf(p, nlen + 1, "%-*.*s",
709 vp->u2.field, vp->u2.field, s);
712 memcpy(p, s, strlen(s) + 1);
714 if (vp->flag & UCASEV_AL) {
716 *q = ksh_toupper(*q);
717 } else if (vp->flag & LCASEV) {
719 *q = ksh_tolower(*q);
726 * make vp->val.s be "name=value" for quick exporting.
729 exportprep(struct tbl *vp, const char *val)
732 char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
733 size_t namelen, vallen;
735 namelen = strlen(vp->name);
736 vallen = strlen(val) + 1;
739 /* since name+val are both in memory this can go unchecked */
740 xp = alloc(namelen + 1 + vallen, vp->areap);
741 memcpy(vp->val.s = xp, vp->name, namelen);
744 /* offset to value */
745 vp->type = xp - vp->val.s;
746 memcpy(xp, val, vallen);
747 afree(op, vp->areap);
751 * lookup variable (according to (set&LOCAL)), set its attributes
752 * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV,
753 * UCASEV_AL), and optionally set its value if an assignment.
756 typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
759 struct tbl *vpbase, *t;
763 bool vappend = false;
764 enum namerefflag new_refflag = SRF_NOP;
766 if ((set & (ARRAY | ASSOC)) == ASSOC) {
767 new_refflag = SRF_ENABLE;
768 set &= ~(ARRAY | ASSOC);
770 if ((clr & (ARRAY | ASSOC)) == ASSOC) {
771 new_refflag = SRF_DISABLE;
772 clr &= ~(ARRAY | ASSOC);
775 /* check for valid variable name, search for value */
776 val = skip_varname(var, false);
778 /* no variable name given */
782 if (new_refflag != SRF_NOP)
784 "reference variable can't be an array");
785 len = array_ref_len(val);
789 * IMPORT is only used when the shell starts up and is
790 * setting up its environment. Allow only simple array
791 * references at this time since parameter/command
792 * substitution is performed on the [expression] which
793 * would be a major security hole.
798 for (i = 1; i < len - 1; i++)
799 if (!ksh_isdigit(val[i]))
805 strndupx(tvar, var, val - var, ATEMP);
807 } else if (set & IMPORT) {
808 /* environment invalid variable name or no assignment */
810 } else if (val[0] == '+' && val[1] == '=') {
811 strndupx(tvar, var, val - var, ATEMP);
814 } else if (val[0] != '\0') {
815 /* other invalid variable names (not from environment) */
818 /* just varname with no value part nor equals sign */
819 strdupx(tvar, var, ATEMP);
821 /* handle foo[*] => foo (whole array) mapping for R39b */
823 if (len > 3 && tvar[len - 3] == '[' && tvar[len - 2] == '*' &&
824 tvar[len - 1] == ']')
825 tvar[len - 3] = '\0';
828 if (new_refflag == SRF_ENABLE) {
829 const char *qval, *ccp;
831 /* bail out on 'nameref foo+=bar' */
833 errorf("appending not allowed for nameref");
834 /* find value if variable already exists */
835 if ((qval = val) == NULL) {
836 varsearch(e->loc, &vp, tvar, hash(tvar));
841 /* check target value for being a valid variable name */
842 ccp = skip_varname(qval, false);
846 if (!(c = (unsigned char)qval[0]))
848 else if (ksh_isdigit(c) && getn(qval, &c))
849 goto nameref_rhs_checked;
850 else if (qval[1] == '\0') switch (c) {
856 goto nameref_rhs_checked;
859 errorf(Tf_sD_s, var, "empty nameref target");
861 len = (*ccp == '[') ? array_ref_len(ccp) : 0;
864 * works for cases "no array", "valid array with
865 * junk after it" and "invalid array"; in the
866 * latter case, len is also 0 and points to '['
868 errorf(Tf_sD_s, qval,
869 "nameref target not a valid parameter name");
872 /* prevent nameref loops */
874 if (!strcmp(qval, tvar))
875 errorf(Tf_sD_s, qval,
876 "expression recurses on parameter");
877 varsearch(e->loc, &vp, qval, hash(qval));
879 if (vp && ((vp->flag & (ARRAY | ASSOC)) == ASSOC))
884 /* prevent typeset from creating a local PATH/ENV/SHELL */
885 if (Flag(FRESTRICTED) && (strcmp(tvar, TPATH) == 0 ||
886 strcmp(tvar, "ENV") == 0 || strcmp(tvar, TSHELL) == 0))
887 errorf(Tf_sD_s, tvar, "restricted");
889 innermost_refflag = new_refflag;
890 vp = (set & LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
892 if (new_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
894 else if (new_refflag == SRF_ENABLE) {
895 if (vp->flag & ARRAY) {
898 /* free up entire array */
899 for (a = vp->u.array; a; ) {
902 if (tmp->flag & ALLOC)
903 afree(tmp->val.s, tmp->areap);
904 afree(tmp, tmp->areap);
912 set &= ~(LOCAL|LOCAL_COPY);
914 vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
917 * only allow export flag to be set; AT&T ksh allows any
918 * attribute to be changed which means it can be truncated or
919 * modified (-L/-R/-Z/-i)
921 if ((vpbase->flag & RDONLY) &&
922 (val || clr || (set & ~EXPORT)))
923 /* XXX check calls - is error here ok by POSIX? */
924 errorfx(2, Tf_ro, tvar);
927 /* most calls are with set/clr == 0 */
932 * XXX if x[0] isn't set, there will be problems: need
933 * to have one copy of attributes for arrays...
935 for (t = vpbase; t; t = t->u.array) {
938 char *free_me = NULL;
940 fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
941 ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
942 ((t->flag & INTEGER) && (clr & INTEGER)) ||
943 (!(t->flag & INTEGER) && (set & INTEGER)));
945 if (t->flag & INTEGER) {
949 s = t->val.s + t->type;
950 free_me = (t->flag & ALLOC) ? t->val.s :
955 if (!(t->flag & INTEGER) && (set & INTEGER)) {
959 t->flag = (t->flag | set) & ~clr;
961 * Don't change base if assignment is to be
962 * done, in case assignment fails.
964 if ((set & INTEGER) && base > 0 && (!val || t != vp))
966 if (set & (LJUST|RJUST|ZEROFIL))
969 if (!setstr(t, s, KSH_RETURN_ERROR)) {
971 * Somewhat arbitrary action
972 * here: zap contents of
973 * variable, but keep the flag
977 if (t->flag & INTEGER)
981 afree(t->val.s, t->areap);
982 t->flag &= ~(ISSET|ALLOC);
986 afree(free_me, t->areap);
997 tval = shf_smprintf(Tf_ss, str_val(vp), val);
1002 if (vp->flag&INTEGER) {
1003 /* do not zero base before assignment */
1004 setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
1005 /* done after assignment to override default */
1009 /* setstr can't fail (readonly check already done) */
1010 setstr(vp, val, KSH_RETURN_ERROR | 0x4);
1015 /* only x[0] is ever exported, so use vpbase */
1016 if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
1018 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
1024 * Unset a variable. The flags can be:
1025 * |1 = tear down entire array
1026 * |2 = keep attributes, only unset content
1029 unset(struct tbl *vp, int flags)
1031 if (vp->flag & ALLOC)
1032 afree(vp->val.s, vp->areap);
1033 if ((vp->flag & ARRAY) && (flags & 1)) {
1034 struct tbl *a, *tmp;
1036 /* free up entire array */
1037 for (a = vp->u.array; a; ) {
1040 if (tmp->flag & ALLOC)
1041 afree(tmp->val.s, tmp->areap);
1042 afree(tmp, tmp->areap);
1047 vp->flag &= ~(ALLOC|ISSET);
1050 /* if foo[0] is being unset, the remainder of the array is kept... */
1051 vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
1052 if (vp->flag & SPECIAL)
1053 /* responsible for 'unspecial'ing var */
1058 * Return a pointer to the first char past a legal variable name
1059 * (returns the argument if there is no legal name, returns a pointer to
1060 * the terminating NUL if whole string is legal).
1063 skip_varname(const char *s, bool aok)
1067 if (s && ksh_isalphx(*s)) {
1070 } while (ksh_isalnux(*s));
1071 if (aok && *s == '[' && (alen = array_ref_len(s)))
1077 /* Return a pointer to the first character past any legal variable name */
1079 skip_wdvarname(const char *s,
1080 /* skip array de-reference? */
1083 if (s[0] == CHAR && ksh_isalphx(s[1])) {
1086 } while (s[0] == CHAR && ksh_isalnux(s[1]));
1087 if (aok && s[0] == CHAR && s[1] == '[') {
1088 /* skip possible array de-reference */
1093 while (/* CONSTCOND */ 1) {
1100 else if (c == ']' && --depth == 0) {
1110 /* Check if coded string s is a variable name */
1112 is_wdvarname(const char *s, bool aok)
1114 const char *p = skip_wdvarname(s, aok);
1116 return (p != s && p[0] == EOS);
1119 /* Check if coded string s is a variable assignment */
1121 is_wdvarassign(const char *s)
1123 const char *p = skip_wdvarname(s, true);
1125 return (p != s && p[0] == CHAR &&
1126 (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1130 * Make the exported environment from the exported names in the dictionary.
1138 struct tbl *vp, **vpp;
1141 for (l = e->loc; l != NULL; l = l->next) {
1143 i = 1 << (l->vars.tshift);
1145 if ((vp = *vpp++) != NULL &&
1146 (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1149 uint32_t h = hash(vp->name);
1151 /* unexport any redefined instances */
1152 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1153 vp2 = ktsearch(&l2->vars, vp->name, h);
1155 vp2->flag &= ~EXPORT;
1157 if ((vp->flag&INTEGER)) {
1158 /* integer to string */
1161 vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1162 /* setstr can't fail here */
1163 setstr(vp, val, KSH_RETURN_ERROR);
1166 /* these special variables are not exported */
1167 if (!strcmp(vp->name, "BEGINLIBPATH") ||
1168 !strcmp(vp->name, "ENDLIBPATH") ||
1169 !strcmp(vp->name, "LIBPATHSTRICT"))
1172 XPput(denv, vp->val.s);
1174 if (l->flags & BF_STOPENV)
1178 return ((char **)XPclose(denv));
1182 * handle special variables with side effects - PATH, SECONDS.
1185 /* Test if name is a special parameter */
1187 special(const char *name)
1191 tp = ktsearch(&specials, name, hash(name));
1192 return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1195 /* Make a variable non-special */
1197 unspecial(const char *name)
1201 tp = ktsearch(&specials, name, hash(name));
1206 static time_t seconds; /* time SECONDS last set */
1207 static mksh_uari_t user_lineno; /* what user set $LINENO to */
1209 /* minimum values from the OS we consider sane, lowered for R53 */
1214 getspec(struct tbl *vp)
1220 switch ((st = special(vp->name))) {
1224 * Do NOT export COLUMNS/LINES. Many applications
1225 * check COLUMNS/LINES before checking ws.ws_col/row,
1226 * so if the app is started with C/L in the environ
1227 * and the window is then resized, the app won't
1228 * see the change cause the environ doesn't change.
1236 num.u = (mksh_uari_t)procpid;
1245 num.u = (mksh_uari_t)current_lineno + user_lineno;
1250 case V_EPOCHREALTIME: {
1251 /* 10(%u) + 1(.) + 6 + NUL */
1254 vp->flag &= ~SPECIAL;
1256 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1257 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1258 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1259 vp->flag |= SPECIAL;
1263 num.i = user_opt.uoptind;
1270 * On start up the value of SECONDS is used before
1271 * it has been set - don't do anything in this case
1272 * (see initcoms[] in main.c).
1274 if (vp->flag & ISSET) {
1276 num.i = tv.tv_sec - seconds;
1281 /* do nothing, do not touch vp at all */
1284 vp->flag &= ~SPECIAL;
1285 setint_n(vp, num.i, 0);
1286 vp->flag |= SPECIAL;
1290 setspec(struct tbl *vp)
1296 switch ((st = special(vp->name))) {
1298 case V_BEGINLIBPATH:
1300 case V_LIBPATHSTRICT:
1301 setextlibpath(vp->name, str_val(vp));
1304 #if HAVE_PERSISTENT_HISTORY
1306 sethistfile(str_val(vp));
1310 setctypes(s = str_val(vp), C_IFS);
1316 strdupx(path, s, APERM);
1317 /* clear tracked aliases */
1320 #ifndef MKSH_NO_CMDLINE_EDITING
1322 x_initterm(str_val(vp));
1326 afree(tmpdir, APERM);
1329 * Use tmpdir iff it is an absolute path, is writable
1330 * and searchable and is a directory...
1336 /* LINTED use of access */
1337 if (mksh_abspath(s) && access(s, W_OK|X_OK) == 0 &&
1338 stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1339 strdupx(tmpdir, s, APERM);
1342 /* common sub-cases */
1345 if (vp->flag & IMPORT) {
1347 unspecial(vp->name);
1348 vp->flag &= ~SPECIAL;
1358 vp->flag &= ~SPECIAL;
1359 if (getint(vp, &num, false) == -1) {
1362 errorf(Tf_sD_sD_s, vp->name, Tbadnum, s);
1365 vp->flag |= SPECIAL;
1368 /* do nothing, do not touch vp at all */
1372 /* process the singular parts of the common cases */
1376 if (num.i >= MIN_COLS)
1383 /* The -1 is because line numbering starts at 1. */
1384 user_lineno = num.u - (mksh_uari_t)current_lineno - 1;
1387 if (num.i >= MIN_LINS)
1391 getopts_reset((int)num.i);
1395 * mksh R39d+ no longer has the traditional repeatability
1396 * of $RANDOM sequences, but always retains state
1398 rndset((unsigned long)num.u);
1405 seconds = tv.tv_sec - num.i;
1409 ksh_tmout = num.i >= 0 ? num.i : 0;
1415 unsetspec(struct tbl *vp)
1418 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1419 * meaning, but OPTARG does not (still set by getopts) and _ is
1420 * also still set in various places. Don't know what AT&T does
1421 * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1422 * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1425 switch (special(vp->name)) {
1427 case V_BEGINLIBPATH:
1429 case V_LIBPATHSTRICT:
1430 setextlibpath(vp->name, "");
1433 #if HAVE_PERSISTENT_HISTORY
1439 setctypes(TC_IFSWS, C_IFS);
1444 strdupx(path, def_path, APERM);
1445 /* clear tracked aliases */
1448 #ifndef MKSH_NO_CMDLINE_EDITING
1454 /* should not become unspecial */
1456 afree(tmpdir, APERM);
1464 /* AT&T ksh leaves previous value in place */
1465 unspecial(vp->name);
1471 * Search for (and possibly create) a table entry starting with
1472 * vp, indexed by val.
1475 arraysearch(struct tbl *vp, uint32_t val)
1477 struct tbl *prev, *curr, *news;
1480 vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
1481 /* the table entry is always [0] */
1486 while (curr && curr->ua.index < val) {
1488 curr = curr->u.array;
1490 if (curr && curr->ua.index == val) {
1491 if (curr->flag&ISSET)
1497 len = strlen(vp->name);
1498 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1499 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1500 memcpy(news->name, vp->name, len);
1502 news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1503 news->type = vp->type;
1504 news->areap = vp->areap;
1505 news->u2.field = vp->u2.field;
1506 news->ua.index = val;
1509 /* not reusing old array entry */
1510 prev->u.array = news;
1511 news->u.array = curr;
1517 * Return the length of an array reference (eg, [1+2]) - cp is assumed
1518 * to point to the open bracket. Returns 0 if there is no matching
1521 * XXX this should parse the actual arithmetic syntax
1524 array_ref_len(const char *cp)
1530 while ((c = *s++) && (c != ']' || --depth))
1539 * Make a copy of the base of an array name
1542 arrayname(const char *str)
1547 if (!(p = cstrchr(str, '[')))
1548 /* Shouldn't happen, but why worry? */
1549 strdupx(rv, str, ATEMP);
1551 strndupx(rv, str, p - str, ATEMP);
1556 /* set (or overwrite, if reset) the array variable var to the values in vals */
1558 set_array(const char *var, bool reset, const char **vals)
1560 struct tbl *vp, *vq;
1561 mksh_uari_t i = 0, j = 0;
1562 const char *ccp = var;
1566 /* to get local array, use "local foo; set -A foo" */
1568 if (n > 0 && var[n - 1] == '+') {
1571 strndupx(cp, var, n - 1, ATEMP);
1576 /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1577 if ((vp->flag&RDONLY))
1578 errorfx(2, Tf_ro, ccp);
1579 /* This code is quite non-optimal */
1581 /* trash existing values and attributes */
1583 /* allocate-by-access the [0] element to keep in scope */
1587 * TODO: would be nice for assignment to completely succeed or
1588 * completely fail. Only really effects integer arrays:
1589 * evaluation of some of vals[] may fail...
1592 /* find out where to set when appending */
1593 for (vq = vp; vq; vq = vq->u.array) {
1594 if (!(vq->flag & ISSET))
1596 if (arrayindex(vq) >= j)
1597 j = arrayindex(vq) + 1;
1601 while ((ccp = vals[i])) {
1602 #if 0 /* temporarily taken out due to regression */
1607 if (*ccp == ']' && --level == 0)
1613 if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1614 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1616 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1617 KSH_UNWIND_ERROR, true);
1625 vq = arraysearch(vp, j);
1626 /* would be nice to deal with errors here... (see above) */
1627 setstr(vq, ccp, KSH_RETURN_ERROR);
1641 BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
1644 /* check if window size has changed */
1645 if (tty_init_fd() < 2) {
1648 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1657 /* bounds check for sane values, use defaults otherwise */
1658 if (x_cols < MIN_COLS)
1660 if (x_lins < MIN_LINS)
1671 register uint32_t h;
1674 BAFHUpdateStr_reg(h, s);
1680 chvt_rndsetup(const void *bp, size_t sz)
1682 register uint32_t h;
1684 /* use LCG as seed but try to get them to deviate immediately */
1688 /* variation through pid, ppid, and the works */
1689 BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
1690 /* some variation, some possibly entropy, depending on OE */
1691 BAFHUpdateMem_reg(h, bp, sz);
1692 /* mix them all up */
1702 * this is the same Linear Congruential PRNG as Borland
1703 * C/C++ allegedly uses in its built-in rand() function
1705 return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1709 rndset(unsigned long v)
1711 register uint32_t h;
1712 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1713 register uint32_t t;
1723 /* clear the allocated space, for valgrind and to avoid UB */
1724 memset(&z, 0, sizeof(z));
1728 BAFHUpdateMem_reg(h, &v, sizeof(v));
1733 z.r = (short)rndget();
1735 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1738 z.qh = (t & 0xFFFF8000) | rndget();
1739 lcg_state = (t << 15) | rndget();
1741 * either we have very chap entropy get and push available,
1742 * with malloc() pulling in this code already anyway, or the
1743 * user requested us to use the old functions
1746 BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
1749 #if defined(arc4random_pushb_fast)
1750 arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1751 lcg_state = arc4random();
1753 lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1755 BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
1760 BAFHUpdateMem_reg(h, &z, sizeof(z));
1766 rndpush(const void *s)
1768 register uint32_t h = qh_state;
1770 BAFHUpdateStr_reg(h, s);
1771 BAFHUpdateOctet_reg(h, 0);
1775 /* record last glob match */
1777 record_match(const char *istr)
1781 vp = local("KSH_MATCH", false);
1783 vp->flag = DEFINED | RDONLY;
1784 setstr(vp, istr, 0x4);
1787 /* typeset, global(deprecated), export, and readonly */
1789 c_typeset(const char **wp)
1791 struct tbl *vp, **p;
1792 uint32_t fset = 0, fclr = 0, flag;
1793 int thing = 0, field = 0, base = 0, i;
1796 const char *fieldstr = NULL, *basestr = NULL;
1797 bool localv = false, func = false, pflag = false, istset = true;
1798 enum namerefflag new_refflag = SRF_NOP;
1816 /* called with 'typeset -' */
1825 /* see comment below regarding possible opions */
1826 opts = istset ? "L#R#UZ#afgi#lnprtux" : "p";
1828 builtin_opt.flags |= GF_PLUSOPT;
1830 * AT&T ksh seems to have 0-9 as options which are multiplied
1831 * to get a number that is used with -L, -R, -Z or -i (eg, -1R2
1832 * sets right justify in a field of 12). This allows options
1833 * to be grouped in an order (eg, -Lu12), but disallows -i8 -L3 and
1834 * does not allow the number to be specified as a separate argument
1835 * Here, the number must follow the RLZi option, but is optional
1836 * (see the # kludge in ksh_getopt()).
1838 while ((i = ksh_getopt(wp, &builtin_opt, opts)) != -1) {
1843 fieldstr = builtin_opt.optarg;
1847 fieldstr = builtin_opt.optarg;
1851 * AT&T ksh uses u, but this conflicts with
1852 * upper/lower case. If this option is changed,
1853 * need to change the -U below as well
1859 fieldstr = builtin_opt.optarg;
1863 * this is supposed to set (-a) or unset (+a) the
1864 * indexed array attribute; it does nothing on an
1865 * existing regular string or indexed array though
1872 localv = (builtin_opt.info & GI_PLUS) ? true : false;
1876 basestr = builtin_opt.optarg;
1882 new_refflag = (builtin_opt.info & GI_PLUS) ?
1883 SRF_DISABLE : SRF_ENABLE;
1885 /* export, readonly: POSIX -p flag */
1887 /* typeset: show values as well */
1899 /* upper case / autoload */
1908 if (builtin_opt.info & GI_PLUS) {
1919 if (fieldstr && !getn(fieldstr, &field)) {
1920 bi_errorf(Tf_sD_s, Tbadnum, fieldstr);
1924 if (!getn(basestr, &base)) {
1925 bi_errorf(Tf_sD_s, "bad integer base", basestr);
1928 if (base < 1 || base > 36)
1932 if (!(builtin_opt.info & GI_MINUSMINUS) && wp[builtin_opt.optind] &&
1933 (wp[builtin_opt.optind][0] == '-' ||
1934 wp[builtin_opt.optind][0] == '+') &&
1935 wp[builtin_opt.optind][1] == '\0') {
1936 thing = wp[builtin_opt.optind][0];
1937 builtin_opt.optind++;
1940 if (func && (((fset|fclr) & ~(TRACE|UCASEV_AL|EXPORT)) ||
1941 new_refflag != SRF_NOP)) {
1942 bi_errorf("only -t, -u and -x options may be used with -f");
1945 if (wp[builtin_opt.optind]) {
1947 * Take care of exclusions.
1948 * At this point, flags in fset are cleared in fclr and vice
1949 * versa. This property should be preserved.
1952 /* LCASEV has priority over UCASEV_AL */
1955 /* LJUST has priority over RJUST */
1957 if ((fset & (ZEROFIL|LJUST)) == ZEROFIL) {
1958 /* -Z implies -ZR */
1963 * Setting these attributes clears the others, unless they
1964 * are also set in this command
1966 if ((fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL | LCASEV |
1967 INTEGER | INT_U | INT_L)) || new_refflag != SRF_NOP)
1968 fclr |= ~fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL |
1969 LCASEV | INTEGER | INT_U | INT_L);
1971 if (new_refflag != SRF_NOP) {
1972 fclr &= ~(ARRAY | ASSOC);
1973 fset &= ~(ARRAY | ASSOC);
1976 if (new_refflag == SRF_DISABLE)
1980 /* set variables and attributes */
1981 if (wp[builtin_opt.optind] &&
1982 /* not "typeset -p varname" */
1983 !(!func && pflag && !(fset | fclr))) {
1987 if (localv && !func)
1989 for (i = builtin_opt.optind; wp[i]; i++) {
1991 f = findfunc(wp[i], hash(wp[i]),
1992 tobool(fset & UCASEV_AL));
1994 /* AT&T ksh does ++rv: bogus */
2002 fpFUNCTf(shl_stdout, 0,
2003 tobool(f->flag & FKSH),
2005 shf_putc('\n', shl_stdout);
2007 } else if (!typeset(wp[i], fset, fclr, field, base)) {
2008 bi_errorf(Tf_sD_s, wp[i], Tnot_ident);
2015 /* list variables and attributes */
2017 /* no difference at this point.. */
2020 for (l = e->loc; l; l = l->next) {
2021 for (p = ktsort(&l->funs); (vp = *p++); ) {
2022 if (flag && (vp->flag & flag) == 0)
2025 fpFUNCTf(shl_stdout, 0,
2026 tobool(vp->flag & FKSH),
2027 vp->name, vp->val.t);
2029 shf_puts(vp->name, shl_stdout);
2030 shf_putc('\n', shl_stdout);
2033 } else if (wp[builtin_opt.optind]) {
2034 for (i = builtin_opt.optind; wp[i]; i++) {
2035 vp = isglobal(wp[i], false);
2036 c_typeset_vardump(vp, flag, thing,
2037 last_lookup_was_array ? 4 : 0, pflag, istset);
2040 c_typeset_vardump_recursive(e->loc, flag, thing, pflag, istset);
2045 c_typeset_vardump_recursive(struct block *l, uint32_t flag, int thing,
2046 bool pflag, bool istset)
2048 struct tbl **blockvars, *vp;
2051 c_typeset_vardump_recursive(l->next, flag, thing, pflag, istset);
2052 blockvars = ktsort(&l->vars);
2053 while ((vp = *blockvars++))
2054 c_typeset_vardump(vp, flag, thing, 0, pflag, istset);
2055 /*XXX doesn’t this leak? */
2059 c_typeset_vardump(struct tbl *vp, uint32_t flag, int thing, int any_set,
2060 bool pflag, bool istset)
2069 * See if the parameter is set (for arrays, if any
2072 for (tvp = vp; tvp; tvp = tvp->u.array)
2073 if (tvp->flag & ISSET) {
2079 * Check attributes - note that all array elements
2080 * have (should have?) the same attributes, so checking
2081 * the first is sufficient.
2083 * Report an unset param only if the user has
2084 * explicitly given it some attribute (like export);
2085 * otherwise, after "echo $FOO", we would report FOO...
2087 if (!any_set && !(vp->flag & USERATTRIB))
2089 if (flag && (vp->flag & flag) == 0)
2091 if (!(vp->flag & ARRAY))
2092 /* optimise later conditionals */
2096 * Ignore array elements that aren't set unless there
2097 * are no set elements, in which case the first is
2100 if (any_set && !(vp->flag & ISSET))
2103 if (!thing && !flag) {
2105 shprintf(Tf_s_s_sN, Tset, "-A", vp->name);
2109 * AT&T ksh prints things like export, integer,
2110 * leftadj, zerofill, etc., but POSIX says must
2111 * be suitable for re-entry...
2113 shprintf(Tf_s_s, Ttypeset, "");
2114 if (((vp->flag & (ARRAY | ASSOC)) == ASSOC))
2115 shprintf(Tf__c_, 'n');
2116 if ((vp->flag & INTEGER))
2117 shprintf(Tf__c_, 'i');
2118 if ((vp->flag & EXPORT))
2119 shprintf(Tf__c_, 'x');
2120 if ((vp->flag & RDONLY))
2121 shprintf(Tf__c_, 'r');
2122 if ((vp->flag & TRACE))
2123 shprintf(Tf__c_, 't');
2124 if ((vp->flag & LJUST))
2125 shprintf("-L%d ", vp->u2.field);
2126 if ((vp->flag & RJUST))
2127 shprintf("-R%d ", vp->u2.field);
2128 if ((vp->flag & ZEROFIL))
2129 shprintf(Tf__c_, 'Z');
2130 if ((vp->flag & LCASEV))
2131 shprintf(Tf__c_, 'l');
2132 if ((vp->flag & UCASEV_AL))
2133 shprintf(Tf__c_, 'u');
2134 if ((vp->flag & INT_U))
2135 shprintf(Tf__c_, 'U');
2137 shprintf(Tf_s_s, istset ? Ttypeset :
2138 (flag & EXPORT) ? Texport : Treadonly, "");
2141 shprintf("%s[%lu]", vp->name, arrayindex(vp));
2143 shf_puts(vp->name, shl_stdout);
2144 if ((!thing && !flag && pflag) ||
2145 (thing == '-' && (vp->flag & ISSET))) {
2147 shf_putc('=', shl_stdout);
2148 /* AT&T ksh can't have justified integers... */
2149 if ((vp->flag & (INTEGER | LJUST | RJUST)) == INTEGER)
2150 shf_puts(s, shl_stdout);
2152 print_value_quoted(shl_stdout, s);
2154 shf_putc('\n', shl_stdout);
2157 * Only report first 'element' of an array with
2162 } while (!(any_set & 4) && (vp = vp->u.array));