OSDN Git Service

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