Correct assorted grammos and typos.
[dragonfly.git] / bin / sh / var.c
blob31b7480653751b90e181c219f678755ff6b29645
1 /*-
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
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. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
36 * @(#)var.c 8.3 (Berkeley) 5/4/95
37 * $FreeBSD: src/bin/sh/var.c,v 1.15.2.2 2002/08/27 01:36:28 tjr Exp $
38 * $DragonFly: src/bin/sh/var.c,v 1.12 2006/09/28 22:29:44 pavalos Exp $
41 #include <unistd.h>
42 #include <stdlib.h>
45 * Shell variables.
48 #include <locale.h>
50 #include "shell.h"
51 #include "output.h"
52 #include "expand.h"
53 #include "nodes.h" /* for other headers */
54 #include "eval.h" /* defines cmdenviron */
55 #include "exec.h"
56 #include "syntax.h"
57 #include "options.h"
58 #include "mail.h"
59 #include "var.h"
60 #include "memalloc.h"
61 #include "error.h"
62 #include "mystring.h"
63 #include "parser.h"
64 #ifndef NO_HISTORY
65 #include "myhistedit.h"
66 #endif
69 #define VTABSIZE 39
72 struct varinit {
73 struct var *var;
74 int flags;
75 const char *text;
76 void (*func)(const char *);
80 #ifndef NO_HISTORY
81 struct var vhistsize;
82 #endif
83 struct var vifs;
84 struct var vmail;
85 struct var vmpath;
86 struct var vpath;
87 struct var vppid;
88 struct var vps1;
89 struct var vps2;
90 struct var vvers;
91 STATIC struct var voptind;
93 STATIC const struct varinit varinit[] = {
94 #ifndef NO_HISTORY
95 { &vhistsize, VSTRFIXED|VTEXTFIXED|VUNSET, "HISTSIZE=",
96 sethistsize },
97 #endif
98 { &vifs, VSTRFIXED|VTEXTFIXED, "IFS= \t\n",
99 NULL },
100 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
101 NULL },
102 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
103 NULL },
104 { &vpath, VSTRFIXED|VTEXTFIXED, "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/pkg/bin:/usr/pkg/sbin",
105 changepath },
106 { &vppid, VSTRFIXED|VTEXTFIXED|VUNSET, "PPID=",
107 NULL },
109 * vps1 depends on uid
111 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
112 NULL },
113 { &voptind, VSTRFIXED|VTEXTFIXED, "OPTIND=1",
114 getoptsreset },
115 { NULL, 0, NULL,
116 NULL }
119 STATIC struct var *vartab[VTABSIZE];
121 STATIC struct var **hashvar(const char *);
122 STATIC int varequal(const char *, const char *);
123 STATIC int localevar(const char *);
126 * Initialize the variable symbol tables and import the environment.
129 #ifdef mkinit
130 INCLUDE "var.h"
131 MKINIT char **environ;
132 INIT {
133 char **envp;
135 initvar();
136 for (envp = environ ; *envp ; envp++) {
137 if (strchr(*envp, '=')) {
138 setvareq(*envp, VEXPORT|VTEXTFIXED);
142 #endif
146 * This routine initializes the builtin variables. It is called when the
147 * shell is initialized and again when a shell procedure is spawned.
150 void
151 initvar(void)
153 char ppid[20];
154 const struct varinit *ip;
155 struct var *vp;
156 struct var **vpp;
158 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
159 if ((vp->flags & VEXPORT) == 0) {
160 vpp = hashvar(ip->text);
161 vp->next = *vpp;
162 *vpp = vp;
163 vp->text = strdup(ip->text);
164 vp->flags = ip->flags;
165 vp->func = ip->func;
169 * PS1 depends on uid
171 if ((vps1.flags & VEXPORT) == 0) {
172 vpp = hashvar("PS1=");
173 vps1.next = *vpp;
174 *vpp = &vps1;
175 vps1.text = strdup(geteuid() ? "PS1=$ " : "PS1=# ");
176 vps1.flags = VSTRFIXED|VTEXTFIXED;
178 if ((vppid.flags & VEXPORT) == 0) {
179 fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
180 setvarsafe("PPID", ppid, 0);
185 * Safe version of setvar, returns 1 on success 0 on failure.
189 setvarsafe(const char *name, const char *val, int flags)
191 struct jmploc jmploc;
192 struct jmploc *volatile savehandler = handler;
193 int err = 0;
194 #if __GNUC__
195 /* Avoid longjmp clobbering */
196 (void) &err;
197 #endif
199 if (setjmp(jmploc.loc))
200 err = 1;
201 else {
202 handler = &jmploc;
203 setvar(name, val, flags);
205 handler = savehandler;
206 return err;
210 * Set the value of a variable. The flags argument is tored with the
211 * flags of the variable. If val is NULL, the variable is unset.
214 void
215 setvar(const char *name, const char *val, int flags)
217 const char *cp;
218 char *p;
219 int len;
220 int namelen;
221 char *nameeq;
222 int isbad;
224 isbad = 0;
225 cp = name;
226 if (!is_name(*cp))
227 isbad = 1;
228 cp++;
229 for (;;) {
230 if (!is_in_name(*cp)) {
231 if (*cp == '\0' || *cp == '=')
232 break;
233 isbad = 1;
235 cp++;
237 namelen = cp - name;
238 if (isbad)
239 error("%.*s: bad variable name", namelen, name);
240 len = namelen + 2; /* 2 is space for '=' and '\0' */
241 if (val == NULL) {
242 flags |= VUNSET;
243 } else {
244 len += strlen(val);
246 p = nameeq = ckmalloc(len);
247 cp = name;
248 while (--namelen >= 0)
249 *p++ = *cp++;
250 *p++ = '=';
251 *p = '\0';
252 if (val)
253 scopy(val, p);
254 setvareq(nameeq, flags);
257 STATIC int
258 localevar(const char *s)
260 static const char * const lnames[7] = {
261 "ALL", "COLLATE", "CTYPE", "MONETARY",
262 "NUMERIC", "TIME", NULL
264 const char * const *ss;
266 if (*s != 'L')
267 return 0;
268 if (varequal(s + 1, "ANG"))
269 return 1;
270 if (strncmp(s + 1, "C_", 2) != 0)
271 return 0;
272 for (ss = lnames; *ss ; ss++)
273 if (varequal(s + 3, *ss))
274 return 1;
275 return 0;
279 * Same as setvar except that the variable and value are passed in
280 * the first argument as name=value. Since the first argument will
281 * be actually stored in the table, it should not be a string that
282 * will go away.
285 void
286 setvareq(char *s, int flags)
288 struct var *vp, **vpp;
289 int len;
291 if (aflag)
292 flags |= VEXPORT;
293 vpp = hashvar(s);
294 for (vp = *vpp ; vp ; vp = vp->next) {
295 if (varequal(s, vp->text)) {
296 if (vp->flags & VREADONLY) {
297 len = strchr(s, '=') - s;
298 error("%.*s: is read only", len, s);
300 INTOFF;
302 if (vp->func && (flags & VNOFUNC) == 0)
303 (*vp->func)(strchr(s, '=') + 1);
305 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
306 ckfree(vp->text);
308 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
309 vp->flags |= flags;
310 vp->text = s;
313 * We could roll this to a function, to handle it as
314 * a regular variable function callback, but why bother?
316 if (vp == &vmpath || (vp == &vmail && ! mpathset()))
317 chkmail(1);
318 if ((vp->flags & VEXPORT) && localevar(s)) {
319 if (putenv(s) != 0)
320 error("putenv: cannot set %s", s);
321 setlocale(LC_ALL, "");
323 INTON;
324 return;
327 /* not found */
328 vp = ckmalloc(sizeof (*vp));
329 vp->flags = flags;
330 vp->text = s;
331 vp->next = *vpp;
332 vp->func = NULL;
333 INTOFF;
334 *vpp = vp;
335 if ((vp->flags & VEXPORT) && localevar(s)) {
336 if (putenv(s) != 0)
337 error("putenv: cannot set %s", s);
338 setlocale(LC_ALL, "");
340 INTON;
346 * Process a linked list of variable assignments.
349 void
350 listsetvar(struct strlist *list)
352 struct strlist *lp;
354 INTOFF;
355 for (lp = list ; lp ; lp = lp->next) {
356 setvareq(savestr(lp->text), 0);
358 INTON;
364 * Find the value of a variable. Returns NULL if not set.
367 char *
368 lookupvar(const char *name)
370 struct var *v;
372 for (v = *hashvar(name) ; v ; v = v->next) {
373 if (varequal(v->text, name)) {
374 if (v->flags & VUNSET)
375 return NULL;
376 return strchr(v->text, '=') + 1;
379 return NULL;
385 * Search the environment of a builtin command. If the second argument
386 * is nonzero, return the value of a variable even if it hasn't been
387 * exported.
390 char *
391 bltinlookup(const char *name, int doall)
393 struct strlist *sp;
394 struct var *v;
396 for (sp = cmdenviron ; sp ; sp = sp->next) {
397 if (varequal(sp->text, name))
398 return strchr(sp->text, '=') + 1;
400 for (v = *hashvar(name) ; v ; v = v->next) {
401 if (varequal(v->text, name)) {
402 if ((v->flags & VUNSET)
403 || (!doall && (v->flags & VEXPORT) == 0))
404 return NULL;
405 return strchr(v->text, '=') + 1;
408 return NULL;
414 * Generate a list of exported variables. This routine is used to construct
415 * the third argument to execve when executing a program.
418 char **
419 environment(void)
421 int nenv;
422 struct var **vpp;
423 struct var *vp;
424 char **env, **ep;
426 nenv = 0;
427 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
428 for (vp = *vpp ; vp ; vp = vp->next)
429 if (vp->flags & VEXPORT)
430 nenv++;
432 ep = env = stalloc((nenv + 1) * sizeof *env);
433 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
434 for (vp = *vpp ; vp ; vp = vp->next)
435 if (vp->flags & VEXPORT)
436 *ep++ = vp->text;
438 *ep = NULL;
439 return env;
444 * Called when a shell procedure is invoked to clear out nonexported
445 * variables. It is also necessary to reallocate variables of with
446 * VSTACK set since these are currently allocated on the stack.
449 #ifdef mkinit
450 void shprocvar(void);
452 SHELLPROC {
453 shprocvar();
455 #endif
457 void
458 shprocvar(void)
460 struct var **vpp;
461 struct var *vp, **prev;
463 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
464 for (prev = vpp ; (vp = *prev) != NULL ; ) {
465 if ((vp->flags & VEXPORT) == 0) {
466 *prev = vp->next;
467 if ((vp->flags & VTEXTFIXED) == 0)
468 ckfree(vp->text);
469 if ((vp->flags & VSTRFIXED) == 0)
470 ckfree(vp);
471 } else {
472 if (vp->flags & VSTACK) {
473 vp->text = savestr(vp->text);
474 vp->flags &=~ VSTACK;
476 prev = &vp->next;
480 initvar();
486 * Command to list all variables which are set. Currently this command
487 * is invoked from the set command when the set command is called without
488 * any variables.
492 showvarscmd(int argc __unused, char **argv __unused)
494 struct var **vpp;
495 struct var *vp;
496 const char *s;
498 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
499 for (vp = *vpp ; vp ; vp = vp->next) {
500 if (vp->flags & VUNSET)
501 continue;
502 for (s = vp->text; *s != '='; s++)
503 out1c(*s);
504 out1c('=');
505 out1qstr(s + 1);
506 out1c('\n');
509 return 0;
515 * The export and readonly commands.
519 exportcmd(int argc, char **argv)
521 struct var **vpp;
522 struct var *vp;
523 char *name;
524 char *p;
525 char *cmdname;
526 int ch, values;
527 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
529 cmdname = argv[0];
530 optreset = optind = 1;
531 opterr = 0;
532 values = 0;
533 while ((ch = getopt(argc, argv, "p")) != -1) {
534 switch (ch) {
535 case 'p':
536 values = 1;
537 break;
538 case '?':
539 default:
540 error("unknown option: -%c", optopt);
543 argc -= optind;
544 argv += optind;
546 listsetvar(cmdenviron);
547 if (argc != 0) {
548 while ((name = *argptr++) != NULL) {
549 if ((p = strchr(name, '=')) != NULL) {
550 p++;
551 } else {
552 vpp = hashvar(name);
553 for (vp = *vpp ; vp ; vp = vp->next) {
554 if (varequal(vp->text, name)) {
556 vp->flags |= flag;
557 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
558 if (putenv(vp->text) != 0)
559 error("putenv: cannot set %s", vp->text);
560 setlocale(LC_ALL, "");
562 goto found;
566 setvar(name, p, flag);
567 found:;
569 } else {
570 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
571 for (vp = *vpp ; vp ; vp = vp->next) {
572 if (vp->flags & flag) {
573 if (values) {
574 out1str(cmdname);
575 out1c(' ');
577 for (p = vp->text ; *p != '=' ; p++)
578 out1c(*p);
579 if (values && !(vp->flags & VUNSET)) {
580 out1c('=');
581 out1qstr(p + 1);
583 out1c('\n');
588 return 0;
593 * The "local" command.
597 localcmd(int argc __unused, char **argv __unused)
599 char *name;
601 if (! in_function())
602 error("Not in a function");
603 while ((name = *argptr++) != NULL) {
604 mklocal(name);
606 return 0;
611 * Make a variable a local variable. When a variable is made local, it's
612 * value and flags are saved in a localvar structure. The saved values
613 * will be restored when the shell function returns. We handle the name
614 * "-" as a special case.
617 void
618 mklocal(char *name)
620 struct localvar *lvp;
621 struct var **vpp;
622 struct var *vp;
624 INTOFF;
625 lvp = ckmalloc(sizeof (struct localvar));
626 if (name[0] == '-' && name[1] == '\0') {
627 lvp->text = ckmalloc(sizeof optlist);
628 memcpy(lvp->text, optlist, sizeof optlist);
629 vp = NULL;
630 } else {
631 vpp = hashvar(name);
632 for (vp = *vpp ; vp && ! varequal(vp->text, name) ; vp = vp->next);
633 if (vp == NULL) {
634 if (strchr(name, '='))
635 setvareq(savestr(name), VSTRFIXED);
636 else
637 setvar(name, NULL, VSTRFIXED);
638 vp = *vpp; /* the new variable */
639 lvp->text = NULL;
640 lvp->flags = VUNSET;
641 } else {
642 lvp->text = vp->text;
643 lvp->flags = vp->flags;
644 vp->flags |= VSTRFIXED|VTEXTFIXED;
645 if (strchr(name, '='))
646 setvareq(savestr(name), 0);
649 lvp->vp = vp;
650 lvp->next = localvars;
651 localvars = lvp;
652 INTON;
657 * Called after a function returns.
660 void
661 poplocalvars(void)
663 struct localvar *lvp;
664 struct var *vp;
666 while ((lvp = localvars) != NULL) {
667 localvars = lvp->next;
668 vp = lvp->vp;
669 if (vp == NULL) { /* $- saved */
670 memcpy(optlist, lvp->text, sizeof optlist);
671 ckfree(lvp->text);
672 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
673 unsetvar(vp->text);
674 } else {
675 if ((vp->flags & VTEXTFIXED) == 0)
676 ckfree(vp->text);
677 vp->flags = lvp->flags;
678 vp->text = lvp->text;
680 ckfree(lvp);
686 setvarcmd(int argc, char **argv)
688 if (argc <= 2)
689 return unsetcmd(argc, argv);
690 else if (argc == 3)
691 setvar(argv[1], argv[2], 0);
692 else
693 error("List assignment not implemented");
694 return 0;
699 * The unset builtin command. We unset the function before we unset the
700 * variable to allow a function to be unset when there is a readonly variable
701 * with the same name.
705 unsetcmd(int argc __unused, char **argv __unused)
707 char **ap;
708 int i;
709 int flg_func = 0;
710 int flg_var = 0;
711 int ret = 0;
713 while ((i = nextopt("vf")) != '\0') {
714 if (i == 'f')
715 flg_func = 1;
716 else
717 flg_var = 1;
719 if (flg_func == 0 && flg_var == 0)
720 flg_var = 1;
722 for (ap = argptr; *ap ; ap++) {
723 if (flg_func)
724 ret |= unsetfunc(*ap);
725 if (flg_var)
726 ret |= unsetvar(*ap);
728 return ret;
733 * Unset the specified variable.
737 unsetvar(const char *s)
739 struct var **vpp;
740 struct var *vp;
742 vpp = hashvar(s);
743 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
744 if (varequal(vp->text, s)) {
745 if (vp->flags & VREADONLY)
746 return (1);
747 INTOFF;
748 if (*(strchr(vp->text, '=') + 1) != '\0')
749 setvar(s, nullstr, 0);
750 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
751 unsetenv(s);
752 setlocale(LC_ALL, "");
754 vp->flags &= ~VEXPORT;
755 vp->flags |= VUNSET;
756 if ((vp->flags & VSTRFIXED) == 0) {
757 if ((vp->flags & VTEXTFIXED) == 0)
758 ckfree(vp->text);
759 *vpp = vp->next;
760 ckfree(vp);
762 INTON;
763 return (0);
766 return (0);
772 * Find the appropriate entry in the hash table from the name.
775 STATIC struct var **
776 hashvar(const char *p)
778 unsigned int hashval;
780 hashval = ((unsigned char) *p) << 4;
781 while (*p && *p != '=')
782 hashval += (unsigned char) *p++;
783 return &vartab[hashval % VTABSIZE];
789 * Returns true if the two strings specify the same varable. The first
790 * variable name is terminated by '='; the second may be terminated by
791 * either '=' or '\0'.
794 STATIC int
795 varequal(const char *p, const char *q)
797 while (*p == *q++) {
798 if (*p++ == '=')
799 return 1;
801 if (*p == '=' && *(q - 1) == '\0')
802 return 1;
803 return 0;