2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 5/4/95";
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
57 #include "nodes.h" /* for other headers */
58 #include "eval.h" /* defines cmdenviron */
70 #include "myhistedit.h"
81 void (*func)(const char *);
96 static struct var voptind;
99 struct localvar *localvars;
102 static const struct varinit varinit[] = {
104 { &vhistsize, VUNSET, "HISTSIZE=",
107 { &vifs, 0, "IFS= \t\n",
109 { &vmail, VUNSET, "MAIL=",
111 { &vmpath, VUNSET, "MAILPATH=",
113 { &vpath, 0, "PATH=" _PATH_DEFPATH,
116 * vps1 depends on uid
118 { &vps2, 0, "PS2=> ",
120 { &vps4, 0, "PS4=+ ",
123 { &vterm, VUNSET, "TERM=",
126 { &voptind, 0, "OPTIND=1",
128 { &vdisvfork, VUNSET, "SH_DISABLE_VFORK=",
134 static struct var *vartab[VTABSIZE];
136 static const char *const locale_names[7] = {
137 "LC_COLLATE", "LC_CTYPE", "LC_MONETARY",
138 "LC_NUMERIC", "LC_TIME", "LC_MESSAGES", NULL
140 static const int locale_categories[7] = {
141 LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME, LC_MESSAGES, 0
144 static int varequal(const char *, const char *);
145 static struct var *find_var(const char *, struct var ***, int *);
146 static int localevar(const char *);
147 static void setvareq_const(const char *s, int flags);
149 extern char **environ;
152 * This routine initializes the builtin variables and imports the environment.
153 * It is called when the shell is initialized.
160 const struct varinit *ip;
165 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
166 if (find_var(ip->text, &vpp, &vp->name_len) != NULL)
170 vp->text = __DECONST(char *, ip->text);
171 vp->flags = ip->flags | VSTRFIXED | VTEXTFIXED;
177 if (find_var("PS1", &vpp, &vps1.name_len) == NULL) {
180 vps1.text = __DECONST(char *, geteuid() ? "PS1=$ " : "PS1=# ");
181 vps1.flags = VSTRFIXED|VTEXTFIXED;
183 fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
184 setvarsafe("PPID", ppid, 0);
185 for (envp = environ ; *envp ; envp++) {
186 if (strchr(*envp, '=')) {
187 setvareq(*envp, VEXPORT|VTEXTFIXED);
190 setvareq_const("OPTIND=1", 0);
191 setvareq_const("IFS= \t\n", 0);
195 * Safe version of setvar, returns 1 on success 0 on failure.
199 setvarsafe(const char *name, const char *val, int flags)
201 struct jmploc jmploc;
202 struct jmploc *const savehandler = handler;
207 if (setjmp(jmploc.loc))
211 setvar(name, val, flags);
213 handler = savehandler;
219 * Set the value of a variable. The flags argument is stored with the
220 * flags of the variable. If val is NULL, the variable is unset.
224 setvar(const char *name, const char *val, int flags)
239 if (! is_in_name(*p)) {
240 if (*p == '\0' || *p == '=')
248 error("%.*s: bad variable name", (int)namelen, name);
249 len = namelen + 2; /* 2 is space for '=' and '\0' */
254 vallen = strlen(val);
258 nameeq = ckmalloc(len);
259 memcpy(nameeq, name, namelen);
260 nameeq[namelen] = '=';
262 memcpy(nameeq + namelen + 1, val, vallen + 1);
264 nameeq[namelen + 1] = '\0';
265 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))
290 * Sets/unsets an environment variable from a pointer that may actually be a
291 * pointer into environ where the string should not be manipulated.
294 change_env(const char *s, int set)
301 if ((eqp = strchr(ss, '=')) != NULL)
303 if (set && eqp != NULL)
304 (void) setenv(ss, eqp + 1, 1);
315 * Same as setvar except that the variable and value are passed in
316 * the first argument as name=value. Since the first argument will
317 * be actually stored in the table, it should not be a string that
322 setvareq(char *s, int flags)
324 struct var *vp, **vpp;
329 if (forcelocal && !(flags & (VNOSET | VNOLOCAL)))
331 vp = find_var(s, &vpp, &nlen);
333 if (vp->flags & VREADONLY) {
334 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
336 error("%.*s: is read only", vp->name_len, vp->text);
338 if (flags & VNOSET) {
339 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
345 if (vp->func && (flags & VNOFUNC) == 0)
346 (*vp->func)(s + vp->name_len + 1);
348 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
351 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
356 * We could roll this to a function, to handle it as
357 * a regular variable function callback, but why bother?
359 * Note: this assumes iflag is not set to 1 initially.
360 * As part of initvar(), this is called before arguments
363 if ((vp == &vmpath || (vp == &vmail && ! mpathset())) &&
366 if ((vp->flags & VEXPORT) && localevar(s)) {
368 (void) setlocale(LC_ALL, "");
375 if (flags & VNOSET) {
376 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
381 vp = ckmalloc(sizeof (*vp));
388 if ((vp->flags & VEXPORT) && localevar(s)) {
390 (void) setlocale(LC_ALL, "");
398 setvareq_const(const char *s, int flags)
400 setvareq(__DECONST(char *, s), flags | VTEXTFIXED);
405 * Process a linked list of variable assignments.
409 listsetvar(struct arglist *list, int flags)
414 for (i = 0; i < list->count; i++)
415 setvareq(savestr(list->args[i]), flags);
422 * Find the value of a variable. Returns NULL if not set.
426 lookupvar(const char *name)
430 v = find_var(name, NULL, NULL);
431 if (v == NULL || v->flags & VUNSET)
433 return v->text + v->name_len + 1;
439 * Search the environment of a builtin command. If the second argument
440 * is nonzero, return the value of a variable even if it hasn't been
445 bltinlookup(const char *name, int doall)
452 if (cmdenviron) for (i = 0; i < cmdenviron->count; i++) {
453 if (varequal(cmdenviron->args[i], name))
454 result = strchr(cmdenviron->args[i], '=') + 1;
459 v = find_var(name, NULL, NULL);
460 if (v == NULL || v->flags & VUNSET ||
461 (!doall && (v->flags & VEXPORT) == 0))
463 return v->text + v->name_len + 1;
468 * Set up locale for a builtin (LANG/LC_* assignments).
477 if (cmdenviron) for (i = 0; i < cmdenviron->count; i++) {
478 if (localevar(cmdenviron->args[i])) {
485 loc = bltinlookup("LC_ALL", 0);
488 setlocale(LC_ALL, loc);
493 locdef = bltinlookup("LANG", 0);
494 for (i = 0; locale_names[i] != NULL; i++) {
495 loc = bltinlookup(locale_names[i], 0);
499 setlocale(locale_categories[i], loc);
506 * Undo the effect of bltinlocaleset().
509 bltinunsetlocale(void)
514 if (cmdenviron) for (i = 0; i < cmdenviron->count; i++) {
515 if (localevar(cmdenviron->args[i])) {
516 setlocale(LC_ALL, "");
525 * Update the localeisutf8 flag.
532 charset = nl_langinfo(CODESET);
533 localeisutf8 = !strcmp(charset, "UTF-8");
540 initial_localeisutf8 = localeisutf8;
544 * Generate a list of exported variables. This routine is used to construct
545 * the third argument to execve when executing a program.
557 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
558 for (vp = *vpp ; vp ; vp = vp->next)
559 if (vp->flags & VEXPORT)
562 ep = env = stalloc((nenv + 1) * sizeof *env);
563 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
564 for (vp = *vpp ; vp ; vp = vp->next)
565 if (vp->flags & VEXPORT)
574 var_compare(const void *a, const void *b)
576 const char *const *sa, *const *sb;
581 * This compares two var=value strings which creates a different
582 * order from what you would probably expect. POSIX is somewhat
583 * ambiguous on what should be sorted exactly.
585 return strcoll(*sa, *sb);
590 * Command to list all variables which are set. This is invoked from the
591 * set command when it is called without any options or operands.
595 showvarscmd(int argc __unused, char **argv __unused)
604 * POSIX requires us to sort the variables.
607 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
608 for (vp = *vpp; vp; vp = vp->next) {
609 if (!(vp->flags & VUNSET))
615 vars = ckmalloc(n * sizeof(*vars));
617 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
618 for (vp = *vpp; vp; vp = vp->next) {
619 if (!(vp->flags & VUNSET))
620 vars[i++] = vp->text;
624 qsort(vars, n, sizeof(*vars), var_compare);
625 for (i = 0; i < n; i++) {
627 * Skip improper variable names so the output remains usable as
630 if (!isassignment(vars[i]))
632 s = strchr(vars[i], '=');
634 outbin(vars[i], s - vars[i], out1);
647 * The export and readonly commands.
651 exportcmd(int argc __unused, char **argv)
660 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
664 while ((ch = nextopt("p")) != '\0') {
672 if (values && *argptr != NULL)
673 error("-p requires no arguments");
674 if (*argptr != NULL) {
675 for (ap = argptr; (name = *ap) != NULL; ap++) {
676 if ((p = strchr(name, '=')) != NULL) {
679 vp = find_var(name, NULL, NULL);
682 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
683 change_env(vp->text, 1);
684 (void) setlocale(LC_ALL, "");
690 setvar(name, p, flag);
693 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
694 for (vp = *vpp ; vp ; vp = vp->next) {
695 if (vp->flags & flag) {
698 * Skip improper variable names
699 * so the output remains usable
702 if (!isassignment(vp->text))
707 if (values && !(vp->flags & VUNSET)) {
709 vp->name_len + 1, out1);
713 outbin(vp->text, vp->name_len,
725 * The "local" command.
729 localcmd(int argc __unused, char **argv __unused)
735 error("Not in a function");
736 while ((name = *argptr++) != NULL) {
744 * Make a variable a local variable. When a variable is made local, it's
745 * value and flags are saved in a localvar structure. The saved values
746 * will be restored when the shell function returns. We handle the name
747 * "-" as a special case.
753 struct localvar *lvp;
758 lvp = ckmalloc(sizeof (struct localvar));
759 if (name[0] == '-' && name[1] == '\0') {
760 lvp->text = ckmalloc(sizeof optval);
761 memcpy(lvp->text, optval, sizeof optval);
764 vp = find_var(name, &vpp, NULL);
766 if (strchr(name, '='))
767 setvareq(savestr(name), VSTRFIXED | VNOLOCAL);
769 setvar(name, NULL, VSTRFIXED | VNOLOCAL);
770 vp = *vpp; /* the new variable */
774 lvp->text = vp->text;
775 lvp->flags = vp->flags;
776 vp->flags |= VSTRFIXED|VTEXTFIXED;
777 if (name[vp->name_len] == '=')
778 setvareq(savestr(name), VNOLOCAL);
782 lvp->next = localvars;
789 * Called after a function returns.
795 struct localvar *lvp;
800 while ((lvp = localvars) != NULL) {
801 localvars = lvp->next;
803 if (vp == NULL) { /* $- saved */
804 memcpy(optval, lvp->text, sizeof optval);
807 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
808 vp->flags &= ~VREADONLY;
809 (void)unsetvar(vp->text);
811 islocalevar = (vp->flags | lvp->flags) & VEXPORT &&
812 localevar(lvp->text);
813 if ((vp->flags & VTEXTFIXED) == 0)
815 vp->flags = lvp->flags;
816 vp->text = lvp->text;
818 (*vp->func)(vp->text + vp->name_len + 1);
820 change_env(vp->text, vp->flags & VEXPORT &&
821 (vp->flags & VUNSET) == 0);
822 setlocale(LC_ALL, "");
833 setvarcmd(int argc, char **argv)
836 return unsetcmd(argc, argv);
838 setvar(argv[1], argv[2], 0);
840 error("too many arguments");
846 * The unset builtin command.
850 unsetcmd(int argc __unused, char **argv __unused)
858 while ((i = nextopt("vf")) != '\0') {
864 if (flg_func == 0 && flg_var == 0)
868 for (ap = argptr; *ap ; ap++) {
870 ret |= unsetfunc(*ap);
872 ret |= unsetvar(*ap);
880 * Unset the specified variable.
881 * Called with interrupts off.
885 unsetvar(const char *s)
890 vp = find_var(s, &vpp, NULL);
893 if (vp->flags & VREADONLY)
895 if (vp->text[vp->name_len + 1] != '\0')
897 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
899 setlocale(LC_ALL, "");
902 vp->flags &= ~VEXPORT;
904 if ((vp->flags & VSTRFIXED) == 0) {
905 if ((vp->flags & VTEXTFIXED) == 0)
916 * Returns true if the two strings specify the same variable. The first
917 * variable name is terminated by '='; the second may be terminated by
918 * either '=' or '\0'.
922 varequal(const char *p, const char *q)
928 if (*p == '=' && *(q - 1) == '\0')
934 * Search for a variable.
935 * 'name' may be terminated by '=' or a NUL.
936 * vppp is set to the pointer to vp, or the list head if vp isn't found
937 * lenp is set to the number of characters in 'name'
941 find_var(const char *name, struct var ***vppp, int *lenp)
943 unsigned int hashval;
945 struct var *vp, **vpp;
946 const char *p = name;
949 while (*p && *p != '=')
950 hashval = 2 * hashval + (unsigned char)*p++;
955 vpp = &vartab[hashval % VTABSIZE];
959 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
960 if (vp->name_len != len)
962 if (memcmp(vp->text, name, len) != 0)