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.65 2012/02/04 23:29:07 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;
100 static const struct varinit varinit[] = {
102 { &vhistsize, VUNSET, "HISTSIZE=",
105 { &vifs, 0, "IFS= \t\n",
107 { &vmail, VUNSET, "MAIL=",
109 { &vmpath, VUNSET, "MAILPATH=",
111 { &vpath, 0, "PATH=" _PATH_DEFPATH,
113 { &vppid, VUNSET, "PPID=",
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 *);
149 * Initialize the variable symbol tables and import the environment.
154 MKINIT char **environ;
159 for (envp = environ ; *envp ; envp++) {
160 if (strchr(*envp, '=')) {
161 setvareq(*envp, VEXPORT|VTEXTFIXED);
169 * This routine initializes the builtin variables. It is called when the
170 * shell is initialized.
177 const struct varinit *ip;
181 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
182 if (find_var(ip->text, &vpp, &vp->name_len) != NULL)
186 vp->text = __DECONST(char *, ip->text);
187 vp->flags = ip->flags | VSTRFIXED | VTEXTFIXED;
193 if (find_var("PS1", &vpp, &vps1.name_len) == NULL) {
196 vps1.text = __DECONST(char *, geteuid() ? "PS1=$ " : "PS1=# ");
197 vps1.flags = VSTRFIXED|VTEXTFIXED;
199 if ((vppid.flags & VEXPORT) == 0) {
200 fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
201 setvarsafe("PPID", ppid, 0);
206 * Safe version of setvar, returns 1 on success 0 on failure.
210 setvarsafe(const char *name, const char *val, int flags)
212 struct jmploc jmploc;
213 struct jmploc *const savehandler = handler;
218 if (setjmp(jmploc.loc))
222 setvar(name, val, flags);
224 handler = savehandler;
230 * Set the value of a variable. The flags argument is stored with the
231 * flags of the variable. If val is NULL, the variable is unset.
235 setvar(const char *name, const char *val, int flags)
249 if (!is_in_name(*p)) {
250 if (*p == '\0' || *p == '=')
258 error("%.*s: bad variable name", namelen, name);
259 len = namelen + 2; /* 2 is space for '=' and '\0' */
265 nameeq = ckmalloc(len);
266 memcpy(nameeq, name, namelen);
267 nameeq[namelen] = '=';
269 scopy(val, nameeq + namelen + 1);
271 nameeq[namelen + 1] = '\0';
272 setvareq(nameeq, flags);
276 localevar(const char *s)
278 const char *const *ss;
282 if (varequal(s + 1, "ANG"))
284 if (strncmp(s + 1, "C_", 2) != 0)
286 if (varequal(s + 3, "ALL"))
288 for (ss = locale_names; *ss ; ss++)
289 if (varequal(s + 3, *ss + 3))
295 * Sets/unsets an environment variable from a pointer that may actually be a
296 * pointer into environ where the string should not be manipulated.
299 change_env(const char *s, int set)
305 if ((eqp = strchr(ss, '=')) != NULL)
307 if (set && eqp != NULL) {
308 if (setenv(ss, eqp + 1, 1) != 0)
309 error("setenv: cannot set %s=%s", ss, eqp + 1);
317 * Same as setvar except that the variable and value are passed in
318 * the first argument as name=value. Since the first argument will
319 * be actually stored in the table, it should not be a string that
324 setvareq(char *s, int flags)
326 struct var *vp, **vpp;
331 if (forcelocal && !(flags & (VNOSET | VNOLOCAL)))
333 vp = find_var(s, &vpp, &nlen);
335 if (vp->flags & VREADONLY)
336 error("%.*s: is read only", vp->name_len, s);
341 if (vp->func && (flags & VNOFUNC) == 0)
342 (*vp->func)(s + vp->name_len + 1);
344 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
347 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
352 * We could roll this to a function, to handle it as
353 * a regular variable function callback, but why bother?
355 * Note: this assumes iflag is not set to 1 initially.
356 * As part of init(), this is called before arguments
359 if ((vp == &vmpath || (vp == &vmail && ! mpathset())) &&
362 if ((vp->flags & VEXPORT) && localevar(s)) {
364 setlocale(LC_ALL, "");
373 vp = ckmalloc(sizeof (*vp));
381 if ((vp->flags & VEXPORT) && localevar(s)) {
383 setlocale(LC_ALL, "");
392 * Process a linked list of variable assignments.
396 listsetvar(struct strlist *list, int flags)
401 for (lp = list ; lp ; lp = lp->next) {
402 setvareq(savestr(lp->text), flags);
410 * Find the value of a variable. Returns NULL if not set.
414 lookupvar(const char *name)
418 v = find_var(name, NULL, NULL);
419 if (v == NULL || v->flags & VUNSET)
421 return v->text + v->name_len + 1;
427 * Search the environment of a builtin command. If the second argument
428 * is nonzero, return the value of a variable even if it hasn't been
433 bltinlookup(const char *name, int doall)
440 for (sp = cmdenviron ; sp ; sp = sp->next) {
441 if (varequal(sp->text, name))
442 result = strchr(sp->text, '=') + 1;
447 v = find_var(name, NULL, NULL);
448 if (v == NULL || v->flags & VUNSET ||
449 (!doall && (v->flags & VEXPORT) == 0))
451 return v->text + v->name_len + 1;
456 * Set up locale for a builtin (LANG/LC_* assignments).
466 for (lp = cmdenviron ; lp ; lp = lp->next) {
467 if (localevar(lp->text)) {
474 loc = bltinlookup("LC_ALL", 0);
477 setlocale(LC_ALL, loc);
482 locdef = bltinlookup("LANG", 0);
483 for (i = 0; locale_names[i] != NULL; i++) {
484 loc = bltinlookup(locale_names[i], 0);
488 setlocale(locale_categories[i], loc);
495 * Undo the effect of bltinlocaleset().
498 bltinunsetlocale(void)
503 for (lp = cmdenviron ; lp ; lp = lp->next) {
504 if (localevar(lp->text)) {
505 setlocale(LC_ALL, "");
514 * Update the localeisutf8 flag.
521 charset = nl_langinfo(CODESET);
522 localeisutf8 = !strcmp(charset, "UTF-8");
529 initial_localeisutf8 = localeisutf8;
533 * Generate a list of exported variables. This routine is used to construct
534 * the third argument to execve when executing a program.
546 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
547 for (vp = *vpp ; vp ; vp = vp->next)
548 if (vp->flags & VEXPORT)
551 ep = env = stalloc((nenv + 1) * sizeof *env);
552 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
553 for (vp = *vpp ; vp ; vp = vp->next)
554 if (vp->flags & VEXPORT)
563 var_compare(const void *a, const void *b)
565 const char *const *sa, *const *sb;
570 * This compares two var=value strings which creates a different
571 * order from what you would probably expect. POSIX is somewhat
572 * ambiguous on what should be sorted exactly.
574 return strcoll(*sa, *sb);
579 * Command to list all variables which are set. This is invoked from the
580 * set command when it is called without any options or operands.
584 showvarscmd(int argc __unused, char **argv __unused)
593 * POSIX requires us to sort the variables.
596 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
597 for (vp = *vpp; vp; vp = vp->next) {
598 if (!(vp->flags & VUNSET))
604 vars = ckmalloc(n * sizeof(*vars));
606 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
607 for (vp = *vpp; vp; vp = vp->next) {
608 if (!(vp->flags & VUNSET))
609 vars[i++] = vp->text;
613 qsort(vars, n, sizeof(*vars), var_compare);
614 for (i = 0; i < n; i++) {
616 * Skip improper variable names so the output remains usable as
619 if (!isassignment(vars[i]))
621 s = strchr(vars[i], '=');
623 outbin(vars[i], s - vars[i], out1);
636 * The export and readonly commands.
640 exportcmd(int argc, char **argv)
648 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
651 optreset = optind = 1;
654 while ((ch = getopt(argc, argv, "p")) != -1) {
661 error("unknown option: -%c", optopt);
667 if (values && argc != 0)
668 error("-p requires no arguments");
670 while ((name = *argv++) != NULL) {
671 if ((p = strchr(name, '=')) != NULL) {
674 vp = find_var(name, NULL, NULL);
677 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
678 change_env(vp->text, 1);
679 setlocale(LC_ALL, "");
685 setvar(name, p, flag);
688 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
689 for (vp = *vpp ; vp ; vp = vp->next) {
690 if (vp->flags & flag) {
693 * Skip improper variable names
694 * so the output remains usable
697 if (!isassignment(vp->text))
702 if (values && !(vp->flags & VUNSET)) {
704 vp->name_len + 1, out1);
708 outbin(vp->text, vp->name_len,
720 * The "local" command.
724 localcmd(int argc __unused, char **argv __unused)
729 error("Not in a function");
730 while ((name = *argptr++) != NULL) {
738 * Make a variable a local variable. When a variable is made local, it's
739 * value and flags are saved in a localvar structure. The saved values
740 * will be restored when the shell function returns. We handle the name
741 * "-" as a special case.
747 struct localvar *lvp;
752 lvp = ckmalloc(sizeof (struct localvar));
753 if (name[0] == '-' && name[1] == '\0') {
754 lvp->text = ckmalloc(sizeof optlist);
755 memcpy(lvp->text, optlist, sizeof optlist);
758 vp = find_var(name, &vpp, NULL);
760 if (strchr(name, '='))
761 setvareq(savestr(name), VSTRFIXED | VNOLOCAL);
763 setvar(name, NULL, VSTRFIXED | VNOLOCAL);
764 vp = *vpp; /* the new variable */
768 lvp->text = vp->text;
769 lvp->flags = vp->flags;
770 vp->flags |= VSTRFIXED|VTEXTFIXED;
771 if (name[vp->name_len] == '=')
772 setvareq(savestr(name), VNOLOCAL);
776 lvp->next = localvars;
783 * Called after a function returns.
789 struct localvar *lvp;
792 while ((lvp = localvars) != NULL) {
793 localvars = lvp->next;
795 if (vp == NULL) { /* $- saved */
796 memcpy(optlist, lvp->text, sizeof optlist);
799 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
802 if ((vp->flags & VTEXTFIXED) == 0)
804 vp->flags = lvp->flags;
805 vp->text = lvp->text;
813 setvarcmd(int argc, char **argv)
816 return unsetcmd(argc, argv);
818 setvar(argv[1], argv[2], 0);
820 error("too many arguments");
826 * The unset builtin command.
830 unsetcmd(int argc __unused, char **argv __unused)
838 while ((i = nextopt("vf")) != '\0') {
844 if (flg_func == 0 && flg_var == 0)
847 for (ap = argptr; *ap ; ap++) {
849 ret |= unsetfunc(*ap);
851 ret |= unsetvar(*ap);
858 * Unset the specified variable.
862 unsetvar(const char *s)
867 vp = find_var(s, &vpp, NULL);
870 if (vp->flags & VREADONLY)
873 if (vp->text[vp->name_len + 1] != '\0')
874 setvar(s, nullstr, 0);
875 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
876 change_env(__DECONST(char *, s), 0);
877 setlocale(LC_ALL, "");
880 vp->flags &= ~VEXPORT;
882 if ((vp->flags & VSTRFIXED) == 0) {
883 if ((vp->flags & VTEXTFIXED) == 0)
895 * Returns true if the two strings specify the same variable. The first
896 * variable name is terminated by '='; the second may be terminated by
897 * either '=' or '\0'.
901 varequal(const char *p, const char *q)
907 if (*p == '=' && *(q - 1) == '\0')
913 * Search for a variable.
914 * 'name' may be terminated by '=' or a NUL.
915 * vppp is set to the pointer to vp, or the list head if vp isn't found
916 * lenp is set to the number of characters in 'name'
920 find_var(const char *name, struct var ***vppp, int *lenp)
922 unsigned int hashval;
924 struct var *vp, **vpp;
925 const char *p = name;
928 while (*p && *p != '=')
929 hashval = 2 * hashval + (unsigned char)*p++;
934 vpp = &vartab[hashval % VTABSIZE];
938 for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
939 if (vp->name_len != len)
941 if (memcmp(vp->text, name, len) != 0)