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