OSDN Git Service

Upgrade to mksh 50.
[android-x86/external-mksh.git] / src / var.c
1 /*      $OpenBSD: var.c,v 1.38 2013/12/20 17:53:09 zhuk Exp $   */
2
3 /*-
4  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5  *               2011, 2012, 2013, 2014
6  *      Thorsten Glaser <tg@mirbsd.org>
7  *
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.
13  *
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.
22  */
23
24 #include "sh.h"
25 #include "mirhash.h"
26
27 #if defined(__OpenBSD__)
28 #include <sys/sysctl.h>
29 #endif
30
31 __RCSID("$MirOS: src/bin/mksh/var.c,v 1.180 2014/06/26 20:36:02 tg Exp $");
32
33 /*-
34  * Variables
35  *
36  * WARNING: unreadable code, needs a rewrite
37  *
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.
41  */
42
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;
47
48 static char *formatstr(struct tbl *, const char *);
49 static void exportprep(struct tbl *, const char *);
50 static int special(const char *);
51 static void unspecial(const char *);
52 static void getspec(struct tbl *);
53 static void setspec(struct tbl *);
54 static void unsetspec(struct tbl *);
55 static int getint(struct tbl *, mksh_ari_u *, bool);
56 static const char *array_index_calc(const char *, bool *, uint32_t *);
57
58 /*
59  * create a new block for function calls and simple commands
60  * assume caller has allocated and set up e->loc
61  */
62 void
63 newblock(void)
64 {
65         struct block *l;
66         static const char *empty[] = { null };
67
68         l = alloc(sizeof(struct block), ATEMP);
69         l->flags = 0;
70         /* TODO: could use e->area (l->area => l->areap) */
71         ainit(&l->area);
72         if (!e->loc) {
73                 l->argc = 0;
74                 l->argv = empty;
75         } else {
76                 l->argc = e->loc->argc;
77                 l->argv = e->loc->argv;
78         }
79         l->exit = l->error = NULL;
80         ktinit(&l->area, &l->vars, 0);
81         ktinit(&l->area, &l->funs, 0);
82         l->next = e->loc;
83         e->loc = l;
84 }
85
86 /*
87  * pop a block handling special variables
88  */
89 void
90 popblock(void)
91 {
92         ssize_t i;
93         struct block *l = e->loc;
94         struct tbl *vp, **vpp = l->vars.tbls, *vq;
95
96         /* pop block */
97         e->loc = l->next;
98
99         i = 1 << (l->vars.tshift);
100         while (--i >= 0)
101                 if ((vp = *vpp++) != NULL && (vp->flag&SPECIAL)) {
102                         if ((vq = global(vp->name))->flag & ISSET)
103                                 setspec(vq);
104                         else
105                                 unsetspec(vq);
106                 }
107         if (l->flags & BF_DOGETOPTS)
108                 user_opt = l->getopts_state;
109         afreeall(&l->area);
110         afree(l, ATEMP);
111 }
112
113 /* called by main() to initialise variable data structures */
114 #define VARSPEC_DEFNS
115 #include "var_spec.h"
116
117 enum var_specs {
118 #define VARSPEC_ENUMS
119 #include "var_spec.h"
120         V_MAX
121 };
122
123 /* this is biased with -1 relative to VARSPEC_ENUMS */
124 static const char * const initvar_names[] = {
125 #define VARSPEC_ITEMS
126 #include "var_spec.h"
127 };
128
129 void
130 initvar(void)
131 {
132         int i = 0;
133         struct tbl *tp;
134
135         ktinit(APERM, &specials,
136             /* currently 14 specials: 75% of 32 = 2^5 */
137             5);
138         while (i < V_MAX - 1) {
139                 tp = ktenter(&specials, initvar_names[i],
140                     hash(initvar_names[i]));
141                 tp->flag = DEFINED|ISSET;
142                 tp->type = ++i;
143         }
144 }
145
146 /* common code for several functions below and c_typeset() */
147 struct block *
148 varsearch(struct block *l, struct tbl **vpp, const char *vn, uint32_t h)
149 {
150         register struct tbl *vp;
151
152         if (l) {
153  varsearch_loop:
154                 if ((vp = ktsearch(&l->vars, vn, h)) != NULL)
155                         goto varsearch_out;
156                 if (l->next != NULL) {
157                         l = l->next;
158                         goto varsearch_loop;
159                 }
160         }
161         vp = NULL;
162  varsearch_out:
163         *vpp = vp;
164         return (l);
165 }
166
167 /*
168  * Used to calculate an array index for global()/local(). Sets *arrayp
169  * to true if this is an array, sets *valp to the array index, returns
170  * the basename of the array. May only be called from global()/local()
171  * and must be their first callee.
172  */
173 static const char *
174 array_index_calc(const char *n, bool *arrayp, uint32_t *valp)
175 {
176         const char *p;
177         size_t len;
178         char *ap = NULL;
179
180         *arrayp = false;
181  redo_from_ref:
182         p = skip_varname(n, false);
183         if (innermost_refflag == SRF_NOP && (p != n) && ksh_isalphx(n[0])) {
184                 struct tbl *vp;
185                 char *vn;
186
187                 strndupx(vn, n, p - n, ATEMP);
188                 /* check if this is a reference */
189                 varsearch(e->loc, &vp, vn, hash(vn));
190                 afree(vn, ATEMP);
191                 if (vp && (vp->flag & (DEFINED | ASSOC | ARRAY)) ==
192                     (DEFINED | ASSOC)) {
193                         char *cp;
194
195                         /* gotcha! */
196                         cp = shf_smprintf("%s%s", str_val(vp), p);
197                         afree(ap, ATEMP);
198                         n = ap = cp;
199                         goto redo_from_ref;
200                 }
201         }
202         innermost_refflag = SRF_NOP;
203
204         if (p != n && *p == '[' && (len = array_ref_len(p))) {
205                 char *sub, *tmp;
206                 mksh_ari_t rval;
207
208                 /* calculate the value of the subscript */
209                 *arrayp = true;
210                 strndupx(tmp, p + 1, len - 2, ATEMP);
211                 sub = substitute(tmp, 0);
212                 afree(tmp, ATEMP);
213                 strndupx(n, n, p - n, ATEMP);
214                 evaluate(sub, &rval, KSH_UNWIND_ERROR, true);
215                 *valp = (uint32_t)rval;
216                 afree(sub, ATEMP);
217         }
218         return (n);
219 }
220
221 /*
222  * Search for variable, if not found create globally.
223  */
224 struct tbl *
225 global(const char *n)
226 {
227         struct block *l = e->loc;
228         struct tbl *vp;
229         int c;
230         bool array;
231         uint32_t h, val;
232
233         /*
234          * check to see if this is an array;
235          * dereference namerefs; must come first
236          */
237         n = array_index_calc(n, &array, &val);
238         h = hash(n);
239         c = (unsigned char)n[0];
240         if (!ksh_isalphx(c)) {
241                 if (array)
242                         errorf("bad substitution");
243                 vp = &vtemp;
244                 vp->flag = DEFINED;
245                 vp->type = 0;
246                 vp->areap = ATEMP;
247                 *vp->name = c;
248                 if (ksh_isdigit(c)) {
249                         if (getn(n, &c) && (c <= l->argc))
250                                 /* setstr can't fail here */
251                                 setstr(vp, l->argv[c], KSH_RETURN_ERROR);
252                         vp->flag |= RDONLY;
253                         return (vp);
254                 }
255                 vp->flag |= RDONLY;
256                 if (n[1] != '\0')
257                         return (vp);
258                 vp->flag |= ISSET|INTEGER;
259                 switch (c) {
260                 case '$':
261                         vp->val.i = kshpid;
262                         break;
263                 case '!':
264                         /* if no job, expand to nothing */
265                         if ((vp->val.i = j_async()) == 0)
266                                 vp->flag &= ~(ISSET|INTEGER);
267                         break;
268                 case '?':
269                         vp->val.i = exstat & 0xFF;
270                         break;
271                 case '#':
272                         vp->val.i = l->argc;
273                         break;
274                 case '-':
275                         vp->flag &= ~INTEGER;
276                         vp->val.s = getoptions();
277                         break;
278                 default:
279                         vp->flag &= ~(ISSET|INTEGER);
280                 }
281                 return (vp);
282         }
283         l = varsearch(e->loc, &vp, n, h);
284         if (vp != NULL)
285                 return (array ? arraysearch(vp, val) : vp);
286         vp = ktenter(&l->vars, n, h);
287         if (array)
288                 vp = arraysearch(vp, val);
289         vp->flag |= DEFINED;
290         if (special(n))
291                 vp->flag |= SPECIAL;
292         return (vp);
293 }
294
295 /*
296  * Search for local variable, if not found create locally.
297  */
298 struct tbl *
299 local(const char *n, bool copy)
300 {
301         struct block *l = e->loc;
302         struct tbl *vp;
303         bool array;
304         uint32_t h, val;
305
306         /*
307          * check to see if this is an array;
308          * dereference namerefs; must come first
309          */
310         n = array_index_calc(n, &array, &val);
311         mkssert(n != NULL);
312         h = hash(n);
313         if (!ksh_isalphx(*n)) {
314                 vp = &vtemp;
315                 vp->flag = DEFINED|RDONLY;
316                 vp->type = 0;
317                 vp->areap = ATEMP;
318                 return (vp);
319         }
320         vp = ktenter(&l->vars, n, h);
321         if (copy && !(vp->flag & DEFINED)) {
322                 struct tbl *vq;
323
324                 varsearch(l->next, &vq, n, h);
325                 if (vq != NULL) {
326                         vp->flag |= vq->flag &
327                             (EXPORT | INTEGER | RDONLY | LJUST | RJUST |
328                             ZEROFIL | LCASEV | UCASEV_AL | INT_U | INT_L);
329                         if (vq->flag & INTEGER)
330                                 vp->type = vq->type;
331                         vp->u2.field = vq->u2.field;
332                 }
333         }
334         if (array)
335                 vp = arraysearch(vp, val);
336         vp->flag |= DEFINED;
337         if (special(n))
338                 vp->flag |= SPECIAL;
339         return (vp);
340 }
341
342 /* get variable string value */
343 char *
344 str_val(struct tbl *vp)
345 {
346         char *s;
347
348         if ((vp->flag&SPECIAL))
349                 getspec(vp);
350         if (!(vp->flag&ISSET))
351                 /* special to dollar() */
352                 s = null;
353         else if (!(vp->flag&INTEGER))
354                 /* string source */
355                 s = vp->val.s + vp->type;
356         else {
357                 /* integer source */
358                 mksh_uari_t n;
359                 unsigned int base;
360                 /**
361                  * worst case number length is when base == 2:
362                  *      1 (minus) + 2 (base, up to 36) + 1 ('#') +
363                  *      number of bits in the mksh_uari_t + 1 (NUL)
364                  */
365                 char strbuf[1 + 2 + 1 + 8 * sizeof(mksh_uari_t) + 1];
366                 const char *digits = (vp->flag & UCASEV_AL) ?
367                     digits_uc : digits_lc;
368
369                 s = strbuf + sizeof(strbuf);
370                 if (vp->flag & INT_U)
371                         n = vp->val.u;
372                 else
373                         n = (vp->val.i < 0) ? -vp->val.u : vp->val.u;
374                 base = (vp->type == 0) ? 10U : (unsigned int)vp->type;
375
376                 if (base == 1 && n == 0)
377                         base = 2;
378                 if (base == 1) {
379                         size_t sz = 1;
380
381                         *(s = strbuf) = '1';
382                         s[1] = '#';
383                         if (!UTFMODE || ((n & 0xFF80) == 0xEF80))
384                                 /* OPTU-16 -> raw octet */
385                                 s[2] = n & 0xFF;
386                         else
387                                 sz = utf_wctomb(s + 2, n);
388                         s[2 + sz] = '\0';
389                 } else {
390                         *--s = '\0';
391                         do {
392                                 *--s = digits[n % base];
393                                 n /= base;
394                         } while (n != 0);
395                         if (base != 10) {
396                                 *--s = '#';
397                                 *--s = digits[base % 10];
398                                 if (base >= 10)
399                                         *--s = digits[base / 10];
400                         }
401                         if (!(vp->flag & INT_U) && vp->val.i < 0)
402                                 *--s = '-';
403                 }
404                 if (vp->flag & (RJUST|LJUST))
405                         /* case already dealt with */
406                         s = formatstr(vp, s);
407                 else
408                         strdupx(s, s, ATEMP);
409         }
410         return (s);
411 }
412
413 /* set variable to string value */
414 int
415 setstr(struct tbl *vq, const char *s, int error_ok)
416 {
417         char *salloc = NULL;
418         bool no_ro_check = tobool(error_ok & 0x4);
419
420         error_ok &= ~0x4;
421         if ((vq->flag & RDONLY) && !no_ro_check) {
422                 warningf(true, "read-only: %s", vq->name);
423                 if (!error_ok)
424                         errorfxz(2);
425                 return (0);
426         }
427         if (!(vq->flag&INTEGER)) {
428                 /* string dest */
429                 if ((vq->flag&ALLOC)) {
430 #ifndef MKSH_SMALL
431                         /* debugging */
432                         if (s >= vq->val.s &&
433                             s <= vq->val.s + strlen(vq->val.s)) {
434                                 internal_errorf(
435                                     "setstr: %s=%s: assigning to self",
436                                     vq->name, s);
437                         }
438 #endif
439                         afree(vq->val.s, vq->areap);
440                 }
441                 vq->flag &= ~(ISSET|ALLOC);
442                 vq->type = 0;
443                 if (s && (vq->flag & (UCASEV_AL|LCASEV|LJUST|RJUST)))
444                         s = salloc = formatstr(vq, s);
445                 if ((vq->flag&EXPORT))
446                         exportprep(vq, s);
447                 else {
448                         strdupx(vq->val.s, s, vq->areap);
449                         vq->flag |= ALLOC;
450                 }
451         } else {
452                 /* integer dest */
453                 if (!v_evaluate(vq, s, error_ok, true))
454                         return (0);
455         }
456         vq->flag |= ISSET;
457         if ((vq->flag&SPECIAL))
458                 setspec(vq);
459         afree(salloc, ATEMP);
460         return (1);
461 }
462
463 /* set variable to integer */
464 void
465 setint(struct tbl *vq, mksh_ari_t n)
466 {
467         if (!(vq->flag&INTEGER)) {
468                 struct tbl *vp = &vtemp;
469                 vp->flag = (ISSET|INTEGER);
470                 vp->type = 0;
471                 vp->areap = ATEMP;
472                 vp->val.i = n;
473                 /* setstr can't fail here */
474                 setstr(vq, str_val(vp), KSH_RETURN_ERROR);
475         } else
476                 vq->val.i = n;
477         vq->flag |= ISSET;
478         if ((vq->flag&SPECIAL))
479                 setspec(vq);
480 }
481
482 static int
483 getint(struct tbl *vp, mksh_ari_u *nump, bool arith)
484 {
485         mksh_uari_t c, num, base;
486         const char *s;
487         bool have_base = false, neg = false;
488
489         if (vp->flag&SPECIAL)
490                 getspec(vp);
491         /* XXX is it possible for ISSET to be set and val.s to be NULL? */
492         if (!(vp->flag&ISSET) || (!(vp->flag&INTEGER) && vp->val.s == NULL))
493                 return (-1);
494         if (vp->flag&INTEGER) {
495                 nump->i = vp->val.i;
496                 return (vp->type);
497         }
498         s = vp->val.s + vp->type;
499         base = 10;
500         num = 0;
501         if (arith && s[0] == '0' && (s[1] | 0x20) == 'x') {
502                 s += 2;
503                 base = 16;
504                 have_base = true;
505         }
506         if (Flag(FPOSIX) && arith && s[0] == '0' && ksh_isdigit(s[1]) &&
507             !(vp->flag & ZEROFIL)) {
508                 /* interpret as octal (deprecated) */
509                 base = 8;
510                 have_base = true;
511         }
512         while ((c = (unsigned char)*s++)) {
513                 if (c == '-') {
514                         neg = true;
515                         continue;
516                 } else if (c == '#') {
517                         if (have_base || num < 1 || num > 36)
518                                 return (-1);
519                         if ((base = num) == 1) {
520                                 unsigned int wc;
521
522                                 if (!UTFMODE)
523                                         wc = *(const unsigned char *)s;
524                                 else if (utf_mbtowc(&wc, s) == (size_t)-1)
525                                         /* OPTU-8 -> OPTU-16 */
526                                         /*
527                                          * (with a twist: 1#\uEF80 converts
528                                          * the same as 1#\x80 does, thus is
529                                          * not round-tripping correctly XXX)
530                                          */
531                                         wc = 0xEF00 + *(const unsigned char *)s;
532                                 nump->u = (mksh_uari_t)wc;
533                                 return (1);
534                         }
535                         num = 0;
536                         have_base = true;
537                         continue;
538                 } else if (ksh_isdigit(c))
539                         c -= '0';
540                 else if (ksh_islower(c))
541                         c -= 'a' - 10;
542                 else if (ksh_isupper(c))
543                         c -= 'A' - 10;
544                 else
545                         return (-1);
546                 if (c >= base)
547                         return (-1);
548                 num = num * base + c;
549         }
550         if (neg)
551                 num = -num;
552         nump->u = num;
553         return (base);
554 }
555
556 /*
557  * convert variable vq to integer variable, setting its value from vp
558  * (vq and vp may be the same)
559  */
560 struct tbl *
561 setint_v(struct tbl *vq, struct tbl *vp, bool arith)
562 {
563         int base;
564         mksh_ari_u num;
565
566         if ((base = getint(vp, &num, arith)) == -1)
567                 return (NULL);
568         setint_n(vq, num.i, 0);
569         if (vq->type == 0)
570                 /* default base */
571                 vq->type = base;
572         return (vq);
573 }
574
575 /* convert variable vq to integer variable, setting its value to num */
576 void
577 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
578 {
579         if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
580                 vq->flag &= ~ALLOC;
581                 vq->type = 0;
582                 afree(vq->val.s, vq->areap);
583         }
584         vq->val.i = num;
585         if (newbase != 0)
586                 vq->type = newbase;
587         vq->flag |= ISSET|INTEGER;
588         if (vq->flag&SPECIAL)
589                 setspec(vq);
590 }
591
592 static char *
593 formatstr(struct tbl *vp, const char *s)
594 {
595         int olen, nlen;
596         char *p, *q;
597         size_t psiz;
598
599         olen = (int)utf_mbswidth(s);
600
601         if (vp->flag & (RJUST|LJUST)) {
602                 if (!vp->u2.field)
603                         /* default field width */
604                         vp->u2.field = olen;
605                 nlen = vp->u2.field;
606         } else
607                 nlen = olen;
608
609         p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
610         if (vp->flag & (RJUST|LJUST)) {
611                 int slen = olen, i = 0;
612
613                 if (vp->flag & RJUST) {
614                         const char *qq = s;
615                         int n = 0;
616
617                         while (i < slen)
618                                 i += utf_widthadj(qq, &qq);
619                         /* strip trailing spaces (AT&T uses qq[-1] == ' ') */
620                         while (qq > s && ksh_isspace(qq[-1])) {
621                                 --qq;
622                                 --slen;
623                         }
624                         if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
625                                 if (!s[0] || !s[1])
626                                         goto uhm_no;
627                                 if (s[1] == '#')
628                                         n = 2;
629                                 else if (s[2] == '#')
630                                         n = 3;
631  uhm_no:
632                                 if (vp->u2.field <= n)
633                                         n = 0;
634                         }
635                         if (n) {
636                                 memcpy(p, s, n);
637                                 s += n;
638                         }
639                         while (slen > vp->u2.field)
640                                 slen -= utf_widthadj(s, &s);
641                         if (vp->u2.field - slen)
642                                 memset(p + n, (vp->flag & ZEROFIL) ? '0' : ' ',
643                                     vp->u2.field - slen);
644                         slen -= n;
645                         shf_snprintf(p + vp->u2.field - slen,
646                             psiz - (vp->u2.field - slen),
647                             "%.*s", slen, s);
648                 } else {
649                         /* strip leading spaces/zeros */
650                         while (ksh_isspace(*s))
651                                 s++;
652                         if (vp->flag & ZEROFIL)
653                                 while (*s == '0')
654                                         s++;
655                         shf_snprintf(p, nlen + 1, "%-*.*s",
656                                 vp->u2.field, vp->u2.field, s);
657                 }
658         } else
659                 memcpy(p, s, strlen(s) + 1);
660
661         if (vp->flag & UCASEV_AL) {
662                 for (q = p; *q; q++)
663                         *q = ksh_toupper(*q);
664         } else if (vp->flag & LCASEV) {
665                 for (q = p; *q; q++)
666                         *q = ksh_tolower(*q);
667         }
668
669         return (p);
670 }
671
672 /*
673  * make vp->val.s be "name=value" for quick exporting.
674  */
675 static void
676 exportprep(struct tbl *vp, const char *val)
677 {
678         char *xp;
679         char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
680         size_t namelen, vallen;
681
682         mkssert(val != NULL);
683
684         namelen = strlen(vp->name);
685         vallen = strlen(val) + 1;
686
687         vp->flag |= ALLOC;
688         /* since name+val are both in memory this can go unchecked */
689         xp = alloc(namelen + 1 + vallen, vp->areap);
690         memcpy(vp->val.s = xp, vp->name, namelen);
691         xp += namelen;
692         *xp++ = '=';
693         /* offset to value */
694         vp->type = xp - vp->val.s;
695         memcpy(xp, val, vallen);
696         if (op != NULL)
697                 afree(op, vp->areap);
698 }
699
700 /*
701  * lookup variable (according to (set&LOCAL)), set its attributes
702  * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV,
703  * UCASEV_AL), and optionally set its value if an assignment.
704  */
705 struct tbl *
706 typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
707 {
708         struct tbl *vp;
709         struct tbl *vpbase, *t;
710         char *tvar;
711         const char *val;
712         size_t len;
713         bool vappend = false;
714         enum namerefflag new_refflag = SRF_NOP;
715
716         if ((set & (ARRAY | ASSOC)) == ASSOC) {
717                 new_refflag = SRF_ENABLE;
718                 set &= ~(ARRAY | ASSOC);
719         }
720         if ((clr & (ARRAY | ASSOC)) == ASSOC) {
721                 new_refflag = SRF_DISABLE;
722                 clr &= ~(ARRAY | ASSOC);
723         }
724
725         /* check for valid variable name, search for value */
726         val = skip_varname(var, false);
727         if (val == var) {
728                 /* no variable name given */
729                 return (NULL);
730         }
731         if (*val == '[') {
732                 if (new_refflag != SRF_NOP)
733                         errorf("%s: %s", var,
734                             "reference variable can't be an array");
735                 len = array_ref_len(val);
736                 if (len == 0)
737                         return (NULL);
738                 /*
739                  * IMPORT is only used when the shell starts up and is
740                  * setting up its environment. Allow only simple array
741                  * references at this time since parameter/command
742                  * substitution is performed on the [expression] which
743                  * would be a major security hole.
744                  */
745                 if (set & IMPORT) {
746                         size_t i;
747
748                         for (i = 1; i < len - 1; i++)
749                                 if (!ksh_isdigit(val[i]))
750                                         return (NULL);
751                 }
752                 val += len;
753         }
754         if (val[0] == '=' || (val[0] == '+' && val[1] == '=')) {
755                 strndupx(tvar, var, val - var, ATEMP);
756                 if (*val++ == '+') {
757                         ++val;
758                         vappend = true;
759                 }
760         } else if ((val[0] != '\0') || (set & IMPORT)) {
761                 /*
762                  * must have a = when setting a variable by importing
763                  * the original environment, otherwise be empty; we
764                  * also end up here when a variable name was invalid
765                  */
766                 return (NULL);
767         } else {
768                 /* just varname with no value part nor equals sign */
769                 strdupx(tvar, var, ATEMP);
770                 val = NULL;
771                 /* handle foo[*] => foo (whole array) mapping for R39b */
772                 len = strlen(tvar);
773                 if (len > 3 && tvar[len - 3] == '[' && tvar[len - 2] == '*' &&
774                     tvar[len - 1] == ']')
775                         tvar[len - 3] = '\0';
776         }
777
778         if (new_refflag == SRF_ENABLE) {
779                 const char *qval, *ccp;
780
781                 /* bail out on 'nameref foo+=bar' */
782                 if (vappend)
783                         errorf("appending not allowed for nameref");
784                 /* find value if variable already exists */
785                 if ((qval = val) == NULL) {
786                         varsearch(e->loc, &vp, tvar, hash(tvar));
787                         if (vp != NULL)
788                                 qval = str_val(vp);
789                 }
790                 /* check target value for being a valid variable name */
791                 ccp = skip_varname(qval, false);
792                 if (ccp == qval)
793                         errorf("%s: %s", var, "empty nameref target");
794                 len = (*ccp == '[') ? array_ref_len(ccp) : 0;
795                 if (ccp[len]) {
796                         /*
797                          * works for cases "no array", "valid array with
798                          * junk after it" and "invalid array"; in the
799                          * latter case, len is also 0 and points to '['
800                          */
801                         errorf("%s: %s", qval,
802                             "nameref target not a valid parameter name");
803                 }
804                 /* prevent nameref loops */
805                 while (qval) {
806                         if (!strcmp(qval, tvar))
807                                 errorf("%s: %s", qval,
808                                     "expression recurses on parameter");
809                         varsearch(e->loc, &vp, qval, hash(qval));
810                         qval = NULL;
811                         if (vp && ((vp->flag & (ARRAY | ASSOC)) == ASSOC))
812                                 qval = str_val(vp);
813                 }
814         }
815
816         /* prevent typeset from creating a local PATH/ENV/SHELL */
817         if (Flag(FRESTRICTED) && (strcmp(tvar, "PATH") == 0 ||
818             strcmp(tvar, "ENV") == 0 || strcmp(tvar, "SHELL") == 0))
819                 errorf("%s: %s", tvar, "restricted");
820
821         innermost_refflag = new_refflag;
822         vp = (set & LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
823             global(tvar);
824         if (new_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
825                 vp->flag &= ~ASSOC;
826         else if (new_refflag == SRF_ENABLE) {
827                 if (vp->flag & ARRAY) {
828                         struct tbl *a, *tmp;
829
830                         /* free up entire array */
831                         for (a = vp->u.array; a; ) {
832                                 tmp = a;
833                                 a = a->u.array;
834                                 if (tmp->flag & ALLOC)
835                                         afree(tmp->val.s, tmp->areap);
836                                 afree(tmp, tmp->areap);
837                         }
838                         vp->u.array = NULL;
839                         vp->flag &= ~ARRAY;
840                 }
841                 vp->flag |= ASSOC;
842         }
843
844         set &= ~(LOCAL|LOCAL_COPY);
845
846         vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
847
848         /*
849          * only allow export flag to be set; AT&T ksh allows any
850          * attribute to be changed which means it can be truncated or
851          * modified (-L/-R/-Z/-i)
852          */
853         if ((vpbase->flag & RDONLY) &&
854             (val || clr || (set & ~EXPORT)))
855                 /* XXX check calls - is error here ok by POSIX? */
856                 errorfx(2, "read-only: %s", tvar);
857         afree(tvar, ATEMP);
858
859         /* most calls are with set/clr == 0 */
860         if (set | clr) {
861                 bool ok = true;
862
863                 /*
864                  * XXX if x[0] isn't set, there will be problems: need
865                  * to have one copy of attributes for arrays...
866                  */
867                 for (t = vpbase; t; t = t->u.array) {
868                         bool fake_assign;
869                         char *s = NULL;
870                         char *free_me = NULL;
871
872                         fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
873                             ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
874                             ((t->flag & INTEGER) && (clr & INTEGER)) ||
875                             (!(t->flag & INTEGER) && (set & INTEGER)));
876                         if (fake_assign) {
877                                 if (t->flag & INTEGER) {
878                                         s = str_val(t);
879                                         free_me = NULL;
880                                 } else {
881                                         s = t->val.s + t->type;
882                                         free_me = (t->flag & ALLOC) ? t->val.s :
883                                             NULL;
884                                 }
885                                 t->flag &= ~ALLOC;
886                         }
887                         if (!(t->flag & INTEGER) && (set & INTEGER)) {
888                                 t->type = 0;
889                                 t->flag &= ~ALLOC;
890                         }
891                         t->flag = (t->flag | set) & ~clr;
892                         /*
893                          * Don't change base if assignment is to be
894                          * done, in case assignment fails.
895                          */
896                         if ((set & INTEGER) && base > 0 && (!val || t != vp))
897                                 t->type = base;
898                         if (set & (LJUST|RJUST|ZEROFIL))
899                                 t->u2.field = field;
900                         if (fake_assign) {
901                                 if (!setstr(t, s, KSH_RETURN_ERROR)) {
902                                         /*
903                                          * Somewhat arbitrary action
904                                          * here: zap contents of
905                                          * variable, but keep the flag
906                                          * settings.
907                                          */
908                                         ok = false;
909                                         if (t->flag & INTEGER)
910                                                 t->flag &= ~ISSET;
911                                         else {
912                                                 if (t->flag & ALLOC)
913                                                         afree(t->val.s, t->areap);
914                                                 t->flag &= ~(ISSET|ALLOC);
915                                                 t->type = 0;
916                                         }
917                                 }
918                                 if (free_me)
919                                         afree(free_me, t->areap);
920                         }
921                 }
922                 if (!ok)
923                         errorfz();
924         }
925
926         if (val != NULL) {
927                 char *tval;
928
929                 if (vappend) {
930                         tval = shf_smprintf("%s%s", str_val(vp), val);
931                         val = tval;
932                 } else
933                         tval = NULL;
934
935                 if (vp->flag&INTEGER) {
936                         /* do not zero base before assignment */
937                         setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
938                         /* done after assignment to override default */
939                         if (base > 0)
940                                 vp->type = base;
941                 } else
942                         /* setstr can't fail (readonly check already done) */
943                         setstr(vp, val, KSH_RETURN_ERROR | 0x4);
944
945                 if (tval != NULL)
946                         afree(tval, ATEMP);
947         }
948
949         /* only x[0] is ever exported, so use vpbase */
950         if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
951             vpbase->type == 0)
952                 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
953
954         return (vp);
955 }
956
957 /**
958  * Unset a variable. The flags can be:
959  * |1   = tear down entire array
960  * |2   = keep attributes, only unset content
961  */
962 void
963 unset(struct tbl *vp, int flags)
964 {
965         if (vp->flag & ALLOC)
966                 afree(vp->val.s, vp->areap);
967         if ((vp->flag & ARRAY) && (flags & 1)) {
968                 struct tbl *a, *tmp;
969
970                 /* free up entire array */
971                 for (a = vp->u.array; a; ) {
972                         tmp = a;
973                         a = a->u.array;
974                         if (tmp->flag & ALLOC)
975                                 afree(tmp->val.s, tmp->areap);
976                         afree(tmp, tmp->areap);
977                 }
978                 vp->u.array = NULL;
979         }
980         if (flags & 2) {
981                 vp->flag &= ~(ALLOC|ISSET);
982                 return;
983         }
984         /* if foo[0] is being unset, the remainder of the array is kept... */
985         vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
986         if (vp->flag & SPECIAL)
987                 /* responsible for 'unspecial'ing var */
988                 unsetspec(vp);
989 }
990
991 /*
992  * Return a pointer to the first char past a legal variable name
993  * (returns the argument if there is no legal name, returns a pointer to
994  * the terminating NUL if whole string is legal).
995  */
996 const char *
997 skip_varname(const char *s, bool aok)
998 {
999         size_t alen;
1000
1001         if (s && ksh_isalphx(*s)) {
1002                 while (*++s && ksh_isalnux(*s))
1003                         ;
1004                 if (aok && *s == '[' && (alen = array_ref_len(s)))
1005                         s += alen;
1006         }
1007         return (s);
1008 }
1009
1010 /* Return a pointer to the first character past any legal variable name */
1011 const char *
1012 skip_wdvarname(const char *s,
1013     /* skip array de-reference? */
1014     bool aok)
1015 {
1016         if (s[0] == CHAR && ksh_isalphx(s[1])) {
1017                 do {
1018                         s += 2;
1019                 } while (s[0] == CHAR && ksh_isalnux(s[1]));
1020                 if (aok && s[0] == CHAR && s[1] == '[') {
1021                         /* skip possible array de-reference */
1022                         const char *p = s;
1023                         char c;
1024                         int depth = 0;
1025
1026                         while (/* CONSTCOND */ 1) {
1027                                 if (p[0] != CHAR)
1028                                         break;
1029                                 c = p[1];
1030                                 p += 2;
1031                                 if (c == '[')
1032                                         depth++;
1033                                 else if (c == ']' && --depth == 0) {
1034                                         s = p;
1035                                         break;
1036                                 }
1037                         }
1038                 }
1039         }
1040         return (s);
1041 }
1042
1043 /* Check if coded string s is a variable name */
1044 int
1045 is_wdvarname(const char *s, bool aok)
1046 {
1047         const char *p = skip_wdvarname(s, aok);
1048
1049         return (p != s && p[0] == EOS);
1050 }
1051
1052 /* Check if coded string s is a variable assignment */
1053 int
1054 is_wdvarassign(const char *s)
1055 {
1056         const char *p = skip_wdvarname(s, true);
1057
1058         return (p != s && p[0] == CHAR &&
1059             (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1060 }
1061
1062 /*
1063  * Make the exported environment from the exported names in the dictionary.
1064  */
1065 char **
1066 makenv(void)
1067 {
1068         ssize_t i;
1069         struct block *l;
1070         XPtrV denv;
1071         struct tbl *vp, **vpp;
1072
1073         XPinit(denv, 64);
1074         for (l = e->loc; l != NULL; l = l->next) {
1075                 vpp = l->vars.tbls;
1076                 i = 1 << (l->vars.tshift);
1077                 while (--i >= 0)
1078                         if ((vp = *vpp++) != NULL &&
1079                             (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1080                                 struct block *l2;
1081                                 struct tbl *vp2;
1082                                 uint32_t h = hash(vp->name);
1083
1084                                 /* unexport any redefined instances */
1085                                 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1086                                         vp2 = ktsearch(&l2->vars, vp->name, h);
1087                                         if (vp2 != NULL)
1088                                                 vp2->flag &= ~EXPORT;
1089                                 }
1090                                 if ((vp->flag&INTEGER)) {
1091                                         /* integer to string */
1092                                         char *val;
1093                                         val = str_val(vp);
1094                                         vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1095                                         /* setstr can't fail here */
1096                                         setstr(vp, val, KSH_RETURN_ERROR);
1097                                 }
1098                                 XPput(denv, vp->val.s);
1099                         }
1100         }
1101         XPput(denv, NULL);
1102         return ((char **)XPclose(denv));
1103 }
1104
1105 /*
1106  * handle special variables with side effects - PATH, SECONDS.
1107  */
1108
1109 /* Test if name is a special parameter */
1110 static int
1111 special(const char *name)
1112 {
1113         struct tbl *tp;
1114
1115         tp = ktsearch(&specials, name, hash(name));
1116         return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1117 }
1118
1119 /* Make a variable non-special */
1120 static void
1121 unspecial(const char *name)
1122 {
1123         struct tbl *tp;
1124
1125         tp = ktsearch(&specials, name, hash(name));
1126         if (tp)
1127                 ktdelete(tp);
1128 }
1129
1130 static time_t seconds;          /* time SECONDS last set */
1131 static int user_lineno;         /* what user set $LINENO to */
1132
1133 static void
1134 getspec(struct tbl *vp)
1135 {
1136         mksh_ari_u num;
1137         int st;
1138         struct timeval tv;
1139
1140         switch ((st = special(vp->name))) {
1141         case V_COLUMNS:
1142         case V_LINES:
1143                 /*
1144                  * Do NOT export COLUMNS/LINES. Many applications
1145                  * check COLUMNS/LINES before checking ws.ws_col/row,
1146                  * so if the app is started with C/L in the environ
1147                  * and the window is then resized, the app won't
1148                  * see the change cause the environ doesn't change.
1149                  */
1150                 if (got_winch)
1151                         change_winsz();
1152                 break;
1153         }
1154         switch (st) {
1155         case V_BASHPID:
1156                 num.u = (mksh_uari_t)procpid;
1157                 break;
1158         case V_COLUMNS:
1159                 num.i = x_cols;
1160                 break;
1161         case V_HISTSIZE:
1162                 num.i = histsize;
1163                 break;
1164         case V_LINENO:
1165                 num.i = current_lineno + user_lineno;
1166                 break;
1167         case V_LINES:
1168                 num.i = x_lins;
1169                 break;
1170         case V_EPOCHREALTIME: {
1171                 /* 10(%u) + 1(.) + 6 + NUL */
1172                 char buf[18];
1173
1174                 vp->flag &= ~SPECIAL;
1175                 mksh_TIME(tv);
1176                 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1177                     (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1178                 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1179                 vp->flag |= SPECIAL;
1180                 return;
1181         }
1182         case V_OPTIND:
1183                 num.i = user_opt.uoptind;
1184                 break;
1185         case V_RANDOM:
1186                 num.i = rndget();
1187                 break;
1188         case V_SECONDS:
1189                 /*
1190                  * On start up the value of SECONDS is used before
1191                  * it has been set - don't do anything in this case
1192                  * (see initcoms[] in main.c).
1193                  */
1194                 if (vp->flag & ISSET) {
1195                         mksh_TIME(tv);
1196                         num.i = tv.tv_sec - seconds;
1197                 } else
1198                         return;
1199                 break;
1200         default:
1201                 /* do nothing, do not touch vp at all */
1202                 return;
1203         }
1204         vp->flag &= ~SPECIAL;
1205         setint_n(vp, num.i, 0);
1206         vp->flag |= SPECIAL;
1207 }
1208
1209 static void
1210 setspec(struct tbl *vp)
1211 {
1212         mksh_ari_u num;
1213         char *s;
1214         int st;
1215
1216         switch ((st = special(vp->name))) {
1217 #if HAVE_PERSISTENT_HISTORY
1218         case V_HISTFILE:
1219                 sethistfile(str_val(vp));
1220                 return;
1221 #endif
1222         case V_IFS:
1223                 setctypes(s = str_val(vp), C_IFS);
1224                 ifs0 = *s;
1225                 return;
1226         case V_PATH:
1227                 if (path)
1228                         afree(path, APERM);
1229                 s = str_val(vp);
1230                 strdupx(path, s, APERM);
1231                 /* clear tracked aliases */
1232                 flushcom(true);
1233                 return;
1234         case V_TMPDIR:
1235                 if (tmpdir) {
1236                         afree(tmpdir, APERM);
1237                         tmpdir = NULL;
1238                 }
1239                 /*
1240                  * Use tmpdir iff it is an absolute path, is writable
1241                  * and searchable and is a directory...
1242                  */
1243                 {
1244                         struct stat statb;
1245
1246                         s = str_val(vp);
1247                         /* LINTED use of access */
1248                         if (s[0] == '/' && access(s, W_OK|X_OK) == 0 &&
1249                             stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1250                                 strdupx(tmpdir, s, APERM);
1251                 }
1252                 return;
1253         /* common sub-cases */
1254         case V_COLUMNS:
1255         case V_LINES:
1256                 if (vp->flag & IMPORT) {
1257                         /* do not touch */
1258                         unspecial(vp->name);
1259                         vp->flag &= ~SPECIAL;
1260                         return;
1261                 }
1262                 /* FALLTHROUGH */
1263         case V_HISTSIZE:
1264         case V_LINENO:
1265         case V_OPTIND:
1266         case V_RANDOM:
1267         case V_SECONDS:
1268         case V_TMOUT:
1269                 vp->flag &= ~SPECIAL;
1270                 if (getint(vp, &num, false) == -1) {
1271                         s = str_val(vp);
1272                         if (st != V_RANDOM)
1273                                 errorf("%s: %s: %s", vp->name, "bad number", s);
1274                         num.u = hash(s);
1275                 }
1276                 vp->flag |= SPECIAL;
1277                 break;
1278         default:
1279                 /* do nothing, do not touch vp at all */
1280                 return;
1281         }
1282
1283         /* process the singular parts of the common cases */
1284
1285         switch (st) {
1286         case V_COLUMNS:
1287                 if (num.i >= MIN_COLS)
1288                         x_cols = num.i;
1289                 break;
1290         case V_HISTSIZE:
1291                 sethistsize(num.i);
1292                 break;
1293         case V_LINENO:
1294                 /* The -1 is because line numbering starts at 1. */
1295                 user_lineno = num.u - current_lineno - 1;
1296                 break;
1297         case V_LINES:
1298                 if (num.i >= MIN_LINS)
1299                         x_lins = num.i;
1300                 break;
1301         case V_OPTIND:
1302                 getopts_reset((int)num.i);
1303                 break;
1304         case V_RANDOM:
1305                 /*
1306                  * mksh R39d+ no longer has the traditional repeatability
1307                  * of $RANDOM sequences, but always retains state
1308                  */
1309                 rndset((unsigned long)num.u);
1310                 break;
1311         case V_SECONDS:
1312                 {
1313                         struct timeval tv;
1314
1315                         mksh_TIME(tv);
1316                         seconds = tv.tv_sec - num.i;
1317                 }
1318                 break;
1319         case V_TMOUT:
1320                 ksh_tmout = num.i >= 0 ? num.i : 0;
1321                 break;
1322         }
1323 }
1324
1325 static void
1326 unsetspec(struct tbl *vp)
1327 {
1328         /*
1329          * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1330          * meaning, but OPTARG does not (still set by getopts) and _ is
1331          * also still set in various places. Don't know what AT&T does
1332          * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1333          * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1334          */
1335
1336         switch (special(vp->name)) {
1337         case V_IFS:
1338                 setctypes(TC_IFSWS, C_IFS);
1339                 ifs0 = ' ';
1340                 break;
1341         case V_PATH:
1342                 if (path)
1343                         afree(path, APERM);
1344                 strdupx(path, def_path, APERM);
1345                 /* clear tracked aliases */
1346                 flushcom(true);
1347                 break;
1348         case V_TMPDIR:
1349                 /* should not become unspecial */
1350                 if (tmpdir) {
1351                         afree(tmpdir, APERM);
1352                         tmpdir = NULL;
1353                 }
1354                 break;
1355         case V_LINENO:
1356         case V_RANDOM:
1357         case V_SECONDS:
1358         case V_TMOUT:
1359                 /* AT&T ksh leaves previous value in place */
1360                 unspecial(vp->name);
1361                 break;
1362         }
1363 }
1364
1365 /*
1366  * Search for (and possibly create) a table entry starting with
1367  * vp, indexed by val.
1368  */
1369 struct tbl *
1370 arraysearch(struct tbl *vp, uint32_t val)
1371 {
1372         struct tbl *prev, *curr, *news;
1373         size_t len;
1374
1375         vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
1376         /* the table entry is always [0] */
1377         if (val == 0)
1378                 return (vp);
1379         prev = vp;
1380         curr = vp->u.array;
1381         while (curr && curr->ua.index < val) {
1382                 prev = curr;
1383                 curr = curr->u.array;
1384         }
1385         if (curr && curr->ua.index == val) {
1386                 if (curr->flag&ISSET)
1387                         return (curr);
1388                 news = curr;
1389         } else
1390                 news = NULL;
1391         if (!news) {
1392                 len = strlen(vp->name);
1393                 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1394                 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1395                 memcpy(news->name, vp->name, len);
1396         }
1397         news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1398         news->type = vp->type;
1399         news->areap = vp->areap;
1400         news->u2.field = vp->u2.field;
1401         news->ua.index = val;
1402
1403         if (curr != news) {
1404                 /* not reusing old array entry */
1405                 prev->u.array = news;
1406                 news->u.array = curr;
1407         }
1408         return (news);
1409 }
1410
1411 /*
1412  * Return the length of an array reference (eg, [1+2]) - cp is assumed
1413  * to point to the open bracket. Returns 0 if there is no matching
1414  * closing bracket.
1415  *
1416  * XXX this should parse the actual arithmetic syntax
1417  */
1418 size_t
1419 array_ref_len(const char *cp)
1420 {
1421         const char *s = cp;
1422         char c;
1423         int depth = 0;
1424
1425         while ((c = *s++) && (c != ']' || --depth))
1426                 if (c == '[')
1427                         depth++;
1428         if (!c)
1429                 return (0);
1430         return (s - cp);
1431 }
1432
1433 /*
1434  * Make a copy of the base of an array name
1435  */
1436 char *
1437 arrayname(const char *str)
1438 {
1439         const char *p;
1440         char *rv;
1441
1442         if ((p = cstrchr(str, '[')) == 0)
1443                 /* Shouldn't happen, but why worry? */
1444                 strdupx(rv, str, ATEMP);
1445         else
1446                 strndupx(rv, str, p - str, ATEMP);
1447
1448         return (rv);
1449 }
1450
1451 /* set (or overwrite, if reset) the array variable var to the values in vals */
1452 mksh_uari_t
1453 set_array(const char *var, bool reset, const char **vals)
1454 {
1455         struct tbl *vp, *vq;
1456         mksh_uari_t i = 0, j = 0;
1457         const char *ccp = var;
1458         char *cp = NULL;
1459         size_t n;
1460
1461         /* to get local array, use "local foo; set -A foo" */
1462         n = strlen(var);
1463         if (n > 0 && var[n - 1] == '+') {
1464                 /* append mode */
1465                 reset = false;
1466                 strndupx(cp, var, n - 1, ATEMP);
1467                 ccp = cp;
1468         }
1469         vp = global(ccp);
1470
1471         /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1472         if ((vp->flag&RDONLY))
1473                 errorfx(2, "read-only: %s", ccp);
1474         /* This code is quite non-optimal */
1475         if (reset) {
1476                 /* trash existing values and attributes */
1477                 unset(vp, 1);
1478                 /* allocate-by-access the [0] element to keep in scope */
1479                 arraysearch(vp, 0);
1480         }
1481         /*
1482          * TODO: would be nice for assignment to completely succeed or
1483          * completely fail. Only really effects integer arrays:
1484          * evaluation of some of vals[] may fail...
1485          */
1486         if (cp != NULL) {
1487                 /* find out where to set when appending */
1488                 for (vq = vp; vq; vq = vq->u.array) {
1489                         if (!(vq->flag & ISSET))
1490                                 continue;
1491                         if (arrayindex(vq) >= j)
1492                                 j = arrayindex(vq) + 1;
1493                 }
1494                 afree(cp, ATEMP);
1495         }
1496         while ((ccp = vals[i])) {
1497 #if 0 /* temporarily taken out due to regression */
1498                 if (*ccp == '[') {
1499                         int level = 0;
1500
1501                         while (*ccp) {
1502                                 if (*ccp == ']' && --level == 0)
1503                                         break;
1504                                 if (*ccp == '[')
1505                                         ++level;
1506                                 ++ccp;
1507                         }
1508                         if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1509                                 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1510                                     ATEMP);
1511                                 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1512                                     KSH_UNWIND_ERROR, true);
1513                                 afree(cp, ATEMP);
1514                                 ccp += 2;
1515                         } else
1516                                 ccp = vals[i];
1517                 }
1518 #endif
1519
1520                 vq = arraysearch(vp, j);
1521                 /* would be nice to deal with errors here... (see above) */
1522                 setstr(vq, ccp, KSH_RETURN_ERROR);
1523                 i++;
1524                 j++;
1525         }
1526
1527         return (i);
1528 }
1529
1530 void
1531 change_winsz(void)
1532 {
1533         struct timeval tv;
1534
1535         mksh_TIME(tv);
1536         BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
1537
1538 #ifdef TIOCGWINSZ
1539         /* check if window size has changed */
1540         if (tty_init_fd() < 2) {
1541                 struct winsize ws;
1542
1543                 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1544                         if (ws.ws_col)
1545                                 x_cols = ws.ws_col;
1546                         if (ws.ws_row)
1547                                 x_lins = ws.ws_row;
1548                 }
1549         }
1550 #endif
1551
1552         /* bounds check for sane values, use defaults otherwise */
1553         if (x_cols < MIN_COLS)
1554                 x_cols = 80;
1555         if (x_lins < MIN_LINS)
1556                 x_lins = 24;
1557
1558 #ifdef SIGWINCH
1559         got_winch = 0;
1560 #endif
1561 }
1562
1563 uint32_t
1564 hash(const void *s)
1565 {
1566         register uint32_t h;
1567
1568         BAFHInit(h);
1569         BAFHUpdateStr_reg(h, s);
1570         BAFHFinish_reg(h);
1571         return (h);
1572 }
1573
1574 uint32_t
1575 chvt_rndsetup(const void *bp, size_t sz)
1576 {
1577         register uint32_t h;
1578
1579         /* use LCG as seed but try to get them to deviate immediately */
1580         h = lcg_state;
1581         (void)rndget();
1582         BAFHFinish_reg(h);
1583         /* variation through pid, ppid, and the works */
1584         BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
1585         /* some variation, some possibly entropy, depending on OE */
1586         BAFHUpdateMem_reg(h, bp, sz);
1587         /* mix them all up */
1588         BAFHFinish_reg(h);
1589
1590         return (h);
1591 }
1592
1593 mksh_ari_t
1594 rndget(void)
1595 {
1596         /*
1597          * this is the same Linear Congruential PRNG as Borland
1598          * C/C++ allegedly uses in its built-in rand() function
1599          */
1600         return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1601 }
1602
1603 void
1604 rndset(unsigned long v)
1605 {
1606         register uint32_t h;
1607 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1608         register uint32_t t;
1609 #endif
1610         struct {
1611                 struct timeval tv;
1612                 void *sp;
1613                 uint32_t qh;
1614                 pid_t pp;
1615                 short r;
1616         } z;
1617
1618 #ifdef DEBUG
1619         /* clear the allocated space, for valgrind */
1620         memset(&z, 0, sizeof(z));
1621 #endif
1622
1623         h = lcg_state;
1624         BAFHFinish_reg(h);
1625         BAFHUpdateMem_reg(h, &v, sizeof(v));
1626
1627         mksh_TIME(z.tv);
1628         z.sp = &lcg_state;
1629         z.pp = procpid;
1630         z.r = (short)rndget();
1631
1632 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1633         t = qh_state;
1634         BAFHFinish_reg(t);
1635         z.qh = (t & 0xFFFF8000) | rndget();
1636         lcg_state = (t << 15) | rndget();
1637         /*
1638          * either we have very chap entropy get and push available,
1639          * with malloc() pulling in this code already anyway, or the
1640          * user requested us to use the old functions
1641          */
1642         t = h;
1643         BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
1644         BAFHFinish_reg(t);
1645         lcg_state = t;
1646 #if defined(arc4random_pushb_fast)
1647         arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1648         lcg_state = arc4random();
1649 #else
1650         lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1651 #endif
1652         BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
1653 #else
1654         z.qh = qh_state;
1655 #endif
1656
1657         BAFHUpdateMem_reg(h, &z, sizeof(z));
1658         BAFHFinish_reg(h);
1659         lcg_state = h;
1660 }
1661
1662 void
1663 rndpush(const void *s)
1664 {
1665         register uint32_t h = qh_state;
1666
1667         BAFHUpdateStr_reg(h, s);
1668         BAFHUpdateOctet_reg(h, 0);
1669         qh_state = h;
1670 }