Home | History | Annotate | Line # | Download | only in ksh
var.c revision 1.13
      1 /*	$NetBSD: var.c,v 1.13 2006/03/19 19:12:23 christos Exp $	*/
      2 
      3 #include <sys/cdefs.h>
      4 
      5 #ifndef lint
      6 __RCSID("$NetBSD: var.c,v 1.13 2006/03/19 19:12:23 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 	}
    345 	return s;
    346 }
    347 
    348 /* get variable integer value, with error checking */
    349 long
    350 intval(vp)
    351 	register struct tbl *vp;
    352 {
    353 	long num;
    354 	int base;
    355 
    356 	base = getint(vp, &num);
    357 	if (base == -1)
    358 		/* XXX check calls - is error here ok by POSIX? */
    359 		errorf("%s: bad number", str_val(vp));
    360 	return num;
    361 }
    362 
    363 /* set variable to string value */
    364 int
    365 setstr(vq, s, error_ok)
    366 	register struct tbl *vq;
    367 	const char *s;
    368 	int error_ok;
    369 {
    370 	char *fs = NULL;
    371 	int no_ro_check = error_ok & 0x4;
    372 	error_ok &= ~0x4;
    373 	if ((vq->flag & RDONLY) && !no_ro_check) {
    374 		warningf(TRUE, "%s: is read only", vq->name);
    375 		if (!error_ok)
    376 			errorf(null);
    377 		return 0;
    378 	}
    379 	if (!(vq->flag&INTEGER)) { /* string dest */
    380 		if ((vq->flag&ALLOC)) {
    381 			/* debugging */
    382 			if (s >= vq->val.s
    383 			    && s <= vq->val.s + strlen(vq->val.s))
    384 				internal_errorf(TRUE,
    385 				    "setstr: %s=%s: assigning to self",
    386 				    vq->name, s);
    387 			afree((void*)vq->val.s, vq->areap);
    388 		}
    389 		vq->flag &= ~(ISSET|ALLOC);
    390 		vq->type = 0;
    391 		if (s && (vq->flag & (UCASEV_AL|LCASEV|LJUST|RJUST)))
    392 			s = fs = formatstr(vq, s);
    393 		if ((vq->flag&EXPORT))
    394 			export(vq, s);
    395 		else {
    396 			vq->val.s = str_save(s, vq->areap);
    397 			vq->flag |= ALLOC;
    398 		}
    399 	} else			/* integer dest */
    400 		if (!v_evaluate(vq, s, error_ok))
    401 			return 0;
    402 	vq->flag |= ISSET;
    403 	if ((vq->flag&SPECIAL))
    404 		setspec(vq);
    405 	if (fs)
    406 		afree(fs, ATEMP);
    407 	return 1;
    408 }
    409 
    410 /* set variable to integer */
    411 void
    412 setint(vq, n)
    413 	register struct tbl *vq;
    414 	long n;
    415 {
    416 	if (!(vq->flag&INTEGER)) {
    417 		register struct tbl *vp = &vtemp;
    418 		vp->flag = (ISSET|INTEGER);
    419 		vp->type = 0;
    420 		vp->areap = ATEMP;
    421 		vp->val.i = n;
    422 		/* setstr can't fail here */
    423 		setstr(vq, str_val(vp), KSH_RETURN_ERROR);
    424 	} else
    425 		vq->val.i = n;
    426 	vq->flag |= ISSET;
    427 	if ((vq->flag&SPECIAL))
    428 		setspec(vq);
    429 }
    430 
    431 int
    432 getint(vp, nump)
    433 	struct tbl *vp;
    434 	long *nump;
    435 {
    436 	register char *s;
    437 	register int c;
    438 	int base, neg;
    439 	int have_base = 0;
    440 	long num;
    441 
    442 	if (vp->flag&SPECIAL)
    443 		getspec(vp);
    444 	/* XXX is it possible for ISSET to be set and val.s to be 0? */
    445 	if (!(vp->flag&ISSET) || (!(vp->flag&INTEGER) && vp->val.s == NULL))
    446 		return -1;
    447 	if (vp->flag&INTEGER) {
    448 		*nump = vp->val.i;
    449 		return vp->type;
    450 	}
    451 	s = vp->val.s + vp->type;
    452 	if (s == NULL)	/* redundant given initial test */
    453 		s = null;
    454 	base = 10;
    455 	num = 0;
    456 	neg = 0;
    457 	for (c = (unsigned char)*s++; c ; c = (unsigned char)*s++) {
    458 		if (c == '-') {
    459 			neg++;
    460 		} else if (c == '#') {
    461 			base = (int) num;
    462 			if (have_base || base < 2 || base > 36)
    463 				return -1;
    464 			num = 0;
    465 			have_base = 1;
    466 		} else if (letnum(c)) {
    467 			if (isdigit(c))
    468 				c -= '0';
    469 			else if (islower(c))
    470 				c -= 'a' - 10; /* todo: assumes ascii */
    471 			else if (isupper(c))
    472 				c -= 'A' - 10; /* todo: assumes ascii */
    473 			else
    474 				c = -1; /* _: force error */
    475 			if (c < 0 || c >= base)
    476 				return -1;
    477 			num = num * base + c;
    478 		} else
    479 			return -1;
    480 	}
    481 	if (neg)
    482 		num = -num;
    483 	*nump = num;
    484 	return base;
    485 }
    486 
    487 /* convert variable vq to integer variable, setting its value from vp
    488  * (vq and vp may be the same)
    489  */
    490 struct tbl *
    491 setint_v(vq, vp)
    492 	register struct tbl *vq, *vp;
    493 {
    494 	int base;
    495 	long num;
    496 
    497 	if ((base = getint(vp, &num)) == -1)
    498 		return NULL;
    499 	if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
    500 		vq->flag &= ~ALLOC;
    501 		afree(vq->val.s, vq->areap);
    502 	}
    503 	vq->val.i = num;
    504 	if (vq->type == 0) /* default base */
    505 		vq->type = base;
    506 	vq->flag |= ISSET|INTEGER;
    507 	if (vq->flag&SPECIAL)
    508 		setspec(vq);
    509 	return vq;
    510 }
    511 
    512 static char *
    513 formatstr(vp, s)
    514 	struct tbl *vp;
    515 	const char *s;
    516 {
    517 	int olen, nlen;
    518 	char *p, *q;
    519 
    520 	olen = strlen(s);
    521 
    522 	if (vp->flag & (RJUST|LJUST)) {
    523 		if (!vp->u2.field)	/* default field width */
    524 			vp->u2.field = olen;
    525 		nlen = vp->u2.field;
    526 	} else
    527 		nlen = olen;
    528 
    529 	p = (char *) alloc(nlen + 1, ATEMP);
    530 	if (vp->flag & (RJUST|LJUST)) {
    531 		int slen;
    532 
    533 		if (vp->flag & RJUST) {
    534 			const char *r = s + olen;
    535 			/* strip trailing spaces (at&t ksh uses q[-1] == ' ') */
    536 			while (r > s && isspace((unsigned char)r[-1]))
    537 				--r;
    538 			slen = r - s;
    539 			if (slen > vp->u2.field) {
    540 				s += slen - vp->u2.field;
    541 				slen = vp->u2.field;
    542 			}
    543 			shf_snprintf(p, nlen + 1,
    544 				((vp->flag & ZEROFIL) && digit(*s)) ?
    545 					  "%0*s%.*s" : "%*s%.*s",
    546 				vp->u2.field - slen, null, slen, s);
    547 		} else {
    548 			/* strip leading spaces/zeros */
    549 			while (isspace((unsigned char)*s))
    550 				s++;
    551 			if (vp->flag & ZEROFIL)
    552 				while (*s == '0')
    553 					s++;
    554 			shf_snprintf(p, nlen + 1, "%-*.*s",
    555 				vp->u2.field, vp->u2.field, s);
    556 		}
    557 	} else
    558 		memcpy(p, s, olen + 1);
    559 
    560 	if (vp->flag & UCASEV_AL) {
    561 		for (q = p; *q; q++)
    562 			if (islower((unsigned char)*q))
    563 				*q = toupper((unsigned char)*q);
    564 	} else if (vp->flag & LCASEV) {
    565 		for (q = p; *q; q++)
    566 			if (isupper((unsigned char)*q))
    567 				*q = tolower((unsigned char)*q);
    568 	}
    569 
    570 	return p;
    571 }
    572 
    573 /*
    574  * make vp->val.s be "name=value" for quick exporting.
    575  */
    576 static void
    577 export(vp, val)
    578 	register struct tbl *vp;
    579 	const char *val;
    580 {
    581 	register char *xp;
    582 	char *op = (vp->flag&ALLOC) ? vp->val.s : NULL;
    583 	int namelen = strlen(vp->name);
    584 	int vallen = strlen(val) + 1;
    585 
    586 	vp->flag |= ALLOC;
    587 	xp = (char*)alloc(namelen + 1 + vallen, vp->areap);
    588 	memcpy(vp->val.s = xp, vp->name, namelen);
    589 	xp += namelen;
    590 	*xp++ = '=';
    591 	vp->type = xp - vp->val.s; /* offset to value */
    592 	memcpy(xp, val, vallen);
    593 	if (op != NULL)
    594 		afree((void*)op, vp->areap);
    595 }
    596 
    597 /*
    598  * lookup variable (according to (set&LOCAL)),
    599  * set its attributes (INTEGER, RDONLY, EXPORT, TRACE, LJUST, RJUST, ZEROFIL,
    600  * LCASEV, UCASEV_AL), and optionally set its value if an assignment.
    601  */
    602 struct tbl *
    603 typeset(var, set, clr, field, base)
    604 	register const char *var;
    605 	Tflag clr, set;
    606 	int field, base;
    607 {
    608 	register struct tbl *vp;
    609 	struct tbl *vpbase, *t;
    610 	char *tvar;
    611 	const char *val;
    612 
    613 	/* check for valid variable name, search for value */
    614 	val = skip_varname(var, FALSE);
    615 	if (val == var)
    616 		return NULL;
    617 	if (*val == '[') {
    618 		int len;
    619 
    620 		len = array_ref_len(val);
    621 		if (len == 0)
    622 			return NULL;
    623 		/* IMPORT is only used when the shell starts up and is
    624 		 * setting up its environment.  Allow only simple array
    625 		 * references at this time since parameter/command substitution
    626 		 * is preformed on the [expression], which would be a major
    627 		 * security hole.
    628 		 */
    629 		if (set & IMPORT) {
    630 			int i;
    631 			for (i = 1; i < len - 1; i++)
    632 				if (!digit(val[i]))
    633 					return NULL;
    634 		}
    635 		val += len;
    636 	}
    637 	if (*val == '=')
    638 		tvar = str_nsave(var, val++ - var, ATEMP);
    639 	else {
    640 		/* Importing from original environment: must have an = */
    641 		if (set & IMPORT)
    642 			return NULL;
    643 		tvar = (char *) __UNCONST(var);
    644 		val = NULL;
    645 	}
    646 
    647 	/* Prevent typeset from creating a local PATH/ENV/SHELL */
    648 	if (Flag(FRESTRICTED) && (strcmp(tvar, "PATH") == 0
    649 				  || strcmp(tvar, "ENV") == 0
    650 				  || strcmp(tvar, "SHELL") == 0))
    651 		errorf("%s: restricted", tvar);
    652 
    653 	vp = (set&LOCAL) ? local(tvar, (set & LOCAL_COPY) ? TRUE : FALSE)
    654 		: global(tvar);
    655 	set &= ~(LOCAL|LOCAL_COPY);
    656 
    657 	vpbase = (vp->flag & ARRAY) ? global(arrayname(var)) : vp;
    658 
    659 	/* only allow export flag to be set.  at&t ksh allows any attribute to
    660 	 * be changed, which means it can be truncated or modified
    661 	 * (-L/-R/-Z/-i).
    662 	 */
    663 	if ((vpbase->flag&RDONLY)
    664 	    && (val || clr || (set & ~EXPORT)))
    665 		/* XXX check calls - is error here ok by POSIX? */
    666 		errorf("%s: is read only", tvar);
    667 	if (val)
    668 		afree(tvar, ATEMP);
    669 
    670 	/* most calls are with set/clr == 0 */
    671 	if (set | clr) {
    672 		int ok = 1;
    673 		/* XXX if x[0] isn't set, there will be problems: need to have
    674 		 * one copy of attributes for arrays...
    675 		 */
    676 		for (t = vpbase; t; t = t->u.array) {
    677 			int fake_assign;
    678 			char UNINITIALIZED(*s);
    679 			char UNINITIALIZED(*free_me);
    680 
    681 			fake_assign = (t->flag & ISSET) && (!val || t != vp)
    682 				      && ((set & (UCASEV_AL|LCASEV|LJUST|RJUST|ZEROFIL))
    683 					  || ((t->flag & INTEGER) && (clr & INTEGER))
    684 					  || (!(t->flag & INTEGER) && (set & INTEGER)));
    685 			if (fake_assign) {
    686 				if (t->flag & INTEGER) {
    687 					s = str_val(t);
    688 					free_me = (char *) 0;
    689 				} else {
    690 					s = t->val.s + t->type;
    691 					free_me = (t->flag & ALLOC) ? t->val.s
    692 								  : (char *) 0;
    693 				}
    694 				t->flag &= ~ALLOC;
    695 			}
    696 			if (!(t->flag & INTEGER) && (set & INTEGER)) {
    697 				t->type = 0;
    698 				t->flag &= ~ALLOC;
    699 			}
    700 			t->flag = (t->flag | set) & ~clr;
    701 			/* Don't change base if assignment is to be done,
    702 			 * in case assignment fails.
    703 			 */
    704 			if ((set & INTEGER) && base > 0 && (!val || t != vp))
    705 				t->type = base;
    706 			if (set & (LJUST|RJUST|ZEROFIL))
    707 				t->u2.field = field;
    708 			if (fake_assign) {
    709 				if (!setstr(t, s, KSH_RETURN_ERROR)) {
    710 					/* Somewhat arbitrary action here:
    711 					 * zap contents of variable, but keep
    712 					 * the flag settings.
    713 					 */
    714 					ok = 0;
    715 					if (t->flag & INTEGER)
    716 						t->flag &= ~ISSET;
    717 					else {
    718 						if (t->flag & ALLOC)
    719 							afree((void*) t->val.s,
    720 							      t->areap);
    721 						t->flag &= ~(ISSET|ALLOC);
    722 						t->type = 0;
    723 					}
    724 				}
    725 				if (free_me)
    726 					afree((void *) free_me, t->areap);
    727 			}
    728 		}
    729 		if (!ok)
    730 		    errorf(null);
    731 	}
    732 
    733 	if (val != NULL) {
    734 		if (vp->flag&INTEGER) {
    735 			/* do not zero base before assignment */
    736 			setstr(vp, val, KSH_UNWIND_ERROR | 0x4);
    737 			/* Done after assignment to override default */
    738 			if (base > 0)
    739 				vp->type = base;
    740 		} else
    741 			/* setstr can't fail (readonly check already done) */
    742 			setstr(vp, val, KSH_RETURN_ERROR | 0x4);
    743 	}
    744 
    745 	/* only x[0] is ever exported, so use vpbase */
    746 	if ((vpbase->flag&EXPORT) && !(vpbase->flag&INTEGER)
    747 	    && vpbase->type == 0)
    748 		export(vpbase, (vpbase->flag&ISSET) ? vpbase->val.s : null);
    749 
    750 	return vp;
    751 }
    752 
    753 /* Unset a variable.  array_ref is set if there was an array reference in
    754  * the name lookup (eg, x[2]).
    755  */
    756 void
    757 unset(vp, array_ref)
    758 	register struct tbl *vp;
    759 	int array_ref;
    760 {
    761 	if (vp->flag & ALLOC)
    762 		afree((void*)vp->val.s, vp->areap);
    763 	if ((vp->flag & ARRAY) && !array_ref) {
    764 		struct tbl *a, *tmp;
    765 
    766 		/* Free up entire array */
    767 		for (a = vp->u.array; a; ) {
    768 			tmp = a;
    769 			a = a->u.array;
    770 			if (tmp->flag & ALLOC)
    771 				afree((void *) tmp->val.s, tmp->areap);
    772 			afree(tmp, tmp->areap);
    773 		}
    774 		vp->u.array = (struct tbl *) 0;
    775 	}
    776 	/* If foo[0] is being unset, the remainder of the array is kept... */
    777 	vp->flag &= SPECIAL | (array_ref ? ARRAY|DEFINED : 0);
    778 	if (vp->flag & SPECIAL)
    779 		unsetspec(vp);	/* responsible for `unspecial'ing var */
    780 }
    781 
    782 /* return a pointer to the first char past a legal variable name (returns the
    783  * argument if there is no legal name, returns * a pointer to the terminating
    784  * null if whole string is legal).
    785  */
    786 char *
    787 skip_varname(s, aok)
    788 	const char *s;
    789 	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 *) __UNCONST(s);
    800 }
    801 
    802 /* Return a pointer to the first character past any legal variable name.  */
    803 char *
    804 skip_wdvarname(s, aok)
    805 	const char *s;
    806 	int aok;	/* skip array de-reference? */
    807 {
    808 	if (s[0] == CHAR && letter(s[1])) {
    809 		do
    810 			s += 2;
    811 		while (s[0] == CHAR && letnum(s[1]));
    812 		if (aok && s[0] == CHAR && s[1] == '[') {
    813 			/* skip possible array de-reference */
    814 			const char *p = s;
    815 			char c;
    816 			int depth = 0;
    817 
    818 			while (1) {
    819 				if (p[0] != CHAR)
    820 					break;
    821 				c = p[1];
    822 				p += 2;
    823 				if (c == '[')
    824 					depth++;
    825 				else if (c == ']' && --depth == 0) {
    826 					s = p;
    827 					break;
    828 				}
    829 			}
    830 		}
    831 	}
    832 	return (char *) __UNCONST(s);
    833 }
    834 
    835 /* Check if coded string s is a variable name */
    836 int
    837 is_wdvarname(s, aok)
    838 	const char *s;
    839 	int aok;
    840 {
    841 	char *p = skip_wdvarname(s, aok);
    842 
    843 	return p != s && p[0] == EOS;
    844 }
    845 
    846 /* Check if coded string s is a variable assignment */
    847 int
    848 is_wdvarassign(s)
    849 	const char *s;
    850 {
    851 	char *p = skip_wdvarname(s, TRUE);
    852 
    853 	return p != s && p[0] == CHAR && p[1] == '=';
    854 }
    855 
    856 /*
    857  * Make the exported environment from the exported names in the dictionary.
    858  */
    859 char **
    860 makenv()
    861 {
    862 	struct block *l = e->loc;
    863 	XPtrV env;
    864 	register struct tbl *vp, **vpp;
    865 	register int i;
    866 
    867 	XPinit(env, 64);
    868 	for (l = e->loc; l != NULL; l = l->next)
    869 		for (vpp = l->vars.tbls, i = l->vars.size; --i >= 0; )
    870 			if ((vp = *vpp++) != NULL
    871 			    && (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
    872 				register struct block *l2;
    873 				register struct tbl *vp2;
    874 				unsigned h = hash(vp->name);
    875 
    876 				/* unexport any redefined instances */
    877 				for (l2 = l->next; l2 != NULL; l2 = l2->next) {
    878 					vp2 = tsearch(&l2->vars, vp->name, h);
    879 					if (vp2 != NULL)
    880 						vp2->flag &= ~EXPORT;
    881 				}
    882 				if ((vp->flag&INTEGER)) {
    883 					/* integer to string */
    884 					char *val;
    885 					val = str_val(vp);
    886 					vp->flag &= ~(INTEGER|RDONLY);
    887 					/* setstr can't fail here */
    888 					setstr(vp, val, KSH_RETURN_ERROR);
    889 				}
    890 				XPput(env, vp->val.s);
    891 			}
    892 	XPput(env, NULL);
    893 	return (char **) XPclose(env);
    894 }
    895 
    896 /*
    897  * Called after a fork in parent to bump the random number generator.
    898  * Done to ensure children will not get the same random number sequence
    899  * if the parent doesn't use $RANDOM.
    900  */
    901 void
    902 change_random()
    903 {
    904     rand();
    905 }
    906 
    907 /*
    908  * handle special variables with side effects - PATH, SECONDS.
    909  */
    910 
    911 /* Test if name is a special parameter */
    912 static int
    913 special(name)
    914 	register const char * name;
    915 {
    916 	register struct tbl *tp;
    917 
    918 	tp = tsearch(&specials, name, hash(name));
    919 	return tp && (tp->flag & ISSET) ? tp->type : V_NONE;
    920 }
    921 
    922 /* Make a variable non-special */
    923 static void
    924 unspecial(name)
    925 	register const char * name;
    926 {
    927 	register struct tbl *tp;
    928 
    929 	tp = tsearch(&specials, name, hash(name));
    930 	if (tp)
    931 		tdelete(tp);
    932 }
    933 
    934 #ifdef KSH
    935 static	time_t	seconds;		/* time SECONDS last set */
    936 #endif /* KSH */
    937 static	int	user_lineno;		/* what user set $LINENO to */
    938 
    939 static void
    940 getspec(vp)
    941 	register struct tbl *vp;
    942 {
    943 	switch (special(vp->name)) {
    944 #ifdef KSH
    945 	  case V_SECONDS:
    946 		vp->flag &= ~SPECIAL;
    947 		/* On start up the value of SECONDS is used before seconds
    948 		 * has been set - don't do anything in this case
    949 		 * (see initcoms[] in main.c).
    950 		 */
    951 		if (vp->flag & ISSET)
    952 			setint(vp, (long) (time((time_t *)0) - seconds));
    953 		vp->flag |= SPECIAL;
    954 		break;
    955 	  case V_RANDOM:
    956 		vp->flag &= ~SPECIAL;
    957 		setint(vp, (long) (rand() & 0x7fff));
    958 		vp->flag |= SPECIAL;
    959 		break;
    960 #endif /* KSH */
    961 #ifdef HISTORY
    962 	  case V_HISTSIZE:
    963 		vp->flag &= ~SPECIAL;
    964 		setint(vp, (long) histsize);
    965 		vp->flag |= SPECIAL;
    966 		break;
    967 #endif /* HISTORY */
    968 	  case V_OPTIND:
    969 		vp->flag &= ~SPECIAL;
    970 		setint(vp, (long) user_opt.uoptind);
    971 		vp->flag |= SPECIAL;
    972 		break;
    973 	  case V_LINENO:
    974 		vp->flag &= ~SPECIAL;
    975 		setint(vp, (long) current_lineno + user_lineno);
    976 		vp->flag |= SPECIAL;
    977 		break;
    978 	}
    979 }
    980 
    981 static void
    982 setspec(vp)
    983 	register struct tbl *vp;
    984 {
    985 	char *s;
    986 
    987 	switch (special(vp->name)) {
    988 	  case V_PATH:
    989 		if (path)
    990 			afree(path, APERM);
    991 		path = str_save(str_val(vp), APERM);
    992 		flushcom(1);	/* clear tracked aliases */
    993 		break;
    994 	  case V_IFS:
    995 		setctypes(s = str_val(vp), C_IFS);
    996 		ifs0 = *s;
    997 		break;
    998 	  case V_OPTIND:
    999 		vp->flag &= ~SPECIAL;
   1000 		getopts_reset((int) intval(vp));
   1001 		vp->flag |= SPECIAL;
   1002 		break;
   1003 	  case V_POSIXLY_CORRECT:
   1004 		change_flag(FPOSIX, OF_SPECIAL, 1);
   1005 		break;
   1006 	  case V_TMPDIR:
   1007 		if (tmpdir) {
   1008 			afree(tmpdir, APERM);
   1009 			tmpdir = (char *) 0;
   1010 		}
   1011 		/* Use tmpdir iff it is an absolute path, is writable and
   1012 		 * searchable and is a directory...
   1013 		 */
   1014 		{
   1015 			struct stat statb;
   1016 			s = str_val(vp);
   1017 			if (ISABSPATH(s) && eaccess(s, W_OK|X_OK) == 0
   1018 			    && stat(s, &statb) == 0 && S_ISDIR(statb.st_mode))
   1019 				tmpdir = str_save(s, APERM);
   1020 		}
   1021 		break;
   1022 #ifdef HISTORY
   1023 	  case V_HISTSIZE:
   1024 		vp->flag &= ~SPECIAL;
   1025 		sethistsize((int) intval(vp));
   1026 		vp->flag |= SPECIAL;
   1027 		break;
   1028 	  case V_HISTFILE:
   1029 		sethistfile(str_val(vp));
   1030 		break;
   1031 #endif /* HISTORY */
   1032 #ifdef EDIT
   1033 	  case V_VISUAL:
   1034 		set_editmode(str_val(vp));
   1035 		break;
   1036 	  case V_EDITOR:
   1037 		if (!(global("VISUAL")->flag & ISSET))
   1038 			set_editmode(str_val(vp));
   1039 		break;
   1040 	  case V_COLUMNS:
   1041 		if ((x_cols = intval(vp)) <= MIN_COLS)
   1042 			x_cols = MIN_COLS;
   1043 		break;
   1044 #endif /* EDIT */
   1045 #ifdef KSH
   1046 	  case V_MAIL:
   1047 		mbset(str_val(vp));
   1048 		break;
   1049 	  case V_MAILPATH:
   1050 		mpset(str_val(vp));
   1051 		break;
   1052 	  case V_MAILCHECK:
   1053 		vp->flag &= ~SPECIAL;
   1054 		mcset(intval(vp));
   1055 		vp->flag |= SPECIAL;
   1056 		break;
   1057 	  case V_RANDOM:
   1058 		vp->flag &= ~SPECIAL;
   1059 		srand((unsigned int)intval(vp));
   1060 		vp->flag |= SPECIAL;
   1061 		break;
   1062 	  case V_SECONDS:
   1063 		vp->flag &= ~SPECIAL;
   1064 		seconds = time((time_t*) 0) - intval(vp);
   1065 		vp->flag |= SPECIAL;
   1066 		break;
   1067 	  case V_TMOUT:
   1068 		/* at&t ksh seems to do this (only listen if integer) */
   1069 		if (vp->flag & INTEGER)
   1070 			ksh_tmout = vp->val.i >= 0 ? vp->val.i : 0;
   1071 		break;
   1072 #endif /* KSH */
   1073 	  case V_LINENO:
   1074 		vp->flag &= ~SPECIAL;
   1075 		/* The -1 is because line numbering starts at 1. */
   1076 		user_lineno = (unsigned int) intval(vp) - current_lineno - 1;
   1077 		vp->flag |= SPECIAL;
   1078 		break;
   1079 	}
   1080 }
   1081 
   1082 static void
   1083 unsetspec(vp)
   1084 	register struct tbl *vp;
   1085 {
   1086 	switch (special(vp->name)) {
   1087 	  case V_PATH:
   1088 		if (path)
   1089 			afree(path, APERM);
   1090 		path = str_save(def_path, APERM);
   1091 		flushcom(1);	/* clear tracked aliases */
   1092 		break;
   1093 	  case V_IFS:
   1094 		setctypes(" \t\n", C_IFS);
   1095 		ifs0 = ' ';
   1096 		break;
   1097 	  case V_TMPDIR:
   1098 		/* should not become unspecial */
   1099 		if (tmpdir) {
   1100 			afree(tmpdir, APERM);
   1101 			tmpdir = (char *) 0;
   1102 		}
   1103 		break;
   1104 #ifdef KSH
   1105 	  case V_MAIL:
   1106 		mbset((char *) 0);
   1107 		break;
   1108 	  case V_MAILPATH:
   1109 		mpset((char *) 0);
   1110 		break;
   1111 #endif /* KSH */
   1112 
   1113 	  case V_LINENO:
   1114 #ifdef KSH
   1115 	  case V_MAILCHECK:	/* at&t ksh leaves previous value in place */
   1116 	  case V_RANDOM:
   1117 	  case V_SECONDS:
   1118 	  case V_TMOUT:		/* at&t ksh leaves previous value in place */
   1119 #endif /* KSH */
   1120 		unspecial(vp->name);
   1121 		break;
   1122 
   1123 	  /* at&t ksh man page says OPTIND, OPTARG and _ lose special meaning,
   1124 	   * but OPTARG does not (still set by getopts) and _ is also still
   1125 	   * set in various places.
   1126 	   * Don't know what at&t does for:
   1127 	   *		MAIL, MAILPATH, HISTSIZE, HISTFILE,
   1128 	   * Unsetting these in at&t ksh does not loose the `specialness':
   1129 	   *    no effect: IFS, COLUMNS, PATH, TMPDIR,
   1130 	   *		VISUAL, EDITOR,
   1131 	   * pdkshisms: no effect:
   1132 	   *		POSIXLY_CORRECT (use set +o posix instead)
   1133 	   */
   1134 	}
   1135 }
   1136 
   1137 /*
   1138  * Search for (and possibly create) a table entry starting with
   1139  * vp, indexed by val.
   1140  */
   1141 static struct tbl *
   1142 arraysearch(vp, val)
   1143 	struct tbl *vp;
   1144 	int val;
   1145 {
   1146 	struct tbl *prev, *curr, *new;
   1147 	size_t namelen = strlen(vp->name) + 1;
   1148 
   1149 	vp->flag |= ARRAY|DEFINED;
   1150 
   1151 	/* The table entry is always [0] */
   1152 	if (val == 0) {
   1153 		vp->index = 0;
   1154 		return vp;
   1155 	}
   1156 	prev = vp;
   1157 	curr = vp->u.array;
   1158 	while (curr && curr->index < val) {
   1159 		prev = curr;
   1160 		curr = curr->u.array;
   1161 	}
   1162 	if (curr && curr->index == val) {
   1163 		if (curr->flag&ISSET)
   1164 			return curr;
   1165 		else
   1166 			new = curr;
   1167 	} else
   1168 		new = (struct tbl *)alloc(sizeof(struct tbl) + namelen,
   1169 		    vp->areap);
   1170 	strlcpy(new->name, vp->name, namelen);
   1171 	new->flag = vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL);
   1172 	new->type = vp->type;
   1173 	new->areap = vp->areap;
   1174 	new->u2.field = vp->u2.field;
   1175 	new->index = val;
   1176 	if (curr != new) {		/* not reusing old array entry */
   1177 		prev->u.array = new;
   1178 		new->u.array = curr;
   1179 	}
   1180 	return new;
   1181 }
   1182 
   1183 /* Return the length of an array reference (eg, [1+2]) - cp is assumed
   1184  * to point to the open bracket.  Returns 0 if there is no matching closing
   1185  * bracket.
   1186  */
   1187 int
   1188 array_ref_len(cp)
   1189 	const char *cp;
   1190 {
   1191 	const char *s = cp;
   1192 	int c;
   1193 	int depth = 0;
   1194 
   1195 	while ((c = *s++) && (c != ']' || --depth))
   1196 		if (c == '[')
   1197 			depth++;
   1198 	if (!c)
   1199 		return 0;
   1200 	return s - cp;
   1201 }
   1202 
   1203 /*
   1204  * Make a copy of the base of an array name
   1205  */
   1206 char *
   1207 arrayname(str)
   1208 	const char *str;
   1209 {
   1210 	const char *p;
   1211 
   1212 	if ((p = strchr(str, '[')) == 0)
   1213 		/* Shouldn't happen, but why worry? */
   1214 		return (char *) __UNCONST(str);
   1215 
   1216 	return str_nsave(str, p - str, ATEMP);
   1217 }
   1218 
   1219 /* Set (or overwrite, if !reset) the array variable var to the values in vals.
   1220  */
   1221 void
   1222 set_array(var, reset, vals)
   1223 	const char *var;
   1224 	int reset;
   1225 	char **vals;
   1226 {
   1227 	struct tbl *vp, *vq;
   1228 	int i;
   1229 
   1230 	/* to get local array, use "typeset foo; set -A foo" */
   1231 	vp = global(var);
   1232 
   1233 	/* Note: at&t ksh allows set -A but not set +A of a read-only var */
   1234 	if ((vp->flag&RDONLY))
   1235 		errorf("%s: is read only", var);
   1236 	/* This code is quite non-optimal */
   1237 	if (reset > 0)
   1238 		/* trash existing values and attributes */
   1239 		unset(vp, 0);
   1240 	/* todo: would be nice for assignment to completely succeed or
   1241 	 * completely fail.  Only really effects integer arrays:
   1242 	 * evaluation of some of vals[] may fail...
   1243 	 */
   1244 	for (i = 0; vals[i]; i++) {
   1245 		vq = arraysearch(vp, i);
   1246 		/* would be nice to deal with errors here... (see above) */
   1247 		setstr(vq, vals[i], KSH_RETURN_ERROR);
   1248 	}
   1249 }
   1250