OSDN Git Service

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