1 /* $OpenBSD: var.c,v 1.34 2007/10/15 02:16:35 deraadt Exp $ */
4 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
5 * Thorsten Glaser <tg@mirbsd.org>
7 * Provided that these terms and disclaimer and all copyright notices
8 * are retained or reproduced in an accompanying document, permission
9 * is granted to deal in this work without restriction, including un-
10 * limited rights to use, publicly perform, distribute, sell, modify,
11 * merge, give away, or sublicence.
13 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
14 * the utmost extent permitted by applicable law, neither express nor
15 * implied; without malicious intent or gross negligence. In no event
16 * may a licensor, author or contributor be held liable for indirect,
17 * direct, other damage, loss, or other issues arising in any way out
18 * of dealing in the work, even if advised of the possibility of such
19 * damage or existence of a defect, except proven that it results out
20 * of said person's immediate fault when using the work as intended.
25 #if defined(__OpenBSD__)
26 #include <sys/sysctl.h>
29 __RCSID("$MirOS: src/bin/mksh/var.c,v 1.132 2011/09/07 15:24:22 tg Exp $");
34 * WARNING: unreadable code, needs a rewrite
36 * if (flag&INTEGER), val.i contains integer value, and type contains base.
37 * otherwise, (val.s + type) contains string value.
38 * if (flag&EXPORT), val.s contains "name=value" for E-Z exporting.
41 static struct tbl vtemp;
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_t *, 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 12 specials -> 80% of 16 (2^4) */
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 */
144 static struct block *
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);
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);
303 if (!ksh_isalphx(*n)) {
305 vp->flag = DEFINED|RDONLY;
310 vp = ktenter(&l->vars, n, h);
311 if (copy && !(vp->flag & DEFINED)) {
314 varsearch(l->next, &vq, n, h);
316 vp->flag |= vq->flag &
317 (EXPORT | INTEGER | RDONLY | LJUST | RJUST |
318 ZEROFIL | LCASEV | UCASEV_AL | INT_U | INT_L);
319 if (vq->flag & INTEGER)
321 vp->u2.field = vq->u2.field;
325 vp = arraysearch(vp, val);
332 /* get variable string value */
334 str_val(struct tbl *vp)
338 if ((vp->flag&SPECIAL))
340 if (!(vp->flag&ISSET))
341 /* special to dollar() */
343 else if (!(vp->flag&INTEGER))
345 s = vp->val.s + vp->type;
351 * worst case number length is when base == 2:
352 * 1 (minus) + 2 (base, up to 36) + 1 ('#') +
353 * number of bits in the mksh_uari_t + 1 (NUL)
355 char strbuf[1 + 2 + 1 + 8 * sizeof(mksh_uari_t) + 1];
356 const char *digits = (vp->flag & UCASEV_AL) ?
357 digits_uc : digits_lc;
359 s = strbuf + sizeof(strbuf);
360 if (vp->flag & INT_U)
363 n = (vp->val.i < 0) ? -vp->val.i : vp->val.i;
364 base = (vp->type == 0) ? 10 : vp->type;
366 if (base == 1 && n == 0)
373 if (!UTFMODE || ((n & 0xFF80) == 0xEF80))
374 /* OPTU-16 -> raw octet */
377 sz = utf_wctomb(s + 2, n);
382 *--s = digits[n % base];
387 *--s = digits[base % 10];
389 *--s = digits[base / 10];
391 if (!(vp->flag & INT_U) && vp->val.i < 0)
394 if (vp->flag & (RJUST|LJUST))
395 /* case already dealt with */
396 s = formatstr(vp, s);
398 strdupx(s, s, ATEMP);
403 /* set variable to string value */
405 setstr(struct tbl *vq, const char *s, int error_ok)
408 int no_ro_check = error_ok & 0x4;
411 if ((vq->flag & RDONLY) && !no_ro_check) {
412 warningf(true, "%s: %s", vq->name, "is read only");
417 if (!(vq->flag&INTEGER)) {
419 if ((vq->flag&ALLOC)) {
421 if (s >= vq->val.s &&
422 s <= vq->val.s + strlen(vq->val.s))
424 "setstr: %s=%s: assigning to self",
426 afree(vq->val.s, vq->areap);
428 vq->flag &= ~(ISSET|ALLOC);
430 if (s && (vq->flag & (UCASEV_AL|LCASEV|LJUST|RJUST)))
431 s = salloc = formatstr(vq, s);
432 if ((vq->flag&EXPORT))
435 strdupx(vq->val.s, s, vq->areap);
440 if (!v_evaluate(vq, s, error_ok, true))
444 if ((vq->flag&SPECIAL))
446 afree(salloc, ATEMP);
450 /* set variable to integer */
452 setint(struct tbl *vq, mksh_ari_t n)
454 if (!(vq->flag&INTEGER)) {
455 struct tbl *vp = &vtemp;
456 vp->flag = (ISSET|INTEGER);
460 /* setstr can't fail here */
461 setstr(vq, str_val(vp), KSH_RETURN_ERROR);
465 if ((vq->flag&SPECIAL))
470 getint(struct tbl *vp, mksh_ari_t *nump, bool arith)
474 bool have_base = false;
477 if (vp->flag&SPECIAL)
479 /* XXX is it possible for ISSET to be set and val.s to be 0? */
480 if (!(vp->flag&ISSET) || (!(vp->flag&INTEGER) && vp->val.s == NULL))
482 if (vp->flag&INTEGER) {
486 s = vp->val.s + vp->type;
490 if (arith && *s == '0' && *(s+1)) {
492 if (*s == 'x' || *s == 'X') {
495 } else if (vp->flag & ZEROFIL) {
502 for (c = *s++; c ; c = *s++) {
506 } else if (c == '#') {
508 if (have_base || base < 1 || base > 36)
514 wc = *(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 + *(unsigned char *)s;
523 *nump = (mksh_ari_t)wc;
529 } else if (ksh_isdigit(c))
531 else if (ksh_islower(c))
533 else if (ksh_isupper(c))
537 if (c < 0 || c >= base)
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)
566 /* convert variable vq to integer variable, setting its value to num */
568 setint_n(struct tbl *vq, mksh_ari_t num)
570 if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
573 afree(vq->val.s, vq->areap);
576 vq->flag |= ISSET|INTEGER;
577 if (vq->flag&SPECIAL)
582 formatstr(struct tbl *vp, const char *s)
588 olen = (int)utf_mbswidth(s);
590 if (vp->flag & (RJUST|LJUST)) {
592 /* default field width */
598 p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
599 if (vp->flag & (RJUST|LJUST)) {
600 int slen = olen, i = 0;
602 if (vp->flag & RJUST) {
607 i += utf_widthadj(qq, &qq);
608 /* strip trailing spaces (AT&T uses qq[-1] == ' ') */
609 while (qq > s && ksh_isspace(qq[-1])) {
613 if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
616 else if (s[2] == '#')
618 if (vp->u2.field <= n)
625 while (slen > vp->u2.field)
626 slen -= utf_widthadj(s, &s);
627 if (vp->u2.field - slen)
628 memset(p + n, (vp->flag & ZEROFIL) ? '0' : ' ',
629 vp->u2.field - slen);
631 shf_snprintf(p + vp->u2.field - slen,
632 psiz - (vp->u2.field - slen),
635 /* strip leading spaces/zeros */
636 while (ksh_isspace(*s))
638 if (vp->flag & ZEROFIL)
641 shf_snprintf(p, nlen + 1, "%-*.*s",
642 vp->u2.field, vp->u2.field, s);
645 memcpy(p, s, strlen(s) + 1);
647 if (vp->flag & UCASEV_AL) {
649 *q = ksh_toupper(*q);
650 } else if (vp->flag & LCASEV) {
652 *q = ksh_tolower(*q);
659 * make vp->val.s be "name=value" for quick exporting.
662 exportprep(struct tbl *vp, const char *val)
665 char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
666 size_t namelen, vallen;
668 namelen = strlen(vp->name);
669 vallen = strlen(val) + 1;
672 /* since name+val are both in memory this can go unchecked */
673 xp = alloc(namelen + 1 + vallen, vp->areap);
674 memcpy(vp->val.s = xp, vp->name, namelen);
677 /* offset to value */
678 vp->type = xp - vp->val.s;
679 memcpy(xp, val, vallen);
681 afree(op, vp->areap);
685 * lookup variable (according to (set&LOCAL)), set its attributes
686 * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV,
687 * UCASEV_AL), and optionally set its value if an assignment.
690 typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
693 struct tbl *vpbase, *t;
697 bool vappend = false;
699 /* check for valid variable name, search for value */
700 val = skip_varname(var, false);
703 mkssert(var != NULL);
706 if (set_refflag != SRF_NOP)
707 errorf("%s: %s", var,
708 "reference variable can't be an array");
709 len = array_ref_len(val);
713 * IMPORT is only used when the shell starts up and is
714 * setting up its environment. Allow only simple array
715 * references at this time since parameter/command
716 * substitution is preformed on the [expression] which
717 * would be a major security hole.
722 for (i = 1; i < len - 1; i++)
723 if (!ksh_isdigit(val[i]))
728 if (val[0] == '=' || (val[0] == '+' && val[1] == '=')) {
729 strndupx(tvar, var, val - var, ATEMP);
735 /* importing from original environment: must have an = */
738 strdupx(tvar, var, ATEMP);
740 /* handle foo[*] => foo (whole array) mapping for R39b */
742 if (len > 3 && tvar[len - 3] == '[' && tvar[len - 2] == '*' &&
743 tvar[len - 1] == ']')
744 tvar[len - 3] = '\0';
747 if (set_refflag == SRF_ENABLE) {
750 /* bail out on 'nameref foo+=bar' */
753 /* find value if variable already exists */
754 if ((qval = val) == NULL) {
755 varsearch(e->loc, &vp, tvar, hash(tvar));
759 /* silently ignore 'nameref foo=foo' */
760 if (qval != NULL && !strcmp(qval, tvar)) {
766 /* prevent typeset from creating a local PATH/ENV/SHELL */
767 if (Flag(FRESTRICTED) && (strcmp(tvar, "PATH") == 0 ||
768 strcmp(tvar, "ENV") == 0 || strcmp(tvar, "SHELL") == 0))
769 errorf("%s: %s", tvar, "restricted");
771 vp = (set&LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
773 if (set_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
775 else if (set_refflag == SRF_ENABLE) {
776 if (vp->flag & ARRAY) {
779 /* free up entire array */
780 for (a = vp->u.array; a; ) {
783 if (tmp->flag & ALLOC)
784 afree(tmp->val.s, tmp->areap);
785 afree(tmp, tmp->areap);
793 set &= ~(LOCAL|LOCAL_COPY);
795 vpbase = (vp->flag & ARRAY) ? global(arrayname(var)) : vp;
798 * only allow export flag to be set; AT&T ksh allows any
799 * attribute to be changed which means it can be truncated or
800 * modified (-L/-R/-Z/-i)
802 if ((vpbase->flag&RDONLY) &&
803 (val || clr || (set & ~EXPORT)))
804 /* XXX check calls - is error here ok by POSIX? */
805 errorfx(2, "%s: %s", tvar, "is read only");
808 /* most calls are with set/clr == 0 */
813 * XXX if x[0] isn't set, there will be problems: need
814 * to have one copy of attributes for arrays...
816 for (t = vpbase; t; t = t->u.array) {
819 char *free_me = NULL;
821 fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
822 ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
823 ((t->flag & INTEGER) && (clr & INTEGER)) ||
824 (!(t->flag & INTEGER) && (set & INTEGER)));
826 if (t->flag & INTEGER) {
830 s = t->val.s + t->type;
831 free_me = (t->flag & ALLOC) ? t->val.s :
836 if (!(t->flag & INTEGER) && (set & INTEGER)) {
840 t->flag = (t->flag | set) & ~clr;
842 * Don't change base if assignment is to be
843 * done, in case assignment fails.
845 if ((set & INTEGER) && base > 0 && (!val || t != vp))
847 if (set & (LJUST|RJUST|ZEROFIL))
850 if (!setstr(t, s, KSH_RETURN_ERROR)) {
852 * Somewhat arbitrary action
853 * here: zap contents of
854 * variable, but keep the flag
858 if (t->flag & INTEGER)
862 afree(t->val.s, t->areap);
863 t->flag &= ~(ISSET|ALLOC);
868 afree(free_me, t->areap);
879 tval = shf_smprintf("%s%s", str_val(vp), val);
884 if (vp->flag&INTEGER) {
885 /* do not zero base before assignment */
886 setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
887 /* done after assignment to override default */
891 /* setstr can't fail (readonly check already done) */
892 setstr(vp, val, KSH_RETURN_ERROR | 0x4);
898 /* only x[0] is ever exported, so use vpbase */
899 if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
901 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
907 * Unset a variable. The flags can be:
908 * |1 = tear down entire array
909 * |2 = keep attributes, only unset content
912 unset(struct tbl *vp, int flags)
914 if (vp->flag & ALLOC)
915 afree(vp->val.s, vp->areap);
916 if ((vp->flag & ARRAY) && (flags & 1)) {
919 /* free up entire array */
920 for (a = vp->u.array; a; ) {
923 if (tmp->flag & ALLOC)
924 afree(tmp->val.s, tmp->areap);
925 afree(tmp, tmp->areap);
930 vp->flag &= ~(ALLOC|ISSET);
933 /* if foo[0] is being unset, the remainder of the array is kept... */
934 vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
935 if (vp->flag & SPECIAL)
936 /* responsible for 'unspecial'ing var */
941 * Return a pointer to the first char past a legal variable name
942 * (returns the argument if there is no legal name, returns a pointer to
943 * the terminating NUL if whole string is legal).
946 skip_varname(const char *s, int aok)
950 if (s && ksh_isalphx(*s)) {
951 while (*++s && ksh_isalnux(*s))
953 if (aok && *s == '[' && (alen = array_ref_len(s)))
959 /* Return a pointer to the first character past any legal variable name */
961 skip_wdvarname(const char *s,
962 /* skip array de-reference? */
965 if (s[0] == CHAR && ksh_isalphx(s[1])) {
968 } while (s[0] == CHAR && ksh_isalnux(s[1]));
969 if (aok && s[0] == CHAR && s[1] == '[') {
970 /* skip possible array de-reference */
975 while (/* CONSTCOND */ 1) {
982 else if (c == ']' && --depth == 0) {
992 /* Check if coded string s is a variable name */
994 is_wdvarname(const char *s, bool aok)
996 const char *p = skip_wdvarname(s, aok);
998 return (p != s && p[0] == EOS);
1001 /* Check if coded string s is a variable assignment */
1003 is_wdvarassign(const char *s)
1005 const char *p = skip_wdvarname(s, true);
1007 return (p != s && p[0] == CHAR &&
1008 (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1012 * Make the exported environment from the exported names in the dictionary.
1020 struct tbl *vp, **vpp;
1023 for (l = e->loc; l != NULL; l = l->next) {
1025 i = 1 << (l->vars.tshift);
1027 if ((vp = *vpp++) != NULL &&
1028 (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1031 uint32_t h = hash(vp->name);
1033 /* unexport any redefined instances */
1034 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1035 vp2 = ktsearch(&l2->vars, vp->name, h);
1037 vp2->flag &= ~EXPORT;
1039 if ((vp->flag&INTEGER)) {
1040 /* integer to string */
1043 vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1044 /* setstr can't fail here */
1045 setstr(vp, val, KSH_RETURN_ERROR);
1047 XPput(denv, vp->val.s);
1051 return ((char **)XPclose(denv));
1055 * handle special variables with side effects - PATH, SECONDS.
1058 /* Test if name is a special parameter */
1060 special(const char *name)
1064 tp = ktsearch(&specials, name, hash(name));
1065 return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1068 /* Make a variable non-special */
1070 unspecial(const char *name)
1074 tp = ktsearch(&specials, name, hash(name));
1079 static time_t seconds; /* time SECONDS last set */
1080 static int user_lineno; /* what user set $LINENO to */
1083 getspec(struct tbl *vp)
1085 register mksh_ari_t i;
1088 switch ((st = special(vp->name))) {
1091 * On start up the value of SECONDS is used before
1092 * it has been set - don't do anything in this case
1093 * (see initcoms[] in main.c).
1095 if (vp->flag & ISSET) {
1098 gettimeofday(&tv, NULL);
1099 i = tv.tv_sec - seconds;
1105 * this is the same Linear Congruential PRNG as Borland
1106 * C/C++ allegedly uses in its built-in rand() function
1108 i = ((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF;
1114 i = user_opt.uoptind;
1117 i = current_lineno + user_lineno;
1122 * Do NOT export COLUMNS/LINES. Many applications
1123 * check COLUMNS/LINES before checking ws.ws_col/row,
1124 * so if the app is started with C/L in the environ
1125 * and the window is then resized, the app won't
1126 * see the change cause the environ doesn't change.
1129 i = st == V_COLUMNS ? x_cols : x_lins;
1132 /* do nothing, do not touch vp at all */
1135 vp->flag &= ~SPECIAL;
1137 vp->flag |= SPECIAL;
1141 setspec(struct tbl *vp)
1147 switch ((st = special(vp->name))) {
1152 strdupx(path, s, APERM);
1153 /* clear tracked aliases */
1157 setctypes(s = str_val(vp), C_IFS);
1162 afree(tmpdir, APERM);
1166 * Use tmpdir iff it is an absolute path, is writable
1167 * and searchable and is a directory...
1173 /* LINTED use of access */
1174 if (s[0] == '/' && access(s, W_OK|X_OK) == 0 &&
1175 stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1176 strdupx(tmpdir, s, APERM);
1179 #if HAVE_PERSISTENT_HISTORY
1181 sethistfile(str_val(vp));
1185 /* common sub-cases */
1194 vp->flag &= ~SPECIAL;
1195 if (getint(vp, &i, false) == -1) {
1198 errorf("%s: %s: %s", vp->name, "bad number", s);
1201 vp->flag |= SPECIAL;
1204 /* do nothing, do not touch vp at all */
1208 /* process the singular parts of the common cases */
1212 getopts_reset((int)i);
1215 sethistsize((int)i);
1227 * mksh R39d+ no longer has the traditional repeatability
1228 * of $RANDOM sequences, but always retains state
1236 gettimeofday(&tv, NULL);
1237 seconds = tv.tv_sec - i;
1241 /* The -1 is because line numbering starts at 1. */
1242 user_lineno = (unsigned int)i - current_lineno - 1;
1245 ksh_tmout = i >= 0 ? i : 0;
1251 unsetspec(struct tbl *vp)
1253 switch (special(vp->name)) {
1257 strdupx(path, def_path, APERM);
1258 /* clear tracked aliases */
1262 setctypes(" \t\n", C_IFS);
1266 /* should not become unspecial */
1268 afree(tmpdir, APERM);
1276 /* AT&T ksh leaves previous value in place */
1277 unspecial(vp->name);
1281 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1282 * meaning, but OPTARG does not (still set by getopts) and _ is
1283 * also still set in various places. Don't know what AT&T does
1284 * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1285 * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1291 * Search for (and possibly create) a table entry starting with
1292 * vp, indexed by val.
1295 arraysearch(struct tbl *vp, uint32_t val)
1297 struct tbl *prev, *curr, *news;
1300 vp->flag = (vp->flag | (ARRAY|DEFINED)) & ~ASSOC;
1301 /* the table entry is always [0] */
1306 while (curr && curr->ua.index < val) {
1308 curr = curr->u.array;
1310 if (curr && curr->ua.index == val) {
1311 if (curr->flag&ISSET)
1317 len = strlen(vp->name);
1318 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1319 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1320 memcpy(news->name, vp->name, len);
1322 news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1323 news->type = vp->type;
1324 news->areap = vp->areap;
1325 news->u2.field = vp->u2.field;
1326 news->ua.index = val;
1329 /* not reusing old array entry */
1330 prev->u.array = news;
1331 news->u.array = curr;
1337 * Return the length of an array reference (eg, [1+2]) - cp is assumed
1338 * to point to the open bracket. Returns 0 if there is no matching
1342 array_ref_len(const char *cp)
1348 while ((c = *s++) && (c != ']' || --depth))
1357 * Make a copy of the base of an array name
1360 arrayname(const char *str)
1365 if ((p = cstrchr(str, '[')) == 0)
1366 /* Shouldn't happen, but why worry? */
1367 strdupx(rv, str, ATEMP);
1369 strndupx(rv, str, p - str, ATEMP);
1374 /* set (or overwrite, if reset) the array variable var to the values in vals */
1376 set_array(const char *var, bool reset, const char **vals)
1378 struct tbl *vp, *vq;
1379 mksh_uari_t i = 0, j = 0;
1386 /* to get local array, use "typeset foo; set -A foo" */
1389 if (n > 0 && var[n - 1] == '+') {
1392 strndupx(cp, var, n - 1, ATEMP);
1394 #define CPORVAR (cp ? cp : var)
1398 vp = global(CPORVAR);
1400 /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1401 if ((vp->flag&RDONLY))
1402 errorfx(2, "%s: %s", CPORVAR, "is read only");
1403 /* This code is quite non-optimal */
1405 /* trash existing values and attributes */
1408 * TODO: would be nice for assignment to completely succeed or
1409 * completely fail. Only really effects integer arrays:
1410 * evaluation of some of vals[] may fail...
1414 /* find out where to set when appending */
1415 for (vq = vp; vq; vq = vq->u.array) {
1416 if (!(vq->flag & ISSET))
1418 if (arrayindex(vq) >= j)
1419 j = arrayindex(vq) + 1;
1424 while ((ccp = vals[i])) {
1430 if (*ccp == ']' && --level == 0)
1436 if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1437 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1439 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1440 KSH_UNWIND_ERROR, true);
1448 vq = arraysearch(vp, j);
1449 /* would be nice to deal with errors here... (see above) */
1450 setstr(vq, ccp, KSH_RETURN_ERROR);
1462 /* first time initialisation */
1465 /* non-FTALKING, try to get an fd anyway */
1466 tty_init(true, false);
1472 /* check if window size has changed */
1476 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1485 /* bounds check for sane values, use defaults otherwise */
1486 if (x_cols < MIN_COLS)
1488 if (x_lins < MIN_LINS)
1499 register uint32_t h;
1502 NZATUpdateString(h, s);
1510 register uint32_t h;
1513 NZATUpdateMem(h, &lcg_state, sizeof(lcg_state));
1514 NZATUpdateMem(h, &v, sizeof(v));
1516 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1518 * either we have very chap entropy get and push available,
1519 * with malloc() pulling in this code already anyway, or the
1520 * user requested us to use the old functions
1523 NZAATFinish(lcg_state);
1524 #if defined(arc4random_pushb_fast)
1525 arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1526 lcg_state = arc4random();
1528 lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1530 NZATUpdateMem(h, &lcg_state, sizeof(lcg_state));