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