Home | History | Annotate | Line # | Download | only in sh
var.c revision 1.52
      1 /*	$NetBSD: var.c,v 1.52 2017/05/10 06:18:43 kre Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Kenneth Almquist.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)var.c	8.3 (Berkeley) 5/4/95";
     39 #else
     40 __RCSID("$NetBSD: var.c,v 1.52 2017/05/10 06:18:43 kre Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <unistd.h>
     45 #include <stdlib.h>
     46 #include <string.h>
     47 #include <paths.h>
     48 #include <limits.h>
     49 
     50 /*
     51  * Shell variables.
     52  */
     53 
     54 #include "shell.h"
     55 #include "output.h"
     56 #include "expand.h"
     57 #include "nodes.h"	/* for other headers */
     58 #include "eval.h"	/* defines cmdenviron */
     59 #include "exec.h"
     60 #include "syntax.h"
     61 #include "options.h"
     62 #include "builtins.h"
     63 #include "mail.h"
     64 #include "var.h"
     65 #include "memalloc.h"
     66 #include "error.h"
     67 #include "mystring.h"
     68 #include "parser.h"
     69 #include "show.h"
     70 #ifndef SMALL
     71 #include "myhistedit.h"
     72 #endif
     73 
     74 #ifdef SMALL
     75 #define VTABSIZE 39
     76 #else
     77 #define VTABSIZE 517
     78 #endif
     79 
     80 
     81 struct varinit {
     82 	struct var *var;
     83 	int flags;
     84 	const char *text;
     85 	void (*func)(const char *);
     86 };
     87 
     88 struct localvar *localvars;
     89 
     90 #ifndef SMALL
     91 struct var vhistsize;
     92 struct var vterm;
     93 #endif
     94 struct var vifs;
     95 struct var vmail;
     96 struct var vmpath;
     97 struct var vpath;
     98 struct var vps1;
     99 struct var vps2;
    100 struct var vps4;
    101 struct var vvers;
    102 struct var voptind;
    103 
    104 char ifs_default[] = " \t\n";
    105 
    106 const struct varinit varinit[] = {
    107 #ifndef SMALL
    108 	{ &vhistsize,	VSTRFIXED|VTEXTFIXED|VUNSET,	"HISTSIZE=",
    109 	  sethistsize },
    110 #endif
    111 	{ &vifs,	VSTRFIXED|VTEXTFIXED,		"IFS= \t\n",
    112 	  NULL },
    113 	{ &vmail,	VSTRFIXED|VTEXTFIXED|VUNSET,	"MAIL=",
    114 	  NULL },
    115 	{ &vmpath,	VSTRFIXED|VTEXTFIXED|VUNSET,	"MAILPATH=",
    116 	  NULL },
    117 	{ &vvers,	VSTRFIXED|VTEXTFIXED|VNOEXPORT, "NETBSD_SHELL=",
    118 	  NULL },
    119 	{ &vpath,	VSTRFIXED|VTEXTFIXED,		"PATH=" _PATH_DEFPATH,
    120 	  changepath },
    121 	/*
    122 	 * vps1 depends on uid
    123 	 */
    124 	{ &vps2,	VSTRFIXED|VTEXTFIXED,		"PS2=> ",
    125 	  NULL },
    126 	{ &vps4,	VSTRFIXED|VTEXTFIXED,		"PS4=+ ",
    127 	  NULL },
    128 #ifndef SMALL
    129 	{ &vterm,	VSTRFIXED|VTEXTFIXED|VUNSET,	"TERM=",
    130 	  setterm },
    131 #endif
    132 	{ &voptind,	VSTRFIXED|VTEXTFIXED|VNOFUNC,	"OPTIND=1",
    133 	  getoptsreset },
    134 	{ NULL,	0,				NULL,
    135 	  NULL }
    136 };
    137 
    138 struct var *vartab[VTABSIZE];
    139 
    140 STATIC int strequal(const char *, const char *);
    141 STATIC struct var *find_var(const char *, struct var ***, int *);
    142 
    143 /*
    144  * Initialize the varable symbol tables and import the environment
    145  */
    146 
    147 #ifdef mkinit
    148 INCLUDE <stdio.h>
    149 INCLUDE <unistd.h>
    150 INCLUDE "var.h"
    151 INCLUDE "version.h"
    152 MKINIT char **environ;
    153 INIT {
    154 	char **envp;
    155 	char buf[64];
    156 
    157 	initvar();
    158 	for (envp = environ ; *envp ; envp++) {
    159 		if (strchr(*envp, '=')) {
    160 			setvareq(*envp, VEXPORT|VTEXTFIXED);
    161 		}
    162 	}
    163 
    164 	/*
    165 	 * PPID is readonly
    166 	 *	set after processing environ to override anything there
    167 	 * Always default IFS, ignore any value from environment.
    168 	 */
    169 	snprintf(buf, sizeof(buf), "%d", (int)getppid());
    170 	setvar("PPID", buf, VREADONLY);
    171 	setvar("IFS", ifs_default, VTEXTFIXED);
    172 	setvar("NETBSD_SHELL", NETBSD_SHELL, VTEXTFIXED|VREADONLY|VNOEXPORT);
    173 }
    174 #endif
    175 
    176 
    177 /*
    178  * This routine initializes the builtin variables.  It is called when the
    179  * shell is initialized and again when a shell procedure is spawned.
    180  */
    181 
    182 void
    183 initvar(void)
    184 {
    185 	const struct varinit *ip;
    186 	struct var *vp;
    187 	struct var **vpp;
    188 
    189 	for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
    190 		if (find_var(ip->text, &vpp, &vp->name_len) != NULL)
    191 			continue;
    192 		vp->next = *vpp;
    193 		*vpp = vp;
    194 		vp->text = strdup(ip->text);
    195 		vp->flags = ip->flags;
    196 		vp->func = ip->func;
    197 	}
    198 	/*
    199 	 * PS1 depends on uid
    200 	 */
    201 	if (find_var("PS1", &vpp, &vps1.name_len) == NULL) {
    202 		vps1.next = *vpp;
    203 		*vpp = &vps1;
    204 		vps1.flags = VSTRFIXED|VTEXTFIXED;
    205 		vps1.text = NULL;
    206 		choose_ps1();
    207 	}
    208 }
    209 
    210 void
    211 choose_ps1(void)
    212 {
    213 	free(vps1.text);
    214 	vps1.text = strdup(geteuid() ? "PS1=$ " : "PS1=# ");
    215 }
    216 
    217 /*
    218  * Safe version of setvar, returns 1 on success 0 on failure.
    219  */
    220 
    221 int
    222 setvarsafe(const char *name, const char *val, int flags)
    223 {
    224 	struct jmploc jmploc;
    225 	struct jmploc *volatile savehandler = handler;
    226 	int volatile err = 0;
    227 
    228 	if (setjmp(jmploc.loc))
    229 		err = 1;
    230 	else {
    231 		handler = &jmploc;
    232 		setvar(name, val, flags);
    233 	}
    234 	handler = savehandler;
    235 	return err;
    236 }
    237 
    238 /*
    239  * Set the value of a variable.  The flags argument is ored with the
    240  * flags of the variable.  If val is NULL, the variable is unset.
    241  */
    242 
    243 void
    244 setvar(const char *name, const char *val, int flags)
    245 {
    246 	const char *p;
    247 	const char *q;
    248 	char *d;
    249 	int len;
    250 	int namelen;
    251 	char *nameeq;
    252 	int isbad;
    253 
    254 	isbad = 0;
    255 	p = name;
    256 	if (! is_name(*p))
    257 		isbad = 1;
    258 	p++;
    259 	for (;;) {
    260 		if (! is_in_name(*p)) {
    261 			if (*p == '\0' || *p == '=')
    262 				break;
    263 			isbad = 1;
    264 		}
    265 		p++;
    266 	}
    267 	namelen = p - name;
    268 	if (isbad)
    269 		error("%.*s: bad variable name", namelen, name);
    270 	len = namelen + 2;		/* 2 is space for '=' and '\0' */
    271 	if (val == NULL) {
    272 		flags |= VUNSET;
    273 	} else {
    274 		len += strlen(val);
    275 	}
    276 	d = nameeq = ckmalloc(len);
    277 	q = name;
    278 	while (--namelen >= 0)
    279 		*d++ = *q++;
    280 	*d++ = '=';
    281 	*d = '\0';
    282 	if (val)
    283 		scopy(val, d);
    284 	setvareq(nameeq, flags);
    285 }
    286 
    287 
    288 
    289 /*
    290  * Same as setvar except that the variable and value are passed in
    291  * the first argument as name=value.  Since the first argument will
    292  * be actually stored in the table, it should not be a string that
    293  * will go away.
    294  */
    295 
    296 void
    297 setvareq(char *s, int flags)
    298 {
    299 	struct var *vp, **vpp;
    300 	int nlen;
    301 
    302 	if (aflag && !(flags & VNOEXPORT))
    303 		flags |= VEXPORT;
    304 	vp = find_var(s, &vpp, &nlen);
    305 	if (vp != NULL) {
    306 		if (vp->flags & VREADONLY)
    307 			error("%.*s: is read only", vp->name_len, s);
    308 		if (flags & VNOSET)
    309 			return;
    310 		INTOFF;
    311 
    312 		if (vp->func && (flags & VNOFUNC) == 0)
    313 			(*vp->func)(s + vp->name_len + 1);
    314 
    315 		if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
    316 			ckfree(vp->text);
    317 
    318 		vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
    319 		if (flags & VNOEXPORT)
    320 			vp->flags &= ~VEXPORT;
    321 		vp->flags |= flags & ~VNOFUNC;
    322 		vp->text = s;
    323 
    324 		/*
    325 		 * We could roll this to a function, to handle it as
    326 		 * a regular variable function callback, but why bother?
    327 		 */
    328 		if (vp == &vmpath || (vp == &vmail && ! mpathset()))
    329 			chkmail(1);
    330 		INTON;
    331 		return;
    332 	}
    333 	/* not found */
    334 	if (flags & VNOSET)
    335 		return;
    336 	vp = ckmalloc(sizeof (*vp));
    337 	vp->flags = flags & ~VNOFUNC;
    338 	vp->text = s;
    339 	vp->name_len = nlen;
    340 	vp->next = *vpp;
    341 	vp->func = NULL;
    342 	*vpp = vp;
    343 }
    344 
    345 
    346 
    347 /*
    348  * Process a linked list of variable assignments.
    349  */
    350 
    351 void
    352 listsetvar(struct strlist *list, int flags)
    353 {
    354 	struct strlist *lp;
    355 
    356 	INTOFF;
    357 	for (lp = list ; lp ; lp = lp->next) {
    358 		setvareq(savestr(lp->text), flags);
    359 	}
    360 	INTON;
    361 }
    362 
    363 void
    364 listmklocal(struct strlist *list, int flags)
    365 {
    366 	struct strlist *lp;
    367 
    368 	for (lp = list ; lp ; lp = lp->next)
    369 		mklocal(lp->text, flags);
    370 }
    371 
    372 
    373 /*
    374  * Find the value of a variable.  Returns NULL if not set.
    375  */
    376 
    377 char *
    378 lookupvar(const char *name)
    379 {
    380 	struct var *v;
    381 
    382 	v = find_var(name, NULL, NULL);
    383 	if (v == NULL || v->flags & VUNSET)
    384 		return NULL;
    385 	return v->text + v->name_len + 1;
    386 }
    387 
    388 
    389 
    390 /*
    391  * Search the environment of a builtin command.  If the second argument
    392  * is nonzero, return the value of a variable even if it hasn't been
    393  * exported.
    394  */
    395 
    396 char *
    397 bltinlookup(const char *name, int doall)
    398 {
    399 	struct strlist *sp;
    400 	struct var *v;
    401 
    402 	for (sp = cmdenviron ; sp ; sp = sp->next) {
    403 		if (strequal(sp->text, name))
    404 			return strchr(sp->text, '=') + 1;
    405 	}
    406 
    407 	v = find_var(name, NULL, NULL);
    408 
    409 	if (v == NULL || v->flags & VUNSET || (!doall && !(v->flags & VEXPORT)))
    410 		return NULL;
    411 	return v->text + v->name_len + 1;
    412 }
    413 
    414 
    415 
    416 /*
    417  * Generate a list of exported variables.  This routine is used to construct
    418  * the third argument to execve when executing a program.
    419  */
    420 
    421 char **
    422 environment(void)
    423 {
    424 	int nenv;
    425 	struct var **vpp;
    426 	struct var *vp;
    427 	char **env;
    428 	char **ep;
    429 
    430 	nenv = 0;
    431 	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
    432 		for (vp = *vpp ; vp ; vp = vp->next)
    433 			if ((vp->flags & (VEXPORT|VUNSET)) == VEXPORT)
    434 				nenv++;
    435 	}
    436 	ep = env = stalloc((nenv + 1) * sizeof *env);
    437 	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
    438 		for (vp = *vpp ; vp ; vp = vp->next)
    439 			if ((vp->flags & (VEXPORT|VUNSET)) == VEXPORT)
    440 				*ep++ = vp->text;
    441 	}
    442 	*ep = NULL;
    443 	return env;
    444 }
    445 
    446 
    447 /*
    448  * Called when a shell procedure is invoked to clear out nonexported
    449  * variables.  It is also necessary to reallocate variables of with
    450  * VSTACK set since these are currently allocated on the stack.
    451  */
    452 
    453 #ifdef mkinit
    454 void shprocvar(void);
    455 
    456 SHELLPROC {
    457 	shprocvar();
    458 }
    459 #endif
    460 
    461 void
    462 shprocvar(void)
    463 {
    464 	struct var **vpp;
    465 	struct var *vp, **prev;
    466 
    467 	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
    468 		for (prev = vpp ; (vp = *prev) != NULL ; ) {
    469 			if ((vp->flags & VEXPORT) == 0) {
    470 				*prev = vp->next;
    471 				if ((vp->flags & VTEXTFIXED) == 0)
    472 					ckfree(vp->text);
    473 				if ((vp->flags & VSTRFIXED) == 0)
    474 					ckfree(vp);
    475 			} else {
    476 				if (vp->flags & VSTACK) {
    477 					vp->text = savestr(vp->text);
    478 					vp->flags &=~ VSTACK;
    479 				}
    480 				prev = &vp->next;
    481 			}
    482 		}
    483 	}
    484 	initvar();
    485 }
    486 
    487 
    488 
    489 /*
    490  * Command to list all variables which are set.  Currently this command
    491  * is invoked from the set command when the set command is called without
    492  * any variables.
    493  */
    494 
    495 void
    496 print_quoted(const char *p)
    497 {
    498 	const char *q;
    499 
    500 	if (p[0] == '\0') {
    501 		out1fmt("''");
    502 		return;
    503 	}
    504 	if (strcspn(p, "|&;<>()$`\\\"' \t\n*?[]#~=%") == strlen(p)) {
    505 		out1fmt("%s", p);
    506 		return;
    507 	}
    508 	while (*p) {
    509 		if (*p == '\'') {
    510 			out1fmt("\\'");
    511 			p++;
    512 			continue;
    513 		}
    514 		q = strchr(p, '\'');
    515 		if (!q) {
    516 			out1fmt("'%s'", p );
    517 			return;
    518 		}
    519 		out1fmt("'%.*s'", (int)(q - p), p );
    520 		p = q;
    521 	}
    522 }
    523 
    524 static int
    525 sort_var(const void *v_v1, const void *v_v2)
    526 {
    527 	const struct var * const *v1 = v_v1;
    528 	const struct var * const *v2 = v_v2;
    529 	char *t1 = (*v1)->text, *t2 = (*v2)->text;
    530 
    531 	if (*t1 == *t2) {
    532 		char *p, *s;
    533 
    534 		STARTSTACKSTR(p);
    535 
    536 		/*
    537 		 * note: if lengths are equal, strings must be different
    538 		 * so we don't care which string we pick for the \0 in
    539 		 * that case.
    540 		 */
    541 		if ((strchr(t1, '=') - t1) <= (strchr(t2, '=') - t2)) {
    542 			s = t1;
    543 			t1 = p;
    544 		} else {
    545 			s = t2;
    546 			t2 = p;
    547 		}
    548 
    549 		while (*s && *s != '=') {
    550 			STPUTC(*s, p);
    551 			s++;
    552 		}
    553 		STPUTC('\0', p);
    554 	}
    555 
    556 	return strcoll(t1, t2);
    557 }
    558 
    559 /*
    560  * POSIX requires that 'set' (but not export or readonly) output the
    561  * variables in lexicographic order - by the locale's collating order (sigh).
    562  * Maybe we could keep them in an ordered balanced binary tree
    563  * instead of hashed lists.
    564  * For now just roll 'em through qsort for printing...
    565  */
    566 
    567 int
    568 showvars(const char *name, int flag, int show_value, const char *xtra)
    569 {
    570 	struct var **vpp;
    571 	struct var *vp;
    572 	const char *p;
    573 
    574 	static struct var **list;	/* static in case we are interrupted */
    575 	static int list_len;
    576 	int count = 0;
    577 
    578 	if (!list) {
    579 		list_len = 32;
    580 		list = ckmalloc(list_len * sizeof *list);
    581 	}
    582 
    583 	for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
    584 		for (vp = *vpp ; vp ; vp = vp->next) {
    585 			if (flag && !(vp->flags & flag))
    586 				continue;
    587 			if (vp->flags & VUNSET && !(show_value & 2))
    588 				continue;
    589 			if (count >= list_len) {
    590 				list = ckrealloc(list,
    591 					(list_len << 1) * sizeof *list);
    592 				list_len <<= 1;
    593 			}
    594 			list[count++] = vp;
    595 		}
    596 	}
    597 
    598 	qsort(list, count, sizeof *list, sort_var);
    599 
    600 	for (vpp = list; count--; vpp++) {
    601 		vp = *vpp;
    602 		if (name)
    603 			out1fmt("%s ", name);
    604 		if (xtra)
    605 			out1fmt("%s ", xtra);
    606 		for (p = vp->text ; *p != '=' ; p++)
    607 			out1c(*p);
    608 		if (!(vp->flags & VUNSET) && show_value) {
    609 			out1fmt("=");
    610 			print_quoted(++p);
    611 		}
    612 		out1c('\n');
    613 	}
    614 	return 0;
    615 }
    616 
    617 
    618 
    619 /*
    620  * The export and readonly commands.
    621  */
    622 
    623 int
    624 exportcmd(int argc, char **argv)
    625 {
    626 	struct var *vp;
    627 	char *name;
    628 	const char *p;
    629 	int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
    630 	int pflg = 0;
    631 	int nflg = 0;
    632 	int xflg = 0;
    633 	int res;
    634 	int c;
    635 	int f;
    636 
    637 	while ((c = nextopt("npx")) != '\0') {
    638 		switch (c) {
    639 		case 'p':
    640 			if (nflg)
    641 				return 1;
    642 			pflg = 3;
    643 			break;
    644 		case 'n':
    645 			if (pflg || xflg || flag == VREADONLY)
    646 				return 1;
    647 			nflg = 1;
    648 			break;
    649 		case 'x':
    650 			if (nflg || flag == VREADONLY)
    651 				return 1;
    652 			flag = VNOEXPORT;
    653 			xflg = 1;
    654 			break;
    655 		default:
    656 			return 1;
    657 		}
    658 	}
    659 
    660 	if (nflg && *argptr == NULL)
    661 		return 1;
    662 
    663 	if (pflg || *argptr == NULL) {
    664 		showvars( pflg ? argv[0] : 0, flag, pflg,
    665 		    pflg && xflg ? "-x" : NULL );
    666 		return 0;
    667 	}
    668 
    669 	res = 0;
    670 	while ((name = *argptr++) != NULL) {
    671 		f = flag;
    672 		if ((p = strchr(name, '=')) != NULL) {
    673 			p++;
    674 		} else {
    675 			vp = find_var(name, NULL, NULL);
    676 			if (vp != NULL) {
    677 				if (nflg)
    678 					vp->flags &= ~flag;
    679 				else if (flag&VEXPORT && vp->flags&VNOEXPORT)
    680 					res = 1;
    681 				else {
    682 					vp->flags |= flag;
    683 					if (flag == VNOEXPORT)
    684 						vp->flags &= ~VEXPORT;
    685 				}
    686 				continue;
    687 			} else
    688 				f |= VUNSET;
    689 		}
    690 		if (!nflg)
    691 			setvar(name, p, f);
    692 	}
    693 	return res;
    694 }
    695 
    696 
    697 /*
    698  * The "local" command.
    699  */
    700 
    701 int
    702 localcmd(int argc, char **argv)
    703 {
    704 	char *name;
    705 
    706 	if (! in_function())
    707 		error("Not in a function");
    708 	while ((name = *argptr++) != NULL) {
    709 		mklocal(name, 0);
    710 	}
    711 	return 0;
    712 }
    713 
    714 
    715 /*
    716  * Make a variable a local variable.  When a variable is made local, its
    717  * value and flags are saved in a localvar structure.  The saved values
    718  * will be restored when the shell function returns.  We handle the name
    719  * "-" as a special case.
    720  */
    721 
    722 void
    723 mklocal(const char *name, int flags)
    724 {
    725 	struct localvar *lvp;
    726 	struct var **vpp;
    727 	struct var *vp;
    728 
    729 	INTOFF;
    730 	lvp = ckmalloc(sizeof (struct localvar));
    731 	if (name[0] == '-' && name[1] == '\0') {
    732 		char *p;
    733 		p = ckmalloc(sizeof_optlist);
    734 		lvp->text = memcpy(p, optlist, sizeof_optlist);
    735 		vp = NULL;
    736 	} else {
    737 		vp = find_var(name, &vpp, NULL);
    738 		if (vp == NULL) {
    739 			if (strchr(name, '='))
    740 				setvareq(savestr(name), VSTRFIXED|flags);
    741 			else
    742 				setvar(name, NULL, VSTRFIXED|flags);
    743 			vp = *vpp;	/* the new variable */
    744 			lvp->text = NULL;
    745 			lvp->flags = VUNSET;
    746 		} else {
    747 			lvp->text = vp->text;
    748 			lvp->flags = vp->flags;
    749 			vp->flags |= VSTRFIXED|VTEXTFIXED;
    750 			if (name[vp->name_len] == '=')
    751 				setvareq(savestr(name), flags);
    752 		}
    753 	}
    754 	lvp->vp = vp;
    755 	lvp->next = localvars;
    756 	localvars = lvp;
    757 	INTON;
    758 }
    759 
    760 
    761 /*
    762  * Called after a function returns.
    763  */
    764 
    765 void
    766 poplocalvars(void)
    767 {
    768 	struct localvar *lvp;
    769 	struct var *vp;
    770 
    771 	while ((lvp = localvars) != NULL) {
    772 		localvars = lvp->next;
    773 		vp = lvp->vp;
    774 		TRACE(("poplocalvar %s", vp ? vp->text : "-"));
    775 		if (vp == NULL) {	/* $- saved */
    776 			memcpy(optlist, lvp->text, sizeof_optlist);
    777 			ckfree(lvp->text);
    778 		} else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
    779 			(void)unsetvar(vp->text, 0);
    780 		} else {
    781 			if (vp->func && (vp->flags & VNOFUNC) == 0)
    782 				(*vp->func)(lvp->text + vp->name_len + 1);
    783 			if ((vp->flags & VTEXTFIXED) == 0)
    784 				ckfree(vp->text);
    785 			vp->flags = lvp->flags;
    786 			vp->text = lvp->text;
    787 		}
    788 		ckfree(lvp);
    789 	}
    790 }
    791 
    792 
    793 int
    794 setvarcmd(int argc, char **argv)
    795 {
    796 	if (argc <= 2)
    797 		return unsetcmd(argc, argv);
    798 	else if (argc == 3)
    799 		setvar(argv[1], argv[2], 0);
    800 	else
    801 		error("List assignment not implemented");
    802 	return 0;
    803 }
    804 
    805 
    806 /*
    807  * The unset builtin command.  We unset the function before we unset the
    808  * variable to allow a function to be unset when there is a readonly variable
    809  * with the same name.
    810  */
    811 
    812 int
    813 unsetcmd(int argc, char **argv)
    814 {
    815 	char **ap;
    816 	int i;
    817 	int flg_func = 0;
    818 	int flg_var = 0;
    819 	int ret = 0;
    820 
    821 	while ((i = nextopt("evf")) != '\0') {
    822 		if (i == 'f')
    823 			flg_func = 1;
    824 		else
    825 			flg_var = i;
    826 	}
    827 	if (flg_func == 0 && flg_var == 0)
    828 		flg_var = 1;
    829 
    830 	for (ap = argptr; *ap ; ap++) {
    831 		if (flg_func)
    832 			ret |= unsetfunc(*ap);
    833 		if (flg_var)
    834 			ret |= unsetvar(*ap, flg_var == 'e');
    835 	}
    836 	return ret;
    837 }
    838 
    839 
    840 /*
    841  * Unset the specified variable.
    842  */
    843 
    844 int
    845 unsetvar(const char *s, int unexport)
    846 {
    847 	struct var **vpp;
    848 	struct var *vp;
    849 
    850 	vp = find_var(s, &vpp, NULL);
    851 	if (vp == NULL)
    852 		return 0;
    853 
    854 	if (vp->flags & VREADONLY && !unexport)
    855 		return 1;
    856 
    857 	INTOFF;
    858 	if (unexport) {
    859 		vp->flags &= ~VEXPORT;
    860 	} else {
    861 		if (vp->text[vp->name_len + 1] != '\0')
    862 			setvar(s, nullstr, 0);
    863 		vp->flags &= ~VEXPORT;
    864 		vp->flags |= VUNSET;
    865 		if ((vp->flags & VSTRFIXED) == 0) {
    866 			if ((vp->flags & VTEXTFIXED) == 0)
    867 				ckfree(vp->text);
    868 			*vpp = vp->next;
    869 			ckfree(vp);
    870 		}
    871 	}
    872 	INTON;
    873 	return 0;
    874 }
    875 
    876 
    877 /*
    878  * Returns true if the two strings specify the same varable.  The first
    879  * variable name is terminated by '='; the second may be terminated by
    880  * either '=' or '\0'.
    881  */
    882 
    883 STATIC int
    884 strequal(const char *p, const char *q)
    885 {
    886 	while (*p == *q++) {
    887 		if (*p++ == '=')
    888 			return 1;
    889 	}
    890 	if (*p == '=' && *(q - 1) == '\0')
    891 		return 1;
    892 	return 0;
    893 }
    894 
    895 /*
    896  * Search for a variable.
    897  * 'name' may be terminated by '=' or a NUL.
    898  * vppp is set to the pointer to vp, or the list head if vp isn't found
    899  * lenp is set to the number of charactets in 'name'
    900  */
    901 
    902 STATIC struct var *
    903 find_var(const char *name, struct var ***vppp, int *lenp)
    904 {
    905 	unsigned int hashval;
    906 	int len;
    907 	struct var *vp, **vpp;
    908 	const char *p = name;
    909 
    910 	hashval = 0;
    911 	while (*p && *p != '=')
    912 		hashval = 2 * hashval + (unsigned char)*p++;
    913 	len = p - name;
    914 
    915 	if (lenp)
    916 		*lenp = len;
    917 	vpp = &vartab[hashval % VTABSIZE];
    918 	if (vppp)
    919 		*vppp = vpp;
    920 
    921 	for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
    922 		if (vp->name_len != len)
    923 			continue;
    924 		if (memcmp(vp->text, name, len) != 0)
    925 			continue;
    926 		if (vppp)
    927 			*vppp = vpp;
    928 		return vp;
    929 	}
    930 	return NULL;
    931 }
    932