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
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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
36 * @(#)var.c 8.3 (Berkeley) 5/4/95
37 * $FreeBSD: src/bin/sh/var.c,v 1.58 2011/05/08 16:15:50 jilles Exp $
54 #include "nodes.h" /* for other headers */
55 #include "eval.h" /* defines cmdenviron */
66 #include "myhistedit.h"
77 void (*func)(const char *);
94 static struct var voptind;
96 static const struct varinit varinit[] = {
98 { &vhistsize, VUNSET, "HISTSIZE=",
101 { &vifs, 0, "IFS= \t\n",
103 { &vmail, VUNSET, "MAIL=",
105 { &vmpath, VUNSET, "MAILPATH=",
107 { &vpath, 0, "PATH=" _PATH_DEFPATH,
109 { &vppid, VUNSET, "PPID=",
112 * vps1 depends on uid
114 { &vps2, 0, "PS2=> ",
116 { &vps4, 0, "PS4=+ ",
119 { &vterm, VUNSET, "TERM=",
122 { &voptind, 0, "OPTIND=1",
128 static struct var *vartab[VTABSIZE];
130 static const char *const locale_names[7] = {
131 "LC_COLLATE", "LC_CTYPE", "LC_MONETARY",
132 "LC_NUMERIC", "LC_TIME", "LC_MESSAGES", NULL
134 static const int locale_categories[7] = {
135 LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME, LC_MESSAGES, 0
138 static int varequal(const char *, const char *);
139 static struct var *find_var(const char *, struct var ***, int *);
140 static int localevar(const char *);
143 * Initialize the variable symbol tables and import the environment.
148 MKINIT char **environ;
153 for (envp = environ ; *envp ; envp++) {
154 if (strchr(*envp, '=')) {
155 setvareq(*envp, VEXPORT|VTEXTFIXED);
163 * This routine initializes the builtin variables. It is called when the
164 * shell is initialized.
171 const struct varinit *ip;
175 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
176 if (find_var(ip->text, &vpp, &vp->name_len) != NULL)
180 vp->text = __DECONST(char *, ip->text);
181 vp->flags = ip->flags | VSTRFIXED | VTEXTFIXED;
187 if (find_var("PS1", &vpp, &vps1.name_len) == NULL) {
190 vps1.text = __DECONST(char *, geteuid() ? "PS1=$ " : "PS1=# ");
191 vps1.flags = VSTRFIXED|VTEXTFIXED;
193 if ((vppid.flags & VEXPORT) == 0) {
194 fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
195 setvarsafe("PPID", ppid, 0);
200 * Safe version of setvar, returns 1 on success 0 on failure.
204 setvarsafe(const char *name, const char *val, int flags)
206 struct jmploc jmploc;
207 struct jmploc *const savehandler = handler;
212 if (setjmp(jmploc.loc))
216 setvar(name, val, flags);
218 handler = savehandler;
224 * Set the value of a variable. The flags argument is stored with the
225 * flags of the variable. If val is NULL, the variable is unset.
229 setvar(const char *name, const char *val, int flags)
243 if (!is_in_name(*p)) {
244 if (*p == '\0' || *p == '=')
252 error("%.*s: bad variable name", namelen, name);
253 len = namelen + 2; /* 2 is space for '=' and '\0' */
259 nameeq = ckmalloc(len);
260 memcpy(nameeq, name, namelen);
261 nameeq[namelen] = '=';
263 scopy(val, nameeq + namelen + 1);
265 nameeq[namelen + 1] = '\0';
266 setvareq(nameeq, flags);
270 localevar(const char *s)
272 const char *const *ss;
276 if (varequal(s + 1, "ANG"))
278 if (strncmp(s + 1, "C_", 2) != 0)
280 if (varequal(s + 3, "ALL"))
282 for (ss = locale_names; *ss ; ss++)
283 if (varequal(s + 3, *ss + 3))
289 * Sets/unsets an environment variable from a pointer that may actually be a
290 * pointer into environ where the string should not be manipulated.
293 change_env(const char *s, int set)
299 if ((eqp = strchr(ss, '=')) != NULL)
301 if (set && eqp != NULL) {
302 if (setenv(ss, eqp + 1, 1) != 0)
303 error("setenv: cannot set %s=%s", ss, eqp + 1);
311 * Same as setvar except that the variable and value are passed in
312 * the first argument as name=value. Since the first argument will
313 * be actually stored in the table, it should not be a string that
318 setvareq(char *s, int flags)
320 struct var *vp, **vpp;
325 vp = find_var(s, &vpp, &nlen);
327 if (vp->flags & VREADONLY)
328 error("%.*s: is read only", vp->name_len, s);
333 if (vp->func && (flags & VNOFUNC) == 0)
334 (*vp->func)(s + vp->name_len + 1);
336 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
339 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
344 * We could roll this to a function, to handle it as
345 * a regular variable function callback, but why bother?
347 * Note: this assumes iflag is not set to 1 initially.
348 * As part of init(), this is called before arguments
351 if ((vp == &vmpath || (vp == &vmail && ! mpathset())) &&
354 if ((vp->flags & VEXPORT) && localevar(s)) {
356 setlocale(LC_ALL, "");
365 vp = ckmalloc(sizeof (*vp));
373 if ((vp->flags & VEXPORT) && localevar(s)) {
375 setlocale(LC_ALL, "");
384 * Process a linked list of variable assignments.
388 listsetvar(struct strlist *list, int flags)
393 for (lp = list ; lp ; lp = lp->next) {
394 setvareq(savestr(lp->text), flags);
402 * Find the value of a variable. Returns NULL if not set.
406 lookupvar(const char *name)
410 v = find_var(name, NULL, NULL);
411 if (v == NULL || v->flags & VUNSET)
413 return v->text + v->name_len + 1;
419 * Search the environment of a builtin command. If the second argument
420 * is nonzero, return the value of a variable even if it hasn't been
425 bltinlookup(const char *name, int doall)
432 for (sp = cmdenviron ; sp ; sp = sp->next) {
433 if (varequal(sp->text, name))
434 result = strchr(sp->text, '=') + 1;
439 v = find_var(name, NULL, NULL);
440 if (v == NULL || v->flags & VUNSET ||
441 (!doall && (v->flags & VEXPORT) == 0))
443 return v->text + v->name_len + 1;
448 * Set up locale for a builtin (LANG/LC_* assignments).
458 for (lp = cmdenviron ; lp ; lp = lp->next) {
459 if (localevar(lp->text)) {
466 loc = bltinlookup("LC_ALL", 0);
469 setlocale(LC_ALL, loc);
474 locdef = bltinlookup("LANG", 0);
475 for (i = 0; locale_names[i] != NULL; i++) {
476 loc = bltinlookup(locale_names[i], 0);
480 setlocale(locale_categories[i], loc);
487 * Undo the effect of bltinlocaleset().
490 bltinunsetlocale(void)
495 for (lp = cmdenviron ; lp ; lp = lp->next) {
496 if (localevar(lp->text)) {
497 setlocale(LC_ALL, "");
506 * Update the localeisutf8 flag.
513 charset = nl_langinfo(CODESET);
514 localeisutf8 = !strcmp(charset, "UTF-8");
518 * Generate a list of exported variables. This routine is used to construct
519 * the third argument to execve when executing a program.
531 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
532 for (vp = *vpp ; vp ; vp = vp->next)
533 if (vp->flags & VEXPORT)
536 ep = env = stalloc((nenv + 1) * sizeof *env);
537 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
538 for (vp = *vpp ; vp ; vp = vp->next)
539 if (vp->flags & VEXPORT)
548 var_compare(const void *a, const void *b)
550 const char *const *sa, *const *sb;
555 * This compares two var=value strings which creates a different
556 * order from what you would probably expect. POSIX is somewhat
557 * ambiguous on what should be sorted exactly.
559 return strcoll(*sa, *sb);
564 * Command to list all variables which are set. This is invoked from the
565 * set command when it is called without any options or operands.
569 showvarscmd(int argc __unused, char **argv __unused)
578 * POSIX requires us to sort the variables.
581 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
582 for (vp = *vpp; vp; vp = vp->next) {
583 if (!(vp->flags & VUNSET))
589 vars = ckmalloc(n * sizeof(*vars));
591 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
592 for (vp = *vpp; vp; vp = vp->next) {
593 if (!(vp->flags & VUNSET))
594 vars[i++] = vp->text;
598 qsort(vars, n, sizeof(*vars), var_compare);
599 for (i = 0; i < n; i++) {
600 s = strchr(vars[i], '=');
602 outbin(vars[i], s - vars[i], out1);
615 * The export and readonly commands.
619 exportcmd(int argc, char **argv)
627 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
630 optreset = optind = 1;
633 while ((ch = getopt(argc, argv, "p")) != -1) {
640 error("unknown option: -%c", optopt);
646 if (values && argc != 0)
647 error("-p requires no arguments");
649 while ((name = *argv++) != NULL) {
650 if ((p = strchr(name, '=')) != NULL) {
653 vp = find_var(name, NULL, NULL);
656 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
657 change_env(vp->text, 1);
658 setlocale(LC_ALL, "");
664 setvar(name, p, flag);
667 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
668 for (vp = *vpp ; vp ; vp = vp->next) {
669 if (vp->flags & flag) {
674 p = strchr(vp->text, '=');
675 if (values && !(vp->flags & VUNSET)) {
677 outbin(vp->text, p - vp->text,
681 outbin(vp->text, p - vp->text,
693 * The "local" command.
697 localcmd(int argc __unused, char **argv __unused)
702 error("Not in a function");
703 while ((name = *argptr++) != NULL) {
711 * Make a variable a local variable. When a variable is made local, it's
712 * value and flags are saved in a localvar structure. The saved values
713 * will be restored when the shell function returns. We handle the name
714 * "-" as a special case.
720 struct localvar *lvp;
725 lvp = ckmalloc(sizeof (struct localvar));
726 if (name[0] == '-' && name[1] == '\0') {
727 lvp->text = ckmalloc(sizeof optlist);
728 memcpy(lvp->text, optlist, sizeof optlist);
731 vp = find_var(name, &vpp, NULL);
733 if (strchr(name, '='))
734 setvareq(savestr(name), VSTRFIXED);
736 setvar(name, NULL, VSTRFIXED);
737 vp = *vpp; /* the new variable */
741 lvp->text = vp->text;
742 lvp->flags = vp->flags;
743 vp->flags |= VSTRFIXED|VTEXTFIXED;
744 if (name[vp->name_len] == '=')
745 setvareq(savestr(name), 0);
749 lvp->next = localvars;
756 * Called after a function returns.
762 struct localvar *lvp;
765 while ((lvp = localvars) != NULL) {
766 localvars = lvp->next;
768 if (vp == NULL) { /* $- saved */
769 memcpy(optlist, lvp->text, sizeof optlist);
772 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
775 if ((vp->flags & VTEXTFIXED) == 0)
777 vp->flags = lvp->flags;
778 vp->text = lvp->text;
786 setvarcmd(int argc, char **argv)
789 return unsetcmd(argc, argv);
791 setvar(argv[1], argv[2], 0);
793 error("too many arguments");
799 * The unset builtin command.
803 unsetcmd(int argc __unused, char **argv __unused)
811 while ((i = nextopt("vf")) != '\0') {
817 if (flg_func == 0 && flg_var == 0)
820 for (ap = argptr; *ap ; ap++) {
822 ret |= unsetfunc(*ap);
824 ret |= unsetvar(*ap);
831 * Unset the specified variable.
835 unsetvar(const char *s)
840 vp = find_var(s, &vpp, NULL);
843 if (vp->flags & VREADONLY)
846 if (vp->text[vp->name_len + 1] != '\0')
847 setvar(s, nullstr, 0);
848 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
849 change_env(__DECONST(char *, s), 0);
850 setlocale(LC_ALL, "");
853 vp->flags &= ~VEXPORT;
855 if ((vp->flags & VSTRFIXED) == 0) {
856 if ((vp->flags & VTEXTFIXED) == 0)
868 * Returns true if the two strings specify the same variable. The first
869 * variable name is terminated by '='; the second may be terminated by
870 * either '=' or '\0'.
874 varequal(const char *p, const char *q)
880 if (*p == '=' && *(q - 1) == '\0')
886 * Search for a variable.
887 * 'name' may be terminated by '=' or a NUL.
888 * vppp is set to the pointer to vp, or the list head if vp isn't found
889 * lenp is set to the number of characters in 'name'
893 find_var(const char *name, struct var ***vppp, int *lenp)
895 unsigned int hashval;
897 struct var *vp, **vpp;
898 const char *p = name;
901 while (*p && *p != '=')
902 hashval = 2 * hashval + (unsigned char)*p++;
907 vpp = &vartab[hashval % VTABSIZE];
911 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
912 if (vp->name_len != len)
914 if (memcmp(vp->text, name, len) != 0)