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.63 2011/06/17 10:21:24 jilles Exp $
54 #include "nodes.h" /* for other headers */
55 #include "eval.h" /* defines cmdenviron */
67 #include "myhistedit.h"
78 void (*func)(const char *);
95 static struct var voptind;
99 static const struct varinit varinit[] = {
101 { &vhistsize, VUNSET, "HISTSIZE=",
104 { &vifs, 0, "IFS= \t\n",
106 { &vmail, VUNSET, "MAIL=",
108 { &vmpath, VUNSET, "MAILPATH=",
110 { &vpath, 0, "PATH=" _PATH_DEFPATH,
112 { &vppid, VUNSET, "PPID=",
115 * vps1 depends on uid
117 { &vps2, 0, "PS2=> ",
119 { &vps4, 0, "PS4=+ ",
122 { &vterm, VUNSET, "TERM=",
125 { &voptind, 0, "OPTIND=1",
131 static struct var *vartab[VTABSIZE];
133 static const char *const locale_names[7] = {
134 "LC_COLLATE", "LC_CTYPE", "LC_MONETARY",
135 "LC_NUMERIC", "LC_TIME", "LC_MESSAGES", NULL
137 static const int locale_categories[7] = {
138 LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME, LC_MESSAGES, 0
141 static int varequal(const char *, const char *);
142 static struct var *find_var(const char *, struct var ***, int *);
143 static int localevar(const char *);
146 * Initialize the variable symbol tables and import the environment.
151 MKINIT char **environ;
156 for (envp = environ ; *envp ; envp++) {
157 if (strchr(*envp, '=')) {
158 setvareq(*envp, VEXPORT|VTEXTFIXED);
166 * This routine initializes the builtin variables. It is called when the
167 * shell is initialized.
174 const struct varinit *ip;
178 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
179 if (find_var(ip->text, &vpp, &vp->name_len) != NULL)
183 vp->text = __DECONST(char *, ip->text);
184 vp->flags = ip->flags | VSTRFIXED | VTEXTFIXED;
190 if (find_var("PS1", &vpp, &vps1.name_len) == NULL) {
193 vps1.text = __DECONST(char *, geteuid() ? "PS1=$ " : "PS1=# ");
194 vps1.flags = VSTRFIXED|VTEXTFIXED;
196 if ((vppid.flags & VEXPORT) == 0) {
197 fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
198 setvarsafe("PPID", ppid, 0);
203 * Safe version of setvar, returns 1 on success 0 on failure.
207 setvarsafe(const char *name, const char *val, int flags)
209 struct jmploc jmploc;
210 struct jmploc *const savehandler = handler;
215 if (setjmp(jmploc.loc))
219 setvar(name, val, flags);
221 handler = savehandler;
227 * Set the value of a variable. The flags argument is stored with the
228 * flags of the variable. If val is NULL, the variable is unset.
232 setvar(const char *name, const char *val, int flags)
246 if (!is_in_name(*p)) {
247 if (*p == '\0' || *p == '=')
255 error("%.*s: bad variable name", namelen, name);
256 len = namelen + 2; /* 2 is space for '=' and '\0' */
262 nameeq = ckmalloc(len);
263 memcpy(nameeq, name, namelen);
264 nameeq[namelen] = '=';
266 scopy(val, nameeq + namelen + 1);
268 nameeq[namelen + 1] = '\0';
269 setvareq(nameeq, flags);
273 localevar(const char *s)
275 const char *const *ss;
279 if (varequal(s + 1, "ANG"))
281 if (strncmp(s + 1, "C_", 2) != 0)
283 if (varequal(s + 3, "ALL"))
285 for (ss = locale_names; *ss ; ss++)
286 if (varequal(s + 3, *ss + 3))
292 * Sets/unsets an environment variable from a pointer that may actually be a
293 * pointer into environ where the string should not be manipulated.
296 change_env(const char *s, int set)
302 if ((eqp = strchr(ss, '=')) != NULL)
304 if (set && eqp != NULL) {
305 if (setenv(ss, eqp + 1, 1) != 0)
306 error("setenv: cannot set %s=%s", ss, eqp + 1);
314 * Same as setvar except that the variable and value are passed in
315 * the first argument as name=value. Since the first argument will
316 * be actually stored in the table, it should not be a string that
321 setvareq(char *s, int flags)
323 struct var *vp, **vpp;
328 if (forcelocal && !(flags & (VNOSET | VNOLOCAL)))
330 vp = find_var(s, &vpp, &nlen);
332 if (vp->flags & VREADONLY)
333 error("%.*s: is read only", vp->name_len, s);
338 if (vp->func && (flags & VNOFUNC) == 0)
339 (*vp->func)(s + vp->name_len + 1);
341 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
344 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
349 * We could roll this to a function, to handle it as
350 * a regular variable function callback, but why bother?
352 * Note: this assumes iflag is not set to 1 initially.
353 * As part of init(), this is called before arguments
356 if ((vp == &vmpath || (vp == &vmail && ! mpathset())) &&
359 if ((vp->flags & VEXPORT) && localevar(s)) {
361 setlocale(LC_ALL, "");
370 vp = ckmalloc(sizeof (*vp));
378 if ((vp->flags & VEXPORT) && localevar(s)) {
380 setlocale(LC_ALL, "");
389 * Process a linked list of variable assignments.
393 listsetvar(struct strlist *list, int flags)
398 for (lp = list ; lp ; lp = lp->next) {
399 setvareq(savestr(lp->text), flags);
407 * Find the value of a variable. Returns NULL if not set.
411 lookupvar(const char *name)
415 v = find_var(name, NULL, NULL);
416 if (v == NULL || v->flags & VUNSET)
418 return v->text + v->name_len + 1;
424 * Search the environment of a builtin command. If the second argument
425 * is nonzero, return the value of a variable even if it hasn't been
430 bltinlookup(const char *name, int doall)
437 for (sp = cmdenviron ; sp ; sp = sp->next) {
438 if (varequal(sp->text, name))
439 result = strchr(sp->text, '=') + 1;
444 v = find_var(name, NULL, NULL);
445 if (v == NULL || v->flags & VUNSET ||
446 (!doall && (v->flags & VEXPORT) == 0))
448 return v->text + v->name_len + 1;
453 * Set up locale for a builtin (LANG/LC_* assignments).
463 for (lp = cmdenviron ; lp ; lp = lp->next) {
464 if (localevar(lp->text)) {
471 loc = bltinlookup("LC_ALL", 0);
474 setlocale(LC_ALL, loc);
479 locdef = bltinlookup("LANG", 0);
480 for (i = 0; locale_names[i] != NULL; i++) {
481 loc = bltinlookup(locale_names[i], 0);
485 setlocale(locale_categories[i], loc);
492 * Undo the effect of bltinlocaleset().
495 bltinunsetlocale(void)
500 for (lp = cmdenviron ; lp ; lp = lp->next) {
501 if (localevar(lp->text)) {
502 setlocale(LC_ALL, "");
511 * Update the localeisutf8 flag.
518 charset = nl_langinfo(CODESET);
519 localeisutf8 = !strcmp(charset, "UTF-8");
526 initial_localeisutf8 = localeisutf8;
530 * Generate a list of exported variables. This routine is used to construct
531 * the third argument to execve when executing a program.
543 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
544 for (vp = *vpp ; vp ; vp = vp->next)
545 if (vp->flags & VEXPORT)
548 ep = env = stalloc((nenv + 1) * sizeof *env);
549 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
550 for (vp = *vpp ; vp ; vp = vp->next)
551 if (vp->flags & VEXPORT)
560 var_compare(const void *a, const void *b)
562 const char *const *sa, *const *sb;
567 * This compares two var=value strings which creates a different
568 * order from what you would probably expect. POSIX is somewhat
569 * ambiguous on what should be sorted exactly.
571 return strcoll(*sa, *sb);
576 * Command to list all variables which are set. This is invoked from the
577 * set command when it is called without any options or operands.
581 showvarscmd(int argc __unused, char **argv __unused)
590 * POSIX requires us to sort the variables.
593 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
594 for (vp = *vpp; vp; vp = vp->next) {
595 if (!(vp->flags & VUNSET))
601 vars = ckmalloc(n * sizeof(*vars));
603 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
604 for (vp = *vpp; vp; vp = vp->next) {
605 if (!(vp->flags & VUNSET))
606 vars[i++] = vp->text;
610 qsort(vars, n, sizeof(*vars), var_compare);
611 for (i = 0; i < n; i++) {
613 * Skip improper variable names so the output remains usable as
616 if (!isassignment(vars[i]))
618 s = strchr(vars[i], '=');
620 outbin(vars[i], s - vars[i], out1);
633 * The export and readonly commands.
637 exportcmd(int argc, char **argv)
645 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
648 optreset = optind = 1;
651 while ((ch = getopt(argc, argv, "p")) != -1) {
658 error("unknown option: -%c", optopt);
664 if (values && argc != 0)
665 error("-p requires no arguments");
667 while ((name = *argv++) != NULL) {
668 if ((p = strchr(name, '=')) != NULL) {
671 vp = find_var(name, NULL, NULL);
674 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
675 change_env(vp->text, 1);
676 setlocale(LC_ALL, "");
682 setvar(name, p, flag);
685 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
686 for (vp = *vpp ; vp ; vp = vp->next) {
687 if (vp->flags & flag) {
690 * Skip improper variable names
691 * so the output remains usable
694 if (!isassignment(vp->text))
699 if (values && !(vp->flags & VUNSET)) {
701 vp->name_len + 1, out1);
705 outbin(vp->text, vp->name_len,
717 * The "local" command.
721 localcmd(int argc __unused, char **argv __unused)
726 error("Not in a function");
727 while ((name = *argptr++) != NULL) {
735 * Make a variable a local variable. When a variable is made local, it's
736 * value and flags are saved in a localvar structure. The saved values
737 * will be restored when the shell function returns. We handle the name
738 * "-" as a special case.
744 struct localvar *lvp;
749 lvp = ckmalloc(sizeof (struct localvar));
750 if (name[0] == '-' && name[1] == '\0') {
751 lvp->text = ckmalloc(sizeof optlist);
752 memcpy(lvp->text, optlist, sizeof optlist);
755 vp = find_var(name, &vpp, NULL);
757 if (strchr(name, '='))
758 setvareq(savestr(name), VSTRFIXED | VNOLOCAL);
760 setvar(name, NULL, VSTRFIXED | VNOLOCAL);
761 vp = *vpp; /* the new variable */
765 lvp->text = vp->text;
766 lvp->flags = vp->flags;
767 vp->flags |= VSTRFIXED|VTEXTFIXED;
768 if (name[vp->name_len] == '=')
769 setvareq(savestr(name), VNOLOCAL);
773 lvp->next = localvars;
780 * Called after a function returns.
786 struct localvar *lvp;
789 while ((lvp = localvars) != NULL) {
790 localvars = lvp->next;
792 if (vp == NULL) { /* $- saved */
793 memcpy(optlist, lvp->text, sizeof optlist);
796 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
799 if ((vp->flags & VTEXTFIXED) == 0)
801 vp->flags = lvp->flags;
802 vp->text = lvp->text;
810 setvarcmd(int argc, char **argv)
813 return unsetcmd(argc, argv);
815 setvar(argv[1], argv[2], 0);
817 error("too many arguments");
823 * The unset builtin command.
827 unsetcmd(int argc __unused, char **argv __unused)
835 while ((i = nextopt("vf")) != '\0') {
841 if (flg_func == 0 && flg_var == 0)
844 for (ap = argptr; *ap ; ap++) {
846 ret |= unsetfunc(*ap);
848 ret |= unsetvar(*ap);
855 * Unset the specified variable.
859 unsetvar(const char *s)
864 vp = find_var(s, &vpp, NULL);
867 if (vp->flags & VREADONLY)
870 if (vp->text[vp->name_len + 1] != '\0')
871 setvar(s, nullstr, 0);
872 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
873 change_env(__DECONST(char *, s), 0);
874 setlocale(LC_ALL, "");
877 vp->flags &= ~VEXPORT;
879 if ((vp->flags & VSTRFIXED) == 0) {
880 if ((vp->flags & VTEXTFIXED) == 0)
892 * Returns true if the two strings specify the same variable. The first
893 * variable name is terminated by '='; the second may be terminated by
894 * either '=' or '\0'.
898 varequal(const char *p, const char *q)
904 if (*p == '=' && *(q - 1) == '\0')
910 * Search for a variable.
911 * 'name' may be terminated by '=' or a NUL.
912 * vppp is set to the pointer to vp, or the list head if vp isn't found
913 * lenp is set to the number of characters in 'name'
917 find_var(const char *name, struct var ***vppp, int *lenp)
919 unsigned int hashval;
921 struct var *vp, **vpp;
922 const char *p = name;
925 while (*p && *p != '=')
926 hashval = 2 * hashval + (unsigned char)*p++;
931 vpp = &vartab[hashval % VTABSIZE];
935 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
936 if (vp->name_len != len)
938 if (memcmp(vp->text, name, len) != 0)