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