OSDN Git Service

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