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 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * @(#)var.c 8.3 (Berkeley) 5/4/95
33 * $FreeBSD: head/bin/sh/var.c 245689 2013-01-20 12:44:50Z jilles $
50 #include "nodes.h" /* for other headers */
51 #include "eval.h" /* defines cmdenviron */
63 #include "myhistedit.h"
74 void (*func)(const char *);
91 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",
124 { &vdisvfork, VUNSET, "SH_DISABLE_VFORK=",
130 static struct var *vartab[VTABSIZE];
132 static const char *const locale_names[7] = {
133 "LC_COLLATE", "LC_CTYPE", "LC_MONETARY",
134 "LC_NUMERIC", "LC_TIME", "LC_MESSAGES", NULL
136 static const int locale_categories[7] = {
137 LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME, LC_MESSAGES, 0
140 static int varequal(const char *, const char *);
141 static struct var *find_var(const char *, struct var ***, int *);
142 static int localevar(const char *);
144 extern char **environ;
147 * This routine initializes the builtin variables and imports the environment.
148 * It is called when the shell is initialized.
155 const struct varinit *ip;
160 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
161 if (find_var(ip->text, &vpp, &vp->name_len) != NULL)
165 vp->text = __DECONST(char *, ip->text);
166 vp->flags = ip->flags | VSTRFIXED | VTEXTFIXED;
172 if (find_var("PS1", &vpp, &vps1.name_len) == NULL) {
175 vps1.text = __DECONST(char *, 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);
182 for (envp = environ ; *envp ; envp++) {
183 if (strchr(*envp, '=')) {
184 setvareq(*envp, VEXPORT|VTEXTFIXED);
190 * Safe version of setvar, returns 1 on success 0 on failure.
194 setvarsafe(const char *name, const char *val, int flags)
196 struct jmploc jmploc;
197 struct jmploc *const savehandler = handler;
202 if (setjmp(jmploc.loc))
206 setvar(name, val, flags);
208 handler = savehandler;
214 * Set the value of a variable. The flags argument is stored with the
215 * flags of the variable. If val is NULL, the variable is unset.
219 setvar(const char *name, const char *val, int flags)
233 if (!is_in_name(*p)) {
234 if (*p == '\0' || *p == '=')
242 error("%.*s: bad variable name", namelen, name);
243 len = namelen + 2; /* 2 is space for '=' and '\0' */
249 nameeq = ckmalloc(len);
250 memcpy(nameeq, name, namelen);
251 nameeq[namelen] = '=';
253 scopy(val, nameeq + namelen + 1);
255 nameeq[namelen + 1] = '\0';
256 setvareq(nameeq, flags);
260 localevar(const char *s)
262 const char *const *ss;
266 if (varequal(s + 1, "ANG"))
268 if (strncmp(s + 1, "C_", 2) != 0)
270 if (varequal(s + 3, "ALL"))
272 for (ss = locale_names; *ss ; ss++)
273 if (varequal(s + 3, *ss + 3))
279 * Sets/unsets an environment variable from a pointer that may actually be a
280 * pointer into environ where the string should not be manipulated.
283 change_env(const char *s, int set)
289 if ((eqp = strchr(ss, '=')) != NULL)
291 if (set && eqp != NULL) {
292 if (setenv(ss, eqp + 1, 1) != 0)
293 error("setenv: cannot set %s=%s", ss, eqp + 1);
301 * Same as setvar except that the variable and value are passed in
302 * the first argument as name=value. Since the first argument will
303 * be actually stored in the table, it should not be a string that
308 setvareq(char *s, int flags)
310 struct var *vp, **vpp;
315 if (forcelocal && !(flags & (VNOSET | VNOLOCAL)))
317 vp = find_var(s, &vpp, &nlen);
319 if (vp->flags & VREADONLY)
320 error("%.*s: is read only", vp->name_len, s);
325 if (vp->func && (flags & VNOFUNC) == 0)
326 (*vp->func)(s + vp->name_len + 1);
328 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
331 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
336 * We could roll this to a function, to handle it as
337 * a regular variable function callback, but why bother?
339 * Note: this assumes iflag is not set to 1 initially.
340 * As part of initvar(), this is called before arguments
343 if ((vp == &vmpath || (vp == &vmail && ! mpathset())) &&
346 if ((vp->flags & VEXPORT) && localevar(s)) {
348 setlocale(LC_ALL, "");
357 vp = ckmalloc(sizeof (*vp));
365 if ((vp->flags & VEXPORT) && localevar(s)) {
367 setlocale(LC_ALL, "");
376 * Process a linked list of variable assignments.
380 listsetvar(struct strlist *list, int flags)
385 for (lp = list ; lp ; lp = lp->next) {
386 setvareq(savestr(lp->text), flags);
394 * Find the value of a variable. Returns NULL if not set.
398 lookupvar(const char *name)
402 v = find_var(name, NULL, NULL);
403 if (v == NULL || v->flags & VUNSET)
405 return v->text + v->name_len + 1;
411 * Search the environment of a builtin command. If the second argument
412 * is nonzero, return the value of a variable even if it hasn't been
417 bltinlookup(const char *name, int doall)
424 for (sp = cmdenviron ; sp ; sp = sp->next) {
425 if (varequal(sp->text, name))
426 result = strchr(sp->text, '=') + 1;
431 v = find_var(name, NULL, NULL);
432 if (v == NULL || v->flags & VUNSET ||
433 (!doall && (v->flags & VEXPORT) == 0))
435 return v->text + v->name_len + 1;
440 * Set up locale for a builtin (LANG/LC_* assignments).
450 for (lp = cmdenviron ; lp ; lp = lp->next) {
451 if (localevar(lp->text)) {
458 loc = bltinlookup("LC_ALL", 0);
461 setlocale(LC_ALL, loc);
466 locdef = bltinlookup("LANG", 0);
467 for (i = 0; locale_names[i] != NULL; i++) {
468 loc = bltinlookup(locale_names[i], 0);
472 setlocale(locale_categories[i], loc);
479 * Undo the effect of bltinlocaleset().
482 bltinunsetlocale(void)
487 for (lp = cmdenviron ; lp ; lp = lp->next) {
488 if (localevar(lp->text)) {
489 setlocale(LC_ALL, "");
498 * Update the localeisutf8 flag.
505 charset = nl_langinfo(CODESET);
506 localeisutf8 = !strcmp(charset, "UTF-8");
513 initial_localeisutf8 = localeisutf8;
517 * Generate a list of exported variables. This routine is used to construct
518 * the third argument to execve when executing a program.
530 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
531 for (vp = *vpp ; vp ; vp = vp->next)
532 if (vp->flags & VEXPORT)
535 ep = env = stalloc((nenv + 1) * sizeof *env);
536 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
537 for (vp = *vpp ; vp ; vp = vp->next)
538 if (vp->flags & VEXPORT)
547 var_compare(const void *a, const void *b)
549 const char *const *sa, *const *sb;
554 * This compares two var=value strings which creates a different
555 * order from what you would probably expect. POSIX is somewhat
556 * ambiguous on what should be sorted exactly.
558 return strcoll(*sa, *sb);
563 * Command to list all variables which are set. This is invoked from the
564 * set command when it is called without any options or operands.
568 showvarscmd(int argc __unused, char **argv __unused)
577 * POSIX requires us to sort the variables.
580 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
581 for (vp = *vpp; vp; vp = vp->next) {
582 if (!(vp->flags & VUNSET))
588 vars = ckmalloc(n * sizeof(*vars));
590 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
591 for (vp = *vpp; vp; vp = vp->next) {
592 if (!(vp->flags & VUNSET))
593 vars[i++] = vp->text;
597 qsort(vars, n, sizeof(*vars), var_compare);
598 for (i = 0; i < n; i++) {
600 * Skip improper variable names so the output remains usable as
603 if (!isassignment(vars[i]))
605 s = strchr(vars[i], '=');
607 outbin(vars[i], s - vars[i], out1);
620 * The export and readonly commands.
624 exportcmd(int argc __unused, char **argv)
633 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
637 while ((ch = nextopt("p")) != '\0') {
645 if (values && *argptr != NULL)
646 error("-p requires no arguments");
647 if (*argptr != NULL) {
648 for (ap = argptr; (name = *ap) != NULL; ap++) {
649 if ((p = strchr(name, '=')) != NULL) {
652 vp = find_var(name, NULL, NULL);
655 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
656 change_env(vp->text, 1);
657 setlocale(LC_ALL, "");
663 setvar(name, p, flag);
666 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
667 for (vp = *vpp ; vp ; vp = vp->next) {
668 if (vp->flags & flag) {
671 * Skip improper variable names
672 * so the output remains usable
675 if (!isassignment(vp->text))
680 if (values && !(vp->flags & VUNSET)) {
682 vp->name_len + 1, out1);
686 outbin(vp->text, vp->name_len,
698 * The "local" command.
702 localcmd(int argc __unused, char **argv __unused)
707 error("Not in a function");
708 while ((name = *argptr++) != NULL) {
716 * Make a variable a local variable. When a variable is made local, it's
717 * value and flags are saved in a localvar structure. The saved values
718 * will be restored when the shell function returns. We handle the name
719 * "-" as a special case.
725 struct localvar *lvp;
730 lvp = ckmalloc(sizeof (struct localvar));
731 if (name[0] == '-' && name[1] == '\0') {
732 lvp->text = ckmalloc(sizeof optlist);
733 memcpy(lvp->text, optlist, sizeof optlist);
736 vp = find_var(name, &vpp, NULL);
738 if (strchr(name, '='))
739 setvareq(savestr(name), VSTRFIXED | VNOLOCAL);
741 setvar(name, NULL, VSTRFIXED | VNOLOCAL);
742 vp = *vpp; /* the new variable */
746 lvp->text = vp->text;
747 lvp->flags = vp->flags;
748 vp->flags |= VSTRFIXED|VTEXTFIXED;
749 if (name[vp->name_len] == '=')
750 setvareq(savestr(name), VNOLOCAL);
754 lvp->next = localvars;
761 * Called after a function returns.
767 struct localvar *lvp;
770 while ((lvp = localvars) != NULL) {
771 localvars = lvp->next;
773 if (vp == NULL) { /* $- saved */
774 memcpy(optlist, lvp->text, sizeof optlist);
777 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
780 if ((vp->flags & VTEXTFIXED) == 0)
782 vp->flags = lvp->flags;
783 vp->text = lvp->text;
791 setvarcmd(int argc, char **argv)
794 return unsetcmd(argc, argv);
796 setvar(argv[1], argv[2], 0);
798 error("too many arguments");
804 * The unset builtin command.
808 unsetcmd(int argc __unused, char **argv __unused)
816 while ((i = nextopt("vf")) != '\0') {
822 if (flg_func == 0 && flg_var == 0)
825 for (ap = argptr; *ap ; ap++) {
827 ret |= unsetfunc(*ap);
829 ret |= unsetvar(*ap);
836 * Unset the specified variable.
840 unsetvar(const char *s)
845 vp = find_var(s, &vpp, NULL);
848 if (vp->flags & VREADONLY)
851 if (vp->text[vp->name_len + 1] != '\0')
852 setvar(s, nullstr, 0);
853 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
854 change_env(__DECONST(char *, s), 0);
855 setlocale(LC_ALL, "");
858 vp->flags &= ~VEXPORT;
860 if ((vp->flags & VSTRFIXED) == 0) {
861 if ((vp->flags & VTEXTFIXED) == 0)
873 * Returns true if the two strings specify the same variable. The first
874 * variable name is terminated by '='; the second may be terminated by
875 * either '=' or '\0'.
879 varequal(const char *p, const char *q)
885 if (*p == '=' && *(q - 1) == '\0')
891 * Search for a variable.
892 * 'name' may be terminated by '=' or a NUL.
893 * vppp is set to the pointer to vp, or the list head if vp isn't found
894 * lenp is set to the number of characters in 'name'
898 find_var(const char *name, struct var ***vppp, int *lenp)
900 unsigned int hashval;
902 struct var *vp, **vpp;
903 const char *p = name;
906 while (*p && *p != '=')
907 hashval = 2 * hashval + (unsigned char)*p++;
912 vpp = &vartab[hashval % VTABSIZE];
916 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
917 if (vp->name_len != len)
919 if (memcmp(vp->text, name, len) != 0)