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.61 2011/06/12 23:06:04 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;
98 static const struct varinit varinit[] = {
100 { &vhistsize, VUNSET, "HISTSIZE=",
103 { &vifs, 0, "IFS= \t\n",
105 { &vmail, VUNSET, "MAIL=",
107 { &vmpath, VUNSET, "MAILPATH=",
109 { &vpath, 0, "PATH=" _PATH_DEFPATH,
111 { &vppid, VUNSET, "PPID=",
114 * vps1 depends on uid
116 { &vps2, 0, "PS2=> ",
118 { &vps4, 0, "PS4=+ ",
121 { &vterm, VUNSET, "TERM=",
124 { &voptind, 0, "OPTIND=1",
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 *);
145 * Initialize the variable symbol tables and import the environment.
150 MKINIT char **environ;
155 for (envp = environ ; *envp ; envp++) {
156 if (strchr(*envp, '=')) {
157 setvareq(*envp, VEXPORT|VTEXTFIXED);
165 * This routine initializes the builtin variables. It is called when the
166 * shell is initialized.
173 const struct varinit *ip;
177 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
178 if (find_var(ip->text, &vpp, &vp->name_len) != NULL)
182 vp->text = __DECONST(char *, ip->text);
183 vp->flags = ip->flags | VSTRFIXED | VTEXTFIXED;
189 if (find_var("PS1", &vpp, &vps1.name_len) == NULL) {
192 vps1.text = __DECONST(char *, geteuid() ? "PS1=$ " : "PS1=# ");
193 vps1.flags = VSTRFIXED|VTEXTFIXED;
195 if ((vppid.flags & VEXPORT) == 0) {
196 fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
197 setvarsafe("PPID", ppid, 0);
202 * Safe version of setvar, returns 1 on success 0 on failure.
206 setvarsafe(const char *name, const char *val, int flags)
208 struct jmploc jmploc;
209 struct jmploc *const savehandler = handler;
214 if (setjmp(jmploc.loc))
218 setvar(name, val, flags);
220 handler = savehandler;
226 * Set the value of a variable. The flags argument is stored with the
227 * flags of the variable. If val is NULL, the variable is unset.
231 setvar(const char *name, const char *val, int flags)
245 if (!is_in_name(*p)) {
246 if (*p == '\0' || *p == '=')
254 error("%.*s: bad variable name", namelen, name);
255 len = namelen + 2; /* 2 is space for '=' and '\0' */
261 nameeq = ckmalloc(len);
262 memcpy(nameeq, name, namelen);
263 nameeq[namelen] = '=';
265 scopy(val, nameeq + namelen + 1);
267 nameeq[namelen + 1] = '\0';
268 setvareq(nameeq, flags);
272 localevar(const char *s)
274 const char *const *ss;
278 if (varequal(s + 1, "ANG"))
280 if (strncmp(s + 1, "C_", 2) != 0)
282 if (varequal(s + 3, "ALL"))
284 for (ss = locale_names; *ss ; ss++)
285 if (varequal(s + 3, *ss + 3))
291 * Sets/unsets an environment variable from a pointer that may actually be a
292 * pointer into environ where the string should not be manipulated.
295 change_env(const char *s, int set)
301 if ((eqp = strchr(ss, '=')) != NULL)
303 if (set && eqp != NULL) {
304 if (setenv(ss, eqp + 1, 1) != 0)
305 error("setenv: cannot set %s=%s", ss, eqp + 1);
313 * Same as setvar except that the variable and value are passed in
314 * the first argument as name=value. Since the first argument will
315 * be actually stored in the table, it should not be a string that
320 setvareq(char *s, int flags)
322 struct var *vp, **vpp;
327 if (forcelocal && !(flags & (VNOSET | VNOLOCAL)))
329 vp = find_var(s, &vpp, &nlen);
331 if (vp->flags & VREADONLY)
332 error("%.*s: is read only", vp->name_len, s);
337 if (vp->func && (flags & VNOFUNC) == 0)
338 (*vp->func)(s + vp->name_len + 1);
340 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
343 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
348 * We could roll this to a function, to handle it as
349 * a regular variable function callback, but why bother?
351 * Note: this assumes iflag is not set to 1 initially.
352 * As part of init(), this is called before arguments
355 if ((vp == &vmpath || (vp == &vmail && ! mpathset())) &&
358 if ((vp->flags & VEXPORT) && localevar(s)) {
360 setlocale(LC_ALL, "");
369 vp = ckmalloc(sizeof (*vp));
377 if ((vp->flags & VEXPORT) && localevar(s)) {
379 setlocale(LC_ALL, "");
388 * Process a linked list of variable assignments.
392 listsetvar(struct strlist *list, int flags)
397 for (lp = list ; lp ; lp = lp->next) {
398 setvareq(savestr(lp->text), flags);
406 * Find the value of a variable. Returns NULL if not set.
410 lookupvar(const char *name)
414 v = find_var(name, NULL, NULL);
415 if (v == NULL || v->flags & VUNSET)
417 return v->text + v->name_len + 1;
423 * Search the environment of a builtin command. If the second argument
424 * is nonzero, return the value of a variable even if it hasn't been
429 bltinlookup(const char *name, int doall)
436 for (sp = cmdenviron ; sp ; sp = sp->next) {
437 if (varequal(sp->text, name))
438 result = strchr(sp->text, '=') + 1;
443 v = find_var(name, NULL, NULL);
444 if (v == NULL || v->flags & VUNSET ||
445 (!doall && (v->flags & VEXPORT) == 0))
447 return v->text + v->name_len + 1;
452 * Set up locale for a builtin (LANG/LC_* assignments).
462 for (lp = cmdenviron ; lp ; lp = lp->next) {
463 if (localevar(lp->text)) {
470 loc = bltinlookup("LC_ALL", 0);
473 setlocale(LC_ALL, loc);
478 locdef = bltinlookup("LANG", 0);
479 for (i = 0; locale_names[i] != NULL; i++) {
480 loc = bltinlookup(locale_names[i], 0);
484 setlocale(locale_categories[i], loc);
491 * Undo the effect of bltinlocaleset().
494 bltinunsetlocale(void)
499 for (lp = cmdenviron ; lp ; lp = lp->next) {
500 if (localevar(lp->text)) {
501 setlocale(LC_ALL, "");
510 * Update the localeisutf8 flag.
517 charset = nl_langinfo(CODESET);
518 localeisutf8 = !strcmp(charset, "UTF-8");
525 initial_localeisutf8 = localeisutf8;
529 * Generate a list of exported variables. This routine is used to construct
530 * the third argument to execve when executing a program.
542 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
543 for (vp = *vpp ; vp ; vp = vp->next)
544 if (vp->flags & VEXPORT)
547 ep = env = stalloc((nenv + 1) * sizeof *env);
548 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
549 for (vp = *vpp ; vp ; vp = vp->next)
550 if (vp->flags & VEXPORT)
559 var_compare(const void *a, const void *b)
561 const char *const *sa, *const *sb;
566 * This compares two var=value strings which creates a different
567 * order from what you would probably expect. POSIX is somewhat
568 * ambiguous on what should be sorted exactly.
570 return strcoll(*sa, *sb);
575 * Command to list all variables which are set. This is invoked from the
576 * set command when it is called without any options or operands.
580 showvarscmd(int argc __unused, char **argv __unused)
589 * POSIX requires us to sort the variables.
592 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
593 for (vp = *vpp; vp; vp = vp->next) {
594 if (!(vp->flags & VUNSET))
600 vars = ckmalloc(n * sizeof(*vars));
602 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
603 for (vp = *vpp; vp; vp = vp->next) {
604 if (!(vp->flags & VUNSET))
605 vars[i++] = vp->text;
609 qsort(vars, n, sizeof(*vars), var_compare);
610 for (i = 0; i < n; i++) {
611 s = strchr(vars[i], '=');
613 outbin(vars[i], s - vars[i], out1);
626 * The export and readonly commands.
630 exportcmd(int argc, char **argv)
638 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
641 optreset = optind = 1;
644 while ((ch = getopt(argc, argv, "p")) != -1) {
651 error("unknown option: -%c", optopt);
657 if (values && argc != 0)
658 error("-p requires no arguments");
660 while ((name = *argv++) != NULL) {
661 if ((p = strchr(name, '=')) != NULL) {
664 vp = find_var(name, NULL, NULL);
667 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
668 change_env(vp->text, 1);
669 setlocale(LC_ALL, "");
675 setvar(name, p, flag);
678 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
679 for (vp = *vpp ; vp ; vp = vp->next) {
680 if (vp->flags & flag) {
685 if (values && !(vp->flags & VUNSET)) {
687 vp->name_len + 1, out1);
691 outbin(vp->text, vp->name_len,
703 * The "local" command.
707 localcmd(int argc __unused, char **argv __unused)
712 error("Not in a function");
713 while ((name = *argptr++) != NULL) {
721 * Make a variable a local variable. When a variable is made local, it's
722 * value and flags are saved in a localvar structure. The saved values
723 * will be restored when the shell function returns. We handle the name
724 * "-" as a special case.
730 struct localvar *lvp;
735 lvp = ckmalloc(sizeof (struct localvar));
736 if (name[0] == '-' && name[1] == '\0') {
737 lvp->text = ckmalloc(sizeof optlist);
738 memcpy(lvp->text, optlist, sizeof optlist);
741 vp = find_var(name, &vpp, NULL);
743 if (strchr(name, '='))
744 setvareq(savestr(name), VSTRFIXED | VNOLOCAL);
746 setvar(name, NULL, VSTRFIXED | VNOLOCAL);
747 vp = *vpp; /* the new variable */
751 lvp->text = vp->text;
752 lvp->flags = vp->flags;
753 vp->flags |= VSTRFIXED|VTEXTFIXED;
754 if (name[vp->name_len] == '=')
755 setvareq(savestr(name), VNOLOCAL);
759 lvp->next = localvars;
766 * Called after a function returns.
772 struct localvar *lvp;
775 while ((lvp = localvars) != NULL) {
776 localvars = lvp->next;
778 if (vp == NULL) { /* $- saved */
779 memcpy(optlist, lvp->text, sizeof optlist);
782 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
785 if ((vp->flags & VTEXTFIXED) == 0)
787 vp->flags = lvp->flags;
788 vp->text = lvp->text;
796 setvarcmd(int argc, char **argv)
799 return unsetcmd(argc, argv);
801 setvar(argv[1], argv[2], 0);
803 error("too many arguments");
809 * The unset builtin command.
813 unsetcmd(int argc __unused, char **argv __unused)
821 while ((i = nextopt("vf")) != '\0') {
827 if (flg_func == 0 && flg_var == 0)
830 for (ap = argptr; *ap ; ap++) {
832 ret |= unsetfunc(*ap);
834 ret |= unsetvar(*ap);
841 * Unset the specified variable.
845 unsetvar(const char *s)
850 vp = find_var(s, &vpp, NULL);
853 if (vp->flags & VREADONLY)
856 if (vp->text[vp->name_len + 1] != '\0')
857 setvar(s, nullstr, 0);
858 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
859 change_env(__DECONST(char *, s), 0);
860 setlocale(LC_ALL, "");
863 vp->flags &= ~VEXPORT;
865 if ((vp->flags & VSTRFIXED) == 0) {
866 if ((vp->flags & VTEXTFIXED) == 0)
878 * Returns true if the two strings specify the same variable. The first
879 * variable name is terminated by '='; the second may be terminated by
880 * either '=' or '\0'.
884 varequal(const char *p, const char *q)
890 if (*p == '=' && *(q - 1) == '\0')
896 * Search for a variable.
897 * 'name' may be terminated by '=' or a NUL.
898 * vppp is set to the pointer to vp, or the list head if vp isn't found
899 * lenp is set to the number of characters in 'name'
903 find_var(const char *name, struct var ***vppp, int *lenp)
905 unsigned int hashval;
907 struct var *vp, **vpp;
908 const char *p = name;
911 while (*p && *p != '=')
912 hashval = 2 * hashval + (unsigned char)*p++;
917 vpp = &vartab[hashval % VTABSIZE];
921 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
922 if (vp->name_len != len)
924 if (memcmp(vp->text, name, len) != 0)