No empty .Rs/.Re
[netbsd-mini2440.git] / bin / sh / var.c
blobf0f837cec6d650f377fb5c33af9462df5850cd52
1 /* $NetBSD: var.c,v 1.38 2006/12/18 00:37:33 christos Exp $ */
3 /*-
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Kenneth Almquist.
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.
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.
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.38 2006/12/18 00:37:33 christos Exp $");
41 #endif
42 #endif /* not lint */
44 #include <unistd.h>
45 #include <stdlib.h>
46 #include <strings.h>
47 #include <paths.h>
50 * Shell variables.
53 #include "shell.h"
54 #include "output.h"
55 #include "expand.h"
56 #include "nodes.h" /* for other headers */
57 #include "eval.h" /* defines cmdenviron */
58 #include "exec.h"
59 #include "syntax.h"
60 #include "options.h"
61 #include "mail.h"
62 #include "var.h"
63 #include "memalloc.h"
64 #include "error.h"
65 #include "mystring.h"
66 #include "parser.h"
67 #include "show.h"
68 #ifndef SMALL
69 #include "myhistedit.h"
70 #endif
72 #ifdef SMALL
73 #define VTABSIZE 39
74 #else
75 #define VTABSIZE 517
76 #endif
79 struct varinit {
80 struct var *var;
81 int flags;
82 const char *text;
83 void (*func)(const char *);
86 struct localvar *localvars;
88 #if ATTY
89 struct var vatty;
90 #endif
91 #ifndef SMALL
92 struct var vhistsize;
93 struct var vterm;
94 #endif
95 struct var vifs;
96 struct var vmail;
97 struct var vmpath;
98 struct var vpath;
99 struct var vps1;
100 struct var vps2;
101 struct var vps4;
102 struct var vvers;
103 struct var voptind;
105 const struct varinit varinit[] = {
106 #if ATTY
107 { &vatty, VSTRFIXED|VTEXTFIXED|VUNSET, "ATTY=",
108 NULL },
109 #endif
110 #ifndef SMALL
111 { &vhistsize, VSTRFIXED|VTEXTFIXED|VUNSET, "HISTSIZE=",
112 sethistsize },
113 #endif
114 { &vifs, VSTRFIXED|VTEXTFIXED, "IFS= \t\n",
115 NULL },
116 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
117 NULL },
118 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
119 NULL },
120 { &vpath, VSTRFIXED|VTEXTFIXED, "PATH=" _PATH_DEFPATH,
121 changepath },
123 * vps1 depends on uid
125 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
126 NULL },
127 { &vps4, VSTRFIXED|VTEXTFIXED, "PS4=+ ",
128 NULL },
129 #ifndef SMALL
130 { &vterm, VSTRFIXED|VTEXTFIXED|VUNSET, "TERM=",
131 setterm },
132 #endif
133 { &voptind, VSTRFIXED|VTEXTFIXED|VNOFUNC, "OPTIND=1",
134 getoptsreset },
135 { NULL, 0, NULL,
136 NULL }
139 struct var *vartab[VTABSIZE];
141 STATIC int strequal(const char *, const char *);
142 STATIC struct var *find_var(const char *, struct var ***, int *);
145 * Initialize the varable symbol tables and import the environment
148 #ifdef mkinit
149 INCLUDE "var.h"
150 MKINIT char **environ;
151 INIT {
152 char **envp;
154 initvar();
155 for (envp = environ ; *envp ; envp++) {
156 if (strchr(*envp, '=')) {
157 setvareq(*envp, VEXPORT|VTEXTFIXED);
161 #endif
165 * This routine initializes the builtin variables. It is called when the
166 * shell is initialized and again when a shell procedure is spawned.
169 void
170 initvar(void)
172 const struct varinit *ip;
173 struct var *vp;
174 struct var **vpp;
176 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
177 if (find_var(ip->text, &vpp, &vp->name_len) != NULL)
178 continue;
179 vp->next = *vpp;
180 *vpp = vp;
181 vp->text = strdup(ip->text);
182 vp->flags = ip->flags;
183 vp->func = ip->func;
186 * PS1 depends on uid
188 if (find_var("PS1", &vpp, &vps1.name_len) == NULL) {
189 vps1.next = *vpp;
190 *vpp = &vps1;
191 vps1.text = strdup(geteuid() ? "PS1=$ " : "PS1=# ");
192 vps1.flags = VSTRFIXED|VTEXTFIXED;
197 * Safe version of setvar, returns 1 on success 0 on failure.
201 setvarsafe(const char *name, const char *val, int flags)
203 struct jmploc jmploc;
204 struct jmploc *volatile savehandler = handler;
205 int volatile err = 0;
207 if (setjmp(jmploc.loc))
208 err = 1;
209 else {
210 handler = &jmploc;
211 setvar(name, val, flags);
213 handler = savehandler;
214 return err;
218 * Set the value of a variable. The flags argument is ored with the
219 * flags of the variable. If val is NULL, the variable is unset.
222 void
223 setvar(const char *name, const char *val, int flags)
225 const char *p;
226 const char *q;
227 char *d;
228 int len;
229 int namelen;
230 char *nameeq;
231 int isbad;
233 isbad = 0;
234 p = name;
235 if (! is_name(*p))
236 isbad = 1;
237 p++;
238 for (;;) {
239 if (! is_in_name(*p)) {
240 if (*p == '\0' || *p == '=')
241 break;
242 isbad = 1;
244 p++;
246 namelen = p - name;
247 if (isbad)
248 error("%.*s: bad variable name", namelen, name);
249 len = namelen + 2; /* 2 is space for '=' and '\0' */
250 if (val == NULL) {
251 flags |= VUNSET;
252 } else {
253 len += strlen(val);
255 d = nameeq = ckmalloc(len);
256 q = name;
257 while (--namelen >= 0)
258 *d++ = *q++;
259 *d++ = '=';
260 *d = '\0';
261 if (val)
262 scopy(val, d);
263 setvareq(nameeq, flags);
269 * Same as setvar except that the variable and value are passed in
270 * the first argument as name=value. Since the first argument will
271 * be actually stored in the table, it should not be a string that
272 * will go away.
275 void
276 setvareq(char *s, int flags)
278 struct var *vp, **vpp;
279 int nlen;
281 if (aflag)
282 flags |= VEXPORT;
283 vp = find_var(s, &vpp, &nlen);
284 if (vp != NULL) {
285 if (vp->flags & VREADONLY)
286 error("%.*s: is read only", vp->name_len, s);
287 if (flags & VNOSET)
288 return;
289 INTOFF;
291 if (vp->func && (flags & VNOFUNC) == 0)
292 (*vp->func)(s + vp->name_len + 1);
294 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
295 ckfree(vp->text);
297 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
298 vp->flags |= flags & ~VNOFUNC;
299 vp->text = s;
302 * We could roll this to a function, to handle it as
303 * a regular variable function callback, but why bother?
305 if (vp == &vmpath || (vp == &vmail && ! mpathset()))
306 chkmail(1);
307 INTON;
308 return;
310 /* not found */
311 if (flags & VNOSET)
312 return;
313 vp = ckmalloc(sizeof (*vp));
314 vp->flags = flags & ~VNOFUNC;
315 vp->text = s;
316 vp->name_len = nlen;
317 vp->next = *vpp;
318 vp->func = NULL;
319 *vpp = vp;
325 * Process a linked list of variable assignments.
328 void
329 listsetvar(struct strlist *list, int flags)
331 struct strlist *lp;
333 INTOFF;
334 for (lp = list ; lp ; lp = lp->next) {
335 setvareq(savestr(lp->text), flags);
337 INTON;
340 void
341 listmklocal(struct strlist *list, int flags)
343 struct strlist *lp;
345 for (lp = list ; lp ; lp = lp->next)
346 mklocal(lp->text, flags);
351 * Find the value of a variable. Returns NULL if not set.
354 char *
355 lookupvar(const char *name)
357 struct var *v;
359 v = find_var(name, NULL, NULL);
360 if (v == NULL || v->flags & VUNSET)
361 return NULL;
362 return v->text + v->name_len + 1;
368 * Search the environment of a builtin command. If the second argument
369 * is nonzero, return the value of a variable even if it hasn't been
370 * exported.
373 char *
374 bltinlookup(const char *name, int doall)
376 struct strlist *sp;
377 struct var *v;
379 for (sp = cmdenviron ; sp ; sp = sp->next) {
380 if (strequal(sp->text, name))
381 return strchr(sp->text, '=') + 1;
384 v = find_var(name, NULL, NULL);
386 if (v == NULL || v->flags & VUNSET || (!doall && !(v->flags & VEXPORT)))
387 return NULL;
388 return v->text + v->name_len + 1;
394 * Generate a list of exported variables. This routine is used to construct
395 * the third argument to execve when executing a program.
398 char **
399 environment(void)
401 int nenv;
402 struct var **vpp;
403 struct var *vp;
404 char **env;
405 char **ep;
407 nenv = 0;
408 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
409 for (vp = *vpp ; vp ; vp = vp->next)
410 if (vp->flags & VEXPORT)
411 nenv++;
413 ep = env = stalloc((nenv + 1) * sizeof *env);
414 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
415 for (vp = *vpp ; vp ; vp = vp->next)
416 if (vp->flags & VEXPORT)
417 *ep++ = vp->text;
419 *ep = NULL;
420 return env;
425 * Called when a shell procedure is invoked to clear out nonexported
426 * variables. It is also necessary to reallocate variables of with
427 * VSTACK set since these are currently allocated on the stack.
430 #ifdef mkinit
431 void shprocvar(void);
433 SHELLPROC {
434 shprocvar();
436 #endif
438 void
439 shprocvar(void)
441 struct var **vpp;
442 struct var *vp, **prev;
444 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
445 for (prev = vpp ; (vp = *prev) != NULL ; ) {
446 if ((vp->flags & VEXPORT) == 0) {
447 *prev = vp->next;
448 if ((vp->flags & VTEXTFIXED) == 0)
449 ckfree(vp->text);
450 if ((vp->flags & VSTRFIXED) == 0)
451 ckfree(vp);
452 } else {
453 if (vp->flags & VSTACK) {
454 vp->text = savestr(vp->text);
455 vp->flags &=~ VSTACK;
457 prev = &vp->next;
461 initvar();
467 * Command to list all variables which are set. Currently this command
468 * is invoked from the set command when the set command is called without
469 * any variables.
472 void
473 print_quoted(const char *p)
475 const char *q;
477 if (strcspn(p, "|&;<>()$`\\\"' \t\n*?[]#~=%") == strlen(p)) {
478 out1fmt("%s", p);
479 return;
481 while (*p) {
482 if (*p == '\'') {
483 out1fmt("\\'");
484 p++;
485 continue;
487 q = index(p, '\'');
488 if (!q) {
489 out1fmt("'%s'", p );
490 return;
492 out1fmt("'%.*s'", (int)(q - p), p );
493 p = q;
497 static int
498 sort_var(const void *v_v1, const void *v_v2)
500 const struct var * const *v1 = v_v1;
501 const struct var * const *v2 = v_v2;
503 /* XXX Will anyone notice we include the '=' of the shorter name? */
504 return strcoll((*v1)->text, (*v2)->text);
508 * POSIX requires that 'set' (but not export or readonly) output the
509 * variables in lexicographic order - by the locale's collating order (sigh).
510 * Maybe we could keep them in an ordered balanced binary tree
511 * instead of hashed lists.
512 * For now just roll 'em through qsort for printing...
516 showvars(const char *name, int flag, int show_value)
518 struct var **vpp;
519 struct var *vp;
520 const char *p;
522 static struct var **list; /* static in case we are interrupted */
523 static int list_len;
524 int count = 0;
526 if (!list) {
527 list_len = 32;
528 list = ckmalloc(list_len * sizeof *list);
531 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
532 for (vp = *vpp ; vp ; vp = vp->next) {
533 if (flag && !(vp->flags & flag))
534 continue;
535 if (vp->flags & VUNSET && !(show_value & 2))
536 continue;
537 if (count >= list_len) {
538 list = ckrealloc(list,
539 (list_len << 1) * sizeof *list);
540 list_len <<= 1;
542 list[count++] = vp;
546 qsort(list, count, sizeof *list, sort_var);
548 for (vpp = list; count--; vpp++) {
549 vp = *vpp;
550 if (name)
551 out1fmt("%s ", name);
552 for (p = vp->text ; *p != '=' ; p++)
553 out1c(*p);
554 if (!(vp->flags & VUNSET) && show_value) {
555 out1fmt("=");
556 print_quoted(++p);
558 out1c('\n');
560 return 0;
566 * The export and readonly commands.
570 exportcmd(int argc, char **argv)
572 struct var *vp;
573 char *name;
574 const char *p;
575 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
576 int pflag;
578 pflag = nextopt("p") == 'p' ? 3 : 0;
579 if (argc <= 1 || pflag) {
580 showvars( pflag ? argv[0] : 0, flag, pflag );
581 return 0;
584 while ((name = *argptr++) != NULL) {
585 if ((p = strchr(name, '=')) != NULL) {
586 p++;
587 } else {
588 vp = find_var(name, NULL, NULL);
589 if (vp != NULL) {
590 vp->flags |= flag;
591 continue;
594 setvar(name, p, flag);
596 return 0;
601 * The "local" command.
605 localcmd(int argc, char **argv)
607 char *name;
609 if (! in_function())
610 error("Not in a function");
611 while ((name = *argptr++) != NULL) {
612 mklocal(name, 0);
614 return 0;
619 * Make a variable a local variable. When a variable is made local, its
620 * value and flags are saved in a localvar structure. The saved values
621 * will be restored when the shell function returns. We handle the name
622 * "-" as a special case.
625 void
626 mklocal(const char *name, int flags)
628 struct localvar *lvp;
629 struct var **vpp;
630 struct var *vp;
632 INTOFF;
633 lvp = ckmalloc(sizeof (struct localvar));
634 if (name[0] == '-' && name[1] == '\0') {
635 char *p;
636 p = ckmalloc(sizeof_optlist);
637 lvp->text = memcpy(p, optlist, sizeof_optlist);
638 vp = NULL;
639 } else {
640 vp = find_var(name, &vpp, NULL);
641 if (vp == NULL) {
642 if (strchr(name, '='))
643 setvareq(savestr(name), VSTRFIXED|flags);
644 else
645 setvar(name, NULL, VSTRFIXED|flags);
646 vp = *vpp; /* the new variable */
647 lvp->text = NULL;
648 lvp->flags = VUNSET;
649 } else {
650 lvp->text = vp->text;
651 lvp->flags = vp->flags;
652 vp->flags |= VSTRFIXED|VTEXTFIXED;
653 if (name[vp->name_len] == '=')
654 setvareq(savestr(name), flags);
657 lvp->vp = vp;
658 lvp->next = localvars;
659 localvars = lvp;
660 INTON;
665 * Called after a function returns.
668 void
669 poplocalvars(void)
671 struct localvar *lvp;
672 struct var *vp;
674 while ((lvp = localvars) != NULL) {
675 localvars = lvp->next;
676 vp = lvp->vp;
677 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
678 if (vp == NULL) { /* $- saved */
679 memcpy(optlist, lvp->text, sizeof_optlist);
680 ckfree(lvp->text);
681 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
682 (void)unsetvar(vp->text, 0);
683 } else {
684 if (vp->func && (vp->flags & VNOFUNC) == 0)
685 (*vp->func)(lvp->text + vp->name_len + 1);
686 if ((vp->flags & VTEXTFIXED) == 0)
687 ckfree(vp->text);
688 vp->flags = lvp->flags;
689 vp->text = lvp->text;
691 ckfree(lvp);
697 setvarcmd(int argc, char **argv)
699 if (argc <= 2)
700 return unsetcmd(argc, argv);
701 else if (argc == 3)
702 setvar(argv[1], argv[2], 0);
703 else
704 error("List assignment not implemented");
705 return 0;
710 * The unset builtin command. We unset the function before we unset the
711 * variable to allow a function to be unset when there is a readonly variable
712 * with the same name.
716 unsetcmd(int argc, char **argv)
718 char **ap;
719 int i;
720 int flg_func = 0;
721 int flg_var = 0;
722 int ret = 0;
724 while ((i = nextopt("evf")) != '\0') {
725 if (i == 'f')
726 flg_func = 1;
727 else
728 flg_var = i;
730 if (flg_func == 0 && flg_var == 0)
731 flg_var = 1;
733 for (ap = argptr; *ap ; ap++) {
734 if (flg_func)
735 ret |= unsetfunc(*ap);
736 if (flg_var)
737 ret |= unsetvar(*ap, flg_var == 'e');
739 return ret;
744 * Unset the specified variable.
748 unsetvar(const char *s, int unexport)
750 struct var **vpp;
751 struct var *vp;
753 vp = find_var(s, &vpp, NULL);
754 if (vp == NULL)
755 return 1;
757 if (vp->flags & VREADONLY)
758 return (1);
760 INTOFF;
761 if (unexport) {
762 vp->flags &= ~VEXPORT;
763 } else {
764 if (vp->text[vp->name_len + 1] != '\0')
765 setvar(s, nullstr, 0);
766 vp->flags &= ~VEXPORT;
767 vp->flags |= VUNSET;
768 if ((vp->flags & VSTRFIXED) == 0) {
769 if ((vp->flags & VTEXTFIXED) == 0)
770 ckfree(vp->text);
771 *vpp = vp->next;
772 ckfree(vp);
775 INTON;
776 return 0;
781 * Returns true if the two strings specify the same varable. The first
782 * variable name is terminated by '='; the second may be terminated by
783 * either '=' or '\0'.
786 STATIC int
787 strequal(const char *p, const char *q)
789 while (*p == *q++) {
790 if (*p++ == '=')
791 return 1;
793 if (*p == '=' && *(q - 1) == '\0')
794 return 1;
795 return 0;
799 * Search for a variable.
800 * 'name' may be terminated by '=' or a NUL.
801 * vppp is set to the pointer to vp, or the list head if vp isn't found
802 * lenp is set to the number of charactets in 'name'
805 STATIC struct var *
806 find_var(const char *name, struct var ***vppp, int *lenp)
808 unsigned int hashval;
809 int len;
810 struct var *vp, **vpp;
811 const char *p = name;
813 hashval = 0;
814 while (*p && *p != '=')
815 hashval = 2 * hashval + (unsigned char)*p++;
816 len = p - name;
818 if (lenp)
819 *lenp = len;
820 vpp = &vartab[hashval % VTABSIZE];
821 if (vppp)
822 *vppp = vpp;
824 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
825 if (vp->name_len != len)
826 continue;
827 if (memcmp(vp->text, name, len) != 0)
828 continue;
829 if (vppp)
830 *vppp = vpp;
831 return vp;
833 return NULL;