1 /* $OpenBSD: var.c,v 1.35 2013/04/05 01:31:30 tedu Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
6 * Thorsten Glaser <tg@mirbsd.org>
8 * Provided that these terms and disclaimer and all copyright notices
9 * are retained or reproduced in an accompanying document, permission
10 * is granted to deal in this work without restriction, including un-
11 * limited rights to use, publicly perform, distribute, sell, modify,
12 * merge, give away, or sublicence.
14 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15 * the utmost extent permitted by applicable law, neither express nor
16 * implied; without malicious intent or gross negligence. In no event
17 * may a licensor, author or contributor be held liable for indirect,
18 * direct, other damage, loss, or other issues arising in any way out
19 * of dealing in the work, even if advised of the possibility of such
20 * damage or existence of a defect, except proven that it results out
21 * of said person's immediate fault when using the work as intended.
26 #if defined(__OpenBSD__)
27 #include <sys/sysctl.h>
30 __RCSID("$MirOS: src/bin/mksh/var.c,v 1.173 2013/05/31 22:47:14 tg Exp $");
35 * WARNING: unreadable code, needs a rewrite
37 * if (flag&INTEGER), val.i contains integer value, and type contains base.
38 * otherwise, (val.s + type) contains string value.
39 * if (flag&EXPORT), val.s contains "name=value" for E-Z exporting.
42 static struct table specials;
43 static uint32_t lcg_state = 5381;
45 static char *formatstr(struct tbl *, const char *);
46 static void exportprep(struct tbl *, const char *);
47 static int special(const char *);
48 static void unspecial(const char *);
49 static void getspec(struct tbl *);
50 static void setspec(struct tbl *);
51 static void unsetspec(struct tbl *);
52 static int getint(struct tbl *, mksh_ari_u *, bool);
53 static const char *array_index_calc(const char *, bool *, uint32_t *);
56 * create a new block for function calls and simple commands
57 * assume caller has allocated and set up e->loc
63 static const char *empty[] = { null };
65 l = alloc(sizeof(struct block), ATEMP);
67 /* TODO: could use e->area (l->area => l->areap) */
73 l->argc = e->loc->argc;
74 l->argv = e->loc->argv;
76 l->exit = l->error = NULL;
77 ktinit(&l->area, &l->vars, 0);
78 ktinit(&l->area, &l->funs, 0);
84 * pop a block handling special variables
90 struct block *l = e->loc;
91 struct tbl *vp, **vpp = l->vars.tbls, *vq;
96 i = 1 << (l->vars.tshift);
98 if ((vp = *vpp++) != NULL && (vp->flag&SPECIAL)) {
99 if ((vq = global(vp->name))->flag & ISSET)
104 if (l->flags & BF_DOGETOPTS)
105 user_opt = l->getopts_state;
110 /* called by main() to initialise variable data structures */
111 #define VARSPEC_DEFNS
112 #include "var_spec.h"
115 #define VARSPEC_ENUMS
116 #include "var_spec.h"
120 /* this is biased with -1 relative to VARSPEC_ENUMS */
121 static const char * const initvar_names[] = {
122 #define VARSPEC_ITEMS
123 #include "var_spec.h"
132 ktinit(APERM, &specials,
133 /* currently 14 specials: 75% of 32 = 2^5 */
135 while (i < V_MAX - 1) {
136 tp = ktenter(&specials, initvar_names[i],
137 hash(initvar_names[i]));
138 tp->flag = DEFINED|ISSET;
143 /* common code for several functions below and c_typeset() */
145 varsearch(struct block *l, struct tbl **vpp, const char *vn, uint32_t h)
147 register struct tbl *vp;
151 if ((vp = ktsearch(&l->vars, vn, h)) != NULL)
153 if (l->next != NULL) {
165 * Used to calculate an array index for global()/local(). Sets *arrayp
166 * to true if this is an array, sets *valp to the array index, returns
167 * the basename of the array.
170 array_index_calc(const char *n, bool *arrayp, uint32_t *valp)
178 p = skip_varname(n, false);
179 if (set_refflag == SRF_NOP && (p != n) && ksh_isalphx(n[0])) {
183 strndupx(vn, n, p - n, ATEMP);
184 /* check if this is a reference */
185 varsearch(e->loc, &vp, vn, hash(vn));
187 if (vp && (vp->flag & (DEFINED|ASSOC|ARRAY)) ==
192 cp = shf_smprintf("%s%s", str_val(vp), p);
199 if (p != n && *p == '[' && (len = array_ref_len(p))) {
203 /* calculate the value of the subscript */
205 strndupx(tmp, p + 1, len - 2, ATEMP);
206 sub = substitute(tmp, 0);
208 strndupx(n, n, p - n, ATEMP);
209 evaluate(sub, &rval, KSH_UNWIND_ERROR, true);
210 *valp = (uint32_t)rval;
217 * Search for variable, if not found create globally.
220 global(const char *n)
222 struct block *l = e->loc;
228 /* Check to see if this is an array */
229 n = array_index_calc(n, &array, &val);
232 if (!ksh_isalphx(c)) {
234 errorf("bad substitution");
240 if (ksh_isdigit(c)) {
241 for (c = 0; ksh_isdigit(*n); n++)
244 /* setstr can't fail here */
245 setstr(vp, l->argv[c], KSH_RETURN_ERROR);
252 vp->flag |= ISSET|INTEGER;
258 /* if no job, expand to nothing */
259 if ((vp->val.i = j_async()) == 0)
260 vp->flag &= ~(ISSET|INTEGER);
263 vp->val.i = exstat & 0xFF;
269 vp->flag &= ~INTEGER;
270 vp->val.s = getoptions();
273 vp->flag &= ~(ISSET|INTEGER);
277 l = varsearch(e->loc, &vp, n, h);
279 return (array ? arraysearch(vp, val) : vp);
280 vp = ktenter(&l->vars, n, h);
282 vp = arraysearch(vp, val);
290 * Search for local variable, if not found create locally.
293 local(const char *n, bool copy)
295 struct block *l = e->loc;
300 /* check to see if this is an array */
301 n = array_index_calc(n, &array, &val);
304 if (!ksh_isalphx(*n)) {
306 vp->flag = DEFINED|RDONLY;
311 vp = ktenter(&l->vars, n, h);
312 if (copy && !(vp->flag & DEFINED)) {
315 varsearch(l->next, &vq, n, h);
317 vp->flag |= vq->flag &
318 (EXPORT | INTEGER | RDONLY | LJUST | RJUST |
319 ZEROFIL | LCASEV | UCASEV_AL | INT_U | INT_L);
320 if (vq->flag & INTEGER)
322 vp->u2.field = vq->u2.field;
326 vp = arraysearch(vp, val);
333 /* get variable string value */
335 str_val(struct tbl *vp)
339 if ((vp->flag&SPECIAL))
341 if (!(vp->flag&ISSET))
342 /* special to dollar() */
344 else if (!(vp->flag&INTEGER))
346 s = vp->val.s + vp->type;
352 * worst case number length is when base == 2:
353 * 1 (minus) + 2 (base, up to 36) + 1 ('#') +
354 * number of bits in the mksh_uari_t + 1 (NUL)
356 char strbuf[1 + 2 + 1 + 8 * sizeof(mksh_uari_t) + 1];
357 const char *digits = (vp->flag & UCASEV_AL) ?
358 digits_uc : digits_lc;
360 s = strbuf + sizeof(strbuf);
361 if (vp->flag & INT_U)
364 n = (vp->val.i < 0) ? -vp->val.u : vp->val.u;
365 base = (vp->type == 0) ? 10U : (unsigned int)vp->type;
367 if (base == 1 && n == 0)
374 if (!UTFMODE || ((n & 0xFF80) == 0xEF80))
375 /* OPTU-16 -> raw octet */
378 sz = utf_wctomb(s + 2, n);
383 *--s = digits[n % base];
388 *--s = digits[base % 10];
390 *--s = digits[base / 10];
392 if (!(vp->flag & INT_U) && vp->val.i < 0)
395 if (vp->flag & (RJUST|LJUST))
396 /* case already dealt with */
397 s = formatstr(vp, s);
399 strdupx(s, s, ATEMP);
404 /* set variable to string value */
406 setstr(struct tbl *vq, const char *s, int error_ok)
409 bool no_ro_check = tobool(error_ok & 0x4);
412 if ((vq->flag & RDONLY) && !no_ro_check) {
413 warningf(true, "read-only: %s", vq->name);
418 if (!(vq->flag&INTEGER)) {
420 if ((vq->flag&ALLOC)) {
423 if (s >= vq->val.s &&
424 s <= vq->val.s + strlen(vq->val.s)) {
426 "setstr: %s=%s: assigning to self",
430 afree(vq->val.s, vq->areap);
432 vq->flag &= ~(ISSET|ALLOC);
434 if (s && (vq->flag & (UCASEV_AL|LCASEV|LJUST|RJUST)))
435 s = salloc = formatstr(vq, s);
436 if ((vq->flag&EXPORT))
439 strdupx(vq->val.s, s, vq->areap);
444 if (!v_evaluate(vq, s, error_ok, true))
448 if ((vq->flag&SPECIAL))
450 afree(salloc, ATEMP);
454 /* set variable to integer */
456 setint(struct tbl *vq, mksh_ari_t n)
458 if (!(vq->flag&INTEGER)) {
459 struct tbl *vp = &vtemp;
460 vp->flag = (ISSET|INTEGER);
464 /* setstr can't fail here */
465 setstr(vq, str_val(vp), KSH_RETURN_ERROR);
469 if ((vq->flag&SPECIAL))
474 getint(struct tbl *vp, mksh_ari_u *nump, bool arith)
476 mksh_uari_t c, num, base;
478 bool have_base = false, neg = false;
480 if (vp->flag&SPECIAL)
482 /* XXX is it possible for ISSET to be set and val.s to be NULL? */
483 if (!(vp->flag&ISSET) || (!(vp->flag&INTEGER) && vp->val.s == NULL))
485 if (vp->flag&INTEGER) {
489 s = vp->val.s + vp->type;
492 if (arith && s[0] == '0' && (s[1] | 0x20) == 'x') {
497 if (Flag(FPOSIX) && arith && s[0] == '0' && ksh_isdigit(s[1]) &&
498 !(vp->flag & ZEROFIL)) {
499 /* interpret as octal (deprecated) */
507 } else if (c == '#') {
508 if (have_base || num < 1 || num > 36)
510 if ((base = num) == 1) {
514 wc = *(const unsigned char *)s;
515 else if (utf_mbtowc(&wc, s) == (size_t)-1)
516 /* OPTU-8 -> OPTU-16 */
518 * (with a twist: 1#\uEF80 converts
519 * the same as 1#\x80 does, thus is
520 * not round-tripping correctly XXX)
522 wc = 0xEF00 + *(const unsigned char *)s;
523 nump->u = (mksh_uari_t)wc;
529 } else if (ksh_isdigit(c))
531 else if (ksh_islower(c))
533 else if (ksh_isupper(c))
539 num = num * base + c;
548 * convert variable vq to integer variable, setting its value from vp
549 * (vq and vp may be the same)
552 setint_v(struct tbl *vq, struct tbl *vp, bool arith)
557 if ((base = getint(vp, &num, arith)) == -1)
559 setint_n(vq, num.i, 0);
566 /* convert variable vq to integer variable, setting its value to num */
568 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
570 if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
573 afree(vq->val.s, vq->areap);
578 vq->flag |= ISSET|INTEGER;
579 if (vq->flag&SPECIAL)
584 formatstr(struct tbl *vp, const char *s)
590 olen = (int)utf_mbswidth(s);
592 if (vp->flag & (RJUST|LJUST)) {
594 /* default field width */
600 p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
601 if (vp->flag & (RJUST|LJUST)) {
602 int slen = olen, i = 0;
604 if (vp->flag & RJUST) {
609 i += utf_widthadj(qq, &qq);
610 /* strip trailing spaces (AT&T uses qq[-1] == ' ') */
611 while (qq > s && ksh_isspace(qq[-1])) {
615 if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
620 else if (s[2] == '#')
623 if (vp->u2.field <= n)
630 while (slen > vp->u2.field)
631 slen -= utf_widthadj(s, &s);
632 if (vp->u2.field - slen)
633 memset(p + n, (vp->flag & ZEROFIL) ? '0' : ' ',
634 vp->u2.field - slen);
636 shf_snprintf(p + vp->u2.field - slen,
637 psiz - (vp->u2.field - slen),
640 /* strip leading spaces/zeros */
641 while (ksh_isspace(*s))
643 if (vp->flag & ZEROFIL)
646 shf_snprintf(p, nlen + 1, "%-*.*s",
647 vp->u2.field, vp->u2.field, s);
650 memcpy(p, s, strlen(s) + 1);
652 if (vp->flag & UCASEV_AL) {
654 *q = ksh_toupper(*q);
655 } else if (vp->flag & LCASEV) {
657 *q = ksh_tolower(*q);
664 * make vp->val.s be "name=value" for quick exporting.
667 exportprep(struct tbl *vp, const char *val)
670 char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
671 size_t namelen, vallen;
673 mkssert(val != NULL);
675 namelen = strlen(vp->name);
676 vallen = strlen(val) + 1;
679 /* since name+val are both in memory this can go unchecked */
680 xp = alloc(namelen + 1 + vallen, vp->areap);
681 memcpy(vp->val.s = xp, vp->name, namelen);
684 /* offset to value */
685 vp->type = xp - vp->val.s;
686 memcpy(xp, val, vallen);
688 afree(op, vp->areap);
692 * lookup variable (according to (set&LOCAL)), set its attributes
693 * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV,
694 * UCASEV_AL), and optionally set its value if an assignment.
697 typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
700 struct tbl *vpbase, *t;
704 bool vappend = false;
706 /* check for valid variable name, search for value */
707 val = skip_varname(var, false);
709 /* no variable name given */
713 if (set_refflag != SRF_NOP)
714 errorf("%s: %s", var,
715 "reference variable can't be an array");
716 len = array_ref_len(val);
720 * IMPORT is only used when the shell starts up and is
721 * setting up its environment. Allow only simple array
722 * references at this time since parameter/command
723 * substitution is performed on the [expression] which
724 * would be a major security hole.
729 for (i = 1; i < len - 1; i++)
730 if (!ksh_isdigit(val[i]))
735 if (val[0] == '=' || (val[0] == '+' && val[1] == '=')) {
736 strndupx(tvar, var, val - var, ATEMP);
741 } else if ((val[0] != '\0') || (set & IMPORT)) {
743 * must have a = when setting a variable by importing
744 * the original environment, otherwise be empty; we
745 * also end up here when a variable name was invalid
749 /* just varname with no value part nor equals sign */
750 strdupx(tvar, var, ATEMP);
752 /* handle foo[*] => foo (whole array) mapping for R39b */
754 if (len > 3 && tvar[len - 3] == '[' && tvar[len - 2] == '*' &&
755 tvar[len - 1] == ']')
756 tvar[len - 3] = '\0';
759 if (set_refflag == SRF_ENABLE) {
762 /* bail out on 'nameref foo+=bar' */
765 /* find value if variable already exists */
766 if ((qval = val) == NULL) {
767 varsearch(e->loc, &vp, tvar, hash(tvar));
771 /* prevent nameref loops */
773 if (!strcmp(qval, tvar))
774 errorf("%s: %s", qval,
775 "expression recurses on parameter");
776 varsearch(e->loc, &vp, qval, hash(qval));
778 if (vp && ((vp->flag & (ARRAY|ASSOC)) == ASSOC))
783 /* prevent typeset from creating a local PATH/ENV/SHELL */
784 if (Flag(FRESTRICTED) && (strcmp(tvar, "PATH") == 0 ||
785 strcmp(tvar, "ENV") == 0 || strcmp(tvar, "SHELL") == 0))
786 errorf("%s: %s", tvar, "restricted");
788 vp = (set&LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
790 if (set_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
792 else if (set_refflag == SRF_ENABLE) {
793 if (vp->flag & ARRAY) {
796 /* free up entire array */
797 for (a = vp->u.array; a; ) {
800 if (tmp->flag & ALLOC)
801 afree(tmp->val.s, tmp->areap);
802 afree(tmp, tmp->areap);
810 set &= ~(LOCAL|LOCAL_COPY);
812 vpbase = (vp->flag & ARRAY) ? global(arrayname(var)) : vp;
815 * only allow export flag to be set; AT&T ksh allows any
816 * attribute to be changed which means it can be truncated or
817 * modified (-L/-R/-Z/-i)
819 if ((vpbase->flag&RDONLY) &&
820 (val || clr || (set & ~EXPORT)))
821 /* XXX check calls - is error here ok by POSIX? */
822 errorfx(2, "read-only: %s", tvar);
825 /* most calls are with set/clr == 0 */
830 * XXX if x[0] isn't set, there will be problems: need
831 * to have one copy of attributes for arrays...
833 for (t = vpbase; t; t = t->u.array) {
836 char *free_me = NULL;
838 fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
839 ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
840 ((t->flag & INTEGER) && (clr & INTEGER)) ||
841 (!(t->flag & INTEGER) && (set & INTEGER)));
843 if (t->flag & INTEGER) {
847 s = t->val.s + t->type;
848 free_me = (t->flag & ALLOC) ? t->val.s :
853 if (!(t->flag & INTEGER) && (set & INTEGER)) {
857 t->flag = (t->flag | set) & ~clr;
859 * Don't change base if assignment is to be
860 * done, in case assignment fails.
862 if ((set & INTEGER) && base > 0 && (!val || t != vp))
864 if (set & (LJUST|RJUST|ZEROFIL))
867 if (!setstr(t, s, KSH_RETURN_ERROR)) {
869 * Somewhat arbitrary action
870 * here: zap contents of
871 * variable, but keep the flag
875 if (t->flag & INTEGER)
879 afree(t->val.s, t->areap);
880 t->flag &= ~(ISSET|ALLOC);
885 afree(free_me, t->areap);
896 tval = shf_smprintf("%s%s", str_val(vp), val);
901 if (vp->flag&INTEGER) {
902 /* do not zero base before assignment */
903 setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
904 /* done after assignment to override default */
908 /* setstr can't fail (readonly check already done) */
909 setstr(vp, val, KSH_RETURN_ERROR | 0x4);
915 /* only x[0] is ever exported, so use vpbase */
916 if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
918 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
924 * Unset a variable. The flags can be:
925 * |1 = tear down entire array
926 * |2 = keep attributes, only unset content
929 unset(struct tbl *vp, int flags)
931 if (vp->flag & ALLOC)
932 afree(vp->val.s, vp->areap);
933 if ((vp->flag & ARRAY) && (flags & 1)) {
936 /* free up entire array */
937 for (a = vp->u.array; a; ) {
940 if (tmp->flag & ALLOC)
941 afree(tmp->val.s, tmp->areap);
942 afree(tmp, tmp->areap);
947 vp->flag &= ~(ALLOC|ISSET);
950 /* if foo[0] is being unset, the remainder of the array is kept... */
951 vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
952 if (vp->flag & SPECIAL)
953 /* responsible for 'unspecial'ing var */
958 * Return a pointer to the first char past a legal variable name
959 * (returns the argument if there is no legal name, returns a pointer to
960 * the terminating NUL if whole string is legal).
963 skip_varname(const char *s, int aok)
967 if (s && ksh_isalphx(*s)) {
968 while (*++s && ksh_isalnux(*s))
970 if (aok && *s == '[' && (alen = array_ref_len(s)))
976 /* Return a pointer to the first character past any legal variable name */
978 skip_wdvarname(const char *s,
979 /* skip array de-reference? */
982 if (s[0] == CHAR && ksh_isalphx(s[1])) {
985 } while (s[0] == CHAR && ksh_isalnux(s[1]));
986 if (aok && s[0] == CHAR && s[1] == '[') {
987 /* skip possible array de-reference */
992 while (/* CONSTCOND */ 1) {
999 else if (c == ']' && --depth == 0) {
1009 /* Check if coded string s is a variable name */
1011 is_wdvarname(const char *s, bool aok)
1013 const char *p = skip_wdvarname(s, aok);
1015 return (p != s && p[0] == EOS);
1018 /* Check if coded string s is a variable assignment */
1020 is_wdvarassign(const char *s)
1022 const char *p = skip_wdvarname(s, true);
1024 return (p != s && p[0] == CHAR &&
1025 (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1029 * Make the exported environment from the exported names in the dictionary.
1037 struct tbl *vp, **vpp;
1040 for (l = e->loc; l != NULL; l = l->next) {
1042 i = 1 << (l->vars.tshift);
1044 if ((vp = *vpp++) != NULL &&
1045 (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1048 uint32_t h = hash(vp->name);
1050 /* unexport any redefined instances */
1051 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1052 vp2 = ktsearch(&l2->vars, vp->name, h);
1054 vp2->flag &= ~EXPORT;
1056 if ((vp->flag&INTEGER)) {
1057 /* integer to string */
1060 vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1061 /* setstr can't fail here */
1062 setstr(vp, val, KSH_RETURN_ERROR);
1064 XPput(denv, vp->val.s);
1068 return ((char **)XPclose(denv));
1072 * handle special variables with side effects - PATH, SECONDS.
1075 /* Test if name is a special parameter */
1077 special(const char *name)
1081 tp = ktsearch(&specials, name, hash(name));
1082 return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1085 /* Make a variable non-special */
1087 unspecial(const char *name)
1091 tp = ktsearch(&specials, name, hash(name));
1096 static time_t seconds; /* time SECONDS last set */
1097 static int user_lineno; /* what user set $LINENO to */
1100 getspec(struct tbl *vp)
1106 switch ((st = special(vp->name))) {
1110 * Do NOT export COLUMNS/LINES. Many applications
1111 * check COLUMNS/LINES before checking ws.ws_col/row,
1112 * so if the app is started with C/L in the environ
1113 * and the window is then resized, the app won't
1114 * see the change cause the environ doesn't change.
1122 num.u = (mksh_uari_t)procpid;
1131 num.i = current_lineno + user_lineno;
1136 case V_EPOCHREALTIME: {
1137 /* 10(%u) + 1(.) + 6 + NUL */
1140 vp->flag &= ~SPECIAL;
1142 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1143 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1144 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1145 vp->flag |= SPECIAL;
1149 num.i = user_opt.uoptind;
1156 * On start up the value of SECONDS is used before
1157 * it has been set - don't do anything in this case
1158 * (see initcoms[] in main.c).
1160 if (vp->flag & ISSET) {
1162 num.i = tv.tv_sec - seconds;
1167 /* do nothing, do not touch vp at all */
1170 vp->flag &= ~SPECIAL;
1171 setint_n(vp, num.i, 0);
1172 vp->flag |= SPECIAL;
1176 setspec(struct tbl *vp)
1182 switch ((st = special(vp->name))) {
1183 #if HAVE_PERSISTENT_HISTORY
1185 sethistfile(str_val(vp));
1189 setctypes(s = str_val(vp), C_IFS);
1196 strdupx(path, s, APERM);
1197 /* clear tracked aliases */
1202 afree(tmpdir, APERM);
1206 * Use tmpdir iff it is an absolute path, is writable
1207 * and searchable and is a directory...
1213 /* LINTED use of access */
1214 if (s[0] == '/' && access(s, W_OK|X_OK) == 0 &&
1215 stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1216 strdupx(tmpdir, s, APERM);
1219 /* common sub-cases */
1222 if (vp->flag & IMPORT) {
1224 unspecial(vp->name);
1225 vp->flag &= ~SPECIAL;
1235 vp->flag &= ~SPECIAL;
1236 if (getint(vp, &num, false) == -1) {
1239 errorf("%s: %s: %s", vp->name, "bad number", s);
1242 vp->flag |= SPECIAL;
1245 /* do nothing, do not touch vp at all */
1249 /* process the singular parts of the common cases */
1253 if (num.i >= MIN_COLS)
1260 /* The -1 is because line numbering starts at 1. */
1261 user_lineno = num.u - current_lineno - 1;
1264 if (num.i >= MIN_LINS)
1268 getopts_reset((int)num.i);
1272 * mksh R39d+ no longer has the traditional repeatability
1273 * of $RANDOM sequences, but always retains state
1275 rndset((unsigned long)num.u);
1282 seconds = tv.tv_sec - num.i;
1286 ksh_tmout = num.i >= 0 ? num.i : 0;
1292 unsetspec(struct tbl *vp)
1295 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1296 * meaning, but OPTARG does not (still set by getopts) and _ is
1297 * also still set in various places. Don't know what AT&T does
1298 * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1299 * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1302 switch (special(vp->name)) {
1304 setctypes(TC_IFSWS, C_IFS);
1310 strdupx(path, def_path, APERM);
1311 /* clear tracked aliases */
1315 /* should not become unspecial */
1317 afree(tmpdir, APERM);
1325 /* AT&T ksh leaves previous value in place */
1326 unspecial(vp->name);
1332 * Search for (and possibly create) a table entry starting with
1333 * vp, indexed by val.
1336 arraysearch(struct tbl *vp, uint32_t val)
1338 struct tbl *prev, *curr, *news;
1341 vp->flag = (vp->flag | (ARRAY|DEFINED)) & ~ASSOC;
1342 /* the table entry is always [0] */
1347 while (curr && curr->ua.index < val) {
1349 curr = curr->u.array;
1351 if (curr && curr->ua.index == val) {
1352 if (curr->flag&ISSET)
1358 len = strlen(vp->name);
1359 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1360 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1361 memcpy(news->name, vp->name, len);
1363 news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1364 news->type = vp->type;
1365 news->areap = vp->areap;
1366 news->u2.field = vp->u2.field;
1367 news->ua.index = val;
1370 /* not reusing old array entry */
1371 prev->u.array = news;
1372 news->u.array = curr;
1378 * Return the length of an array reference (eg, [1+2]) - cp is assumed
1379 * to point to the open bracket. Returns 0 if there is no matching
1383 array_ref_len(const char *cp)
1389 while ((c = *s++) && (c != ']' || --depth))
1398 * Make a copy of the base of an array name
1401 arrayname(const char *str)
1406 if ((p = cstrchr(str, '[')) == 0)
1407 /* Shouldn't happen, but why worry? */
1408 strdupx(rv, str, ATEMP);
1410 strndupx(rv, str, p - str, ATEMP);
1415 /* set (or overwrite, if reset) the array variable var to the values in vals */
1417 set_array(const char *var, bool reset, const char **vals)
1419 struct tbl *vp, *vq;
1420 mksh_uari_t i = 0, j = 0;
1421 const char *ccp = var;
1425 /* to get local array, use "local foo; set -A foo" */
1427 if (n > 0 && var[n - 1] == '+') {
1430 strndupx(cp, var, n - 1, ATEMP);
1435 /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1436 if ((vp->flag&RDONLY))
1437 errorfx(2, "read-only: %s", ccp);
1438 /* This code is quite non-optimal */
1440 /* trash existing values and attributes */
1442 /* allocate-by-access the [0] element to keep in scope */
1446 * TODO: would be nice for assignment to completely succeed or
1447 * completely fail. Only really effects integer arrays:
1448 * evaluation of some of vals[] may fail...
1451 /* find out where to set when appending */
1452 for (vq = vp; vq; vq = vq->u.array) {
1453 if (!(vq->flag & ISSET))
1455 if (arrayindex(vq) >= j)
1456 j = arrayindex(vq) + 1;
1460 while ((ccp = vals[i])) {
1465 if (*ccp == ']' && --level == 0)
1471 if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1472 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1474 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1475 KSH_UNWIND_ERROR, true);
1482 vq = arraysearch(vp, j);
1483 /* would be nice to deal with errors here... (see above) */
1484 setstr(vq, ccp, KSH_RETURN_ERROR);
1496 /* check if window size has changed */
1497 if (tty_init_fd() < 2) {
1500 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1509 /* bounds check for sane values, use defaults otherwise */
1510 if (x_cols < MIN_COLS)
1512 if (x_lins < MIN_LINS)
1523 register uint32_t h;
1526 NZATUpdateString(h, s);
1535 * this is the same Linear Congruential PRNG as Borland
1536 * C/C++ allegedly uses in its built-in rand() function
1538 return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1542 rndset(unsigned long v)
1544 register uint32_t h;
1547 NZATUpdateMem(h, &lcg_state, sizeof(lcg_state));
1548 NZATUpdateMem(h, &v, sizeof(v));
1550 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1552 * either we have very chap entropy get and push available,
1553 * with malloc() pulling in this code already anyway, or the
1554 * user requested us to use the old functions
1557 NZAATFinish(lcg_state);
1558 #if defined(arc4random_pushb_fast)
1559 arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1560 lcg_state = arc4random();
1562 lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1564 NZATUpdateMem(h, &lcg_state, sizeof(lcg_state));