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, 2018
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.226 2018/07/15 17:21:24 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 *, bool);
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)
108 unsetspec(vq, false);
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 21 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) && ctype(n[0], C_ALPHX)) {
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 && ord(*p) == ORD('[') && (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 (!ctype(c, C_ALPHX)) {
259 if (ctype(c, C_DIGIT)) {
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 (!ctype(*vn, C_ALPHX)) {
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)
418 s[2] = (unsigned char)n;
419 else if ((n & 0xFF80) == 0xEF80)
420 /* OPTU-16 -> raw octet */
421 s[2] = asc2rtt(n & 0xFF);
423 sz = utf_wctomb(s + 2, n);
428 *--s = digits[n % base];
433 *--s = digits[base % 10];
435 *--s = digits[base / 10];
437 if (!(vp->flag & INT_U) && vp->val.i < 0)
440 if (vp->flag & (RJUST|LJUST))
441 /* case already dealt with */
442 s = formatstr(vp, s);
444 strdupx(s, s, ATEMP);
449 /* set variable to string value */
451 setstr(struct tbl *vq, const char *s, int error_ok)
454 bool no_ro_check = tobool(error_ok & 0x4);
457 if ((vq->flag & RDONLY) && !no_ro_check) {
458 warningf(true, Tf_ro, vq->name);
463 if (!(vq->flag&INTEGER)) {
465 if ((vq->flag&ALLOC)) {
468 if (s >= vq->val.s &&
469 s <= strnul(vq->val.s)) {
471 "setstr: %s=%s: assigning to self",
475 afree(vq->val.s, vq->areap);
477 vq->flag &= ~(ISSET|ALLOC);
479 if (s && (vq->flag & (UCASEV_AL|LCASEV|LJUST|RJUST)))
480 s = salloc = formatstr(vq, s);
481 if ((vq->flag&EXPORT))
484 strdupx(vq->val.s, s, vq->areap);
489 if (!v_evaluate(vq, s, error_ok, true))
493 if ((vq->flag&SPECIAL))
495 afree(salloc, ATEMP);
499 /* set variable to integer */
501 setint(struct tbl *vq, mksh_ari_t n)
503 if (!(vq->flag&INTEGER)) {
504 vtemp->flag = (ISSET|INTEGER);
506 vtemp->areap = ATEMP;
508 /* setstr can't fail here */
509 setstr(vq, str_val(vtemp), KSH_RETURN_ERROR);
513 if ((vq->flag&SPECIAL))
518 getint(struct tbl *vp, mksh_ari_u *nump, bool arith)
520 mksh_uari_t c, num = 0, base = 10;
522 bool have_base = false, neg = false;
524 if (vp->flag & SPECIAL)
526 /* XXX is it possible for ISSET to be set and val.s to be NULL? */
527 if (!(vp->flag & ISSET) || (!(vp->flag & INTEGER) && vp->val.s == NULL))
529 if (vp->flag & INTEGER) {
533 s = vp->val.s + vp->type;
536 c = (unsigned char)*s++;
537 } while (ctype(c, C_SPACE));
544 c = (unsigned char)*s++;
548 if (c == '0' && arith) {
549 if (ksh_eq(s[0], 'X', 'x')) {
550 /* interpret as hexadecimal */
553 goto getint_c_style_base;
554 } else if (Flag(FPOSIX) && ctype(s[0], C_DIGIT) &&
555 !(vp->flag & ZEROFIL)) {
556 /* interpret as octal (deprecated) */
560 c = (unsigned char)*s++;
566 /* ksh-style base determination */
567 if (have_base || num < 1)
569 if ((base = num) == 1) {
570 /* mksh-specific extension */
574 wc = *(const unsigned char *)s;
575 else if (utf_mbtowc(&wc, s) == (size_t)-1)
576 /* OPTU-8 -> OPTU-16 */
578 * (with a twist: 1#\uEF80 converts
579 * the same as 1#\x80 does, thus is
580 * not round-tripping correctly XXX)
582 wc = 0xEF00 + rtt2asc(*s);
583 nump->u = (mksh_uari_t)wc;
585 } else if (base > 36)
591 if (ctype(c, C_DIGIT))
593 else if (ctype(c, C_UPPER))
594 c = ksh_numuc(c) + 10;
595 else if (ctype(c, C_LOWER))
596 c = ksh_numlc(c) + 10;
601 /* handle overflow as truncation */
602 num = num * base + c;
603 } while ((c = (unsigned char)*s++));
612 * convert variable vq to integer variable, setting its value from vp
613 * (vq and vp may be the same)
616 setint_v(struct tbl *vq, struct tbl *vp, bool arith)
621 if ((base = getint(vp, &num, arith)) == -1)
623 setint_n(vq, num.i, 0);
630 /* convert variable vq to integer variable, setting its value to num */
632 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
634 if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
637 afree(vq->val.s, vq->areap);
642 vq->flag |= ISSET|INTEGER;
643 if (vq->flag&SPECIAL)
648 formatstr(struct tbl *vp, const char *s)
654 olen = (int)utf_mbswidth(s);
656 if (vp->flag & (RJUST|LJUST)) {
658 /* default field width */
664 p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
665 if (vp->flag & (RJUST|LJUST)) {
668 if (vp->flag & RJUST) {
672 qq = utf_skipcols(s, slen, &slen);
674 /* strip trailing spaces (AT&T uses qq[-1] == ' ') */
675 while (qq > s && ctype(qq[-1], C_SPACE)) {
679 if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
684 else if (s[2] == '#')
687 if (vp->u2.field <= n)
694 while (slen > vp->u2.field)
695 slen -= utf_widthadj(s, &s);
696 if (vp->u2.field - slen)
697 memset(p + n, (vp->flag & ZEROFIL) ? '0' : ' ',
698 vp->u2.field - slen);
700 shf_snprintf(p + vp->u2.field - slen,
701 psiz - (vp->u2.field - slen),
704 /* strip leading spaces/zeros */
705 while (ctype(*s, C_SPACE))
707 if (vp->flag & ZEROFIL)
710 shf_snprintf(p, psiz, "%-*.*s",
711 vp->u2.field, vp->u2.field, s);
714 memcpy(p, s, strlen(s) + 1);
716 if (vp->flag & UCASEV_AL) {
718 *q = ksh_toupper(*q);
719 } else if (vp->flag & LCASEV) {
721 *q = ksh_tolower(*q);
728 * make vp->val.s be "name=value" for quick exporting.
731 exportprep(struct tbl *vp, const char *val)
734 char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
735 size_t namelen, vallen;
737 namelen = strlen(vp->name);
738 vallen = strlen(val) + 1;
741 /* since name+val are both in memory this can go unchecked */
742 xp = alloc(namelen + 1 + vallen, vp->areap);
743 memcpy(vp->val.s = xp, vp->name, namelen);
746 /* offset to value */
747 vp->type = xp - vp->val.s;
748 memcpy(xp, val, vallen);
749 afree(op, vp->areap);
753 * lookup variable (according to (set&LOCAL)), set its attributes
754 * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV,
755 * UCASEV_AL), and optionally set its value if an assignment.
758 typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
761 struct tbl *vpbase, *t;
765 bool vappend = false;
766 enum namerefflag new_refflag = SRF_NOP;
768 if ((set & (ARRAY | ASSOC)) == ASSOC) {
769 new_refflag = SRF_ENABLE;
770 set &= ~(ARRAY | ASSOC);
772 if ((clr & (ARRAY | ASSOC)) == ASSOC) {
773 new_refflag = SRF_DISABLE;
774 clr &= ~(ARRAY | ASSOC);
777 /* check for valid variable name, search for value */
778 val = skip_varname(var, false);
780 /* no variable name given */
783 if (ord(*val) == ORD('[')) {
784 if (new_refflag != SRF_NOP)
786 "reference variable can't be an array");
787 len = array_ref_len(val);
791 * IMPORT is only used when the shell starts up and is
792 * setting up its environment. Allow only simple array
793 * references at this time since parameter/command
794 * substitution is performed on the [expression] which
795 * would be a major security hole.
800 for (i = 1; i < len - 1; i++)
801 if (!ctype(val[i], C_DIGIT))
806 if (ord(val[0]) == ORD('=')) {
807 strndupx(tvar, var, val - var, ATEMP);
809 } else if (set & IMPORT) {
810 /* environment invalid variable name or no assignment */
812 } else if (ord(val[0]) == ORD('+') && ord(val[1]) == ORD('=')) {
813 strndupx(tvar, var, val - var, ATEMP);
816 } else if (val[0] != '\0') {
817 /* other invalid variable names (not from environment) */
820 /* just varname with no value part nor equals sign */
821 strdupx(tvar, var, ATEMP);
823 /* handle foo[*] => foo (whole array) mapping for R39b */
825 if (len > 3 && ord(tvar[len - 3]) == ORD('[') &&
826 ord(tvar[len - 2]) == ORD('*') &&
827 ord(tvar[len - 1]) == ORD(']'))
828 tvar[len - 3] = '\0';
831 if (new_refflag == SRF_ENABLE) {
832 const char *qval, *ccp;
834 /* bail out on 'nameref foo+=bar' */
836 errorf("appending not allowed for nameref");
837 /* find value if variable already exists */
838 if ((qval = val) == NULL) {
839 varsearch(e->loc, &vp, tvar, hash(tvar));
844 /* check target value for being a valid variable name */
845 ccp = skip_varname(qval, false);
849 if (!(c = (unsigned char)qval[0]))
851 else if (ctype(c, C_DIGIT) && getn(qval, &c))
852 goto nameref_rhs_checked;
853 else if (qval[1] == '\0') switch (c) {
859 goto nameref_rhs_checked;
862 errorf(Tf_sD_s, var, "empty nameref target");
864 len = (ord(*ccp) == ORD('[')) ? array_ref_len(ccp) : 0;
867 * works for cases "no array", "valid array with
868 * junk after it" and "invalid array"; in the
869 * latter case, len is also 0 and points to '['
871 errorf(Tf_sD_s, qval,
872 "nameref target not a valid parameter name");
875 /* prevent nameref loops */
877 if (!strcmp(qval, tvar))
878 errorf(Tf_sD_s, qval,
879 "expression recurses on parameter");
880 varsearch(e->loc, &vp, qval, hash(qval));
882 if (vp && ((vp->flag & (ARRAY | ASSOC)) == ASSOC))
887 /* prevent typeset from creating a local PATH/ENV/SHELL */
888 if (Flag(FRESTRICTED) && (strcmp(tvar, TPATH) == 0 ||
889 strcmp(tvar, "ENV") == 0 || strcmp(tvar, TSHELL) == 0))
890 errorf(Tf_sD_s, tvar, "restricted");
892 innermost_refflag = new_refflag;
893 vp = (set & LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
895 if (new_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
897 else if (new_refflag == SRF_ENABLE) {
898 if (vp->flag & ARRAY) {
901 /* free up entire array */
902 for (a = vp->u.array; a; ) {
905 if (tmp->flag & ALLOC)
906 afree(tmp->val.s, tmp->areap);
907 afree(tmp, tmp->areap);
915 set &= ~(LOCAL|LOCAL_COPY);
917 vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
920 * only allow export and readonly flag to be set; AT&T ksh
921 * allows any attribute to be changed which means it can be
922 * truncated or modified (-L/-R/-Z/-i)
924 if ((vpbase->flag & RDONLY) &&
925 (val || clr || (set & ~(EXPORT | RDONLY))))
926 /* XXX check calls - is error here ok by POSIX? */
927 errorfx(2, Tf_ro, tvar);
930 /* most calls are with set/clr == 0 */
935 * XXX if x[0] isn't set, there will be problems: need
936 * to have one copy of attributes for arrays...
938 for (t = vpbase; t; t = t->u.array) {
941 char *free_me = NULL;
943 fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
944 ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
945 ((t->flag & INTEGER) && (clr & INTEGER)) ||
946 (!(t->flag & INTEGER) && (set & INTEGER)));
948 if (t->flag & INTEGER) {
952 s = t->val.s + t->type;
953 free_me = (t->flag & ALLOC) ? t->val.s :
958 if (!(t->flag & INTEGER) && (set & INTEGER)) {
962 t->flag = (t->flag | set) & ~clr;
964 * Don't change base if assignment is to be
965 * done, in case assignment fails.
967 if ((set & INTEGER) && base > 0 && (!val || t != vp))
969 if (set & (LJUST|RJUST|ZEROFIL))
972 if (!setstr(t, s, KSH_RETURN_ERROR)) {
974 * Somewhat arbitrary action
975 * here: zap contents of
976 * variable, but keep the flag
980 if (t->flag & INTEGER)
984 afree(t->val.s, t->areap);
985 t->flag &= ~(ISSET|ALLOC);
989 afree(free_me, t->areap);
1000 tval = shf_smprintf(Tf_ss, str_val(vp), val);
1005 if (vp->flag&INTEGER) {
1006 /* do not zero base before assignment */
1007 setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
1008 /* done after assignment to override default */
1012 /* setstr can't fail (readonly check already done) */
1013 setstr(vp, val, KSH_RETURN_ERROR | 0x4);
1018 /* only x[0] is ever exported, so use vpbase */
1019 if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
1021 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
1027 * Unset a variable. The flags can be:
1028 * |1 = tear down entire array
1029 * |2 = keep attributes, only unset content
1032 unset(struct tbl *vp, int flags)
1034 if (vp->flag & ALLOC)
1035 afree(vp->val.s, vp->areap);
1036 if ((vp->flag & ARRAY) && (flags & 1)) {
1037 struct tbl *a, *tmp;
1039 /* free up entire array */
1040 for (a = vp->u.array; a; ) {
1043 if (tmp->flag & ALLOC)
1044 afree(tmp->val.s, tmp->areap);
1045 afree(tmp, tmp->areap);
1050 vp->flag &= ~(ALLOC|ISSET);
1053 /* if foo[0] is being unset, the remainder of the array is kept... */
1054 vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
1055 if (vp->flag & SPECIAL)
1056 /* responsible for 'unspecial'ing var */
1057 unsetspec(vp, true);
1061 * Return a pointer to the first char past a legal variable name
1062 * (returns the argument if there is no legal name, returns a pointer to
1063 * the terminating NUL if whole string is legal).
1066 skip_varname(const char *s, bool aok)
1070 if (s && ctype(*s, C_ALPHX)) {
1073 } while (ctype(*s, C_ALNUX));
1074 if (aok && ord(*s) == ORD('[') && (alen = array_ref_len(s)))
1080 /* Return a pointer to the first character past any legal variable name */
1082 skip_wdvarname(const char *s,
1083 /* skip array de-reference? */
1086 if (s[0] == CHAR && ctype(s[1], C_ALPHX)) {
1089 } while (s[0] == CHAR && ctype(s[1], C_ALNUX));
1090 if (aok && s[0] == CHAR && ord(s[1]) == ORD('[')) {
1091 /* skip possible array de-reference */
1096 while (/* CONSTCOND */ 1) {
1101 if (ord(c) == ORD('['))
1103 else if (ord(c) == ORD(']') && --depth == 0) {
1113 /* Check if coded string s is a variable name */
1115 is_wdvarname(const char *s, bool aok)
1117 const char *p = skip_wdvarname(s, aok);
1119 return (p != s && p[0] == EOS);
1122 /* Check if coded string s is a variable assignment */
1124 is_wdvarassign(const char *s)
1126 const char *p = skip_wdvarname(s, true);
1128 return (p != s && p[0] == CHAR &&
1129 (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1133 * Make the exported environment from the exported names in the dictionary.
1141 struct tbl *vp, **vpp;
1144 for (l = e->loc; l != NULL; l = l->next) {
1146 i = 1 << (l->vars.tshift);
1148 if ((vp = *vpp++) != NULL &&
1149 (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1152 uint32_t h = hash(vp->name);
1154 /* unexport any redefined instances */
1155 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1156 vp2 = ktsearch(&l2->vars, vp->name, h);
1158 vp2->flag &= ~EXPORT;
1160 if ((vp->flag&INTEGER)) {
1161 /* integer to string */
1164 vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1165 /* setstr can't fail here */
1166 setstr(vp, val, KSH_RETURN_ERROR);
1169 /* these special variables are not exported */
1170 if (!strcmp(vp->name, "BEGINLIBPATH") ||
1171 !strcmp(vp->name, "ENDLIBPATH") ||
1172 !strcmp(vp->name, "LIBPATHSTRICT"))
1175 XPput(denv, vp->val.s);
1177 if (l->flags & BF_STOPENV)
1181 return ((char **)XPclose(denv));
1185 * handle special variables with side effects - PATH, SECONDS.
1188 /* Test if name is a special parameter */
1190 special(const char *name)
1194 tp = ktsearch(&specials, name, hash(name));
1195 return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1198 /* Make a variable non-special */
1200 unspecial(const char *name)
1204 tp = ktsearch(&specials, name, hash(name));
1209 static time_t seconds; /* time SECONDS last set */
1210 static mksh_uari_t user_lineno; /* what user set $LINENO to */
1212 /* minimum values from the OS we consider sane, lowered for R53 */
1217 getspec(struct tbl *vp)
1223 switch ((st = special(vp->name))) {
1227 * Do NOT export COLUMNS/LINES. Many applications
1228 * check COLUMNS/LINES before checking ws.ws_col/row,
1229 * so if the app is started with C/L in the environ
1230 * and the window is then resized, the app won't
1231 * see the change cause the environ doesn't change.
1239 num.u = (mksh_uari_t)procpid;
1248 num.u = (mksh_uari_t)current_lineno + user_lineno;
1253 case V_EPOCHREALTIME: {
1254 /* 10(%u) + 1(.) + 6 + NUL */
1257 vp->flag &= ~SPECIAL;
1259 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1260 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1261 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1262 vp->flag |= SPECIAL;
1266 num.i = user_opt.uoptind;
1273 * On start up the value of SECONDS is used before
1274 * it has been set - don't do anything in this case
1275 * (see initcoms[] in main.c).
1277 if (vp->flag & ISSET) {
1279 num.i = tv.tv_sec - seconds;
1284 /* do nothing, do not touch vp at all */
1287 vp->flag &= ~SPECIAL;
1288 setint_n(vp, num.i, 0);
1289 vp->flag |= SPECIAL;
1293 setspec(struct tbl *vp)
1297 int st = special(vp->name);
1304 case V_BEGINLIBPATH:
1307 /* convert backslashes to slashes for convenience */
1308 if (!(vp->flag&INTEGER)) {
1311 if (*s == ORD('\\'))
1321 case V_BEGINLIBPATH:
1323 case V_LIBPATHSTRICT:
1324 setextlibpath(vp->name, str_val(vp));
1327 #if HAVE_PERSISTENT_HISTORY
1329 sethistfile(str_val(vp));
1333 set_ifs(str_val(vp));
1338 strdupx(path, s, APERM);
1339 /* clear tracked aliases */
1342 #ifndef MKSH_NO_CMDLINE_EDITING
1344 x_initterm(str_val(vp));
1348 afree(tmpdir, APERM);
1351 * Use tmpdir iff it is an absolute path, is writable
1352 * and searchable and is a directory...
1358 /* LINTED use of access */
1359 if (mksh_abspath(s) && access(s, W_OK|X_OK) == 0 &&
1360 stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1361 strdupx(tmpdir, s, APERM);
1364 /* common sub-cases */
1367 if (vp->flag & IMPORT) {
1369 unspecial(vp->name);
1370 vp->flag &= ~SPECIAL;
1380 vp->flag &= ~SPECIAL;
1381 if (getint(vp, &num, false) == -1) {
1384 errorf(Tf_sD_sD_s, vp->name, Tbadnum, s);
1387 vp->flag |= SPECIAL;
1389 #ifdef MKSH_EARLY_LOCALE_TRACKING
1397 /* do nothing, do not touch vp at all */
1401 /* process the singular parts of the common cases */
1405 if (num.i >= MIN_COLS)
1412 /* The -1 is because line numbering starts at 1. */
1413 user_lineno = num.u - (mksh_uari_t)current_lineno - 1;
1416 if (num.i >= MIN_LINS)
1420 getopts_reset((int)num.i);
1424 * mksh R39d+ no longer has the traditional repeatability
1425 * of $RANDOM sequences, but always retains state
1427 rndset((unsigned long)num.u);
1434 seconds = tv.tv_sec - num.i;
1438 ksh_tmout = num.i >= 0 ? num.i : 0;
1444 unsetspec(struct tbl *vp, bool dounset)
1447 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1448 * meaning, but OPTARG does not (still set by getopts) and _ is
1449 * also still set in various places. Don't know what AT&T does
1450 * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1451 * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1454 switch (special(vp->name)) {
1456 case V_BEGINLIBPATH:
1458 case V_LIBPATHSTRICT:
1459 setextlibpath(vp->name, "");
1462 #if HAVE_PERSISTENT_HISTORY
1472 strdupx(path, def_path, APERM);
1473 /* clear tracked aliases */
1476 #ifndef MKSH_NO_CMDLINE_EDITING
1482 /* should not become unspecial */
1484 afree(tmpdir, APERM);
1492 /* AT&T ksh leaves previous value in place */
1493 unspecial(vp->name);
1495 #ifdef MKSH_EARLY_LOCALE_TRACKING
1502 /* should not become unspecial, but allow unsetting */
1506 unspecial(vp->name);
1512 * Search for (and possibly create) a table entry starting with
1513 * vp, indexed by val.
1516 arraysearch(struct tbl *vp, uint32_t val)
1518 struct tbl *prev, *curr, *news;
1521 vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
1522 /* the table entry is always [0] */
1527 while (curr && curr->ua.index < val) {
1529 curr = curr->u.array;
1531 if (curr && curr->ua.index == val) {
1532 if (curr->flag&ISSET)
1538 len = strlen(vp->name);
1539 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1540 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1541 memcpy(news->name, vp->name, len);
1543 news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1544 news->type = vp->type;
1545 news->areap = vp->areap;
1546 news->u2.field = vp->u2.field;
1547 news->ua.index = val;
1550 /* not reusing old array entry */
1551 prev->u.array = news;
1552 news->u.array = curr;
1558 * Return the length of an array reference (eg, [1+2]) - cp is assumed
1559 * to point to the open bracket. Returns 0 if there is no matching
1562 * XXX this should parse the actual arithmetic syntax
1565 array_ref_len(const char *cp)
1571 while ((c = *s++) && (ord(c) != ORD(']') || --depth))
1572 if (ord(c) == ORD('['))
1580 * Make a copy of the base of an array name
1583 arrayname(const char *str)
1588 if (!(p = cstrchr(str, '[')))
1589 /* Shouldn't happen, but why worry? */
1590 strdupx(rv, str, ATEMP);
1592 strndupx(rv, str, p - str, ATEMP);
1597 /* set (or overwrite, if reset) the array variable var to the values in vals */
1599 set_array(const char *var, bool reset, const char **vals)
1601 struct tbl *vp, *vq;
1602 mksh_uari_t i = 0, j = 0;
1603 const char *ccp = var;
1607 /* to get local array, use "local foo; set -A foo" */
1609 if (n > 0 && var[n - 1] == '+') {
1612 strndupx(cp, var, n - 1, ATEMP);
1617 /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1618 if ((vp->flag&RDONLY))
1619 errorfx(2, Tf_ro, ccp);
1620 /* This code is quite non-optimal */
1622 /* trash existing values and attributes */
1624 /* allocate-by-access the [0] element to keep in scope */
1626 /* honour set -o allexport */
1628 typeset(ccp, EXPORT, 0, 0, 0);
1631 * TODO: would be nice for assignment to completely succeed or
1632 * completely fail. Only really effects integer arrays:
1633 * evaluation of some of vals[] may fail...
1636 /* find out where to set when appending */
1637 for (vq = vp; vq; vq = vq->u.array) {
1638 if (!(vq->flag & ISSET))
1640 if (arrayindex(vq) >= j)
1641 j = arrayindex(vq) + 1;
1645 while ((ccp = vals[i])) {
1646 #if 0 /* temporarily taken out due to regression */
1647 if (ord(*ccp) == ORD('[')) {
1651 if (ord(*ccp) == ORD(']') && --level == 0)
1653 if (ord(*ccp) == ORD('['))
1657 if (ord(*ccp) == ORD(']') && level == 0 &&
1658 ord(ccp[1]) == ORD('=')) {
1659 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1661 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1662 KSH_UNWIND_ERROR, true);
1670 vq = arraysearch(vp, j);
1671 /* would be nice to deal with errors here... (see above) */
1672 setstr(vq, ccp, KSH_RETURN_ERROR);
1686 BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
1689 /* check if window size has changed */
1690 if (tty_init_fd() < 2) {
1693 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1702 /* bounds check for sane values, use defaults otherwise */
1703 if (x_cols < MIN_COLS)
1705 if (x_lins < MIN_LINS)
1716 register uint32_t h;
1719 BAFHUpdateStr_reg(h, s);
1725 chvt_rndsetup(const void *bp, size_t sz)
1727 register uint32_t h;
1729 /* use LCG as seed but try to get them to deviate immediately */
1733 /* variation through pid, ppid, and the works */
1734 BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
1735 /* some variation, some possibly entropy, depending on OE */
1736 BAFHUpdateMem_reg(h, bp, sz);
1737 /* mix them all up */
1747 * this is the same Linear Congruential PRNG as Borland
1748 * C/C++ allegedly uses in its built-in rand() function
1750 return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1754 rndset(unsigned long v)
1756 register uint32_t h;
1757 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1758 register uint32_t t;
1768 /* clear the allocated space, for valgrind and to avoid UB */
1769 memset(&z, 0, sizeof(z));
1773 BAFHUpdateMem_reg(h, &v, sizeof(v));
1778 z.r = (short)rndget();
1780 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1783 z.qh = (t & 0xFFFF8000) | rndget();
1784 lcg_state = (t << 15) | rndget();
1786 * either we have very chap entropy get and push available,
1787 * with malloc() pulling in this code already anyway, or the
1788 * user requested us to use the old functions
1791 BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
1794 #if defined(arc4random_pushb_fast)
1795 arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1796 lcg_state = arc4random();
1798 lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1800 BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
1805 BAFHUpdateMem_reg(h, &z, sizeof(z));
1811 rndpush(const void *s)
1813 register uint32_t h = qh_state;
1815 BAFHUpdateStr_reg(h, s);
1816 BAFHUpdateOctet_reg(h, 0);
1820 /* record last glob match */
1822 record_match(const char *istr)
1826 vp = local("KSH_MATCH", false);
1828 vp->flag = DEFINED | RDONLY;
1829 setstr(vp, istr, 0x4);
1832 /* typeset, global(deprecated), export, and readonly */
1834 c_typeset(const char **wp)
1836 struct tbl *vp, **p;
1837 uint32_t fset = 0, fclr = 0, flag;
1838 int thing = 0, field = 0, base = 0, i;
1841 const char *fieldstr = NULL, *basestr = NULL;
1842 bool localv = false, func = false, pflag = false, istset = true;
1843 enum namerefflag new_refflag = SRF_NOP;
1861 /* called with 'typeset -' */
1870 /* see comment below regarding possible opions */
1871 opts = istset ? "L#R#UZ#afgi#lnprtux" : "p";
1873 builtin_opt.flags |= GF_PLUSOPT;
1875 * AT&T ksh seems to have 0-9 as options which are multiplied
1876 * to get a number that is used with -L, -R, -Z or -i (eg, -1R2
1877 * sets right justify in a field of 12). This allows options
1878 * to be grouped in an order (eg, -Lu12), but disallows -i8 -L3 and
1879 * does not allow the number to be specified as a separate argument
1880 * Here, the number must follow the RLZi option, but is optional
1881 * (see the # kludge in ksh_getopt()).
1883 while ((i = ksh_getopt(wp, &builtin_opt, opts)) != -1) {
1888 fieldstr = builtin_opt.optarg;
1892 fieldstr = builtin_opt.optarg;
1896 * AT&T ksh uses u, but this conflicts with
1897 * upper/lower case. If this option is changed,
1898 * need to change the -U below as well
1904 fieldstr = builtin_opt.optarg;
1908 * this is supposed to set (-a) or unset (+a) the
1909 * indexed array attribute; it does nothing on an
1910 * existing regular string or indexed array though
1917 localv = (builtin_opt.info & GI_PLUS) ? true : false;
1921 basestr = builtin_opt.optarg;
1927 new_refflag = (builtin_opt.info & GI_PLUS) ?
1928 SRF_DISABLE : SRF_ENABLE;
1930 /* export, readonly: POSIX -p flag */
1932 /* typeset: show values as well */
1944 /* upper case / autoload */
1953 if (builtin_opt.info & GI_PLUS) {
1964 if (fieldstr && !getn(fieldstr, &field)) {
1965 bi_errorf(Tf_sD_s, Tbadnum, fieldstr);
1969 if (!getn(basestr, &base)) {
1970 bi_errorf(Tf_sD_s, "bad integer base", basestr);
1973 if (base < 1 || base > 36)
1977 if (!(builtin_opt.info & GI_MINUSMINUS) && wp[builtin_opt.optind] &&
1978 (wp[builtin_opt.optind][0] == '-' ||
1979 wp[builtin_opt.optind][0] == '+') &&
1980 wp[builtin_opt.optind][1] == '\0') {
1981 thing = wp[builtin_opt.optind][0];
1982 builtin_opt.optind++;
1985 if (func && (((fset|fclr) & ~(TRACE|UCASEV_AL|EXPORT)) ||
1986 new_refflag != SRF_NOP)) {
1987 bi_errorf("only -t, -u and -x options may be used with -f");
1990 if (wp[builtin_opt.optind]) {
1992 * Take care of exclusions.
1993 * At this point, flags in fset are cleared in fclr and vice
1994 * versa. This property should be preserved.
1997 /* LCASEV has priority over UCASEV_AL */
2000 /* LJUST has priority over RJUST */
2002 if ((fset & (ZEROFIL|LJUST)) == ZEROFIL) {
2003 /* -Z implies -ZR */
2008 * Setting these attributes clears the others, unless they
2009 * are also set in this command
2011 if ((fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL | LCASEV |
2012 INTEGER | INT_U | INT_L)) || new_refflag != SRF_NOP)
2013 fclr |= ~fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL |
2014 LCASEV | INTEGER | INT_U | INT_L);
2016 if (new_refflag != SRF_NOP) {
2017 fclr &= ~(ARRAY | ASSOC);
2018 fset &= ~(ARRAY | ASSOC);
2021 if (new_refflag == SRF_DISABLE)
2025 /* set variables and attributes */
2026 if (wp[builtin_opt.optind] &&
2027 /* not "typeset -p varname" */
2028 !(!func && pflag && !(fset | fclr))) {
2032 if (localv && !func)
2034 for (i = builtin_opt.optind; wp[i]; i++) {
2036 f = findfunc(wp[i], hash(wp[i]),
2037 tobool(fset & UCASEV_AL));
2039 /* AT&T ksh does ++rv: bogus */
2047 fpFUNCTf(shl_stdout, 0,
2048 tobool(f->flag & FKSH),
2050 shf_putc('\n', shl_stdout);
2052 } else if (!typeset(wp[i], fset, fclr, field, base)) {
2053 bi_errorf(Tf_sD_s, wp[i], Tnot_ident);
2060 /* list variables and attributes */
2062 /* no difference at this point.. */
2065 for (l = e->loc; l; l = l->next) {
2066 for (p = ktsort(&l->funs); (vp = *p++); ) {
2067 if (flag && (vp->flag & flag) == 0)
2070 fpFUNCTf(shl_stdout, 0,
2071 tobool(vp->flag & FKSH),
2072 vp->name, vp->val.t);
2074 shf_puts(vp->name, shl_stdout);
2075 shf_putc('\n', shl_stdout);
2078 } else if (wp[builtin_opt.optind]) {
2079 for (i = builtin_opt.optind; wp[i]; i++) {
2080 vp = isglobal(wp[i], false);
2081 c_typeset_vardump(vp, flag, thing,
2082 last_lookup_was_array ? 4 : 0, pflag, istset);
2085 c_typeset_vardump_recursive(e->loc, flag, thing, pflag, istset);
2090 c_typeset_vardump_recursive(struct block *l, uint32_t flag, int thing,
2091 bool pflag, bool istset)
2093 struct tbl **blockvars, *vp;
2096 c_typeset_vardump_recursive(l->next, flag, thing, pflag, istset);
2097 blockvars = ktsort(&l->vars);
2098 while ((vp = *blockvars++))
2099 c_typeset_vardump(vp, flag, thing, 0, pflag, istset);
2100 /*XXX doesn’t this leak? */
2104 c_typeset_vardump(struct tbl *vp, uint32_t flag, int thing, int any_set,
2105 bool pflag, bool istset)
2114 * See if the parameter is set (for arrays, if any
2117 for (tvp = vp; tvp; tvp = tvp->u.array)
2118 if (tvp->flag & ISSET) {
2124 * Check attributes - note that all array elements
2125 * have (should have?) the same attributes, so checking
2126 * the first is sufficient.
2128 * Report an unset param only if the user has
2129 * explicitly given it some attribute (like export);
2130 * otherwise, after "echo $FOO", we would report FOO...
2132 if (!any_set && !(vp->flag & USERATTRIB))
2134 if (flag && (vp->flag & flag) == 0)
2136 if (!(vp->flag & ARRAY))
2137 /* optimise later conditionals */
2141 * Ignore array elements that aren't set unless there
2142 * are no set elements, in which case the first is
2145 if (any_set && !(vp->flag & ISSET))
2148 if (!thing && !flag) {
2150 shprintf(Tf_s_s_sN, Tset, "-A", vp->name);
2154 * AT&T ksh prints things like export, integer,
2155 * leftadj, zerofill, etc., but POSIX says must
2156 * be suitable for re-entry...
2158 shprintf(Tf_s_s, Ttypeset, "");
2159 if (((vp->flag & (ARRAY | ASSOC)) == ASSOC))
2160 shprintf(Tf__c_, 'n');
2161 if ((vp->flag & INTEGER))
2162 shprintf(Tf__c_, 'i');
2163 if ((vp->flag & EXPORT))
2164 shprintf(Tf__c_, 'x');
2165 if ((vp->flag & RDONLY))
2166 shprintf(Tf__c_, 'r');
2167 if ((vp->flag & TRACE))
2168 shprintf(Tf__c_, 't');
2169 if ((vp->flag & LJUST))
2170 shprintf("-L%d ", vp->u2.field);
2171 if ((vp->flag & RJUST))
2172 shprintf("-R%d ", vp->u2.field);
2173 if ((vp->flag & ZEROFIL))
2174 shprintf(Tf__c_, 'Z');
2175 if ((vp->flag & LCASEV))
2176 shprintf(Tf__c_, 'l');
2177 if ((vp->flag & UCASEV_AL))
2178 shprintf(Tf__c_, 'u');
2179 if ((vp->flag & INT_U))
2180 shprintf(Tf__c_, 'U');
2182 shprintf(Tf_s_s, istset ? Ttypeset :
2183 (flag & EXPORT) ? Texport : Treadonly, "");
2186 shprintf("%s[%lu]", vp->name, arrayindex(vp));
2188 shf_puts(vp->name, shl_stdout);
2189 if ((!thing && !flag && pflag) ||
2190 (thing == '-' && (vp->flag & ISSET))) {
2192 shf_putc('=', shl_stdout);
2193 /* AT&T ksh can't have justified integers... */
2194 if ((vp->flag & (INTEGER | LJUST | RJUST)) == INTEGER)
2195 shf_puts(s, shl_stdout);
2197 print_value_quoted(shl_stdout, s);
2199 shf_putc('\n', shl_stdout);
2202 * Only report first 'element' of an array with
2207 } while (!(any_set & 4) && (vp = vp->u.array));