var.c
1/* $OpenBSD: var.c,v 1.73 2023/07/23 23:42:03 kn Exp $ */
2
3#include <sys/stat.h>
4#include <sys/time.h>
5
6#include <ctype.h>
7#include <errno.h>
8#include <inttypes.h>
9#include <limits.h>
10#include <stdlib.h>
11#include <string.h>
12#include <time.h>
13#include <unistd.h>
14
15#include "sh.h"
16
17#if !defined(SMALL) && !defined(NO_CURSES)
18#ifdef HAVE_CURSES
19# include <term.h>
20# include <curses.h>
21#elif defined(HAVE_NCURSES)
22# include <term.h>
23# include <ncurses.h>
24#elif defined(HAVE_NCURSESNCURSES)
25# include <ncurses/term.h>
26# include <ncurses/ncurses.h>
27#endif
28#endif
29
30/*
31 * Variables
32 *
33 * WARNING: unreadable code, needs a rewrite
34 *
35 * if (flag&INTEGER), val.i contains integer value, and type contains base.
36 * otherwise, (val.s + type) contains string value.
37 * if (flag&EXPORT), val.s contains "name=value" for E-Z exporting.
38 */
39static struct tbl vtemp;
40static struct table specials;
41static char *formatstr(struct tbl *, const char *);
42static void export(struct tbl *, const char *);
43static int special(const char *);
44static void unspecial(const char *);
45static void getspec(struct tbl *);
46static void setspec(struct tbl *);
47static void unsetspec(struct tbl *);
48static struct tbl *arraysearch(struct tbl *, int);
49
50/*
51 * create a new block for function calls and simple commands
52 * assume caller has allocated and set up genv->loc
53 */
54void
55newblock(void)
56{
57 struct block *l;
58 static char *const empty[] = {null};
59
60 l = alloc(sizeof(struct block), ATEMP);
61 l->flags = 0;
62 ainit(&l->area); /* todo: could use genv->area (l->area => l->areap) */
63 if (!genv->loc) {
64 l->argc = 0;
65 l->argv = (char **) empty;
66 } else {
67 l->argc = genv->loc->argc;
68 l->argv = genv->loc->argv;
69 }
70 l->exit = l->error = NULL;
71 ktinit(&l->vars, &l->area, 0);
72 ktinit(&l->funs, &l->area, 0);
73 l->next = genv->loc;
74 genv->loc = l;
75}
76
77/*
78 * pop a block handling special variables
79 */
80void
81popblock(void)
82{
83 struct block *l = genv->loc;
84 struct tbl *vp, **vpp = l->vars.tbls, *vq;
85 int i;
86
87 genv->loc = l->next; /* pop block */
88 for (i = l->vars.size; --i >= 0; )
89 if ((vp = *vpp++) != NULL && (vp->flag&SPECIAL)) {
90 if ((vq = global(vp->name))->flag & ISSET)
91 setspec(vq);
92 else
93 unsetspec(vq);
94 }
95 if (l->flags & BF_DOGETOPTS)
96 user_opt = l->getopts_state;
97 afreeall(&l->area);
98 afree(l, ATEMP);
99}
100
101/* called by main() to initialize variable data structures */
102void
103initvar(void)
104{
105 static const struct {
106 const char *name;
107 int v;
108 } names[] = {
109 { "COLUMNS", V_COLUMNS },
110 { "IFS", V_IFS },
111 { "OPTIND", V_OPTIND },
112 { "PATH", V_PATH },
113 { "POSIXLY_CORRECT", V_POSIXLY_CORRECT },
114 { "TMPDIR", V_TMPDIR },
115 { "HISTCONTROL", V_HISTCONTROL },
116 { "HISTFILE", V_HISTFILE },
117 { "HISTSIZE", V_HISTSIZE },
118 { "EDITOR", V_EDITOR },
119 { "VISUAL", V_VISUAL },
120#ifndef SMALL
121 { "MAIL", V_MAIL },
122 { "MAILCHECK", V_MAILCHECK },
123 { "MAILPATH", V_MAILPATH },
124#endif /* SMALL */
125 { "RANDOM", V_RANDOM },
126 { "SECONDS", V_SECONDS },
127 { "TMOUT", V_TMOUT },
128 { "LINENO", V_LINENO },
129 { "TERM", V_TERM },
130 { NULL, 0 }
131 };
132 int i;
133 struct tbl *tp;
134
135 ktinit(&specials, APERM, 32); /* must be 2^n (currently 19 specials) */
136 for (i = 0; names[i].name; i++) {
137 tp = ktenter(&specials, names[i].name, hash(names[i].name));
138 tp->flag = DEFINED|ISSET;
139 tp->type = names[i].v;
140 }
141}
142
143/* Used to calculate an array index for global()/local(). Sets *arrayp to
144 * non-zero if this is an array, sets *valp to the array index, returns
145 * the basename of the array.
146 */
147static const char *
148array_index_calc(const char *n, bool *arrayp, int *valp)
149{
150 const char *p;
151 int len;
152
153 *arrayp = false;
154 p = skip_varname(n, false);
155 if (p != n && *p == '[' && (len = array_ref_len(p))) {
156 char *sub, *tmp;
157 int64_t rval;
158
159 /* Calculate the value of the subscript */
160 *arrayp = true;
161 tmp = str_nsave(p+1, len-2, ATEMP);
162 sub = substitute(tmp, 0);
163 afree(tmp, ATEMP);
164 n = str_nsave(n, p - n, ATEMP);
165 evaluate(sub, &rval, KSH_UNWIND_ERROR, true);
166 if (rval < 0 || rval > INT_MAX)
167 errorf("%s: subscript %" PRIi64 " out of range",
168 n, rval);
169 *valp = rval;
170 afree(sub, ATEMP);
171 }
172 return n;
173}
174
175/*
176 * Search for variable, if not found create globally.
177 */
178struct tbl *
179global(const char *n)
180{
181 struct block *l = genv->loc;
182 struct tbl *vp;
183 long num;
184 int c;
185 unsigned int h;
186 bool array;
187 int val;
188
189 /* Check to see if this is an array */
190 n = array_index_calc(n, &array, &val);
191 h = hash(n);
192 c = (unsigned char)n[0];
193 if (!letter(c)) {
194 if (array)
195 errorf("bad substitution");
196 vp = &vtemp;
197 vp->flag = DEFINED;
198 vp->type = 0;
199 vp->areap = ATEMP;
200 *vp->name = c;
201 if (digit(c)) {
202 errno = 0;
203 num = strtol(n, NULL, 10);
204 if (errno == 0 && num <= l->argc)
205 /* setstr can't fail here */
206 setstr(vp, l->argv[num], KSH_RETURN_ERROR);
207 vp->flag |= RDONLY;
208 return vp;
209 }
210 vp->flag |= RDONLY;
211 if (n[1] != '\0')
212 return vp;
213 vp->flag |= ISSET|INTEGER;
214 switch (c) {
215 case '$':
216 vp->val.i = kshpid;
217 break;
218 case '!':
219 /* If no job, expand to nothing */
220 if ((vp->val.i = j_async()) == 0)
221 vp->flag &= ~(ISSET|INTEGER);
222 break;
223 case '?':
224 vp->val.i = exstat;
225 break;
226 case '#':
227 vp->val.i = l->argc;
228 break;
229 case '-':
230 vp->flag &= ~INTEGER;
231 vp->val.s = getoptions();
232 break;
233 default:
234 vp->flag &= ~(ISSET|INTEGER);
235 }
236 return vp;
237 }
238 for (l = genv->loc; ; l = l->next) {
239 vp = ktsearch(&l->vars, n, h);
240 if (vp != NULL) {
241 if (array)
242 return arraysearch(vp, val);
243 else
244 return vp;
245 }
246 if (l->next == NULL)
247 break;
248 }
249 vp = ktenter(&l->vars, n, h);
250 if (array)
251 vp = arraysearch(vp, val);
252 vp->flag |= DEFINED;
253 if (special(n))
254 vp->flag |= SPECIAL;
255 return vp;
256}
257
258/*
259 * Search for local variable, if not found create locally.
260 */
261struct tbl *
262local(const char *n, bool copy)
263{
264 struct block *l = genv->loc;
265 struct tbl *vp;
266 unsigned int h;
267 bool array;
268 int val;
269
270 /* Check to see if this is an array */
271 n = array_index_calc(n, &array, &val);
272 h = hash(n);
273 if (!letter(*n)) {
274 vp = &vtemp;
275 vp->flag = DEFINED|RDONLY;
276 vp->type = 0;
277 vp->areap = ATEMP;
278 return vp;
279 }
280 vp = ktenter(&l->vars, n, h);
281 if (copy && !(vp->flag & DEFINED)) {
282 struct block *ll = l;
283 struct tbl *vq = NULL;
284
285 while ((ll = ll->next) && !(vq = ktsearch(&ll->vars, n, h)))
286 ;
287 if (vq) {
288 vp->flag |= vq->flag &
289 (EXPORT | INTEGER | RDONLY | LJUST | RJUST |
290 ZEROFIL | LCASEV | UCASEV_AL | INT_U | INT_L);
291 if (vq->flag & INTEGER)
292 vp->type = vq->type;
293 vp->u2.field = vq->u2.field;
294 }
295 }
296 if (array)
297 vp = arraysearch(vp, val);
298 vp->flag |= DEFINED;
299 if (special(n))
300 vp->flag |= SPECIAL;
301 return vp;
302}
303
304/* get variable string value */
305char *
306str_val(struct tbl *vp)
307{
308 char *s;
309
310 if ((vp->flag&SPECIAL))
311 getspec(vp);
312 if (!(vp->flag&ISSET))
313 s = null; /* special to dollar() */
314 else if (!(vp->flag&INTEGER)) /* string source */
315 s = vp->val.s + vp->type;
316 else { /* integer source */
317 /* worst case number length is when base=2, so use
318 * minus base # number BITS(int64_t) NUL */
319 char strbuf[1 + 2 + 1 + BITS(int64_t) + 1];
320 const char *digits = (vp->flag & UCASEV_AL) ?
321 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" :
322 "0123456789abcdefghijklmnopqrstuvwxyz";
323 uint64_t n;
324 unsigned int base;
325
326 s = strbuf + sizeof(strbuf);
327 if (vp->flag & INT_U)
328 n = (uint64_t) vp->val.i;
329 else
330 n = (vp->val.i < 0) ? -vp->val.i : vp->val.i;
331 base = (vp->type == 0) ? 10 : vp->type;
332 if (base < 2 || base > strlen(digits))
333 base = 10;
334
335 *--s = '\0';
336 do {
337 *--s = digits[n % base];
338 n /= base;
339 } while (n != 0);
340 if (base != 10) {
341 *--s = '#';
342 *--s = digits[base % 10];
343 if (base >= 10)
344 *--s = digits[base / 10];
345 }
346 if (!(vp->flag & INT_U) && vp->val.i < 0)
347 *--s = '-';
348 if (vp->flag & (RJUST|LJUST)) /* case already dealt with */
349 s = formatstr(vp, s);
350 else
351 s = str_save(s, ATEMP);
352 }
353 return s;
354}
355
356/* get variable integer value, with error checking */
357int64_t
358intval(struct tbl *vp)
359{
360 int64_t num;
361 int base;
362
363 base = getint(vp, &num, false);
364 if (base == -1)
365 /* XXX check calls - is error here ok by POSIX? */
366 errorf("%s: bad number", str_val(vp));
367 return num;
368}
369
370/* set variable to string value */
371int
372setstr(struct tbl *vq, const char *s, int error_ok)
373{
374 const char *fs = NULL;
375 int no_ro_check = error_ok & KSH_IGNORE_RDONLY;
376 error_ok &= ~KSH_IGNORE_RDONLY;
377 if ((vq->flag & RDONLY) && !no_ro_check) {
378 warningf(true, "%s: is read only", vq->name);
379 if (!error_ok)
380 errorf(NULL);
381 return 0;
382 }
383 if (!(vq->flag&INTEGER)) { /* string dest */
384 if ((vq->flag&ALLOC)) {
385 /* debugging */
386 if (s >= vq->val.s &&
387 s <= vq->val.s + strlen(vq->val.s))
388 internal_errorf("%s: %s=%s: assigning to self",
389 __func__, vq->name, s);
390 afree(vq->val.s, vq->areap);
391 }
392 vq->flag &= ~(ISSET|ALLOC);
393 vq->type = 0;
394 if (s && (vq->flag & (UCASEV_AL|LCASEV|LJUST|RJUST)))
395 fs = s = formatstr(vq, s);
396 if ((vq->flag&EXPORT))
397 export(vq, s);
398 else {
399 vq->val.s = str_save(s, vq->areap);
400 vq->flag |= ALLOC;
401 }
402 } else { /* integer dest */
403 if (!v_evaluate(vq, s, error_ok, true))
404 return 0;
405 }
406 vq->flag |= ISSET;
407 if ((vq->flag&SPECIAL))
408 setspec(vq);
409 afree((void *)fs, ATEMP);
410 return 1;
411}
412
413/* set variable to integer */
414void
415setint(struct tbl *vq, int64_t n)
416{
417 if (!(vq->flag&INTEGER)) {
418 struct tbl *vp = &vtemp;
419 vp->flag = (ISSET|INTEGER);
420 vp->type = 0;
421 vp->areap = ATEMP;
422 vp->val.i = n;
423 /* setstr can't fail here */
424 setstr(vq, str_val(vp), KSH_RETURN_ERROR);
425 } else
426 vq->val.i = n;
427 vq->flag |= ISSET;
428 if ((vq->flag&SPECIAL))
429 setspec(vq);
430}
431
432int
433getint(struct tbl *vp, int64_t *nump, bool arith)
434{
435 char *s;
436 int c;
437 int base, neg;
438 int have_base = 0;
439 int64_t num;
440
441 if (vp->flag&SPECIAL)
442 getspec(vp);
443 /* XXX is it possible for ISSET to be set and val.s to be 0? */
444 if (!(vp->flag&ISSET) || (!(vp->flag&INTEGER) && vp->val.s == NULL))
445 return -1;
446 if (vp->flag&INTEGER) {
447 *nump = vp->val.i;
448 return vp->type;
449 }
450 s = vp->val.s + vp->type;
451 if (s == NULL) /* redundant given initial test */
452 s = null;
453 base = 10;
454 num = 0;
455 neg = 0;
456 if (arith && *s == '0' && *(s+1)) {
457 s++;
458 if (*s == 'x' || *s == 'X') {
459 s++;
460 base = 16;
461 } else if (vp->flag & ZEROFIL) {
462 while (*s == '0')
463 s++;
464 } else
465 base = 8;
466 have_base++;
467 }
468 for (c = (unsigned char)*s++; c ; c = (unsigned char)*s++) {
469 if (c == '-') {
470 neg++;
471 } else if (c == '#') {
472 base = (int) num;
473 if (have_base || base < 2 || base > 36)
474 return -1;
475 num = 0;
476 have_base = 1;
477 } else if (letnum(c)) {
478 if (isdigit(c))
479 c -= '0';
480 else if (islower(c))
481 c -= 'a' - 10; /* todo: assumes ascii */
482 else if (isupper(c))
483 c -= 'A' - 10; /* todo: assumes ascii */
484 else
485 c = -1; /* _: force error */
486 if (c < 0 || c >= base)
487 return -1;
488 num = num * base + c;
489 } else
490 return -1;
491 }
492 if (neg)
493 num = -num;
494 *nump = num;
495 return base;
496}
497
498/* convert variable vq to integer variable, setting its value from vp
499 * (vq and vp may be the same)
500 */
501struct tbl *
502setint_v(struct tbl *vq, struct tbl *vp, bool arith)
503{
504 int base;
505 int64_t num;
506
507 if ((base = getint(vp, &num, arith)) == -1)
508 return NULL;
509 if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
510 vq->flag &= ~ALLOC;
511 afree(vq->val.s, vq->areap);
512 }
513 vq->val.i = num;
514 if (vq->type == 0) /* default base */
515 vq->type = base;
516 vq->flag |= ISSET|INTEGER;
517 if (vq->flag&SPECIAL)
518 setspec(vq);
519 return vq;
520}
521
522static char *
523formatstr(struct tbl *vp, const char *s)
524{
525 int olen, nlen;
526 char *p, *q;
527
528 olen = strlen(s);
529
530 if (vp->flag & (RJUST|LJUST)) {
531 if (!vp->u2.field) /* default field width */
532 vp->u2.field = olen;
533 nlen = vp->u2.field;
534 } else
535 nlen = olen;
536
537 p = alloc(nlen + 1, ATEMP);
538 if (vp->flag & (RJUST|LJUST)) {
539 int slen;
540
541 if (vp->flag & RJUST) {
542 const char *r = s + olen;
543 /* strip trailing spaces (at&t ksh uses r[-1] == ' ') */
544 while (r > s && isspace((unsigned char)r[-1]))
545 --r;
546 slen = r - s;
547 if (slen > vp->u2.field) {
548 s += slen - vp->u2.field;
549 slen = vp->u2.field;
550 }
551 shf_snprintf(p, nlen + 1,
552 ((vp->flag & ZEROFIL) && digit(*s)) ?
553 "%0*s%.*s" : "%*s%.*s",
554 vp->u2.field - slen, null, slen, s);
555 } else {
556 /* strip leading spaces/zeros */
557 while (isspace((unsigned char)*s))
558 s++;
559 if (vp->flag & ZEROFIL)
560 while (*s == '0')
561 s++;
562 shf_snprintf(p, nlen + 1, "%-*.*s",
563 vp->u2.field, vp->u2.field, s);
564 }
565 } else
566 memcpy(p, s, olen + 1);
567
568 if (vp->flag & UCASEV_AL) {
569 for (q = p; *q; q++)
570 if (islower((unsigned char)*q))
571 *q = toupper((unsigned char)*q);
572 } else if (vp->flag & LCASEV) {
573 for (q = p; *q; q++)
574 if (isupper((unsigned char)*q))
575 *q = tolower((unsigned char)*q);
576 }
577
578 return p;
579}
580
581/*
582 * make vp->val.s be "name=value" for quick exporting.
583 */
584static void
585export(struct tbl *vp, const char *val)
586{
587 char *xp;
588 char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
589 int namelen = strlen(vp->name);
590 int vallen = strlen(val) + 1;
591
592 vp->flag |= ALLOC;
593 xp = alloc(namelen + 1 + vallen, vp->areap);
594 memcpy(vp->val.s = xp, vp->name, namelen);
595 xp += namelen;
596 *xp++ = '=';
597 vp->type = xp - vp->val.s; /* offset to value */
598 memcpy(xp, val, vallen);
599 afree(op, vp->areap);
600}
601
602/*
603 * lookup variable (according to (set&LOCAL)),
604 * set its attributes (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL,
605 * LCASEV, UCASEV_AL), and optionally set its value if an assignment.
606 */
607struct tbl *
608typeset(const char *var, int set, int clr, int field, int base)
609{
610 struct tbl *vp;
611 struct tbl *vpbase, *t;
612 char *tvar;
613 const char *val;
614
615 /* check for valid variable name, search for value */
616 val = skip_varname(var, false);
617 if (val == var)
618 return NULL;
619 if (*val == '[') {
620 int len;
621
622 len = array_ref_len(val);
623 if (len == 0)
624 return NULL;
625 /* IMPORT is only used when the shell starts up and is
626 * setting up its environment. Allow only simple array
627 * references at this time since parameter/command substitution
628 * is preformed on the [expression], which would be a major
629 * security hole.
630 */
631 if (set & IMPORT) {
632 int i;
633 for (i = 1; i < len - 1; i++)
634 if (!digit(val[i]))
635 return NULL;
636 }
637 val += len;
638 }
639 if (*val == '=')
640 tvar = str_nsave(var, val++ - var, ATEMP);
641 else {
642 /* Importing from original environment: must have an = */
643 if (set & IMPORT)
644 return NULL;
645 tvar = (char *) var;
646 val = NULL;
647 }
648
649 /* Prevent typeset from creating a local PATH/ENV/SHELL */
650 if (Flag(FRESTRICTED) && (strcmp(tvar, "PATH") == 0 ||
651 strcmp(tvar, "ENV") == 0 || strcmp(tvar, "SHELL") == 0))
652 errorf("%s: restricted", tvar);
653
654 vp = (set&LOCAL) ? local(tvar, (set & LOCAL_COPY) ? true : false) :
655 global(tvar);
656 set &= ~(LOCAL|LOCAL_COPY);
657
658 vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
659
660 /* only allow export flag to be set. at&t ksh allows any attribute to
661 * be changed, which means it can be truncated or modified
662 * (-L/-R/-Z/-i).
663 */
664 if ((vpbase->flag&RDONLY) &&
665 (val || clr || (set & ~EXPORT)))
666 /* XXX check calls - is error here ok by POSIX? */
667 errorf("%s: is read only", tvar);
668 if (val)
669 afree(tvar, ATEMP);
670
671 /* most calls are with set/clr == 0 */
672 if (set | clr) {
673 int ok = 1;
674 /* XXX if x[0] isn't set, there will be problems: need to have
675 * one copy of attributes for arrays...
676 */
677 for (t = vpbase; t; t = t->u.array) {
678 int fake_assign;
679 int error_ok = KSH_RETURN_ERROR;
680 char *s = NULL;
681 char *free_me = NULL;
682
683 fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
684 ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL)) ||
685 ((t->flag & INTEGER) && (clr & INTEGER)) ||
686 (!(t->flag & INTEGER) && (set & INTEGER)));
687 if (fake_assign) {
688 if (t->flag & INTEGER) {
689 s = str_val(t);
690 free_me = NULL;
691 } else {
692 s = t->val.s + t->type;
693 free_me = (t->flag & ALLOC) ? t->val.s :
694 NULL;
695 }
696 t->flag &= ~ALLOC;
697 }
698 if (!(t->flag & INTEGER) && (set & INTEGER)) {
699 t->type = 0;
700 t->flag &= ~ALLOC;
701 }
702 if (!(t->flag & RDONLY) && (set & RDONLY)) {
703 /* allow var to be initialized read-only */
704 error_ok |= KSH_IGNORE_RDONLY;
705 }
706 t->flag = (t->flag | set) & ~clr;
707 /* Don't change base if assignment is to be done,
708 * in case assignment fails.
709 */
710 if ((set & INTEGER) && base > 0 && (!val || t != vp))
711 t->type = base;
712 if (set & (LJUST|RJUST|ZEROFIL))
713 t->u2.field = field;
714 if (fake_assign) {
715 if (!setstr(t, s, error_ok)) {
716 /* Somewhat arbitrary action here:
717 * zap contents of variable, but keep
718 * the flag settings.
719 */
720 ok = 0;
721 if (t->flag & INTEGER)
722 t->flag &= ~ISSET;
723 else {
724 if (t->flag & ALLOC)
725 afree(t->val.s, t->areap);
726 t->flag &= ~(ISSET|ALLOC);
727 t->type = 0;
728 }
729 }
730 afree(free_me, t->areap);
731 }
732 }
733 if (!ok)
734 errorf(NULL);
735 }
736
737 if (val != NULL) {
738 if (vp->flag&INTEGER) {
739 /* do not zero base before assignment */
740 setstr(vp, val, KSH_UNWIND_ERROR | KSH_IGNORE_RDONLY);
741 /* Done after assignment to override default */
742 if (base > 0)
743 vp->type = base;
744 } else
745 /* setstr can't fail (readonly check already done) */
746 setstr(vp, val, KSH_RETURN_ERROR | KSH_IGNORE_RDONLY);
747 }
748
749 /* only x[0] is ever exported, so use vpbase */
750 if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER) &&
751 vpbase->type == 0)
752 export(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
753
754 return vp;
755}
756
757/* Unset a variable. array_ref is set if there was an array reference in
758 * the name lookup (eg, x[2]).
759 */
760void
761unset(struct tbl *vp, int array_ref)
762{
763 if (vp->flag & ALLOC)
764 afree(vp->val.s, vp->areap);
765 if ((vp->flag & ARRAY) && !array_ref) {
766 struct tbl *a, *tmp;
767
768 /* Free up entire array */
769 for (a = vp->u.array; a; ) {
770 tmp = a;
771 a = a->u.array;
772 if (tmp->flag & ALLOC)
773 afree(tmp->val.s, tmp->areap);
774 afree(tmp, tmp->areap);
775 }
776 vp->u.array = NULL;
777 }
778 /* If foo[0] is being unset, the remainder of the array is kept... */
779 vp->flag &= SPECIAL | (array_ref ? ARRAY|DEFINED : 0);
780 if (vp->flag & SPECIAL)
781 unsetspec(vp); /* responsible for `unspecial'ing var */
782}
783
784/* return a pointer to the first char past a legal variable name (returns the
785 * argument if there is no legal name, returns * a pointer to the terminating
786 * null if whole string is legal).
787 */
788char *
789skip_varname(const char *s, int aok)
790{
791 int alen;
792
793 if (s && letter(*s)) {
794 while (*++s && letnum(*s))
795 ;
796 if (aok && *s == '[' && (alen = array_ref_len(s)))
797 s += alen;
798 }
799 return (char *) s;
800}
801
802/* Return a pointer to the first character past any legal variable name. */
803char *
804skip_wdvarname(const char *s,
805 int aok) /* skip array de-reference? */
806{
807 if (s[0] == CHAR && letter(s[1])) {
808 do {
809 s += 2;
810 } while (s[0] == CHAR && letnum(s[1]));
811 if (aok && s[0] == CHAR && s[1] == '[') {
812 /* skip possible array de-reference */
813 const char *p = s;
814 char c;
815 int depth = 0;
816
817 while (1) {
818 if (p[0] != CHAR)
819 break;
820 c = p[1];
821 p += 2;
822 if (c == '[')
823 depth++;
824 else if (c == ']' && --depth == 0) {
825 s = p;
826 break;
827 }
828 }
829 }
830 }
831 return (char *) s;
832}
833
834/* Check if coded string s is a variable name */
835int
836is_wdvarname(const char *s, int aok)
837{
838 char *p = skip_wdvarname(s, aok);
839
840 return p != s && p[0] == EOS;
841}
842
843/* Check if coded string s is a variable assignment */
844int
845is_wdvarassign(const char *s)
846{
847 char *p = skip_wdvarname(s, true);
848
849 return p != s && p[0] == CHAR && p[1] == '=';
850}
851
852/*
853 * Make the exported environment from the exported names in the dictionary.
854 */
855char **
856makenv(void)
857{
858 struct block *l;
859 XPtrV env;
860 struct tbl *vp, **vpp;
861 int i;
862
863 XPinit(env, 64);
864 for (l = genv->loc; l != NULL; l = l->next)
865 for (vpp = l->vars.tbls, i = l->vars.size; --i >= 0; )
866 if ((vp = *vpp++) != NULL &&
867 (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
868 struct block *l2;
869 struct tbl *vp2;
870 unsigned int h = hash(vp->name);
871
872 /* unexport any redefined instances */
873 for (l2 = l->next; l2 != NULL; l2 = l2->next) {
874 vp2 = ktsearch(&l2->vars, vp->name, h);
875 if (vp2 != NULL)
876 vp2->flag &= ~EXPORT;
877 }
878 if ((vp->flag&INTEGER)) {
879 /* integer to string */
880 char *val;
881 val = str_val(vp);
882 vp->flag &= ~(INTEGER|RDONLY);
883 /* setstr can't fail here */
884 setstr(vp, val, KSH_RETURN_ERROR);
885 }
886 XPput(env, vp->val.s);
887 }
888 XPput(env, NULL);
889 return (char **) XPclose(env);
890}
891
892/*
893 * Called after a fork in parent to bump the random number generator.
894 * Done to ensure children will not get the same random number sequence
895 * if the parent doesn't use $RANDOM.
896 */
897void
898change_random(void)
899{
900 rand();
901}
902
903/*
904 * handle special variables with side effects - PATH, SECONDS.
905 */
906
907/* Test if name is a special parameter */
908static int
909special(const char *name)
910{
911 struct tbl *tp;
912
913 tp = ktsearch(&specials, name, hash(name));
914 return tp && (tp->flag & ISSET) ? tp->type : V_NONE;
915}
916
917/* Make a variable non-special */
918static void
919unspecial(const char *name)
920{
921 struct tbl *tp;
922
923 tp = ktsearch(&specials, name, hash(name));
924 if (tp)
925 ktdelete(tp);
926}
927
928static struct timespec seconds; /* time SECONDS last set */
929static int user_lineno; /* what user set $LINENO to */
930
931static void
932getspec(struct tbl *vp)
933{
934 switch (special(vp->name)) {
935 case V_SECONDS:
936 vp->flag &= ~SPECIAL;
937 /* On start up the value of SECONDS is used before seconds
938 * has been set - don't do anything in this case
939 * (see initcoms[] in main.c).
940 */
941 if (vp->flag & ISSET) {
942 struct timespec difference, now;
943
944 clock_gettime(CLOCK_MONOTONIC, &now);
945 timespecsub(&now, &seconds, &difference);
946 setint(vp, (int64_t)difference.tv_sec);
947 }
948 vp->flag |= SPECIAL;
949 break;
950 case V_RANDOM:
951 vp->flag &= ~SPECIAL;
952 setint(vp, (int64_t) (rand() & 0x7fff));
953 vp->flag |= SPECIAL;
954 break;
955 case V_HISTSIZE:
956 vp->flag &= ~SPECIAL;
957 setint(vp, (int64_t) histsize);
958 vp->flag |= SPECIAL;
959 break;
960 case V_OPTIND:
961 vp->flag &= ~SPECIAL;
962 setint(vp, (int64_t) user_opt.uoptind);
963 vp->flag |= SPECIAL;
964 break;
965 case V_LINENO:
966 vp->flag &= ~SPECIAL;
967 setint(vp, (int64_t) current_lineno + user_lineno);
968 vp->flag |= SPECIAL;
969 break;
970 }
971}
972
973static void
974setspec(struct tbl *vp)
975{
976 char *s;
977
978 switch (special(vp->name)) {
979 case V_PATH:
980 afree(search_path, APERM);
981 search_path = str_save(str_val(vp), APERM);
982 flushcom(1); /* clear tracked aliases */
983 break;
984 case V_IFS:
985 setctypes(s = str_val(vp), C_IFS);
986 ifs0 = *s;
987 break;
988 case V_OPTIND:
989 vp->flag &= ~SPECIAL;
990 getopts_reset((int) intval(vp));
991 vp->flag |= SPECIAL;
992 break;
993 case V_POSIXLY_CORRECT:
994 change_flag(FPOSIX, OF_SPECIAL, 1);
995 break;
996 case V_TMPDIR:
997 afree(tmpdir, APERM);
998 tmpdir = NULL;
999 /* Use tmpdir iff it is an absolute path, is writable and
1000 * searchable and is a directory...
1001 */
1002 {
1003 struct stat statb;
1004
1005 s = str_val(vp);
1006 if (s[0] == '/' && access(s, W_OK|X_OK) == 0 &&
1007 stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
1008 tmpdir = str_save(s, APERM);
1009 }
1010 break;
1011 case V_HISTCONTROL:
1012 sethistcontrol(str_val(vp));
1013 break;
1014 case V_HISTSIZE:
1015 vp->flag &= ~SPECIAL;
1016 sethistsize((int) intval(vp));
1017 vp->flag |= SPECIAL;
1018 break;
1019 case V_HISTFILE:
1020 sethistfile(str_val(vp));
1021 break;
1022 case V_VISUAL:
1023 set_editmode(str_val(vp));
1024 break;
1025 case V_EDITOR:
1026 if (!(global("VISUAL")->flag & ISSET))
1027 set_editmode(str_val(vp));
1028 break;
1029 case V_COLUMNS:
1030 {
1031 int64_t l;
1032
1033 if (getint(vp, &l, false) == -1) {
1034 x_cols = MIN_COLS;
1035 break;
1036 }
1037 if (l <= MIN_COLS || l > INT_MAX)
1038 x_cols = MIN_COLS;
1039 else
1040 x_cols = l;
1041 }
1042 break;
1043#ifndef SMALL
1044 case V_MAIL:
1045 mbset(str_val(vp));
1046 break;
1047 case V_MAILPATH:
1048 mpset(str_val(vp));
1049 break;
1050 case V_MAILCHECK:
1051 vp->flag &= ~SPECIAL;
1052 mcset(intval(vp));
1053 vp->flag |= SPECIAL;
1054 break;
1055#endif /* SMALL */
1056 case V_RANDOM:
1057 vp->flag &= ~SPECIAL;
1058 srand_deterministic((unsigned int)intval(vp));
1059 vp->flag |= SPECIAL;
1060 break;
1061 case V_SECONDS:
1062 vp->flag &= ~SPECIAL;
1063 clock_gettime(CLOCK_MONOTONIC, &seconds);
1064 seconds.tv_sec -= intval(vp);
1065 vp->flag |= SPECIAL;
1066 break;
1067 case V_TMOUT:
1068 /* Enforce integer to avoid command execution from initcoms[] */
1069 vp->flag &= ~SPECIAL;
1070 intval(vp);
1071 vp->flag |= SPECIAL;
1072 /* at&t ksh seems to do this (only listen if integer) */
1073 if (vp->flag & INTEGER)
1074 ksh_tmout = vp->val.i >= 0 ? vp->val.i : 0;
1075 break;
1076 case V_LINENO:
1077 vp->flag &= ~SPECIAL;
1078 /* The -1 is because line numbering starts at 1. */
1079 user_lineno = (unsigned int) intval(vp) - current_lineno - 1;
1080 vp->flag |= SPECIAL;
1081 break;
1082 case V_TERM:
1083#if !defined(SMALL) && !defined(NO_CURSES)
1084 {
1085 int ret;
1086
1087 vp->flag &= ~SPECIAL;
1088 if (setupterm(str_val(vp), shl_out->fd, &ret) == ERR)
1089 del_curterm(cur_term);
1090 vp->flag |= SPECIAL;
1091 }
1092#endif
1093 break;
1094 }
1095}
1096
1097static void
1098unsetspec(struct tbl *vp)
1099{
1100 switch (special(vp->name)) {
1101 case V_PATH:
1102 afree(search_path, APERM);
1103 search_path = str_save(def_path, APERM);
1104 flushcom(1); /* clear tracked aliases */
1105 break;
1106 case V_IFS:
1107 setctypes(" \t\n", C_IFS);
1108 ifs0 = ' ';
1109 break;
1110 case V_TMPDIR:
1111 /* should not become unspecial */
1112 afree(tmpdir, APERM);
1113 tmpdir = NULL;
1114 break;
1115#ifndef SMALL
1116 case V_MAIL:
1117 mbset(NULL);
1118 break;
1119 case V_MAILPATH:
1120 mpset(NULL);
1121 break;
1122#endif /* SMALL */
1123 case V_HISTCONTROL:
1124 sethistcontrol(NULL);
1125 break;
1126 case V_LINENO:
1127#ifndef SMALL
1128 case V_MAILCHECK: /* at&t ksh leaves previous value in place */
1129#endif /* SMALL */
1130 case V_RANDOM:
1131 case V_SECONDS:
1132 case V_TMOUT: /* at&t ksh leaves previous value in place */
1133 unspecial(vp->name);
1134 break;
1135
1136 /* at&t ksh man page says OPTIND, OPTARG and _ lose special meaning,
1137 * but OPTARG does not (still set by getopts) and _ is also still
1138 * set in various places.
1139 * Don't know what at&t does for:
1140 * MAIL, MAILPATH, HISTSIZE, HISTFILE,
1141 * Unsetting these in at&t ksh does not loose the `specialness':
1142 * no effect: IFS, COLUMNS, PATH, TMPDIR,
1143 * VISUAL, EDITOR,
1144 * pdkshisms: no effect:
1145 * POSIXLY_CORRECT (use set +o posix instead)
1146 */
1147 }
1148}
1149
1150/*
1151 * Search for (and possibly create) a table entry starting with
1152 * vp, indexed by val.
1153 */
1154static struct tbl *
1155arraysearch(struct tbl *vp, int val)
1156{
1157 struct tbl *prev, *curr, *new;
1158 size_t namelen = strlen(vp->name) + 1;
1159
1160 vp->flag |= ARRAY|DEFINED;
1161 vp->index = 0;
1162 /* The table entry is always [0] */
1163 if (val == 0)
1164 return vp;
1165 prev = vp;
1166 curr = vp->u.array;
1167 while (curr && curr->index < val) {
1168 prev = curr;
1169 curr = curr->u.array;
1170 }
1171 if (curr && curr->index == val) {
1172 if (curr->flag&ISSET)
1173 return curr;
1174 else
1175 new = curr;
1176 } else
1177 new = alloc(sizeof(struct tbl) + namelen,
1178 vp->areap);
1179 strlcpy(new->name, vp->name, namelen);
1180 new->flag = vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL);
1181 new->type = vp->type;
1182 new->areap = vp->areap;
1183 new->u2.field = vp->u2.field;
1184 new->index = val;
1185 if (curr != new) { /* not reusing old array entry */
1186 prev->u.array = new;
1187 new->u.array = curr;
1188 }
1189 return new;
1190}
1191
1192/* Return the length of an array reference (eg, [1+2]) - cp is assumed
1193 * to point to the open bracket. Returns 0 if there is no matching closing
1194 * bracket.
1195 */
1196int
1197array_ref_len(const char *cp)
1198{
1199 const char *s = cp;
1200 int c;
1201 int depth = 0;
1202
1203 while ((c = *s++) && (c != ']' || --depth))
1204 if (c == '[')
1205 depth++;
1206 if (!c)
1207 return 0;
1208 return s - cp;
1209}
1210
1211/*
1212 * Make a copy of the base of an array name
1213 */
1214char *
1215arrayname(const char *str)
1216{
1217 const char *p;
1218
1219 if ((p = strchr(str, '[')) == 0)
1220 /* Shouldn't happen, but why worry? */
1221 return (char *) str;
1222
1223 return str_nsave(str, p - str, ATEMP);
1224}
1225
1226/* Set (or overwrite, if !reset) the array variable var to the values in vals.
1227 */
1228void
1229set_array(const char *var, int reset, char **vals)
1230{
1231 struct tbl *vp, *vq;
1232 int i;
1233
1234 /* to get local array, use "typeset foo; set -A foo" */
1235 vp = global(var);
1236
1237 /* Note: at&t ksh allows set -A but not set +A of a read-only var */
1238 if ((vp->flag&RDONLY))
1239 errorf("%s: is read only", var);
1240 /* This code is quite non-optimal */
1241 if (reset > 0)
1242 /* trash existing values and attributes */
1243 unset(vp, 0);
1244 /* todo: would be nice for assignment to completely succeed or
1245 * completely fail. Only really effects integer arrays:
1246 * evaluation of some of vals[] may fail...
1247 */
1248 for (i = 0; vals[i]; i++) {
1249 vq = arraysearch(vp, i);
1250 /* would be nice to deal with errors here... (see above) */
1251 setstr(vq, vals[i], KSH_RETURN_ERROR);
1252 }
1253}