kernel - Finish implementing PG_RAM / pipelined mmap operation
[dragonfly.git] / bin / sh / var.c
blob9a288eab024ad214295fcbacfd6b909e3e548da5
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.15 2007/01/14 17:29:58 pavalos Exp $
41 #include <unistd.h>
42 #include <stdlib.h>
45 * Shell variables.
48 #include <locale.h>
49 #include <paths.h>
51 #include "shell.h"
52 #include "output.h"
53 #include "expand.h"
54 #include "nodes.h" /* for other headers */
55 #include "eval.h" /* defines cmdenviron */
56 #include "exec.h"
57 #include "syntax.h"
58 #include "options.h"
59 #include "mail.h"
60 #include "var.h"
61 #include "memalloc.h"
62 #include "error.h"
63 #include "mystring.h"
64 #include "parser.h"
65 #ifndef NO_HISTORY
66 #include "myhistedit.h"
67 #endif
70 #define VTABSIZE 39
73 struct varinit {
74 struct var *var;
75 int flags;
76 const char *text;
77 void (*func)(const char *);
81 #ifndef NO_HISTORY
82 struct var vhistsize;
83 #endif
84 struct var vifs;
85 struct var vmail;
86 struct var vmpath;
87 struct var vpath;
88 struct var vppid;
89 struct var vps1;
90 struct var vps2;
91 struct var vps4;
92 struct var vvers;
93 STATIC struct var voptind;
95 STATIC const struct varinit varinit[] = {
96 #ifndef NO_HISTORY
97 { &vhistsize, VSTRFIXED|VTEXTFIXED|VUNSET, "HISTSIZE=",
98 sethistsize },
99 #endif
100 { &vifs, VSTRFIXED|VTEXTFIXED, "IFS= \t\n",
101 NULL },
102 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
103 NULL },
104 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
105 NULL },
106 { &vpath, VSTRFIXED|VTEXTFIXED|VEXPORT,
107 #ifdef _PATH_DEFPATH
108 "PATH=" _PATH_DEFPATH,
109 #else
110 "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/pkg/bin:/usr/pkg/sbin",
111 #endif
112 changepath },
113 { &vppid, VSTRFIXED|VTEXTFIXED|VUNSET, "PPID=",
114 NULL },
116 * vps1 depends on uid
118 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
119 NULL },
120 { &vps4, VSTRFIXED|VTEXTFIXED, "PS4=+ ",
121 NULL },
122 { &voptind, VSTRFIXED|VTEXTFIXED, "OPTIND=1",
123 getoptsreset },
124 { NULL, 0, NULL,
125 NULL }
128 STATIC struct var *vartab[VTABSIZE];
130 STATIC struct var **hashvar(const char *);
131 STATIC int varequal(const char *, const char *);
132 STATIC int localevar(const char *);
135 * Initialize the variable symbol tables and import the environment.
138 #ifdef mkinit
139 INCLUDE "var.h"
140 MKINIT char **environ;
141 INIT {
142 char **envp;
144 initvar();
145 for (envp = environ ; *envp ; envp++) {
146 if (strchr(*envp, '=')) {
147 setvareq(*envp, VEXPORT|VTEXTFIXED);
151 #endif
155 * This routine initializes the builtin variables. It is called when the
156 * shell is initialized and again when a shell procedure is spawned.
159 void
160 initvar(void)
162 char ppid[20];
163 const struct varinit *ip;
164 struct var *vp;
165 struct var **vpp;
167 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
168 if ((vp->flags & VEXPORT) == 0) {
169 vpp = hashvar(ip->text);
170 vp->next = *vpp;
171 *vpp = vp;
172 vp->text = strdup(ip->text);
173 vp->flags = ip->flags;
174 vp->func = ip->func;
178 * PS1 depends on uid
180 if ((vps1.flags & VEXPORT) == 0) {
181 vpp = hashvar("PS1=");
182 vps1.next = *vpp;
183 *vpp = &vps1;
184 vps1.text = strdup(geteuid() ? "PS1=$ " : "PS1=# ");
185 vps1.flags = VSTRFIXED|VTEXTFIXED;
187 if ((vppid.flags & VEXPORT) == 0) {
188 fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
189 setvarsafe("PPID", ppid, 0);
194 * Safe version of setvar, returns 1 on success 0 on failure.
198 setvarsafe(const char *name, const char *val, int flags)
200 struct jmploc jmploc;
201 struct jmploc *volatile savehandler = handler;
202 int err = 0;
204 if (setjmp(jmploc.loc))
205 err = 1;
206 else {
207 handler = &jmploc;
208 setvar(name, val, flags);
210 handler = savehandler;
211 return err;
215 * Set the value of a variable. The flags argument is stored with the
216 * flags of the variable. If val is NULL, the variable is unset.
219 void
220 setvar(const char *name, const char *val, int flags)
222 const char *cp;
223 char *p;
224 int len;
225 int namelen;
226 char *nameeq;
227 int isbad;
229 isbad = 0;
230 cp = name;
231 if (!is_name(*cp))
232 isbad = 1;
233 cp++;
234 for (;;) {
235 if (!is_in_name(*cp)) {
236 if (*cp == '\0' || *cp == '=')
237 break;
238 isbad = 1;
240 cp++;
242 namelen = cp - name;
243 if (isbad)
244 error("%.*s: bad variable name", namelen, name);
245 len = namelen + 2; /* 2 is space for '=' and '\0' */
246 if (val == NULL) {
247 flags |= VUNSET;
248 } else {
249 len += strlen(val);
251 p = nameeq = ckmalloc(len);
252 cp = name;
253 while (--namelen >= 0)
254 *p++ = *cp++;
255 *p++ = '=';
256 *p = '\0';
257 if (val)
258 scopy(val, p);
259 setvareq(nameeq, flags);
262 STATIC int
263 localevar(const char *s)
265 static const char * const lnames[7] = {
266 "ALL", "COLLATE", "CTYPE", "MONETARY",
267 "NUMERIC", "TIME", NULL
269 const char * const *ss;
271 if (*s != 'L')
272 return 0;
273 if (varequal(s + 1, "ANG"))
274 return 1;
275 if (strncmp(s + 1, "C_", 2) != 0)
276 return 0;
277 for (ss = lnames; *ss ; ss++)
278 if (varequal(s + 3, *ss))
279 return 1;
280 return 0;
284 * Sets/unsets an environment variable from a pointer that may actually be a
285 * pointer into environ where the string should not be manipulated.
287 static void
288 change_env(char *s, int set)
290 char *eqp;
291 char *ss;
293 ss = savestr(s);
294 if ((eqp = strchr(ss, '=')) != NULL)
295 *eqp = '\0';
296 if (set && eqp != NULL) {
297 if (setenv(ss, eqp + 1, 1) != 0)
298 error("setenv: cannot set %s=%s", ss, eqp + 1);
299 } else
300 unsetenv(ss);
301 ckfree(ss);
306 * Same as setvar except that the variable and value are passed in
307 * the first argument as name=value. Since the first argument will
308 * be actually stored in the table, it should not be a string that
309 * will go away.
312 void
313 setvareq(char *s, int flags)
315 struct var *vp, **vpp;
316 int len;
318 if (aflag)
319 flags |= VEXPORT;
320 vpp = hashvar(s);
321 for (vp = *vpp ; vp ; vp = vp->next) {
322 if (varequal(s, vp->text)) {
323 if (vp->flags & VREADONLY) {
324 len = strchr(s, '=') - s;
325 error("%.*s: is read only", len, s);
327 INTOFF;
329 if (vp->func && (flags & VNOFUNC) == 0)
330 (*vp->func)(strchr(s, '=') + 1);
332 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
333 ckfree(vp->text);
335 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
336 vp->flags |= flags;
337 vp->text = s;
340 * We could roll this to a function, to handle it as
341 * a regular variable function callback, but why bother?
343 if (vp == &vmpath || (vp == &vmail && ! mpathset()))
344 chkmail(1);
345 if ((vp->flags & VEXPORT) && localevar(s)) {
346 change_env(s, 1);
347 setlocale(LC_ALL, "");
349 INTON;
350 return;
353 /* not found */
354 vp = ckmalloc(sizeof (*vp));
355 vp->flags = flags;
356 vp->text = s;
357 vp->next = *vpp;
358 vp->func = NULL;
359 INTOFF;
360 *vpp = vp;
361 if ((vp->flags & VEXPORT) && localevar(s)) {
362 change_env(s, 1);
363 setlocale(LC_ALL, "");
365 INTON;
371 * Process a linked list of variable assignments.
374 void
375 listsetvar(struct strlist *list)
377 struct strlist *lp;
379 INTOFF;
380 for (lp = list ; lp ; lp = lp->next) {
381 setvareq(savestr(lp->text), 0);
383 INTON;
389 * Find the value of a variable. Returns NULL if not set.
392 char *
393 lookupvar(const char *name)
395 struct var *v;
397 for (v = *hashvar(name) ; v ; v = v->next) {
398 if (varequal(v->text, name)) {
399 if (v->flags & VUNSET)
400 return NULL;
401 return strchr(v->text, '=') + 1;
404 return NULL;
410 * Search the environment of a builtin command. If the second argument
411 * is nonzero, return the value of a variable even if it hasn't been
412 * exported.
415 char *
416 bltinlookup(const char *name, int doall)
418 struct strlist *sp;
419 struct var *v;
421 for (sp = cmdenviron ; sp ; sp = sp->next) {
422 if (varequal(sp->text, name))
423 return strchr(sp->text, '=') + 1;
425 for (v = *hashvar(name) ; v ; v = v->next) {
426 if (varequal(v->text, name)) {
427 if ((v->flags & VUNSET)
428 || (!doall && (v->flags & VEXPORT) == 0))
429 return NULL;
430 return strchr(v->text, '=') + 1;
433 return NULL;
439 * Generate a list of exported variables. This routine is used to construct
440 * the third argument to execve when executing a program.
443 char **
444 environment(void)
446 int nenv;
447 struct var **vpp;
448 struct var *vp;
449 char **env, **ep;
451 nenv = 0;
452 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
453 for (vp = *vpp ; vp ; vp = vp->next)
454 if (vp->flags & VEXPORT)
455 nenv++;
457 ep = env = stalloc((nenv + 1) * sizeof *env);
458 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
459 for (vp = *vpp ; vp ; vp = vp->next)
460 if (vp->flags & VEXPORT)
461 *ep++ = vp->text;
463 *ep = NULL;
464 return env;
469 * Called when a shell procedure is invoked to clear out nonexported
470 * variables. It is also necessary to reallocate variables of with
471 * VSTACK set since these are currently allocated on the stack.
474 #ifdef mkinit
475 void shprocvar(void);
477 SHELLPROC {
478 shprocvar();
480 #endif
482 void
483 shprocvar(void)
485 struct var **vpp;
486 struct var *vp, **prev;
488 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
489 for (prev = vpp ; (vp = *prev) != NULL ; ) {
490 if ((vp->flags & VEXPORT) == 0) {
491 *prev = vp->next;
492 if ((vp->flags & VTEXTFIXED) == 0)
493 ckfree(vp->text);
494 if ((vp->flags & VSTRFIXED) == 0)
495 ckfree(vp);
496 } else {
497 if (vp->flags & VSTACK) {
498 vp->text = savestr(vp->text);
499 vp->flags &=~ VSTACK;
501 prev = &vp->next;
505 initvar();
509 static int
510 var_compare(const void *a, const void *b)
512 const char *const *sa, *const *sb;
514 sa = a;
515 sb = b;
517 * This compares two var=value strings which creates a different
518 * order from what you would probably expect. POSIX is somewhat
519 * ambiguous on what should be sorted exactly.
521 return strcoll(*sa, *sb);
526 * Command to list all variables which are set. Currently this command
527 * is invoked from the set command when the set command is called without
528 * any variables.
532 showvarscmd(int argc __unused, char **argv __unused)
534 struct var **vpp;
535 struct var *vp;
536 const char *s;
537 const char **vars;
538 int i, n;
541 * POSIX requires us to sort the variables.
543 n = 0;
544 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
545 for (vp = *vpp; vp; vp = vp->next) {
546 if (!(vp->flags & VUNSET))
547 n++;
551 INTON;
552 vars = ckmalloc(n * sizeof(*vars));
553 i = 0;
554 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
555 for (vp = *vpp; vp; vp = vp->next) {
556 if (!(vp->flags & VUNSET))
557 vars[i++] = vp->text;
561 qsort(vars, n, sizeof(*vars), var_compare);
562 for (i = 0; i < n; i++) {
563 for (s = vars[i]; *s != '='; s++)
564 out1c(*s);
565 out1c('=');
566 out1qstr(s + 1);
567 out1c('\n');
569 ckfree(vars);
570 INTOFF;
572 return 0;
578 * The export and readonly commands.
582 exportcmd(int argc, char **argv)
584 struct var **vpp;
585 struct var *vp;
586 char *name;
587 char *p;
588 char *cmdname;
589 int ch, values;
590 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
592 cmdname = argv[0];
593 optreset = optind = 1;
594 opterr = 0;
595 values = 0;
596 while ((ch = getopt(argc, argv, "p")) != -1) {
597 switch (ch) {
598 case 'p':
599 values = 1;
600 break;
601 case '?':
602 default:
603 error("unknown option: -%c", optopt);
606 argc -= optind;
607 argv += optind;
609 if (values && argc != 0)
610 error("-p requires no arguments");
611 listsetvar(cmdenviron);
612 if (argc != 0) {
613 while ((name = *argv++) != NULL) {
614 if ((p = strchr(name, '=')) != NULL) {
615 p++;
616 } else {
617 vpp = hashvar(name);
618 for (vp = *vpp ; vp ; vp = vp->next) {
619 if (varequal(vp->text, name)) {
621 vp->flags |= flag;
622 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
623 change_env(vp->text, 1);
624 setlocale(LC_ALL, "");
626 goto found;
630 setvar(name, p, flag);
631 found:;
633 } else {
634 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
635 for (vp = *vpp ; vp ; vp = vp->next) {
636 if (vp->flags & flag) {
637 if (values) {
638 out1str(cmdname);
639 out1c(' ');
641 for (p = vp->text ; *p != '=' ; p++)
642 out1c(*p);
643 if (values && !(vp->flags & VUNSET)) {
644 out1c('=');
645 out1qstr(p + 1);
647 out1c('\n');
652 return 0;
657 * The "local" command.
661 localcmd(int argc __unused, char **argv __unused)
663 char *name;
665 if (! in_function())
666 error("Not in a function");
667 while ((name = *argptr++) != NULL) {
668 mklocal(name);
670 return 0;
675 * Make a variable a local variable. When a variable is made local, it's
676 * value and flags are saved in a localvar structure. The saved values
677 * will be restored when the shell function returns. We handle the name
678 * "-" as a special case.
681 void
682 mklocal(char *name)
684 struct localvar *lvp;
685 struct var **vpp;
686 struct var *vp;
688 INTOFF;
689 lvp = ckmalloc(sizeof (struct localvar));
690 if (name[0] == '-' && name[1] == '\0') {
691 lvp->text = ckmalloc(sizeof optlist);
692 memcpy(lvp->text, optlist, sizeof optlist);
693 vp = NULL;
694 } else {
695 vpp = hashvar(name);
696 for (vp = *vpp ; vp && ! varequal(vp->text, name) ; vp = vp->next);
697 if (vp == NULL) {
698 if (strchr(name, '='))
699 setvareq(savestr(name), VSTRFIXED);
700 else
701 setvar(name, NULL, VSTRFIXED);
702 vp = *vpp; /* the new variable */
703 lvp->text = NULL;
704 lvp->flags = VUNSET;
705 } else {
706 lvp->text = vp->text;
707 lvp->flags = vp->flags;
708 vp->flags |= VSTRFIXED|VTEXTFIXED;
709 if (strchr(name, '='))
710 setvareq(savestr(name), 0);
713 lvp->vp = vp;
714 lvp->next = localvars;
715 localvars = lvp;
716 INTON;
721 * Called after a function returns.
724 void
725 poplocalvars(void)
727 struct localvar *lvp;
728 struct var *vp;
730 while ((lvp = localvars) != NULL) {
731 localvars = lvp->next;
732 vp = lvp->vp;
733 if (vp == NULL) { /* $- saved */
734 memcpy(optlist, lvp->text, sizeof optlist);
735 ckfree(lvp->text);
736 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
737 unsetvar(vp->text);
738 } else {
739 if ((vp->flags & VTEXTFIXED) == 0)
740 ckfree(vp->text);
741 vp->flags = lvp->flags;
742 vp->text = lvp->text;
744 ckfree(lvp);
750 setvarcmd(int argc, char **argv)
752 if (argc <= 2)
753 return unsetcmd(argc, argv);
754 else if (argc == 3)
755 setvar(argv[1], argv[2], 0);
756 else
757 error("List assignment not implemented");
758 return 0;
763 * The unset builtin command. We unset the function before we unset the
764 * variable to allow a function to be unset when there is a readonly variable
765 * with the same name.
769 unsetcmd(int argc __unused, char **argv __unused)
771 char **ap;
772 int i;
773 int flg_func = 0;
774 int flg_var = 0;
775 int ret = 0;
777 while ((i = nextopt("vf")) != '\0') {
778 if (i == 'f')
779 flg_func = 1;
780 else
781 flg_var = 1;
783 if (flg_func == 0 && flg_var == 0)
784 flg_var = 1;
786 for (ap = argptr; *ap ; ap++) {
787 if (flg_func)
788 ret |= unsetfunc(*ap);
789 if (flg_var)
790 ret |= unsetvar(*ap);
792 return ret;
797 * Unset the specified variable.
801 unsetvar(const char *s)
803 struct var **vpp;
804 struct var *vp;
806 vpp = hashvar(s);
807 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
808 if (varequal(vp->text, s)) {
809 if (vp->flags & VREADONLY)
810 return (1);
811 INTOFF;
812 if (*(strchr(vp->text, '=') + 1) != '\0')
813 setvar(s, nullstr, 0);
814 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
815 change_env(__DECONST(char *, s), 0);
816 setlocale(LC_ALL, "");
818 vp->flags &= ~VEXPORT;
819 vp->flags |= VUNSET;
820 if ((vp->flags & VSTRFIXED) == 0) {
821 if ((vp->flags & VTEXTFIXED) == 0)
822 ckfree(vp->text);
823 *vpp = vp->next;
824 ckfree(vp);
826 INTON;
827 return (0);
830 return (0);
836 * Find the appropriate entry in the hash table from the name.
839 STATIC struct var **
840 hashvar(const char *p)
842 unsigned int hashval;
844 hashval = ((unsigned char) *p) << 4;
845 while (*p && *p != '=')
846 hashval += (unsigned char) *p++;
847 return &vartab[hashval % VTABSIZE];
853 * Returns true if the two strings specify the same varable. The first
854 * variable name is terminated by '='; the second may be terminated by
855 * either '=' or '\0'.
858 STATIC int
859 varequal(const char *p, const char *q)
861 while (*p == *q++) {
862 if (*p++ == '=')
863 return 1;
865 if (*p == '=' && *(q - 1) == '\0')
866 return 1;
867 return 0;