OSDN Git Service

Merge "Upgrade to mksh R55."
[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, 2017
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.214 2017/04/02 16:47:43 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 void c_typeset_vardump(struct tbl *, uint32_t, int, int, bool, bool);
49 static void c_typeset_vardump_recursive(struct block *, uint32_t, int, bool,
50     bool);
51 static char *formatstr(struct tbl *, const char *);
52 static void exportprep(struct tbl *, const char *);
53 static int special(const char *);
54 static void unspecial(const char *);
55 static void getspec(struct tbl *);
56 static void setspec(struct tbl *);
57 static void unsetspec(struct tbl *);
58 static int getint(struct tbl *, mksh_ari_u *, bool);
59 static const char *array_index_calc(const char *, bool *, uint32_t *);
60
61 /*
62  * create a new block for function calls and simple commands
63  * assume caller has allocated and set up e->loc
64  */
65 void
66 newblock(void)
67 {
68         struct block *l;
69         static const char *empty[] = { null };
70
71         l = alloc(sizeof(struct block), ATEMP);
72         l->flags = 0;
73         /* TODO: could use e->area (l->area => l->areap) */
74         ainit(&l->area);
75         if (!e->loc) {
76                 l->argc = 0;
77                 l->argv = empty;
78         } else {
79                 l->argc = e->loc->argc;
80                 l->argv = e->loc->argv;
81         }
82         l->exit = l->error = NULL;
83         ktinit(&l->area, &l->vars, 0);
84         ktinit(&l->area, &l->funs, 0);
85         l->next = e->loc;
86         e->loc = l;
87 }
88
89 /*
90  * pop a block handling special variables
91  */
92 void
93 popblock(void)
94 {
95         ssize_t i;
96         struct block *l = e->loc;
97         struct tbl *vp, **vpp = l->vars.tbls, *vq;
98
99         /* pop block */
100         e->loc = l->next;
101
102         i = 1 << (l->vars.tshift);
103         while (--i >= 0)
104                 if ((vp = *vpp++) != NULL && (vp->flag&SPECIAL)) {
105                         if ((vq = global(vp->name))->flag & ISSET)
106                                 setspec(vq);
107                         else
108                                 unsetspec(vq);
109                 }
110         if (l->flags & BF_DOGETOPTS)
111                 user_opt = l->getopts_state;
112         afreeall(&l->area);
113         afree(l, ATEMP);
114 }
115
116 /* called by main() to initialise variable data structures */
117 #define VARSPEC_DEFNS
118 #include "var_spec.h"
119
120 enum var_specs {
121 #define VARSPEC_ENUMS
122 #include "var_spec.h"
123         V_MAX
124 };
125
126 /* this is biased with -1 relative to VARSPEC_ENUMS */
127 static const char * const initvar_names[] = {
128 #define VARSPEC_ITEMS
129 #include "var_spec.h"
130 };
131
132 void
133 initvar(void)
134 {
135         int i = 0;
136         struct tbl *tp;
137
138         ktinit(APERM, &specials,
139             /* currently 18 specials: 75% of 32 = 2^5 */
140             5);
141         while (i < V_MAX - 1) {
142                 tp = ktenter(&specials, initvar_names[i],
143                     hash(initvar_names[i]));
144                 tp->flag = DEFINED|ISSET;
145                 tp->type = ++i;
146         }
147 }
148
149 /* common code for several functions below and c_typeset() */
150 struct block *
151 varsearch(struct block *l, struct tbl **vpp, const char *vn, uint32_t h)
152 {
153         register struct tbl *vp;
154
155         if (l) {
156  varsearch_loop:
157                 if ((vp = ktsearch(&l->vars, vn, h)) != NULL)
158                         goto varsearch_out;
159                 if (l->next != NULL) {
160                         l = l->next;
161                         goto varsearch_loop;
162                 }
163         }
164         vp = NULL;
165  varsearch_out:
166         *vpp = vp;
167         return (l);
168 }
169
170 /*
171  * Used to calculate an array index for global()/local(). Sets *arrayp
172  * to true if this is an array, sets *valp to the array index, returns
173  * the basename of the array. May only be called from global()/local()
174  * and must be their first callee.
175  */
176 static const char *
177 array_index_calc(const char *n, bool *arrayp, uint32_t *valp)
178 {
179         const char *p;
180         size_t len;
181         char *ap = NULL;
182
183         *arrayp = false;
184  redo_from_ref:
185         p = skip_varname(n, false);
186         if (innermost_refflag == SRF_NOP && (p != n) && ksh_isalphx(n[0])) {
187                 struct tbl *vp;
188                 char *vn;
189
190                 strndupx(vn, n, p - n, ATEMP);
191                 /* check if this is a reference */
192                 varsearch(e->loc, &vp, vn, hash(vn));
193                 afree(vn, ATEMP);
194                 if (vp && (vp->flag & (DEFINED | ASSOC | ARRAY)) ==
195                     (DEFINED | ASSOC)) {
196                         char *cp;
197
198                         /* gotcha! */
199                         cp = shf_smprintf(Tf_ss, str_val(vp), p);
200                         afree(ap, ATEMP);
201                         n = ap = cp;
202                         goto redo_from_ref;
203                 }
204         }
205         innermost_refflag = SRF_NOP;
206
207         if (p != n && *p == '[' && (len = array_ref_len(p))) {
208                 char *sub, *tmp;
209                 mksh_ari_t rval;
210
211                 /* calculate the value of the subscript */
212                 *arrayp = true;
213                 strndupx(tmp, p + 1, len - 2, ATEMP);
214                 sub = substitute(tmp, 0);
215                 afree(tmp, ATEMP);
216                 strndupx(n, n, p - n, ATEMP);
217                 evaluate(sub, &rval, KSH_UNWIND_ERROR, true);
218                 *valp = (uint32_t)rval;
219                 afree(sub, ATEMP);
220         }
221         return (n);
222 }
223
224 #define vn vname.ro
225 /*
226  * Search for variable, if not found create globally.
227  */
228 struct tbl *
229 global(const char *n)
230 {
231         return (isglobal(n, true));
232 }
233
234 /* search for variable; if not found, return NULL or create globally */
235 struct tbl *
236 isglobal(const char *n, bool docreate)
237 {
238         struct tbl *vp;
239         union mksh_cchack vname;
240         struct block *l = e->loc;
241         int c;
242         bool array;
243         uint32_t h, val;
244
245         /*
246          * check to see if this is an array;
247          * dereference namerefs; must come first
248          */
249         vn = array_index_calc(n, &array, &val);
250         h = hash(vn);
251         c = (unsigned char)vn[0];
252         if (!ksh_isalphx(c)) {
253                 if (array)
254                         errorf(Tbadsubst);
255                 vp = vtemp;
256                 vp->flag = DEFINED;
257                 vp->type = 0;
258                 vp->areap = ATEMP;
259                 if (ksh_isdigit(c)) {
260                         if (getn(vn, &c)) {
261                                 /* main.c:main_init() says 12 */
262                                 shf_snprintf(vp->name, 12, Tf_d, c);
263                                 if (c <= l->argc) {
264                                         /* setstr can't fail here */
265                                         setstr(vp, l->argv[c],
266                                             KSH_RETURN_ERROR);
267                                 }
268                         } else
269                                 vp->name[0] = '\0';
270                         vp->flag |= RDONLY;
271                         goto out;
272                 }
273                 vp->name[0] = c;
274                 vp->name[1] = '\0';
275                 vp->flag |= RDONLY;
276                 if (vn[1] != '\0')
277                         goto out;
278                 vp->flag |= ISSET|INTEGER;
279                 switch (c) {
280                 case '$':
281                         vp->val.i = kshpid;
282                         break;
283                 case '!':
284                         /* if no job, expand to nothing */
285                         if ((vp->val.i = j_async()) == 0)
286                                 vp->flag &= ~(ISSET|INTEGER);
287                         break;
288                 case '?':
289                         vp->val.i = exstat & 0xFF;
290                         break;
291                 case '#':
292                         vp->val.i = l->argc;
293                         break;
294                 case '-':
295                         vp->flag &= ~INTEGER;
296                         vp->val.s = getoptions();
297                         break;
298                 default:
299                         vp->flag &= ~(ISSET|INTEGER);
300                 }
301                 goto out;
302         }
303         l = varsearch(e->loc, &vp, vn, h);
304         if (vp == NULL && docreate)
305                 vp = ktenter(&l->vars, vn, h);
306         else
307                 docreate = false;
308         if (vp != NULL) {
309                 if (array)
310                         vp = arraysearch(vp, val);
311                 if (docreate) {
312                         vp->flag |= DEFINED;
313                         if (special(vn))
314                                 vp->flag |= SPECIAL;
315                 }
316         }
317  out:
318         last_lookup_was_array = array;
319         if (vn != n)
320                 afree(vname.rw, ATEMP);
321         return (vp);
322 }
323
324 /*
325  * Search for local variable, if not found create locally.
326  */
327 struct tbl *
328 local(const char *n, bool copy)
329 {
330         struct tbl *vp;
331         union mksh_cchack vname;
332         struct block *l = e->loc;
333         bool array;
334         uint32_t h, val;
335
336         /*
337          * check to see if this is an array;
338          * dereference namerefs; must come first
339          */
340         vn = array_index_calc(n, &array, &val);
341         h = hash(vn);
342         if (!ksh_isalphx(*vn)) {
343                 vp = vtemp;
344                 vp->flag = DEFINED|RDONLY;
345                 vp->type = 0;
346                 vp->areap = ATEMP;
347                 goto out;
348         }
349         vp = ktenter(&l->vars, vn, h);
350         if (copy && !(vp->flag & DEFINED)) {
351                 struct tbl *vq;
352
353                 varsearch(l->next, &vq, vn, h);
354                 if (vq != NULL) {
355                         vp->flag |= vq->flag &
356                             (EXPORT | INTEGER | RDONLY | LJUST | RJUST |
357                             ZEROFIL | LCASEV | UCASEV_AL | INT_U | INT_L);
358                         if (vq->flag & INTEGER)
359                                 vp->type = vq->type;
360                         vp->u2.field = vq->u2.field;
361                 }
362         }
363         if (array)
364                 vp = arraysearch(vp, val);
365         vp->flag |= DEFINED;
366         if (special(vn))
367                 vp->flag |= SPECIAL;
368  out:
369         last_lookup_was_array = array;
370         if (vn != n)
371                 afree(vname.rw, ATEMP);
372         return (vp);
373 }
374 #undef vn
375
376 /* get variable string value */
377 char *
378 str_val(struct tbl *vp)
379 {
380         char *s;
381
382         if ((vp->flag&SPECIAL))
383                 getspec(vp);
384         if (!(vp->flag&ISSET))
385                 /* special to dollar() */
386                 s = null;
387         else if (!(vp->flag&INTEGER))
388                 /* string source */
389                 s = vp->val.s + vp->type;
390         else {
391                 /* integer source */
392                 mksh_uari_t n;
393                 unsigned int base;
394                 /**
395                  * worst case number length is when base == 2:
396                  *      1 (minus) + 2 (base, up to 36) + 1 ('#') +
397                  *      number of bits in the mksh_uari_t + 1 (NUL)
398                  */
399                 char strbuf[1 + 2 + 1 + 8 * sizeof(mksh_uari_t) + 1];
400                 const char *digits = (vp->flag & UCASEV_AL) ?
401                     digits_uc : digits_lc;
402
403                 s = strbuf + sizeof(strbuf);
404                 if (vp->flag & INT_U)
405                         n = vp->val.u;
406                 else
407                         n = (vp->val.i < 0) ? -vp->val.u : vp->val.u;
408                 base = (vp->type == 0) ? 10U : (unsigned int)vp->type;
409
410                 if (base == 1 && n == 0)
411                         base = 2;
412                 if (base == 1) {
413                         size_t sz = 1;
414
415                         *(s = strbuf) = '1';
416                         s[1] = '#';
417                         if (!UTFMODE || ((n & 0xFF80) == 0xEF80))
418                                 /* OPTU-16 -> raw octet */
419                                 s[2] = n & 0xFF;
420                         else
421                                 sz = utf_wctomb(s + 2, n);
422                         s[2 + sz] = '\0';
423                 } else {
424                         *--s = '\0';
425                         do {
426                                 *--s = digits[n % base];
427                                 n /= base;
428                         } while (n != 0);
429                         if (base != 10) {
430                                 *--s = '#';
431                                 *--s = digits[base % 10];
432                                 if (base >= 10)
433                                         *--s = digits[base / 10];
434                         }
435                         if (!(vp->flag & INT_U) && vp->val.i < 0)
436                                 *--s = '-';
437                 }
438                 if (vp->flag & (RJUST|LJUST))
439                         /* case already dealt with */
440                         s = formatstr(vp, s);
441                 else
442                         strdupx(s, s, ATEMP);
443         }
444         return (s);
445 }
446
447 /* set variable to string value */
448 int
449 setstr(struct tbl *vq, const char *s, int error_ok)
450 {
451         char *salloc = NULL;
452         bool no_ro_check = tobool(error_ok & 0x4);
453
454         error_ok &= ~0x4;
455         if ((vq->flag & RDONLY) && !no_ro_check) {
456                 warningf(true, Tf_ro, vq->name);
457                 if (!error_ok)
458                         errorfxz(2);
459                 return (0);
460         }
461         if (!(vq->flag&INTEGER)) {
462                 /* string dest */
463                 if ((vq->flag&ALLOC)) {
464 #ifndef MKSH_SMALL
465                         /* debugging */
466                         if (s >= vq->val.s &&
467                             s <= vq->val.s + strlen(vq->val.s)) {
468                                 internal_errorf(
469                                     "setstr: %s=%s: assigning to self",
470                                     vq->name, s);
471                         }
472 #endif
473                         afree(vq->val.s, vq->areap);
474                 }
475                 vq->flag &= ~(ISSET|ALLOC);
476                 vq->type = 0;
477                 if (s && (vq->flag & (UCASEV_AL|LCASEV|LJUST|RJUST)))
478                         s = salloc = formatstr(vq, s);
479                 if ((vq->flag&EXPORT))
480                         exportprep(vq, s);
481                 else {
482                         strdupx(vq->val.s, s, vq->areap);
483                         vq->flag |= ALLOC;
484                 }
485         } else {
486                 /* integer dest */
487                 if (!v_evaluate(vq, s, error_ok, true))
488                         return (0);
489         }
490         vq->flag |= ISSET;
491         if ((vq->flag&SPECIAL))
492                 setspec(vq);
493         afree(salloc, ATEMP);
494         return (1);
495 }
496
497 /* set variable to integer */
498 void
499 setint(struct tbl *vq, mksh_ari_t n)
500 {
501         if (!(vq->flag&INTEGER)) {
502                 vtemp->flag = (ISSET|INTEGER);
503                 vtemp->type = 0;
504                 vtemp->areap = ATEMP;
505                 vtemp->val.i = n;
506                 /* setstr can't fail here */
507                 setstr(vq, str_val(vtemp), KSH_RETURN_ERROR);
508         } else
509                 vq->val.i = n;
510         vq->flag |= ISSET;
511         if ((vq->flag&SPECIAL))
512                 setspec(vq);
513 }
514
515 static int
516 getint(struct tbl *vp, mksh_ari_u *nump, bool arith)
517 {
518         mksh_uari_t c, num = 0, base = 10;
519         const char *s;
520         bool have_base = false, neg = false;
521
522         if (vp->flag & SPECIAL)
523                 getspec(vp);
524         /* XXX is it possible for ISSET to be set and val.s to be NULL? */
525         if (!(vp->flag & ISSET) || (!(vp->flag & INTEGER) && vp->val.s == NULL))
526                 return (-1);
527         if (vp->flag & INTEGER) {
528                 nump->i = vp->val.i;
529                 return (vp->type);
530         }
531         s = vp->val.s + vp->type;
532
533         do {
534                 c = (unsigned char)*s++;
535         } while (ksh_isspace(c));
536
537         switch (c) {
538         case '-':
539                 neg = true;
540                 /* FALLTHROUGH */
541         case '+':
542                 c = (unsigned char)*s++;
543                 break;
544         }
545
546         if (c == '0' && arith) {
547                 if (ksh_eq(s[0], 'X', 'x')) {
548                         /* interpret as hexadecimal */
549                         base = 16;
550                         ++s;
551                         goto getint_c_style_base;
552                 } else if (Flag(FPOSIX) && ksh_isdigit(s[0]) &&
553                     !(vp->flag & ZEROFIL)) {
554                         /* interpret as octal (deprecated) */
555                         base = 8;
556  getint_c_style_base:
557                         have_base = true;
558                         c = (unsigned char)*s++;
559                 }
560         }
561
562         do {
563                 if (c == '#') {
564                         /* ksh-style base determination */
565                         if (have_base || num < 1)
566                                 return (-1);
567                         if ((base = num) == 1) {
568                                 /* mksh-specific extension */
569                                 unsigned int wc;
570
571                                 if (!UTFMODE)
572                                         wc = *(const unsigned char *)s;
573                                 else if (utf_mbtowc(&wc, s) == (size_t)-1)
574                                         /* OPTU-8 -> OPTU-16 */
575                                         /*
576                                          * (with a twist: 1#\uEF80 converts
577                                          * the same as 1#\x80 does, thus is
578                                          * not round-tripping correctly XXX)
579                                          */
580                                         wc = 0xEF00 + *(const unsigned char *)s;
581                                 nump->u = (mksh_uari_t)wc;
582                                 return (1);
583                         } else if (base > 36)
584                                 base = 10;
585                         num = 0;
586                         have_base = true;
587                         continue;
588                 }
589                 if (ksh_isdigit(c))
590                         c = ksh_numdig(c);
591                 else if (ksh_isupper(c))
592                         c = ksh_numuc(c) + 10;
593                 else if (ksh_islower(c))
594                         c = ksh_numlc(c) + 10;
595                 else
596                         return (-1);
597                 if (c >= base)
598                         return (-1);
599                 /* handle overflow as truncation */
600                 num = num * base + c;
601         } while ((c = (unsigned char)*s++));
602
603         if (neg)
604                 num = -num;
605         nump->u = num;
606         return (base);
607 }
608
609 /*
610  * convert variable vq to integer variable, setting its value from vp
611  * (vq and vp may be the same)
612  */
613 struct tbl *
614 setint_v(struct tbl *vq, struct tbl *vp, bool arith)
615 {
616         int base;
617         mksh_ari_u num;
618
619         if ((base = getint(vp, &num, arith)) == -1)
620                 return (NULL);
621         setint_n(vq, num.i, 0);
622         if (vq->type == 0)
623                 /* default base */
624                 vq->type = base;
625         return (vq);
626 }
627
628 /* convert variable vq to integer variable, setting its value to num */
629 void
630 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
631 {
632         if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
633                 vq->flag &= ~ALLOC;
634                 vq->type = 0;
635                 afree(vq->val.s, vq->areap);
636         }
637         vq->val.i = num;
638         if (newbase != 0)
639                 vq->type = newbase;
640         vq->flag |= ISSET|INTEGER;
641         if (vq->flag&SPECIAL)
642                 setspec(vq);
643 }
644
645 static char *
646 formatstr(struct tbl *vp, const char *s)
647 {
648         int olen, nlen;
649         char *p, *q;
650         size_t psiz;
651
652         olen = (int)utf_mbswidth(s);
653
654         if (vp->flag & (RJUST|LJUST)) {
655                 if (!vp->u2.field)
656                         /* default field width */
657                         vp->u2.field = olen;
658                 nlen = vp->u2.field;
659         } else
660                 nlen = olen;
661
662         p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
663         if (vp->flag & (RJUST|LJUST)) {
664                 int slen = olen;
665
666                 if (vp->flag & RJUST) {
667                         const char *qq;
668                         int n = 0;
669
670                         qq = utf_skipcols(s, slen, &slen);
671
672                         /* strip trailing spaces (AT&T uses qq[-1] == ' ') */
673                         while (qq > s && ksh_isspace(qq[-1])) {
674                                 --qq;
675                                 --slen;
676                         }
677                         if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
678                                 if (!s[0] || !s[1])
679                                         goto uhm_no;
680                                 if (s[1] == '#')
681                                         n = 2;
682                                 else if (s[2] == '#')
683                                         n = 3;
684  uhm_no:
685                                 if (vp->u2.field <= n)
686                                         n = 0;
687                         }
688                         if (n) {
689                                 memcpy(p, s, n);
690                                 s += n;
691                         }
692                         while (slen > vp->u2.field)
693                                 slen -= utf_widthadj(s, &s);
694                         if (vp->u2.field - slen)
695                                 memset(p + n, (vp->flag & ZEROFIL) ? '0' : ' ',
696                                     vp->u2.field - slen);
697                         slen -= n;
698                         shf_snprintf(p + vp->u2.field - slen,
699                             psiz - (vp->u2.field - slen),
700                             "%.*s", slen, s);
701                 } else {
702                         /* strip leading spaces/zeros */
703                         while (ksh_isspace(*s))
704                                 s++;
705                         if (vp->flag & ZEROFIL)
706                                 while (*s == '0')
707                                         s++;
708                         shf_snprintf(p, nlen + 1, "%-*.*s",
709                                 vp->u2.field, vp->u2.field, s);
710                 }
711         } else
712                 memcpy(p, s, strlen(s) + 1);
713
714         if (vp->flag & UCASEV_AL) {
715                 for (q = p; *q; q++)
716                         *q = ksh_toupper(*q);
717         } else if (vp->flag & LCASEV) {
718                 for (q = p; *q; q++)
719                         *q = ksh_tolower(*q);
720         }
721
722         return (p);
723 }
724
725 /*
726  * make vp->val.s be "name=value" for quick exporting.
727  */
728 static void
729 exportprep(struct tbl *vp, const char *val)
730 {
731         char *xp;
732         char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
733         size_t namelen, vallen;
734
735         namelen = strlen(vp->name);
736         vallen = strlen(val) + 1;
737
738         vp->flag |= ALLOC;
739         /* since name+val are both in memory this can go unchecked */
740         xp = alloc(namelen + 1 + vallen, vp->areap);
741         memcpy(vp->val.s = xp, vp->name, namelen);
742         xp += namelen;
743         *xp++ = '=';
744         /* offset to value */
745         vp->type = xp - vp->val.s;
746         memcpy(xp, val, vallen);
747         afree(op, vp->areap);
748 }
749
750 /*
751  * lookup variable (according to (set&LOCAL)), set its attributes
752  * (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL, LCASEV,
753  * UCASEV_AL), and optionally set its value if an assignment.
754  */
755 struct tbl *
756 typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
757 {
758         struct tbl *vp;
759         struct tbl *vpbase, *t;
760         char *tvar;
761         const char *val;
762         size_t len;
763         bool vappend = false;
764         enum namerefflag new_refflag = SRF_NOP;
765
766         if ((set & (ARRAY | ASSOC)) == ASSOC) {
767                 new_refflag = SRF_ENABLE;
768                 set &= ~(ARRAY | ASSOC);
769         }
770         if ((clr & (ARRAY | ASSOC)) == ASSOC) {
771                 new_refflag = SRF_DISABLE;
772                 clr &= ~(ARRAY | ASSOC);
773         }
774
775         /* check for valid variable name, search for value */
776         val = skip_varname(var, false);
777         if (val == var) {
778                 /* no variable name given */
779                 return (NULL);
780         }
781         if (*val == '[') {
782                 if (new_refflag != SRF_NOP)
783                         errorf(Tf_sD_s, var,
784                             "reference variable can't be an array");
785                 len = array_ref_len(val);
786                 if (len == 0)
787                         return (NULL);
788                 /*
789                  * IMPORT is only used when the shell starts up and is
790                  * setting up its environment. Allow only simple array
791                  * references at this time since parameter/command
792                  * substitution is performed on the [expression] which
793                  * would be a major security hole.
794                  */
795                 if (set & IMPORT) {
796                         size_t i;
797
798                         for (i = 1; i < len - 1; i++)
799                                 if (!ksh_isdigit(val[i]))
800                                         return (NULL);
801                 }
802                 val += len;
803         }
804         if (val[0] == '=') {
805                 strndupx(tvar, var, val - var, ATEMP);
806                 ++val;
807         } else if (set & IMPORT) {
808                 /* environment invalid variable name or no assignment */
809                 return (NULL);
810         } else if (val[0] == '+' && val[1] == '=') {
811                 strndupx(tvar, var, val - var, ATEMP);
812                 val += 2;
813                 vappend = true;
814         } else if (val[0] != '\0') {
815                 /* other invalid variable names (not from environment) */
816                 return (NULL);
817         } else {
818                 /* just varname with no value part nor equals sign */
819                 strdupx(tvar, var, ATEMP);
820                 val = NULL;
821                 /* handle foo[*] => foo (whole array) mapping for R39b */
822                 len = strlen(tvar);
823                 if (len > 3 && tvar[len - 3] == '[' && tvar[len - 2] == '*' &&
824                     tvar[len - 1] == ']')
825                         tvar[len - 3] = '\0';
826         }
827
828         if (new_refflag == SRF_ENABLE) {
829                 const char *qval, *ccp;
830
831                 /* bail out on 'nameref foo+=bar' */
832                 if (vappend)
833                         errorf("appending not allowed for nameref");
834                 /* find value if variable already exists */
835                 if ((qval = val) == NULL) {
836                         varsearch(e->loc, &vp, tvar, hash(tvar));
837                         if (vp == NULL)
838                                 goto nameref_empty;
839                         qval = str_val(vp);
840                 }
841                 /* check target value for being a valid variable name */
842                 ccp = skip_varname(qval, false);
843                 if (ccp == qval) {
844                         int c;
845
846                         if (!(c = (unsigned char)qval[0]))
847                                 goto nameref_empty;
848                         else if (ksh_isdigit(c) && getn(qval, &c))
849                                 goto nameref_rhs_checked;
850                         else if (qval[1] == '\0') switch (c) {
851                         case '$':
852                         case '!':
853                         case '?':
854                         case '#':
855                         case '-':
856                                 goto nameref_rhs_checked;
857                         }
858  nameref_empty:
859                         errorf(Tf_sD_s, var, "empty nameref target");
860                 }
861                 len = (*ccp == '[') ? array_ref_len(ccp) : 0;
862                 if (ccp[len]) {
863                         /*
864                          * works for cases "no array", "valid array with
865                          * junk after it" and "invalid array"; in the
866                          * latter case, len is also 0 and points to '['
867                          */
868                         errorf(Tf_sD_s, qval,
869                             "nameref target not a valid parameter name");
870                 }
871  nameref_rhs_checked:
872                 /* prevent nameref loops */
873                 while (qval) {
874                         if (!strcmp(qval, tvar))
875                                 errorf(Tf_sD_s, qval,
876                                     "expression recurses on parameter");
877                         varsearch(e->loc, &vp, qval, hash(qval));
878                         qval = NULL;
879                         if (vp && ((vp->flag & (ARRAY | ASSOC)) == ASSOC))
880                                 qval = str_val(vp);
881                 }
882         }
883
884         /* prevent typeset from creating a local PATH/ENV/SHELL */
885         if (Flag(FRESTRICTED) && (strcmp(tvar, TPATH) == 0 ||
886             strcmp(tvar, "ENV") == 0 || strcmp(tvar, TSHELL) == 0))
887                 errorf(Tf_sD_s, tvar, "restricted");
888
889         innermost_refflag = new_refflag;
890         vp = (set & LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
891             global(tvar);
892         if (new_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
893                 vp->flag &= ~ASSOC;
894         else if (new_refflag == SRF_ENABLE) {
895                 if (vp->flag & ARRAY) {
896                         struct tbl *a, *tmp;
897
898                         /* free up entire array */
899                         for (a = vp->u.array; a; ) {
900                                 tmp = a;
901                                 a = a->u.array;
902                                 if (tmp->flag & ALLOC)
903                                         afree(tmp->val.s, tmp->areap);
904                                 afree(tmp, tmp->areap);
905                         }
906                         vp->u.array = NULL;
907                         vp->flag &= ~ARRAY;
908                 }
909                 vp->flag |= ASSOC;
910         }
911
912         set &= ~(LOCAL|LOCAL_COPY);
913
914         vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
915
916         /*
917          * only allow export flag to be set; AT&T ksh allows any
918          * attribute to be changed which means it can be truncated or
919          * modified (-L/-R/-Z/-i)
920          */
921         if ((vpbase->flag & RDONLY) &&
922             (val || clr || (set & ~EXPORT)))
923                 /* XXX check calls - is error here ok by POSIX? */
924                 errorfx(2, Tf_ro, tvar);
925         afree(tvar, ATEMP);
926
927         /* most calls are with set/clr == 0 */
928         if (set | clr) {
929                 bool ok = true;
930
931                 /*
932                  * XXX if x[0] isn't set, there will be problems: need
933                  * to have one copy of attributes for arrays...
934                  */
935                 for (t = vpbase; t; t = t->u.array) {
936                         bool fake_assign;
937                         char *s = NULL;
938                         char *free_me = NULL;
939
940                         fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
941                             ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
942                             ((t->flag & INTEGER) && (clr & INTEGER)) ||
943                             (!(t->flag & INTEGER) && (set & INTEGER)));
944                         if (fake_assign) {
945                                 if (t->flag & INTEGER) {
946                                         s = str_val(t);
947                                         free_me = NULL;
948                                 } else {
949                                         s = t->val.s + t->type;
950                                         free_me = (t->flag & ALLOC) ? t->val.s :
951                                             NULL;
952                                 }
953                                 t->flag &= ~ALLOC;
954                         }
955                         if (!(t->flag & INTEGER) && (set & INTEGER)) {
956                                 t->type = 0;
957                                 t->flag &= ~ALLOC;
958                         }
959                         t->flag = (t->flag | set) & ~clr;
960                         /*
961                          * Don't change base if assignment is to be
962                          * done, in case assignment fails.
963                          */
964                         if ((set & INTEGER) && base > 0 && (!val || t != vp))
965                                 t->type = base;
966                         if (set & (LJUST|RJUST|ZEROFIL))
967                                 t->u2.field = field;
968                         if (fake_assign) {
969                                 if (!setstr(t, s, KSH_RETURN_ERROR)) {
970                                         /*
971                                          * Somewhat arbitrary action
972                                          * here: zap contents of
973                                          * variable, but keep the flag
974                                          * settings.
975                                          */
976                                         ok = false;
977                                         if (t->flag & INTEGER)
978                                                 t->flag &= ~ISSET;
979                                         else {
980                                                 if (t->flag & ALLOC)
981                                                         afree(t->val.s, t->areap);
982                                                 t->flag &= ~(ISSET|ALLOC);
983                                                 t->type = 0;
984                                         }
985                                 }
986                                 afree(free_me, t->areap);
987                         }
988                 }
989                 if (!ok)
990                         errorfz();
991         }
992
993         if (val != NULL) {
994                 char *tval;
995
996                 if (vappend) {
997                         tval = shf_smprintf(Tf_ss, str_val(vp), val);
998                         val = tval;
999                 } else
1000                         tval = NULL;
1001
1002                 if (vp->flag&INTEGER) {
1003                         /* do not zero base before assignment */
1004                         setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
1005                         /* done after assignment to override default */
1006                         if (base > 0)
1007                                 vp->type = base;
1008                 } else
1009                         /* setstr can't fail (readonly check already done) */
1010                         setstr(vp, val, KSH_RETURN_ERROR | 0x4);
1011
1012                 afree(tval, ATEMP);
1013         }
1014
1015         /* only x[0] is ever exported, so use vpbase */
1016         if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
1017             vpbase->type == 0)
1018                 exportprep(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
1019
1020         return (vp);
1021 }
1022
1023 /**
1024  * Unset a variable. The flags can be:
1025  * |1   = tear down entire array
1026  * |2   = keep attributes, only unset content
1027  */
1028 void
1029 unset(struct tbl *vp, int flags)
1030 {
1031         if (vp->flag & ALLOC)
1032                 afree(vp->val.s, vp->areap);
1033         if ((vp->flag & ARRAY) && (flags & 1)) {
1034                 struct tbl *a, *tmp;
1035
1036                 /* free up entire array */
1037                 for (a = vp->u.array; a; ) {
1038                         tmp = a;
1039                         a = a->u.array;
1040                         if (tmp->flag & ALLOC)
1041                                 afree(tmp->val.s, tmp->areap);
1042                         afree(tmp, tmp->areap);
1043                 }
1044                 vp->u.array = NULL;
1045         }
1046         if (flags & 2) {
1047                 vp->flag &= ~(ALLOC|ISSET);
1048                 return;
1049         }
1050         /* if foo[0] is being unset, the remainder of the array is kept... */
1051         vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
1052         if (vp->flag & SPECIAL)
1053                 /* responsible for 'unspecial'ing var */
1054                 unsetspec(vp);
1055 }
1056
1057 /*
1058  * Return a pointer to the first char past a legal variable name
1059  * (returns the argument if there is no legal name, returns a pointer to
1060  * the terminating NUL if whole string is legal).
1061  */
1062 const char *
1063 skip_varname(const char *s, bool aok)
1064 {
1065         size_t alen;
1066
1067         if (s && ksh_isalphx(*s)) {
1068                 do {
1069                         ++s;
1070                 } while (ksh_isalnux(*s));
1071                 if (aok && *s == '[' && (alen = array_ref_len(s)))
1072                         s += alen;
1073         }
1074         return (s);
1075 }
1076
1077 /* Return a pointer to the first character past any legal variable name */
1078 const char *
1079 skip_wdvarname(const char *s,
1080     /* skip array de-reference? */
1081     bool aok)
1082 {
1083         if (s[0] == CHAR && ksh_isalphx(s[1])) {
1084                 do {
1085                         s += 2;
1086                 } while (s[0] == CHAR && ksh_isalnux(s[1]));
1087                 if (aok && s[0] == CHAR && s[1] == '[') {
1088                         /* skip possible array de-reference */
1089                         const char *p = s;
1090                         char c;
1091                         int depth = 0;
1092
1093                         while (/* CONSTCOND */ 1) {
1094                                 if (p[0] != CHAR)
1095                                         break;
1096                                 c = p[1];
1097                                 p += 2;
1098                                 if (c == '[')
1099                                         depth++;
1100                                 else if (c == ']' && --depth == 0) {
1101                                         s = p;
1102                                         break;
1103                                 }
1104                         }
1105                 }
1106         }
1107         return (s);
1108 }
1109
1110 /* Check if coded string s is a variable name */
1111 int
1112 is_wdvarname(const char *s, bool aok)
1113 {
1114         const char *p = skip_wdvarname(s, aok);
1115
1116         return (p != s && p[0] == EOS);
1117 }
1118
1119 /* Check if coded string s is a variable assignment */
1120 int
1121 is_wdvarassign(const char *s)
1122 {
1123         const char *p = skip_wdvarname(s, true);
1124
1125         return (p != s && p[0] == CHAR &&
1126             (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
1127 }
1128
1129 /*
1130  * Make the exported environment from the exported names in the dictionary.
1131  */
1132 char **
1133 makenv(void)
1134 {
1135         ssize_t i;
1136         struct block *l;
1137         XPtrV denv;
1138         struct tbl *vp, **vpp;
1139
1140         XPinit(denv, 64);
1141         for (l = e->loc; l != NULL; l = l->next) {
1142                 vpp = l->vars.tbls;
1143                 i = 1 << (l->vars.tshift);
1144                 while (--i >= 0)
1145                         if ((vp = *vpp++) != NULL &&
1146                             (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
1147                                 struct block *l2;
1148                                 struct tbl *vp2;
1149                                 uint32_t h = hash(vp->name);
1150
1151                                 /* unexport any redefined instances */
1152                                 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
1153                                         vp2 = ktsearch(&l2->vars, vp->name, h);
1154                                         if (vp2 != NULL)
1155                                                 vp2->flag &= ~EXPORT;
1156                                 }
1157                                 if ((vp->flag&INTEGER)) {
1158                                         /* integer to string */
1159                                         char *val;
1160                                         val = str_val(vp);
1161                                         vp->flag &= ~(INTEGER|RDONLY|SPECIAL);
1162                                         /* setstr can't fail here */
1163                                         setstr(vp, val, KSH_RETURN_ERROR);
1164                                 }
1165 #ifdef __OS2__
1166                                 /* these special variables are not exported */
1167                                 if (!strcmp(vp->name, "BEGINLIBPATH") ||
1168                                     !strcmp(vp->name, "ENDLIBPATH") ||
1169                                     !strcmp(vp->name, "LIBPATHSTRICT"))
1170                                         continue;
1171 #endif
1172                                 XPput(denv, vp->val.s);
1173                         }
1174                 if (l->flags & BF_STOPENV)
1175                         break;
1176         }
1177         XPput(denv, NULL);
1178         return ((char **)XPclose(denv));
1179 }
1180
1181 /*
1182  * handle special variables with side effects - PATH, SECONDS.
1183  */
1184
1185 /* Test if name is a special parameter */
1186 static int
1187 special(const char *name)
1188 {
1189         struct tbl *tp;
1190
1191         tp = ktsearch(&specials, name, hash(name));
1192         return (tp && (tp->flag & ISSET) ? tp->type : V_NONE);
1193 }
1194
1195 /* Make a variable non-special */
1196 static void
1197 unspecial(const char *name)
1198 {
1199         struct tbl *tp;
1200
1201         tp = ktsearch(&specials, name, hash(name));
1202         if (tp)
1203                 ktdelete(tp);
1204 }
1205
1206 static time_t seconds;          /* time SECONDS last set */
1207 static mksh_uari_t user_lineno; /* what user set $LINENO to */
1208
1209 /* minimum values from the OS we consider sane, lowered for R53 */
1210 #define MIN_COLS        4
1211 #define MIN_LINS        2
1212
1213 static void
1214 getspec(struct tbl *vp)
1215 {
1216         mksh_ari_u num;
1217         int st;
1218         struct timeval tv;
1219
1220         switch ((st = special(vp->name))) {
1221         case V_COLUMNS:
1222         case V_LINES:
1223                 /*
1224                  * Do NOT export COLUMNS/LINES. Many applications
1225                  * check COLUMNS/LINES before checking ws.ws_col/row,
1226                  * so if the app is started with C/L in the environ
1227                  * and the window is then resized, the app won't
1228                  * see the change cause the environ doesn't change.
1229                  */
1230                 if (got_winch)
1231                         change_winsz();
1232                 break;
1233         }
1234         switch (st) {
1235         case V_BASHPID:
1236                 num.u = (mksh_uari_t)procpid;
1237                 break;
1238         case V_COLUMNS:
1239                 num.i = x_cols;
1240                 break;
1241         case V_HISTSIZE:
1242                 num.i = histsize;
1243                 break;
1244         case V_LINENO:
1245                 num.u = (mksh_uari_t)current_lineno + user_lineno;
1246                 break;
1247         case V_LINES:
1248                 num.i = x_lins;
1249                 break;
1250         case V_EPOCHREALTIME: {
1251                 /* 10(%u) + 1(.) + 6 + NUL */
1252                 char buf[18];
1253
1254                 vp->flag &= ~SPECIAL;
1255                 mksh_TIME(tv);
1256                 shf_snprintf(buf, sizeof(buf), "%u.%06u",
1257                     (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1258                 setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
1259                 vp->flag |= SPECIAL;
1260                 return;
1261         }
1262         case V_OPTIND:
1263                 num.i = user_opt.uoptind;
1264                 break;
1265         case V_RANDOM:
1266                 num.i = rndget();
1267                 break;
1268         case V_SECONDS:
1269                 /*
1270                  * On start up the value of SECONDS is used before
1271                  * it has been set - don't do anything in this case
1272                  * (see initcoms[] in main.c).
1273                  */
1274                 if (vp->flag & ISSET) {
1275                         mksh_TIME(tv);
1276                         num.i = tv.tv_sec - seconds;
1277                 } else
1278                         return;
1279                 break;
1280         default:
1281                 /* do nothing, do not touch vp at all */
1282                 return;
1283         }
1284         vp->flag &= ~SPECIAL;
1285         setint_n(vp, num.i, 0);
1286         vp->flag |= SPECIAL;
1287 }
1288
1289 static void
1290 setspec(struct tbl *vp)
1291 {
1292         mksh_ari_u num;
1293         char *s;
1294         int st;
1295
1296         switch ((st = special(vp->name))) {
1297 #ifdef __OS2__
1298         case V_BEGINLIBPATH:
1299         case V_ENDLIBPATH:
1300         case V_LIBPATHSTRICT:
1301                 setextlibpath(vp->name, str_val(vp));
1302                 return;
1303 #endif
1304 #if HAVE_PERSISTENT_HISTORY
1305         case V_HISTFILE:
1306                 sethistfile(str_val(vp));
1307                 return;
1308 #endif
1309         case V_IFS:
1310                 setctypes(s = str_val(vp), C_IFS);
1311                 ifs0 = *s;
1312                 return;
1313         case V_PATH:
1314                 afree(path, APERM);
1315                 s = str_val(vp);
1316                 strdupx(path, s, APERM);
1317                 /* clear tracked aliases */
1318                 flushcom(true);
1319                 return;
1320 #ifndef MKSH_NO_CMDLINE_EDITING
1321         case V_TERM:
1322                 x_initterm(str_val(vp));
1323                 return;
1324 #endif
1325         case V_TMPDIR:
1326                 afree(tmpdir, APERM);
1327                 tmpdir = NULL;
1328                 /*
1329                  * Use tmpdir iff it is an absolute path, is writable
1330                  * and searchable and is a directory...
1331                  */
1332                 {
1333                         struct stat statb;
1334
1335                         s = str_val(vp);
1336                         /* LINTED use of access */
1337                         if (mksh_abspath(s) && access(s, W_OK|X_OK) == 0 &&
1338                             stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1339                                 strdupx(tmpdir, s, APERM);
1340                 }
1341                 return;
1342         /* common sub-cases */
1343         case V_COLUMNS:
1344         case V_LINES:
1345                 if (vp->flag & IMPORT) {
1346                         /* do not touch */
1347                         unspecial(vp->name);
1348                         vp->flag &= ~SPECIAL;
1349                         return;
1350                 }
1351                 /* FALLTHROUGH */
1352         case V_HISTSIZE:
1353         case V_LINENO:
1354         case V_OPTIND:
1355         case V_RANDOM:
1356         case V_SECONDS:
1357         case V_TMOUT:
1358                 vp->flag &= ~SPECIAL;
1359                 if (getint(vp, &num, false) == -1) {
1360                         s = str_val(vp);
1361                         if (st != V_RANDOM)
1362                                 errorf(Tf_sD_sD_s, vp->name, Tbadnum, s);
1363                         num.u = hash(s);
1364                 }
1365                 vp->flag |= SPECIAL;
1366                 break;
1367         default:
1368                 /* do nothing, do not touch vp at all */
1369                 return;
1370         }
1371
1372         /* process the singular parts of the common cases */
1373
1374         switch (st) {
1375         case V_COLUMNS:
1376                 if (num.i >= MIN_COLS)
1377                         x_cols = num.i;
1378                 break;
1379         case V_HISTSIZE:
1380                 sethistsize(num.i);
1381                 break;
1382         case V_LINENO:
1383                 /* The -1 is because line numbering starts at 1. */
1384                 user_lineno = num.u - (mksh_uari_t)current_lineno - 1;
1385                 break;
1386         case V_LINES:
1387                 if (num.i >= MIN_LINS)
1388                         x_lins = num.i;
1389                 break;
1390         case V_OPTIND:
1391                 getopts_reset((int)num.i);
1392                 break;
1393         case V_RANDOM:
1394                 /*
1395                  * mksh R39d+ no longer has the traditional repeatability
1396                  * of $RANDOM sequences, but always retains state
1397                  */
1398                 rndset((unsigned long)num.u);
1399                 break;
1400         case V_SECONDS:
1401                 {
1402                         struct timeval tv;
1403
1404                         mksh_TIME(tv);
1405                         seconds = tv.tv_sec - num.i;
1406                 }
1407                 break;
1408         case V_TMOUT:
1409                 ksh_tmout = num.i >= 0 ? num.i : 0;
1410                 break;
1411         }
1412 }
1413
1414 static void
1415 unsetspec(struct tbl *vp)
1416 {
1417         /*
1418          * AT&T ksh man page says OPTIND, OPTARG and _ lose special
1419          * meaning, but OPTARG does not (still set by getopts) and _ is
1420          * also still set in various places. Don't know what AT&T does
1421          * for HISTSIZE, HISTFILE. Unsetting these in AT&T ksh does not
1422          * loose the 'specialness': IFS, COLUMNS, PATH, TMPDIR
1423          */
1424
1425         switch (special(vp->name)) {
1426 #ifdef __OS2__
1427         case V_BEGINLIBPATH:
1428         case V_ENDLIBPATH:
1429         case V_LIBPATHSTRICT:
1430                 setextlibpath(vp->name, "");
1431                 return;
1432 #endif
1433 #if HAVE_PERSISTENT_HISTORY
1434         case V_HISTFILE:
1435                 sethistfile(NULL);
1436                 return;
1437 #endif
1438         case V_IFS:
1439                 setctypes(TC_IFSWS, C_IFS);
1440                 ifs0 = ' ';
1441                 break;
1442         case V_PATH:
1443                 afree(path, APERM);
1444                 strdupx(path, def_path, APERM);
1445                 /* clear tracked aliases */
1446                 flushcom(true);
1447                 break;
1448 #ifndef MKSH_NO_CMDLINE_EDITING
1449         case V_TERM:
1450                 x_initterm(null);
1451                 return;
1452 #endif
1453         case V_TMPDIR:
1454                 /* should not become unspecial */
1455                 if (tmpdir) {
1456                         afree(tmpdir, APERM);
1457                         tmpdir = NULL;
1458                 }
1459                 break;
1460         case V_LINENO:
1461         case V_RANDOM:
1462         case V_SECONDS:
1463         case V_TMOUT:
1464                 /* AT&T ksh leaves previous value in place */
1465                 unspecial(vp->name);
1466                 break;
1467         }
1468 }
1469
1470 /*
1471  * Search for (and possibly create) a table entry starting with
1472  * vp, indexed by val.
1473  */
1474 struct tbl *
1475 arraysearch(struct tbl *vp, uint32_t val)
1476 {
1477         struct tbl *prev, *curr, *news;
1478         size_t len;
1479
1480         vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
1481         /* the table entry is always [0] */
1482         if (val == 0)
1483                 return (vp);
1484         prev = vp;
1485         curr = vp->u.array;
1486         while (curr && curr->ua.index < val) {
1487                 prev = curr;
1488                 curr = curr->u.array;
1489         }
1490         if (curr && curr->ua.index == val) {
1491                 if (curr->flag&ISSET)
1492                         return (curr);
1493                 news = curr;
1494         } else
1495                 news = NULL;
1496         if (!news) {
1497                 len = strlen(vp->name);
1498                 checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
1499                 news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
1500                 memcpy(news->name, vp->name, len);
1501         }
1502         news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
1503         news->type = vp->type;
1504         news->areap = vp->areap;
1505         news->u2.field = vp->u2.field;
1506         news->ua.index = val;
1507
1508         if (curr != news) {
1509                 /* not reusing old array entry */
1510                 prev->u.array = news;
1511                 news->u.array = curr;
1512         }
1513         return (news);
1514 }
1515
1516 /*
1517  * Return the length of an array reference (eg, [1+2]) - cp is assumed
1518  * to point to the open bracket. Returns 0 if there is no matching
1519  * closing bracket.
1520  *
1521  * XXX this should parse the actual arithmetic syntax
1522  */
1523 size_t
1524 array_ref_len(const char *cp)
1525 {
1526         const char *s = cp;
1527         char c;
1528         int depth = 0;
1529
1530         while ((c = *s++) && (c != ']' || --depth))
1531                 if (c == '[')
1532                         depth++;
1533         if (!c)
1534                 return (0);
1535         return (s - cp);
1536 }
1537
1538 /*
1539  * Make a copy of the base of an array name
1540  */
1541 char *
1542 arrayname(const char *str)
1543 {
1544         const char *p;
1545         char *rv;
1546
1547         if (!(p = cstrchr(str, '[')))
1548                 /* Shouldn't happen, but why worry? */
1549                 strdupx(rv, str, ATEMP);
1550         else
1551                 strndupx(rv, str, p - str, ATEMP);
1552
1553         return (rv);
1554 }
1555
1556 /* set (or overwrite, if reset) the array variable var to the values in vals */
1557 mksh_uari_t
1558 set_array(const char *var, bool reset, const char **vals)
1559 {
1560         struct tbl *vp, *vq;
1561         mksh_uari_t i = 0, j = 0;
1562         const char *ccp = var;
1563         char *cp = NULL;
1564         size_t n;
1565
1566         /* to get local array, use "local foo; set -A foo" */
1567         n = strlen(var);
1568         if (n > 0 && var[n - 1] == '+') {
1569                 /* append mode */
1570                 reset = false;
1571                 strndupx(cp, var, n - 1, ATEMP);
1572                 ccp = cp;
1573         }
1574         vp = global(ccp);
1575
1576         /* Note: AT&T ksh allows set -A but not set +A of a read-only var */
1577         if ((vp->flag&RDONLY))
1578                 errorfx(2, Tf_ro, ccp);
1579         /* This code is quite non-optimal */
1580         if (reset) {
1581                 /* trash existing values and attributes */
1582                 unset(vp, 1);
1583                 /* allocate-by-access the [0] element to keep in scope */
1584                 arraysearch(vp, 0);
1585         }
1586         /*
1587          * TODO: would be nice for assignment to completely succeed or
1588          * completely fail. Only really effects integer arrays:
1589          * evaluation of some of vals[] may fail...
1590          */
1591         if (cp != NULL) {
1592                 /* find out where to set when appending */
1593                 for (vq = vp; vq; vq = vq->u.array) {
1594                         if (!(vq->flag & ISSET))
1595                                 continue;
1596                         if (arrayindex(vq) >= j)
1597                                 j = arrayindex(vq) + 1;
1598                 }
1599                 afree(cp, ATEMP);
1600         }
1601         while ((ccp = vals[i])) {
1602 #if 0 /* temporarily taken out due to regression */
1603                 if (*ccp == '[') {
1604                         int level = 0;
1605
1606                         while (*ccp) {
1607                                 if (*ccp == ']' && --level == 0)
1608                                         break;
1609                                 if (*ccp == '[')
1610                                         ++level;
1611                                 ++ccp;
1612                         }
1613                         if (*ccp == ']' && level == 0 && ccp[1] == '=') {
1614                                 strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
1615                                     ATEMP);
1616                                 evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
1617                                     KSH_UNWIND_ERROR, true);
1618                                 afree(cp, ATEMP);
1619                                 ccp += 2;
1620                         } else
1621                                 ccp = vals[i];
1622                 }
1623 #endif
1624
1625                 vq = arraysearch(vp, j);
1626                 /* would be nice to deal with errors here... (see above) */
1627                 setstr(vq, ccp, KSH_RETURN_ERROR);
1628                 i++;
1629                 j++;
1630         }
1631
1632         return (i);
1633 }
1634
1635 void
1636 change_winsz(void)
1637 {
1638         struct timeval tv;
1639
1640         mksh_TIME(tv);
1641         BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
1642
1643 #ifdef TIOCGWINSZ
1644         /* check if window size has changed */
1645         if (tty_init_fd() < 2) {
1646                 struct winsize ws;
1647
1648                 if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
1649                         if (ws.ws_col)
1650                                 x_cols = ws.ws_col;
1651                         if (ws.ws_row)
1652                                 x_lins = ws.ws_row;
1653                 }
1654         }
1655 #endif
1656
1657         /* bounds check for sane values, use defaults otherwise */
1658         if (x_cols < MIN_COLS)
1659                 x_cols = 80;
1660         if (x_lins < MIN_LINS)
1661                 x_lins = 24;
1662
1663 #ifdef SIGWINCH
1664         got_winch = 0;
1665 #endif
1666 }
1667
1668 uint32_t
1669 hash(const void *s)
1670 {
1671         register uint32_t h;
1672
1673         BAFHInit(h);
1674         BAFHUpdateStr_reg(h, s);
1675         BAFHFinish_reg(h);
1676         return (h);
1677 }
1678
1679 uint32_t
1680 chvt_rndsetup(const void *bp, size_t sz)
1681 {
1682         register uint32_t h;
1683
1684         /* use LCG as seed but try to get them to deviate immediately */
1685         h = lcg_state;
1686         (void)rndget();
1687         BAFHFinish_reg(h);
1688         /* variation through pid, ppid, and the works */
1689         BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
1690         /* some variation, some possibly entropy, depending on OE */
1691         BAFHUpdateMem_reg(h, bp, sz);
1692         /* mix them all up */
1693         BAFHFinish_reg(h);
1694
1695         return (h);
1696 }
1697
1698 mksh_ari_t
1699 rndget(void)
1700 {
1701         /*
1702          * this is the same Linear Congruential PRNG as Borland
1703          * C/C++ allegedly uses in its built-in rand() function
1704          */
1705         return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
1706 }
1707
1708 void
1709 rndset(unsigned long v)
1710 {
1711         register uint32_t h;
1712 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1713         register uint32_t t;
1714 #endif
1715         struct {
1716                 struct timeval tv;
1717                 void *sp;
1718                 uint32_t qh;
1719                 pid_t pp;
1720                 short r;
1721         } z;
1722
1723         /* clear the allocated space, for valgrind and to avoid UB */
1724         memset(&z, 0, sizeof(z));
1725
1726         h = lcg_state;
1727         BAFHFinish_reg(h);
1728         BAFHUpdateMem_reg(h, &v, sizeof(v));
1729
1730         mksh_TIME(z.tv);
1731         z.sp = &lcg_state;
1732         z.pp = procpid;
1733         z.r = (short)rndget();
1734
1735 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
1736         t = qh_state;
1737         BAFHFinish_reg(t);
1738         z.qh = (t & 0xFFFF8000) | rndget();
1739         lcg_state = (t << 15) | rndget();
1740         /*
1741          * either we have very chap entropy get and push available,
1742          * with malloc() pulling in this code already anyway, or the
1743          * user requested us to use the old functions
1744          */
1745         t = h;
1746         BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
1747         BAFHFinish_reg(t);
1748         lcg_state = t;
1749 #if defined(arc4random_pushb_fast)
1750         arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
1751         lcg_state = arc4random();
1752 #else
1753         lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
1754 #endif
1755         BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
1756 #else
1757         z.qh = qh_state;
1758 #endif
1759
1760         BAFHUpdateMem_reg(h, &z, sizeof(z));
1761         BAFHFinish_reg(h);
1762         lcg_state = h;
1763 }
1764
1765 void
1766 rndpush(const void *s)
1767 {
1768         register uint32_t h = qh_state;
1769
1770         BAFHUpdateStr_reg(h, s);
1771         BAFHUpdateOctet_reg(h, 0);
1772         qh_state = h;
1773 }
1774
1775 /* record last glob match */
1776 void
1777 record_match(const char *istr)
1778 {
1779         struct tbl *vp;
1780
1781         vp = local("KSH_MATCH", false);
1782         unset(vp, 1);
1783         vp->flag = DEFINED | RDONLY;
1784         setstr(vp, istr, 0x4);
1785 }
1786
1787 /* typeset, global(deprecated), export, and readonly */
1788 int
1789 c_typeset(const char **wp)
1790 {
1791         struct tbl *vp, **p;
1792         uint32_t fset = 0, fclr = 0, flag;
1793         int thing = 0, field = 0, base = 0, i;
1794         struct block *l;
1795         const char *opts;
1796         const char *fieldstr = NULL, *basestr = NULL;
1797         bool localv = false, func = false, pflag = false, istset = true;
1798         enum namerefflag new_refflag = SRF_NOP;
1799
1800         switch (**wp) {
1801
1802         /* export */
1803         case 'e':
1804                 fset |= EXPORT;
1805                 istset = false;
1806                 break;
1807
1808         /* readonly */
1809         case 'r':
1810                 fset |= RDONLY;
1811                 istset = false;
1812                 break;
1813
1814         /* set */
1815         case 's':
1816                 /* called with 'typeset -' */
1817                 break;
1818
1819         /* typeset */
1820         case 't':
1821                 localv = true;
1822                 break;
1823         }
1824
1825         /* see comment below regarding possible opions */
1826         opts = istset ? "L#R#UZ#afgi#lnprtux" : "p";
1827
1828         builtin_opt.flags |= GF_PLUSOPT;
1829         /*
1830          * AT&T ksh seems to have 0-9 as options which are multiplied
1831          * to get a number that is used with -L, -R, -Z or -i (eg, -1R2
1832          * sets right justify in a field of 12). This allows options
1833          * to be grouped in an order (eg, -Lu12), but disallows -i8 -L3 and
1834          * does not allow the number to be specified as a separate argument
1835          * Here, the number must follow the RLZi option, but is optional
1836          * (see the # kludge in ksh_getopt()).
1837          */
1838         while ((i = ksh_getopt(wp, &builtin_opt, opts)) != -1) {
1839                 flag = 0;
1840                 switch (i) {
1841                 case 'L':
1842                         flag = LJUST;
1843                         fieldstr = builtin_opt.optarg;
1844                         break;
1845                 case 'R':
1846                         flag = RJUST;
1847                         fieldstr = builtin_opt.optarg;
1848                         break;
1849                 case 'U':
1850                         /*
1851                          * AT&T ksh uses u, but this conflicts with
1852                          * upper/lower case. If this option is changed,
1853                          * need to change the -U below as well
1854                          */
1855                         flag = INT_U;
1856                         break;
1857                 case 'Z':
1858                         flag = ZEROFIL;
1859                         fieldstr = builtin_opt.optarg;
1860                         break;
1861                 case 'a':
1862                         /*
1863                          * this is supposed to set (-a) or unset (+a) the
1864                          * indexed array attribute; it does nothing on an
1865                          * existing regular string or indexed array though
1866                          */
1867                         break;
1868                 case 'f':
1869                         func = true;
1870                         break;
1871                 case 'g':
1872                         localv = (builtin_opt.info & GI_PLUS) ? true : false;
1873                         break;
1874                 case 'i':
1875                         flag = INTEGER;
1876                         basestr = builtin_opt.optarg;
1877                         break;
1878                 case 'l':
1879                         flag = LCASEV;
1880                         break;
1881                 case 'n':
1882                         new_refflag = (builtin_opt.info & GI_PLUS) ?
1883                             SRF_DISABLE : SRF_ENABLE;
1884                         break;
1885                 /* export, readonly: POSIX -p flag */
1886                 case 'p':
1887                         /* typeset: show values as well */
1888                         pflag = true;
1889                         if (istset)
1890                                 continue;
1891                         break;
1892                 case 'r':
1893                         flag = RDONLY;
1894                         break;
1895                 case 't':
1896                         flag = TRACE;
1897                         break;
1898                 case 'u':
1899                         /* upper case / autoload */
1900                         flag = UCASEV_AL;
1901                         break;
1902                 case 'x':
1903                         flag = EXPORT;
1904                         break;
1905                 case '?':
1906                         return (1);
1907                 }
1908                 if (builtin_opt.info & GI_PLUS) {
1909                         fclr |= flag;
1910                         fset &= ~flag;
1911                         thing = '+';
1912                 } else {
1913                         fset |= flag;
1914                         fclr &= ~flag;
1915                         thing = '-';
1916                 }
1917         }
1918
1919         if (fieldstr && !getn(fieldstr, &field)) {
1920                 bi_errorf(Tf_sD_s, Tbadnum, fieldstr);
1921                 return (1);
1922         }
1923         if (basestr) {
1924                 if (!getn(basestr, &base)) {
1925                         bi_errorf(Tf_sD_s, "bad integer base", basestr);
1926                         return (1);
1927                 }
1928                 if (base < 1 || base > 36)
1929                         base = 10;
1930         }
1931
1932         if (!(builtin_opt.info & GI_MINUSMINUS) && wp[builtin_opt.optind] &&
1933             (wp[builtin_opt.optind][0] == '-' ||
1934             wp[builtin_opt.optind][0] == '+') &&
1935             wp[builtin_opt.optind][1] == '\0') {
1936                 thing = wp[builtin_opt.optind][0];
1937                 builtin_opt.optind++;
1938         }
1939
1940         if (func && (((fset|fclr) & ~(TRACE|UCASEV_AL|EXPORT)) ||
1941             new_refflag != SRF_NOP)) {
1942                 bi_errorf("only -t, -u and -x options may be used with -f");
1943                 return (1);
1944         }
1945         if (wp[builtin_opt.optind]) {
1946                 /*
1947                  * Take care of exclusions.
1948                  * At this point, flags in fset are cleared in fclr and vice
1949                  * versa. This property should be preserved.
1950                  */
1951                 if (fset & LCASEV)
1952                         /* LCASEV has priority over UCASEV_AL */
1953                         fset &= ~UCASEV_AL;
1954                 if (fset & LJUST)
1955                         /* LJUST has priority over RJUST */
1956                         fset &= ~RJUST;
1957                 if ((fset & (ZEROFIL|LJUST)) == ZEROFIL) {
1958                         /* -Z implies -ZR */
1959                         fset |= RJUST;
1960                         fclr &= ~RJUST;
1961                 }
1962                 /*
1963                  * Setting these attributes clears the others, unless they
1964                  * are also set in this command
1965                  */
1966                 if ((fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL | LCASEV |
1967                     INTEGER | INT_U | INT_L)) || new_refflag != SRF_NOP)
1968                         fclr |= ~fset & (LJUST | RJUST | ZEROFIL | UCASEV_AL |
1969                             LCASEV | INTEGER | INT_U | INT_L);
1970         }
1971         if (new_refflag != SRF_NOP) {
1972                 fclr &= ~(ARRAY | ASSOC);
1973                 fset &= ~(ARRAY | ASSOC);
1974                 fclr |= EXPORT;
1975                 fset |= ASSOC;
1976                 if (new_refflag == SRF_DISABLE)
1977                         fclr |= ASSOC;
1978         }
1979
1980         /* set variables and attributes */
1981         if (wp[builtin_opt.optind] &&
1982             /* not "typeset -p varname" */
1983             !(!func && pflag && !(fset | fclr))) {
1984                 int rv = 0;
1985                 struct tbl *f;
1986
1987                 if (localv && !func)
1988                         fset |= LOCAL;
1989                 for (i = builtin_opt.optind; wp[i]; i++) {
1990                         if (func) {
1991                                 f = findfunc(wp[i], hash(wp[i]),
1992                                     tobool(fset & UCASEV_AL));
1993                                 if (!f) {
1994                                         /* AT&T ksh does ++rv: bogus */
1995                                         rv = 1;
1996                                         continue;
1997                                 }
1998                                 if (fset | fclr) {
1999                                         f->flag |= fset;
2000                                         f->flag &= ~fclr;
2001                                 } else {
2002                                         fpFUNCTf(shl_stdout, 0,
2003                                             tobool(f->flag & FKSH),
2004                                             wp[i], f->val.t);
2005                                         shf_putc('\n', shl_stdout);
2006                                 }
2007                         } else if (!typeset(wp[i], fset, fclr, field, base)) {
2008                                 bi_errorf(Tf_sD_s, wp[i], Tnot_ident);
2009                                 return (1);
2010                         }
2011                 }
2012                 return (rv);
2013         }
2014
2015         /* list variables and attributes */
2016
2017         /* no difference at this point.. */
2018         flag = fset | fclr;
2019         if (func) {
2020                 for (l = e->loc; l; l = l->next) {
2021                         for (p = ktsort(&l->funs); (vp = *p++); ) {
2022                                 if (flag && (vp->flag & flag) == 0)
2023                                         continue;
2024                                 if (thing == '-')
2025                                         fpFUNCTf(shl_stdout, 0,
2026                                             tobool(vp->flag & FKSH),
2027                                             vp->name, vp->val.t);
2028                                 else
2029                                         shf_puts(vp->name, shl_stdout);
2030                                 shf_putc('\n', shl_stdout);
2031                         }
2032                 }
2033         } else if (wp[builtin_opt.optind]) {
2034                 for (i = builtin_opt.optind; wp[i]; i++) {
2035                         vp = isglobal(wp[i], false);
2036                         c_typeset_vardump(vp, flag, thing,
2037                             last_lookup_was_array ? 4 : 0, pflag, istset);
2038                 }
2039         } else
2040                 c_typeset_vardump_recursive(e->loc, flag, thing, pflag, istset);
2041         return (0);
2042 }
2043
2044 static void
2045 c_typeset_vardump_recursive(struct block *l, uint32_t flag, int thing,
2046     bool pflag, bool istset)
2047 {
2048         struct tbl **blockvars, *vp;
2049
2050         if (l->next)
2051                 c_typeset_vardump_recursive(l->next, flag, thing, pflag, istset);
2052         blockvars = ktsort(&l->vars);
2053         while ((vp = *blockvars++))
2054                 c_typeset_vardump(vp, flag, thing, 0, pflag, istset);
2055         /*XXX doesn’t this leak? */
2056 }
2057
2058 static void
2059 c_typeset_vardump(struct tbl *vp, uint32_t flag, int thing, int any_set,
2060     bool pflag, bool istset)
2061 {
2062         struct tbl *tvp;
2063         char *s;
2064
2065         if (!vp)
2066                 return;
2067
2068         /*
2069          * See if the parameter is set (for arrays, if any
2070          * element is set).
2071          */
2072         for (tvp = vp; tvp; tvp = tvp->u.array)
2073                 if (tvp->flag & ISSET) {
2074                         any_set |= 1;
2075                         break;
2076                 }
2077
2078         /*
2079          * Check attributes - note that all array elements
2080          * have (should have?) the same attributes, so checking
2081          * the first is sufficient.
2082          *
2083          * Report an unset param only if the user has
2084          * explicitly given it some attribute (like export);
2085          * otherwise, after "echo $FOO", we would report FOO...
2086          */
2087         if (!any_set && !(vp->flag & USERATTRIB))
2088                 return;
2089         if (flag && (vp->flag & flag) == 0)
2090                 return;
2091         if (!(vp->flag & ARRAY))
2092                 /* optimise later conditionals */
2093                 any_set = 0;
2094         do {
2095                 /*
2096                  * Ignore array elements that aren't set unless there
2097                  * are no set elements, in which case the first is
2098                  * reported on
2099                  */
2100                 if (any_set && !(vp->flag & ISSET))
2101                         continue;
2102                 /* no arguments */
2103                 if (!thing && !flag) {
2104                         if (any_set == 1) {
2105                                 shprintf(Tf_s_s_sN, Tset, "-A", vp->name);
2106                                 any_set = 2;
2107                         }
2108                         /*
2109                          * AT&T ksh prints things like export, integer,
2110                          * leftadj, zerofill, etc., but POSIX says must
2111                          * be suitable for re-entry...
2112                          */
2113                         shprintf(Tf_s_s, Ttypeset, "");
2114                         if (((vp->flag & (ARRAY | ASSOC)) == ASSOC))
2115                                 shprintf(Tf__c_, 'n');
2116                         if ((vp->flag & INTEGER))
2117                                 shprintf(Tf__c_, 'i');
2118                         if ((vp->flag & EXPORT))
2119                                 shprintf(Tf__c_, 'x');
2120                         if ((vp->flag & RDONLY))
2121                                 shprintf(Tf__c_, 'r');
2122                         if ((vp->flag & TRACE))
2123                                 shprintf(Tf__c_, 't');
2124                         if ((vp->flag & LJUST))
2125                                 shprintf("-L%d ", vp->u2.field);
2126                         if ((vp->flag & RJUST))
2127                                 shprintf("-R%d ", vp->u2.field);
2128                         if ((vp->flag & ZEROFIL))
2129                                 shprintf(Tf__c_, 'Z');
2130                         if ((vp->flag & LCASEV))
2131                                 shprintf(Tf__c_, 'l');
2132                         if ((vp->flag & UCASEV_AL))
2133                                 shprintf(Tf__c_, 'u');
2134                         if ((vp->flag & INT_U))
2135                                 shprintf(Tf__c_, 'U');
2136                 } else if (pflag) {
2137                         shprintf(Tf_s_s, istset ? Ttypeset :
2138                             (flag & EXPORT) ? Texport : Treadonly, "");
2139                 }
2140                 if (any_set)
2141                         shprintf("%s[%lu]", vp->name, arrayindex(vp));
2142                 else
2143                         shf_puts(vp->name, shl_stdout);
2144                 if ((!thing && !flag && pflag) ||
2145                     (thing == '-' && (vp->flag & ISSET))) {
2146                         s = str_val(vp);
2147                         shf_putc('=', shl_stdout);
2148                         /* AT&T ksh can't have justified integers... */
2149                         if ((vp->flag & (INTEGER | LJUST | RJUST)) == INTEGER)
2150                                 shf_puts(s, shl_stdout);
2151                         else
2152                                 print_value_quoted(shl_stdout, s);
2153                 }
2154                 shf_putc('\n', shl_stdout);
2155
2156                 /*
2157                  * Only report first 'element' of an array with
2158                  * no set elements.
2159                  */
2160                 if (!any_set)
2161                         return;
2162         } while (!(any_set & 4) && (vp = vp->u.array));
2163 }