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,
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.166 2013/02/18 22:24:52 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_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 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.i : vp->val.i;
365 base = (vp->type == 0) ? 10 : 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_t *nump, bool arith)
479 bool have_base = false;
481 if (vp->flag&SPECIAL)
483 /* XXX is it possible for ISSET to be set and val.s to be 0? */
484 if (!(vp->flag&ISSET) || (!(vp->flag&INTEGER) && vp->val.s == NULL))
486 if (vp->flag&INTEGER) {
490 s = vp->val.s + vp->type;
494 if (arith && s[0] == '0' && (s[1] | 0x20) == 'x') {
499 #ifdef MKSH_LEGACY_MODE
500 if (arith && s[0] == '0' && ksh_isdigit(s[1]) &&
501 !(vp->flag & ZEROFIL)) {
502 /* interpret as octal (deprecated) */
511 } else if (c == '#') {
512 if (have_base || num < 1 || num > 36)
519 wc = *(const unsigned char *)s;
520 else if (utf_mbtowc(&wc, s) == (size_t)-1)
521 /* OPTU-8 -> OPTU-16 */
523 * (with a twist: 1#\uEF80 converts
524 * the same as 1#\x80 does, thus is
525 * not round-tripping correctly XXX)
527 wc = 0xEF00 + *(const unsigned char *)s;
528 *nump = (mksh_ari_t)wc;
534 } else if (ksh_isdigit(c))
536 else if (ksh_islower(c))
538 else if (ksh_isupper(c))
542 if (c < 0 || c >= base)
544 num = num * base + c;
546 *nump = neg ? -((mksh_ari_t)num) : (mksh_ari_t)num;
551 * convert variable vq to integer variable, setting its value from vp
552 * (vq and vp may be the same)
555 setint_v(struct tbl *vq, struct tbl *vp, bool arith)
560 if ((base = getint(vp, &num, arith)) == -1)
562 setint_n(vq, num, 0);
569 /* convert variable vq to integer variable, setting its value to num */
571 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
573 if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
576 afree(vq->val.s, vq->areap);
581 vq->flag |= ISSET|INTEGER;
582 if (vq->flag&SPECIAL)
587 formatstr(struct tbl *vp, const char *s)
593 olen = (int)utf_mbswidth(s);
595 if (vp->flag & (RJUST|LJUST)) {
597 /* default field width */
603 p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
604 if (vp->flag & (RJUST|LJUST)) {
605 int slen = olen, i = 0;
607 if (vp->flag & RJUST) {
612 i += utf_widthadj(qq, &qq);
613 /* strip trailing spaces (AT&T uses qq[-1] == ' ') */
614 while (qq > s && ksh_isspace(qq[-1])) {
618 if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
623 else if (s[2] == '#')
626 if (vp->u2.field <= n)
633 while (slen > vp->u2.field)
634 slen -= utf_widthadj(s, &s);
635 if (vp->u2.field - slen)
636 memset(p + n, (vp->flag & ZEROFIL) ? '0' : ' ',
637 vp->u2.field - slen);
639 shf_snprintf(p + vp->u2.field - slen,
640 psiz - (vp->u2.field - slen),
643 /* strip leading spaces/zeros */
644 while (ksh_isspace(*s))
646 if (vp->flag & ZEROFIL)
649 shf_snprintf(p, nlen + 1, "%-*.*s",
650 vp->u2.field, vp->u2.field, s);
653 memcpy(p, s, strlen(s) + 1);
655 if (vp->flag & UCASEV_AL) {
657 *q = ksh_toupper(*q);
658 } else if (vp->flag & LCASEV) {
660 *q = ksh_tolower(*q);
667 * make vp->val.s be "name=value" for quick exporting.
670 exportprep(struct tbl *vp, const char *val)
673 char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
674 size_t namelen, vallen;
676 mkssert(val != NULL);
678 namelen = strlen(vp->name);
679 vallen = strlen(val) + 1;
682 /* since name+val are both in memory this can go unchecked */
683 xp = alloc(namelen + 1 + vallen, vp->areap);
684 memcpy(vp->val.s = xp, vp->name, namelen);
687 /* offset to value */
688 vp->type = xp - vp->val.s;
689 memcpy(xp, val, vallen);
691 afree(op, vp->areap);
695 * lookup variable (according to (set&LOCAL)), set its attributes
696 * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV,
697 * UCASEV_AL), and optionally set its value if an assignment.
700 typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
703 struct tbl *vpbase, *t;
707 bool vappend = false;
709 /* check for valid variable name, search for value */
710 val = skip_varname(var, false);
712 if (set_refflag != SRF_NOP)
713 errorf("%s: %s", var,
714 "reference variable can't be an array");
715 len = array_ref_len(val);
719 * IMPORT is only used when the shell starts up and is
720 * setting up its environment. Allow only simple array
721 * references at this time since parameter/command
722 * substitution is performed on the [expression] which
723 * would be a major security hole.
728 for (i = 1; i < len - 1; i++)
729 if (!ksh_isdigit(val[i]))
734 if (val[0] == '=' || (val[0] == '+' && val[1] == '=')) {
735 strndupx(tvar, var, val - var, ATEMP);
740 } else if ((val[0] != '\0') || (set & IMPORT)) {
742 * must have a = when setting a variable by importing
743 * the original environment, otherwise be empty; we
744 * 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 /* silently ignore 'nameref foo=foo' */
772 if (qval != NULL && !strcmp(qval, tvar)) {
778 /* prevent typeset from creating a local PATH/ENV/SHELL */
779 if (Flag(FRESTRICTED) && (strcmp(tvar, "PATH") == 0 ||
780 strcmp(tvar, "ENV") == 0 || strcmp(tvar, "SHELL") == 0))
781 errorf("%s: %s", tvar, "restricted");
783 vp = (set&LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
785 if (set_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
787 else if (set_refflag == SRF_ENABLE) {
788 if (vp->flag & ARRAY) {
791 /* free up entire array */
792 for (a = vp->u.array; a; ) {
795 if (tmp->flag & ALLOC)
796 afree(tmp->val.s, tmp->areap);
797 afree(tmp, tmp->areap);
805 set &= ~(LOCAL|LOCAL_COPY);
807 vpbase = (vp->flag & ARRAY) ? global(arrayname(var)) : vp;
810 * only allow export flag to be set; AT&T ksh allows any
811 * attribute to be changed which means it can be truncated or
812 * modified (-L/-R/-Z/-i)
814 if ((vpbase->flag&RDONLY) &&
815 (val || clr || (set & ~EXPORT)))
816 /* XXX check calls - is error here ok by POSIX? */
817 errorfx(2, "read-only: %s", tvar);
820 /* most calls are with set/clr == 0 */
825 * XXX if x[0] isn't set, there will be problems: need
826 * to have one copy of attributes for arrays...
828 for (t = vpbase; t; t = t->u.array) {
831 char *free_me = NULL;
833 fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
834 ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
835 ((t->flag & INTEGER) && (clr & INTEGER)) ||
836 (!(t->flag & INTEGER) && (set & INTEGER)));
838 if (t->flag & INTEGER) {
842 s = t->val.s + t->type;
843 free_me = (t->flag & ALLOC) ? t->val.s :
848 if (!(t->flag & INTEGER) && (set & INTEGER)) {
852 t->flag = (t->flag | set) & ~clr;
854 * Don't change base if assignment is to be
855 * done, in case assignment fails.
857 if ((set & INTEGER) && base > 0 && (!val || t != vp))
859 if (set & (LJUST|RJUST|ZEROFIL))
862 if (!setstr(t, s, KSH_RETURN_ERROR)) {
864 * Somewhat arbitrary action
865 * here: zap contents of
866 * variable, but keep the flag
870 if (t->flag & INTEGER)
874 afree(t->val.s, t->areap);
875 t->flag &= ~(ISSET|ALLOC);
880 afree(free_me, t->areap);
891 tval = shf_smprintf("%s%s", str_val(vp), val);
896 if (vp->flag&INTEGER) {
897 /* do not zero base before assignment */
898 setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
899 /* done after assignment to override default */
903 /* setstr can't fail (readonly check already done) */
904 setstr(vp, val, KSH_RETURN_ERROR | 0x4);
910 /* only x[0] is ever exported, so use vpbase */
911 if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
913 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
919 * Unset a variable. The flags can be:
920 * |1 = tear down entire array
921 * |2 = keep attributes, only unset content
924 unset(struct tbl *vp, int flags)
926 if (vp->flag & ALLOC)
927 afree(vp->val.s, vp->areap);
928 if ((vp->flag & ARRAY) && (flags & 1)) {
931 /* free up entire array */
932 for (a = vp->u.array; a; ) {
935 if (tmp->flag & ALLOC)
936 afree(tmp->val.s, tmp->areap);
937 afree(tmp, tmp->areap);
942 vp->flag &= ~(ALLOC|ISSET);
945 /* if foo[0] is being unset, the remainder of the array is kept... */
946 vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
947 if (vp->flag & SPECIAL)
948 /* responsible for 'unspecial'ing var */
953 * Return a pointer to the first char past a legal variable name
954 * (returns the argument if there is no legal name, returns a pointer to
955 * the terminating NUL if whole string is legal).
958 skip_varname(const char *s, int aok)
962 if (s && ksh_isalphx(*s)) {
963 while (*++s && ksh_isalnux(*s))
965 if (aok && *s == '[' && (alen = array_ref_len(s)))
971 /* Return a pointer to the first character past any legal variable name */
973 skip_wdvarname(const char *s,
974 /* skip array de-reference? */
977 if (s[0] == CHAR && ksh_isalphx(s[1])) {
980 } while (s[0] == CHAR && ksh_isalnux(s[1]));
981 if (aok && s[0] == CHAR && s[1] == '[') {
982 /* skip possible array de-reference */
987 while (/* CONSTCOND */ 1) {
994 else if (c == ']' && --depth == 0) {
1004 /* Check if coded string s is a variable name */
1006 is_wdvarname(const char *s, bool aok)
1008 const char *p = skip_wdvarname(s, aok);
1010 return (p != s && p[0] == EOS);
1013 /* Check if coded string s is a variable assignment */
1015 is_wdvarassign(const char *s)
1017 const char *p = skip_wdvarname(s, true);
1019 return (p != s && p[0] == CHAR &&
1020 (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1024 * Make the exported environment from the exported names in the dictionary.
1032 struct tbl *vp, **vpp;
1035 for (l = e->loc; l != NULL; l = l->next) {
1037 i = 1 << (l->vars.tshift);
1039 if ((vp = *vpp++) != NULL &&
1040 (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1043 uint32_t h = hash(vp->name);
1045 /* unexport any redefined instances */
1046 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1047 vp2 = ktsearch(&l2->vars, vp->name, h);
1049 vp2->flag &= ~EXPORT;
1051 if ((vp->flag&INTEGER)) {
1052 /* integer to string */
1055 vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1056 /* setstr can't fail here */
1057 setstr(vp, val, KSH_RETURN_ERROR);
1059 XPput(denv, vp->val.s);
1063 return ((char **)XPclose(denv));
1067 * handle special variables with side effects - PATH, SECONDS.
1070 /* Test if name is a special parameter */
1072 special(const char *name)
1076 tp = ktsearch(&specials, name, hash(name));
1077 return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1080 /* Make a variable non-special */
1082 unspecial(const char *name)
1086 tp = ktsearch(&specials, name, hash(name));
1091 static time_t seconds; /* time SECONDS last set */
1092 static int user_lineno; /* what user set $LINENO to */
1095 getspec(struct tbl *vp)
1097 register mksh_ari_t i;
1101 switch ((st = special(vp->name))) {
1105 * Do NOT export COLUMNS/LINES. Many applications
1106 * check COLUMNS/LINES before checking ws.ws_col/row,
1107 * so if the app is started with C/L in the environ
1108 * and the window is then resized, the app won't
1109 * see the change cause the environ doesn't change.
1117 i = (mksh_ari_t)procpid;
1126 i = current_lineno + user_lineno;
1131 case V_EPOCHREALTIME: {
1132 /* 10(%u) + 1(.) + 6 + NUL */
1135 vp->flag &= ~SPECIAL;
1137 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1138 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1139 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1140 vp->flag |= SPECIAL;
1144 i = user_opt.uoptind;
1151 * On start up the value of SECONDS is used before
1152 * it has been set - don't do anything in this case
1153 * (see initcoms[] in main.c).
1155 if (vp->flag & ISSET) {
1157 i = tv.tv_sec - seconds;
1162 /* do nothing, do not touch vp at all */
1165 vp->flag &= ~SPECIAL;
1167 vp->flag |= SPECIAL;
1171 setspec(struct tbl *vp)
1177 switch ((st = special(vp->name))) {
1178 #if HAVE_PERSISTENT_HISTORY
1180 sethistfile(str_val(vp));
1184 setctypes(s = str_val(vp), C_IFS);
1191 strdupx(path, s, APERM);
1192 /* clear tracked aliases */
1197 afree(tmpdir, APERM);
1201 * Use tmpdir iff it is an absolute path, is writable
1202 * and searchable and is a directory...
1208 /* LINTED use of access */
1209 if (s[0] == '/' && access(s, W_OK|X_OK) == 0 &&
1210 stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1211 strdupx(tmpdir, s, APERM);
1214 /* common sub-cases */
1217 if (vp->flag & IMPORT) {
1219 unspecial(vp->name);
1220 vp->flag &= ~SPECIAL;
1230 vp->flag &= ~SPECIAL;
1231 if (getint(vp, &i, false) == -1) {
1234 errorf("%s: %s: %s", vp->name, "bad number", s);
1237 vp->flag |= SPECIAL;
1240 /* do nothing, do not touch vp at all */
1244 /* process the singular parts of the common cases */
1255 /* The -1 is because line numbering starts at 1. */
1256 user_lineno = (unsigned int)i - current_lineno - 1;
1263 getopts_reset((int)i);
1267 * mksh R39d+ no longer has the traditional repeatability
1268 * of $RANDOM sequences, but always retains state
1277 seconds = tv.tv_sec - i;
1281 ksh_tmout = i >= 0 ? i : 0;
1287 unsetspec(struct tbl *vp)
1290 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1291 * meaning, but OPTARG does not (still set by getopts) and _ is
1292 * also still set in various places. Don't know what AT&T does
1293 * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1294 * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1297 switch (special(vp->name)) {
1299 setctypes(TC_IFSWS, C_IFS);
1305 strdupx(path, def_path, APERM);
1306 /* clear tracked aliases */
1310 /* should not become unspecial */
1312 afree(tmpdir, APERM);
1320 /* AT&T ksh leaves previous value in place */
1321 unspecial(vp->name);
1327 * Search for (and possibly create) a table entry starting with
1328 * vp, indexed by val.
1331 arraysearch(struct tbl *vp, uint32_t val)
1333 struct tbl *prev, *curr, *news;
1336 vp->flag = (vp->flag | (ARRAY|DEFINED)) & ~ASSOC;
1337 /* the table entry is always [0] */
1342 while (curr && curr->ua.index < val) {
1344 curr = curr->u.array;
1346 if (curr && curr->ua.index == val) {
1347 if (curr->flag&ISSET)
1353 len = strlen(vp->name);
1354 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1355 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1356 memcpy(news->name, vp->name, len);
1358 news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1359 news->type = vp->type;
1360 news->areap = vp->areap;
1361 news->u2.field = vp->u2.field;
1362 news->ua.index = val;
1365 /* not reusing old array entry */
1366 prev->u.array = news;
1367 news->u.array = curr;
1373 * Return the length of an array reference (eg, [1+2]) - cp is assumed
1374 * to point to the open bracket. Returns 0 if there is no matching
1378 array_ref_len(const char *cp)
1384 while ((c = *s++) && (c != ']' || --depth))
1393 * Make a copy of the base of an array name
1396 arrayname(const char *str)
1401 if ((p = cstrchr(str, '[')) == 0)
1402 /* Shouldn't happen, but why worry? */
1403 strdupx(rv, str, ATEMP);
1405 strndupx(rv, str, p - str, ATEMP);
1410 /* set (or overwrite, if reset) the array variable var to the values in vals */
1412 set_array(const char *var, bool reset, const char **vals)
1414 struct tbl *vp, *vq;
1415 mksh_uari_t i = 0, j = 0;
1416 const char *ccp = var;
1420 /* to get local array, use "local foo; set -A foo" */
1422 if (n > 0 && var[n - 1] == '+') {
1425 strndupx(cp, var, n - 1, ATEMP);
1430 /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1431 if ((vp->flag&RDONLY))
1432 errorfx(2, "read-only: %s", ccp);
1433 /* This code is quite non-optimal */
1435 /* trash existing values and attributes */
1437 /* allocate-by-access the [0] element to keep in scope */
1441 * TODO: would be nice for assignment to completely succeed or
1442 * completely fail. Only really effects integer arrays:
1443 * evaluation of some of vals[] may fail...
1446 /* find out where to set when appending */
1447 for (vq = vp; vq; vq = vq->u.array) {
1448 if (!(vq->flag & ISSET))
1450 if (arrayindex(vq) >= j)
1451 j = arrayindex(vq) + 1;
1455 while ((ccp = vals[i])) {
1460 if (*ccp == ']' && --level == 0)
1466 if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1467 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1469 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1470 KSH_UNWIND_ERROR, true);
1477 vq = arraysearch(vp, j);
1478 /* would be nice to deal with errors here... (see above) */
1479 setstr(vq, ccp, KSH_RETURN_ERROR);
1491 /* check if window size has changed */
1492 if (tty_init_fd() < 2) {
1495 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1504 /* bounds check for sane values, use defaults otherwise */
1505 if (x_cols < MIN_COLS)
1507 if (x_lins < MIN_LINS)
1518 register uint32_t h;
1521 NZATUpdateString(h, s);
1530 * this is the same Linear Congruential PRNG as Borland
1531 * C/C++ allegedly uses in its built-in rand() function
1533 return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1539 register uint32_t h;
1542 NZATUpdateMem(h, &lcg_state, sizeof(lcg_state));
1543 NZATUpdateMem(h, &v, sizeof(v));
1545 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1547 * either we have very chap entropy get and push available,
1548 * with malloc() pulling in this code already anyway, or the
1549 * user requested us to use the old functions
1552 NZAATFinish(lcg_state);
1553 #if defined(arc4random_pushb_fast)
1554 arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1555 lcg_state = arc4random();
1557 lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1559 NZATUpdateMem(h, &lcg_state, sizeof(lcg_state));