OSDN Git Service

Merge "Upgrade to mksh R53a." am: c19d20531c am: 8b302a0123 am: c8ed698e56
[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.207 2016/08/01 21:38: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 15 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                                 XPput(denv, vp->val.s);
1153                         }
1154                 if (l->flags & BF_STOPENV)
1155                         break;
1156         }
1157         XPput(denv, NULL);
1158         return ((char **)XPclose(denv));
1159 }
1160
1161 /*
1162  * handle special variables with side effects - PATH, SECONDS.
1163  */
1164
1165 /* Test if name is a special parameter */
1166 static int
1167 special(const char *name)
1168 {
1169         struct tbl *tp;
1170
1171         tp = ktsearch(&specials, name, hash(name));
1172         return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1173 }
1174
1175 /* Make a variable non-special */
1176 static void
1177 unspecial(const char *name)
1178 {
1179         struct tbl *tp;
1180
1181         tp = ktsearch(&specials, name, hash(name));
1182         if (tp)
1183                 ktdelete(tp);
1184 }
1185
1186 static time_t seconds;          /* time SECONDS last set */
1187 static mksh_uari_t user_lineno; /* what user set $LINENO to */
1188
1189 /* minimum values from the OS we consider sane, lowered for R53 */
1190 #define MIN_COLS        4
1191 #define MIN_LINS        2
1192
1193 static void
1194 getspec(struct tbl *vp)
1195 {
1196         mksh_ari_u num;
1197         int st;
1198         struct timeval tv;
1199
1200         switch ((st = special(vp->name))) {
1201         case V_COLUMNS:
1202         case V_LINES:
1203                 /*
1204                  * Do NOT export COLUMNS/LINES. Many applications
1205                  * check COLUMNS/LINES before checking ws.ws_col/row,
1206                  * so if the app is started with C/L in the environ
1207                  * and the window is then resized, the app won't
1208                  * see the change cause the environ doesn't change.
1209                  */
1210                 if (got_winch)
1211                         change_winsz();
1212                 break;
1213         }
1214         switch (st) {
1215         case V_BASHPID:
1216                 num.u = (mksh_uari_t)procpid;
1217                 break;
1218         case V_COLUMNS:
1219                 num.i = x_cols;
1220                 break;
1221         case V_HISTSIZE:
1222                 num.i = histsize;
1223                 break;
1224         case V_LINENO:
1225                 num.u = (mksh_uari_t)current_lineno + user_lineno;
1226                 break;
1227         case V_LINES:
1228                 num.i = x_lins;
1229                 break;
1230         case V_EPOCHREALTIME: {
1231                 /* 10(%u) + 1(.) + 6 + NUL */
1232                 char buf[18];
1233
1234                 vp->flag &= ~SPECIAL;
1235                 mksh_TIME(tv);
1236                 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1237                     (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1238                 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1239                 vp->flag |= SPECIAL;
1240                 return;
1241         }
1242         case V_OPTIND:
1243                 num.i = user_opt.uoptind;
1244                 break;
1245         case V_RANDOM:
1246                 num.i = rndget();
1247                 break;
1248         case V_SECONDS:
1249                 /*
1250                  * On start up the value of SECONDS is used before
1251                  * it has been set - don't do anything in this case
1252                  * (see initcoms[] in main.c).
1253                  */
1254                 if (vp->flag & ISSET) {
1255                         mksh_TIME(tv);
1256                         num.i = tv.tv_sec - seconds;
1257                 } else
1258                         return;
1259                 break;
1260         default:
1261                 /* do nothing, do not touch vp at all */
1262                 return;
1263         }
1264         vp->flag &= ~SPECIAL;
1265         setint_n(vp, num.i, 0);
1266         vp->flag |= SPECIAL;
1267 }
1268
1269 static void
1270 setspec(struct tbl *vp)
1271 {
1272         mksh_ari_u num;
1273         char *s;
1274         int st;
1275
1276         switch ((st = special(vp->name))) {
1277 #if HAVE_PERSISTENT_HISTORY
1278         case V_HISTFILE:
1279                 sethistfile(str_val(vp));
1280                 return;
1281 #endif
1282         case V_IFS:
1283                 setctypes(s = str_val(vp), C_IFS);
1284                 ifs0 = *s;
1285                 return;
1286         case V_PATH:
1287                 afree(path, APERM);
1288                 s = str_val(vp);
1289                 strdupx(path, s, APERM);
1290                 /* clear tracked aliases */
1291                 flushcom(true);
1292                 return;
1293 #ifndef MKSH_NO_CMDLINE_EDITING
1294         case V_TERM:
1295                 x_initterm(str_val(vp));
1296                 return;
1297 #endif
1298         case V_TMPDIR:
1299                 afree(tmpdir, APERM);
1300                 tmpdir = NULL;
1301                 /*
1302                  * Use tmpdir iff it is an absolute path, is writable
1303                  * and searchable and is a directory...
1304                  */
1305                 {
1306                         struct stat statb;
1307
1308                         s = str_val(vp);
1309                         /* LINTED use of access */
1310                         if (mksh_abspath(s) && access(s, W_OK|X_OK) == 0 &&
1311                             stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1312                                 strdupx(tmpdir, s, APERM);
1313                 }
1314                 return;
1315         /* common sub-cases */
1316         case V_COLUMNS:
1317         case V_LINES:
1318                 if (vp->flag & IMPORT) {
1319                         /* do not touch */
1320                         unspecial(vp->name);
1321                         vp->flag &= ~SPECIAL;
1322                         return;
1323                 }
1324                 /* FALLTHROUGH */
1325         case V_HISTSIZE:
1326         case V_LINENO:
1327         case V_OPTIND:
1328         case V_RANDOM:
1329         case V_SECONDS:
1330         case V_TMOUT:
1331                 vp->flag &= ~SPECIAL;
1332                 if (getint(vp, &num, false) == -1) {
1333                         s = str_val(vp);
1334                         if (st != V_RANDOM)
1335                                 errorf(Tf_sD_sD_s, vp->name, "bad number", s);
1336                         num.u = hash(s);
1337                 }
1338                 vp->flag |= SPECIAL;
1339                 break;
1340         default:
1341                 /* do nothing, do not touch vp at all */
1342                 return;
1343         }
1344
1345         /* process the singular parts of the common cases */
1346
1347         switch (st) {
1348         case V_COLUMNS:
1349                 if (num.i >= MIN_COLS)
1350                         x_cols = num.i;
1351                 break;
1352         case V_HISTSIZE:
1353                 sethistsize(num.i);
1354                 break;
1355         case V_LINENO:
1356                 /* The -1 is because line numbering starts at 1. */
1357                 user_lineno = num.u - (mksh_uari_t)current_lineno - 1;
1358                 break;
1359         case V_LINES:
1360                 if (num.i >= MIN_LINS)
1361                         x_lins = num.i;
1362                 break;
1363         case V_OPTIND:
1364                 getopts_reset((int)num.i);
1365                 break;
1366         case V_RANDOM:
1367                 /*
1368                  * mksh R39d+ no longer has the traditional repeatability
1369                  * of $RANDOM sequences, but always retains state
1370                  */
1371                 rndset((unsigned long)num.u);
1372                 break;
1373         case V_SECONDS:
1374                 {
1375                         struct timeval tv;
1376
1377                         mksh_TIME(tv);
1378                         seconds = tv.tv_sec - num.i;
1379                 }
1380                 break;
1381         case V_TMOUT:
1382                 ksh_tmout = num.i >= 0 ? num.i : 0;
1383                 break;
1384         }
1385 }
1386
1387 static void
1388 unsetspec(struct tbl *vp)
1389 {
1390         /*
1391          * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1392          * meaning, but OPTARG does not (still set by getopts) and _ is
1393          * also still set in various places. Don't know what AT&T does
1394          * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1395          * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1396          */
1397
1398         switch (special(vp->name)) {
1399 #if HAVE_PERSISTENT_HISTORY
1400         case V_HISTFILE:
1401                 sethistfile(NULL);
1402                 return;
1403 #endif
1404         case V_IFS:
1405                 setctypes(TC_IFSWS, C_IFS);
1406                 ifs0 = ' ';
1407                 break;
1408         case V_PATH:
1409                 afree(path, APERM);
1410                 strdupx(path, def_path, APERM);
1411                 /* clear tracked aliases */
1412                 flushcom(true);
1413                 break;
1414 #ifndef MKSH_NO_CMDLINE_EDITING
1415         case V_TERM:
1416                 x_initterm(null);
1417                 return;
1418 #endif
1419         case V_TMPDIR:
1420                 /* should not become unspecial */
1421                 if (tmpdir) {
1422                         afree(tmpdir, APERM);
1423                         tmpdir = NULL;
1424                 }
1425                 break;
1426         case V_LINENO:
1427         case V_RANDOM:
1428         case V_SECONDS:
1429         case V_TMOUT:
1430                 /* AT&T ksh leaves previous value in place */
1431                 unspecial(vp->name);
1432                 break;
1433         }
1434 }
1435
1436 /*
1437  * Search for (and possibly create) a table entry starting with
1438  * vp, indexed by val.
1439  */
1440 struct tbl *
1441 arraysearch(struct tbl *vp, uint32_t val)
1442 {
1443         struct tbl *prev, *curr, *news;
1444         size_t len;
1445
1446         vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
1447         /* the table entry is always [0] */
1448         if (val == 0)
1449                 return (vp);
1450         prev = vp;
1451         curr = vp->u.array;
1452         while (curr && curr->ua.index < val) {
1453                 prev = curr;
1454                 curr = curr->u.array;
1455         }
1456         if (curr && curr->ua.index == val) {
1457                 if (curr->flag&ISSET)
1458                         return (curr);
1459                 news = curr;
1460         } else
1461                 news = NULL;
1462         if (!news) {
1463                 len = strlen(vp->name);
1464                 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1465                 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1466                 memcpy(news->name, vp->name, len);
1467         }
1468         news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1469         news->type = vp->type;
1470         news->areap = vp->areap;
1471         news->u2.field = vp->u2.field;
1472         news->ua.index = val;
1473
1474         if (curr != news) {
1475                 /* not reusing old array entry */
1476                 prev->u.array = news;
1477                 news->u.array = curr;
1478         }
1479         return (news);
1480 }
1481
1482 /*
1483  * Return the length of an array reference (eg, [1+2]) - cp is assumed
1484  * to point to the open bracket. Returns 0 if there is no matching
1485  * closing bracket.
1486  *
1487  * XXX this should parse the actual arithmetic syntax
1488  */
1489 size_t
1490 array_ref_len(const char *cp)
1491 {
1492         const char *s = cp;
1493         char c;
1494         int depth = 0;
1495
1496         while ((c = *s++) && (c != ']' || --depth))
1497                 if (c == '[')
1498                         depth++;
1499         if (!c)
1500                 return (0);
1501         return (s - cp);
1502 }
1503
1504 /*
1505  * Make a copy of the base of an array name
1506  */
1507 char *
1508 arrayname(const char *str)
1509 {
1510         const char *p;
1511         char *rv;
1512
1513         if (!(p = cstrchr(str, '[')))
1514                 /* Shouldn't happen, but why worry? */
1515                 strdupx(rv, str, ATEMP);
1516         else
1517                 strndupx(rv, str, p - str, ATEMP);
1518
1519         return (rv);
1520 }
1521
1522 /* set (or overwrite, if reset) the array variable var to the values in vals */
1523 mksh_uari_t
1524 set_array(const char *var, bool reset, const char **vals)
1525 {
1526         struct tbl *vp, *vq;
1527         mksh_uari_t i = 0, j = 0;
1528         const char *ccp = var;
1529         char *cp = NULL;
1530         size_t n;
1531
1532         /* to get local array, use "local foo; set -A foo" */
1533         n = strlen(var);
1534         if (n > 0 && var[n - 1] == '+') {
1535                 /* append mode */
1536                 reset = false;
1537                 strndupx(cp, var, n - 1, ATEMP);
1538                 ccp = cp;
1539         }
1540         vp = global(ccp);
1541
1542         /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1543         if ((vp->flag&RDONLY))
1544                 errorfx(2, Tf_ro, ccp);
1545         /* This code is quite non-optimal */
1546         if (reset) {
1547                 /* trash existing values and attributes */
1548                 unset(vp, 1);
1549                 /* allocate-by-access the [0] element to keep in scope */
1550                 arraysearch(vp, 0);
1551         }
1552         /*
1553          * TODO: would be nice for assignment to completely succeed or
1554          * completely fail. Only really effects integer arrays:
1555          * evaluation of some of vals[] may fail...
1556          */
1557         if (cp != NULL) {
1558                 /* find out where to set when appending */
1559                 for (vq = vp; vq; vq = vq->u.array) {
1560                         if (!(vq->flag & ISSET))
1561                                 continue;
1562                         if (arrayindex(vq) >= j)
1563                                 j = arrayindex(vq) + 1;
1564                 }
1565                 afree(cp, ATEMP);
1566         }
1567         while ((ccp = vals[i])) {
1568 #if 0 /* temporarily taken out due to regression */
1569                 if (*ccp == '[') {
1570                         int level = 0;
1571
1572                         while (*ccp) {
1573                                 if (*ccp == ']' && --level == 0)
1574                                         break;
1575                                 if (*ccp == '[')
1576                                         ++level;
1577                                 ++ccp;
1578                         }
1579                         if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1580                                 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1581                                     ATEMP);
1582                                 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1583                                     KSH_UNWIND_ERROR, true);
1584                                 afree(cp, ATEMP);
1585                                 ccp += 2;
1586                         } else
1587                                 ccp = vals[i];
1588                 }
1589 #endif
1590
1591                 vq = arraysearch(vp, j);
1592                 /* would be nice to deal with errors here... (see above) */
1593                 setstr(vq, ccp, KSH_RETURN_ERROR);
1594                 i++;
1595                 j++;
1596         }
1597
1598         return (i);
1599 }
1600
1601 void
1602 change_winsz(void)
1603 {
1604         struct timeval tv;
1605
1606         mksh_TIME(tv);
1607         BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
1608
1609 #ifdef TIOCGWINSZ
1610         /* check if window size has changed */
1611         if (tty_init_fd() < 2) {
1612                 struct winsize ws;
1613
1614                 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1615                         if (ws.ws_col)
1616                                 x_cols = ws.ws_col;
1617                         if (ws.ws_row)
1618                                 x_lins = ws.ws_row;
1619                 }
1620         }
1621 #endif
1622
1623         /* bounds check for sane values, use defaults otherwise */
1624         if (x_cols < MIN_COLS)
1625                 x_cols = 80;
1626         if (x_lins < MIN_LINS)
1627                 x_lins = 24;
1628
1629 #ifdef SIGWINCH
1630         got_winch = 0;
1631 #endif
1632 }
1633
1634 uint32_t
1635 hash(const void *s)
1636 {
1637         register uint32_t h;
1638
1639         BAFHInit(h);
1640         BAFHUpdateStr_reg(h, s);
1641         BAFHFinish_reg(h);
1642         return (h);
1643 }
1644
1645 uint32_t
1646 chvt_rndsetup(const void *bp, size_t sz)
1647 {
1648         register uint32_t h;
1649
1650         /* use LCG as seed but try to get them to deviate immediately */
1651         h = lcg_state;
1652         (void)rndget();
1653         BAFHFinish_reg(h);
1654         /* variation through pid, ppid, and the works */
1655         BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
1656         /* some variation, some possibly entropy, depending on OE */
1657         BAFHUpdateMem_reg(h, bp, sz);
1658         /* mix them all up */
1659         BAFHFinish_reg(h);
1660
1661         return (h);
1662 }
1663
1664 mksh_ari_t
1665 rndget(void)
1666 {
1667         /*
1668          * this is the same Linear Congruential PRNG as Borland
1669          * C/C++ allegedly uses in its built-in rand() function
1670          */
1671         return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1672 }
1673
1674 void
1675 rndset(unsigned long v)
1676 {
1677         register uint32_t h;
1678 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1679         register uint32_t t;
1680 #endif
1681         struct {
1682                 struct timeval tv;
1683                 void *sp;
1684                 uint32_t qh;
1685                 pid_t pp;
1686                 short r;
1687         } z;
1688
1689 #ifdef DEBUG
1690         /* clear the allocated space, for valgrind */
1691         memset(&z, 0, sizeof(z));
1692 #endif
1693
1694         h = lcg_state;
1695         BAFHFinish_reg(h);
1696         BAFHUpdateMem_reg(h, &v, sizeof(v));
1697
1698         mksh_TIME(z.tv);
1699         z.sp = &lcg_state;
1700         z.pp = procpid;
1701         z.r = (short)rndget();
1702
1703 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1704         t = qh_state;
1705         BAFHFinish_reg(t);
1706         z.qh = (t & 0xFFFF8000) | rndget();
1707         lcg_state = (t << 15) | rndget();
1708         /*
1709          * either we have very chap entropy get and push available,
1710          * with malloc() pulling in this code already anyway, or the
1711          * user requested us to use the old functions
1712          */
1713         t = h;
1714         BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
1715         BAFHFinish_reg(t);
1716         lcg_state = t;
1717 #if defined(arc4random_pushb_fast)
1718         arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1719         lcg_state = arc4random();
1720 #else
1721         lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1722 #endif
1723         BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
1724 #else
1725         z.qh = qh_state;
1726 #endif
1727
1728         BAFHUpdateMem_reg(h, &z, sizeof(z));
1729         BAFHFinish_reg(h);
1730         lcg_state = h;
1731 }
1732
1733 void
1734 rndpush(const void *s)
1735 {
1736         register uint32_t h = qh_state;
1737
1738         BAFHUpdateStr_reg(h, s);
1739         BAFHUpdateOctet_reg(h, 0);
1740         qh_state = h;
1741 }
1742
1743 /* record last glob match */
1744 void
1745 record_match(const char *istr)
1746 {
1747         struct tbl *vp;
1748
1749         vp = local("KSH_MATCH", false);
1750         unset(vp, 1);
1751         vp->flag = DEFINED | RDONLY;
1752         setstr(vp, istr, 0x4);
1753 }