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