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.59 2011/05/08 17:40:10 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");
521 initial_localeisutf8 = localeisutf8;
525 * Generate a list of exported variables. This routine is used to construct
526 * the third argument to execve when executing a program.
538 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
539 for (vp = *vpp ; vp ; vp = vp->next)
540 if (vp->flags & VEXPORT)
543 ep = env = stalloc((nenv + 1) * sizeof *env);
544 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
545 for (vp = *vpp ; vp ; vp = vp->next)
546 if (vp->flags & VEXPORT)
555 var_compare(const void *a, const void *b)
557 const char *const *sa, *const *sb;
562 * This compares two var=value strings which creates a different
563 * order from what you would probably expect. POSIX is somewhat
564 * ambiguous on what should be sorted exactly.
566 return strcoll(*sa, *sb);
571 * Command to list all variables which are set. This is invoked from the
572 * set command when it is called without any options or operands.
576 showvarscmd(int argc __unused, char **argv __unused)
585 * POSIX requires us to sort the variables.
588 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
589 for (vp = *vpp; vp; vp = vp->next) {
590 if (!(vp->flags & VUNSET))
596 vars = ckmalloc(n * sizeof(*vars));
598 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
599 for (vp = *vpp; vp; vp = vp->next) {
600 if (!(vp->flags & VUNSET))
601 vars[i++] = vp->text;
605 qsort(vars, n, sizeof(*vars), var_compare);
606 for (i = 0; i < n; i++) {
607 s = strchr(vars[i], '=');
609 outbin(vars[i], s - vars[i], out1);
622 * The export and readonly commands.
626 exportcmd(int argc, char **argv)
634 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
637 optreset = optind = 1;
640 while ((ch = getopt(argc, argv, "p")) != -1) {
647 error("unknown option: -%c", optopt);
653 if (values && argc != 0)
654 error("-p requires no arguments");
656 while ((name = *argv++) != NULL) {
657 if ((p = strchr(name, '=')) != NULL) {
660 vp = find_var(name, NULL, NULL);
663 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
664 change_env(vp->text, 1);
665 setlocale(LC_ALL, "");
671 setvar(name, p, flag);
674 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
675 for (vp = *vpp ; vp ; vp = vp->next) {
676 if (vp->flags & flag) {
681 p = strchr(vp->text, '=');
682 if (values && !(vp->flags & VUNSET)) {
684 outbin(vp->text, p - vp->text,
688 outbin(vp->text, p - vp->text,
700 * The "local" command.
704 localcmd(int argc __unused, char **argv __unused)
709 error("Not in a function");
710 while ((name = *argptr++) != NULL) {
718 * Make a variable a local variable. When a variable is made local, it's
719 * value and flags are saved in a localvar structure. The saved values
720 * will be restored when the shell function returns. We handle the name
721 * "-" as a special case.
727 struct localvar *lvp;
732 lvp = ckmalloc(sizeof (struct localvar));
733 if (name[0] == '-' && name[1] == '\0') {
734 lvp->text = ckmalloc(sizeof optlist);
735 memcpy(lvp->text, optlist, sizeof optlist);
738 vp = find_var(name, &vpp, NULL);
740 if (strchr(name, '='))
741 setvareq(savestr(name), VSTRFIXED);
743 setvar(name, NULL, VSTRFIXED);
744 vp = *vpp; /* the new variable */
748 lvp->text = vp->text;
749 lvp->flags = vp->flags;
750 vp->flags |= VSTRFIXED|VTEXTFIXED;
751 if (name[vp->name_len] == '=')
752 setvareq(savestr(name), 0);
756 lvp->next = localvars;
763 * Called after a function returns.
769 struct localvar *lvp;
772 while ((lvp = localvars) != NULL) {
773 localvars = lvp->next;
775 if (vp == NULL) { /* $- saved */
776 memcpy(optlist, lvp->text, sizeof optlist);
779 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
782 if ((vp->flags & VTEXTFIXED) == 0)
784 vp->flags = lvp->flags;
785 vp->text = lvp->text;
793 setvarcmd(int argc, char **argv)
796 return unsetcmd(argc, argv);
798 setvar(argv[1], argv[2], 0);
800 error("too many arguments");
806 * The unset builtin command.
810 unsetcmd(int argc __unused, char **argv __unused)
818 while ((i = nextopt("vf")) != '\0') {
824 if (flg_func == 0 && flg_var == 0)
827 for (ap = argptr; *ap ; ap++) {
829 ret |= unsetfunc(*ap);
831 ret |= unsetvar(*ap);
838 * Unset the specified variable.
842 unsetvar(const char *s)
847 vp = find_var(s, &vpp, NULL);
850 if (vp->flags & VREADONLY)
853 if (vp->text[vp->name_len + 1] != '\0')
854 setvar(s, nullstr, 0);
855 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
856 change_env(__DECONST(char *, s), 0);
857 setlocale(LC_ALL, "");
860 vp->flags &= ~VEXPORT;
862 if ((vp->flags & VSTRFIXED) == 0) {
863 if ((vp->flags & VTEXTFIXED) == 0)
875 * Returns true if the two strings specify the same variable. The first
876 * variable name is terminated by '='; the second may be terminated by
877 * either '=' or '\0'.
881 varequal(const char *p, const char *q)
887 if (*p == '=' && *(q - 1) == '\0')
893 * Search for a variable.
894 * 'name' may be terminated by '=' or a NUL.
895 * vppp is set to the pointer to vp, or the list head if vp isn't found
896 * lenp is set to the number of characters in 'name'
900 find_var(const char *name, struct var ***vppp, int *lenp)
902 unsigned int hashval;
904 struct var *vp, **vpp;
905 const char *p = name;
908 while (*p && *p != '=')
909 hashval = 2 * hashval + (unsigned char)*p++;
914 vpp = &vartab[hashval % VTABSIZE];
918 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
919 if (vp->name_len != len)
921 if (memcmp(vp->text, name, len) != 0)