builtin: Process multi-byte characters in read(1)
[dash.git] / src / var.c
blobeb4075f9828c4f014187e7d7a9c9fdb6b8144aa3
1 /*-
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1997-2005
5 * Herbert Xu <herbert@gondor.apana.org.au>. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Kenneth Almquist.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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
32 * SUCH DAMAGE.
35 #include <unistd.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #ifdef HAVE_PATHS_H
39 #include <paths.h>
40 #endif
43 * Shell variables.
46 #include "shell.h"
47 #include "output.h"
48 #include "expand.h"
49 #include "nodes.h" /* for other headers */
50 #include "exec.h"
51 #include "syntax.h"
52 #include "options.h"
53 #include "mail.h"
54 #include "var.h"
55 #include "memalloc.h"
56 #include "error.h"
57 #include "mystring.h"
58 #include "parser.h"
59 #include "show.h"
60 #ifndef SMALL
61 #include "myhistedit.h"
62 #endif
63 #include "system.h"
66 #define VTABSIZE 39
69 struct localvar_list {
70 struct localvar_list *next;
71 struct localvar *lv;
74 MKINIT struct localvar_list *localvar_stack;
76 const char defpathvar[] =
77 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
78 char defifsvar[] = "IFS= \t\n";
79 MKINIT char defoptindvar[] = "OPTIND=1";
81 int lineno;
82 char linenovar[sizeof("LINENO=")+sizeof(int)*CHAR_BIT/3+1] = "LINENO=";
84 /* Some macros in var.h depend on the order, add new variables to the end. */
85 struct var varinit[] = {
86 #if ATTY
87 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "ATTY\0", 0 },
88 #endif
89 { 0, VSTRFIXED|VTEXTFIXED, defifsvar, changeifs },
90 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
91 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
92 { 0, VSTRFIXED|VTEXTFIXED, defpathvar, changepath },
93 { 0, VSTRFIXED|VTEXTFIXED, "PS1=$ ", 0 },
94 { 0, VSTRFIXED|VTEXTFIXED, "PS2=> ", 0 },
95 { 0, VSTRFIXED|VTEXTFIXED, "PS4=+ ", 0 },
96 { 0, VSTRFIXED|VTEXTFIXED|VNOFUNC, defoptindvar, getoptsreset },
97 #ifdef WITH_LINENO
98 { 0, VSTRFIXED|VTEXTFIXED, linenovar, 0 },
99 #endif
100 #ifndef SMALL
101 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "TERM\0", 0 },
102 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "HISTSIZE\0", sethistsize },
103 #endif
106 STATIC struct var *vartab[VTABSIZE];
108 STATIC struct var **hashvar(const char *);
109 STATIC int vpcmp(const void *, const void *);
110 STATIC struct var **findvar(const char *);
113 * Initialize the varable symbol tables and import the environment
116 #ifdef mkinit
117 INCLUDE <unistd.h>
118 INCLUDE <sys/types.h>
119 INCLUDE <sys/stat.h>
120 INCLUDE "cd.h"
121 INCLUDE "output.h"
122 INCLUDE "var.h"
123 MKINIT char **environ;
124 INIT {
125 char **envp;
126 static char ppid[32] = "PPID=";
127 const char *p;
128 struct stat64 st1, st2;
130 initvar();
131 for (envp = environ ; *envp ; envp++) {
132 p = endofname(*envp);
133 if (p != *envp && *p == '=') {
134 setvareq(*envp, VEXPORT|VTEXTFIXED);
138 setvareq(defifsvar, VTEXTFIXED);
139 setvareq(defoptindvar, VTEXTFIXED);
141 fmtstr(ppid + 5, sizeof(ppid) - 5, "%ld", (long) getppid());
142 setvareq(ppid, VTEXTFIXED);
144 p = lookupvar("PWD");
145 if (p)
146 if (*p != '/' || stat64(p, &st1) || stat64(dotdir, &st2) ||
147 st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
148 p = 0;
149 setpwd(p, 0);
152 RESET {
153 unwindlocalvars(0);
155 #endif
157 static char *varnull(const char *s)
159 return (strchr(s, '=') ?: nullstr - 1) + 1;
163 * This routine initializes the builtin variables. It is called when the
164 * shell is initialized.
167 void
168 initvar(void)
170 struct var *vp;
171 struct var *end;
172 struct var **vpp;
174 vp = varinit;
175 end = vp + sizeof(varinit) / sizeof(varinit[0]);
176 do {
177 vpp = hashvar(vp->text);
178 vp->next = *vpp;
179 *vpp = vp;
180 } while (++vp < end);
182 * PS1 depends on uid
184 if (!geteuid())
185 vps1.text = "PS1=# ";
189 * Set the value of a variable. The flags argument is ored with the
190 * flags of the variable. If val is NULL, the variable is unset.
193 struct var *setvar(const char *name, const char *val, int flags)
195 char *p, *q;
196 size_t namelen;
197 char *nameeq;
198 size_t vallen;
199 struct var *vp;
201 q = endofname(name);
202 p = strchrnul(q, '=');
203 namelen = p - name;
204 if (!namelen || p != q)
205 sh_error("%.*s: bad variable name", namelen, name);
206 vallen = 0;
207 if (val == NULL) {
208 flags |= VUNSET;
209 } else {
210 vallen = strlen(val);
212 INTOFF;
213 p = mempcpy(nameeq = ckmalloc(namelen + vallen + 2), name, namelen);
214 if (val) {
215 *p++ = '=';
216 p = mempcpy(p, val, vallen);
218 *p = '\0';
219 vp = setvareq(nameeq, flags | VNOSAVE);
220 INTON;
222 return vp;
226 * Set the given integer as the value of a variable. The flags argument is
227 * ored with the flags of the variable.
230 intmax_t setvarint(const char *name, intmax_t val, int flags)
232 int len = max_int_length(sizeof(val));
233 char buf[len];
235 fmtstr(buf, len, "%" PRIdMAX, val);
236 setvar(name, buf, flags);
237 return val;
243 * Same as setvar except that the variable and value are passed in
244 * the first argument as name=value. Since the first argument will
245 * be actually stored in the table, it should not be a string that
246 * will go away.
247 * Called with interrupts off.
250 struct var *setvareq(char *s, int flags)
252 struct var *vp, **vpp;
254 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
255 vpp = findvar(s);
256 vp = *vpp;
257 if (vp) {
258 unsigned bits;
260 if (vp->flags & VREADONLY) {
261 const char *n;
263 if (flags & VNOSAVE)
264 free(s);
265 n = vp->text;
266 sh_error("%.*s: is read only", strchrnul(n, '=') - n,
270 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
271 ckfree(vp->text);
273 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) != VUNSET)
274 bits = ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
275 else if ((vp->flags & VSTRFIXED))
276 bits = VSTRFIXED;
277 else {
278 *vpp = vp->next;
279 ckfree(vp);
280 out_free:
281 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
282 ckfree(s);
283 goto out;
286 flags |= vp->flags & bits;
287 } else {
288 if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
289 goto out_free;
290 /* not found */
291 vp = ckmalloc(sizeof (*vp));
292 vp->next = *vpp;
293 vp->func = NULL;
294 *vpp = vp;
296 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
297 s = savestr(s);
298 vp->text = s;
299 vp->flags = flags;
301 if (vp->func && (flags & VNOFUNC) == 0)
302 (*vp->func)(varnull(s));
304 out:
305 return vp;
309 * Find the value of a variable. Returns NULL if not set.
312 char *
313 lookupvar(const char *name)
315 struct var *v;
317 if ((v = *findvar(name)) && !(v->flags & VUNSET)) {
318 #ifdef WITH_LINENO
319 if (v == &vlineno && v->text == linenovar) {
320 fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
322 #endif
323 return strchrnul(v->text, '=') + 1;
325 return NULL;
328 intmax_t lookupvarint(const char *name)
330 return atomax(lookupvar(name) ?: nullstr, 0);
336 * Generate a list of variables satisfying the given conditions.
339 char **
340 listvars(int on, int off, char ***end)
342 struct var **vpp;
343 struct var *vp;
344 char **ep;
345 int mask;
347 STARTSTACKSTR(ep);
348 vpp = vartab;
349 mask = on | off;
350 do {
351 for (vp = *vpp ; vp ; vp = vp->next)
352 if ((vp->flags & mask) == on) {
353 if (ep == stackstrend())
354 ep = growstackstr();
355 *ep++ = (char *) vp->text;
357 } while (++vpp < vartab + VTABSIZE);
358 if (ep == stackstrend())
359 ep = growstackstr();
360 if (end)
361 *end = ep;
362 *ep++ = NULL;
363 return grabstackstr(ep);
369 * POSIX requires that 'set' (but not export or readonly) output the
370 * variables in lexicographic order - by the locale's collating order (sigh).
371 * Maybe we could keep them in an ordered balanced binary tree
372 * instead of hashed lists.
373 * For now just roll 'em through qsort for printing...
377 showvars(const char *prefix, int on, int off)
379 const char *sep;
380 char **ep, **epend;
382 ep = listvars(on, off, &epend);
383 qsort(ep, epend - ep, sizeof(char *), vpcmp);
385 sep = *prefix ? spcstr : prefix;
387 for (; ep < epend; ep++) {
388 const char *p;
389 const char *q;
391 p = strchrnul(*ep, '=');
392 q = nullstr;
393 if (*p)
394 q = single_quote(++p);
396 out1fmt("%s%s%.*s%s\n", prefix, sep, (int)(p - *ep), *ep, q);
399 return 0;
405 * The export and readonly commands.
409 exportcmd(int argc, char **argv)
411 struct var *vp;
412 char *name;
413 const char *p;
414 char **aptr;
415 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
416 int notp;
418 notp = nextopt("p") - 'p';
419 if (notp && ((name = *(aptr = argptr)))) {
420 do {
421 if ((p = strchr(name, '=')) != NULL) {
422 p++;
423 } else {
424 if ((vp = *findvar(name))) {
425 vp->flags |= flag;
426 continue;
429 setvar(name, p, flag);
430 } while ((name = *++aptr) != NULL);
431 } else {
432 showvars(argv[0], flag, 0);
434 return 0;
439 * The "local" command.
443 localcmd(int argc, char **argv)
445 char *name;
447 if (!localvar_stack)
448 sh_error("not in a function");
450 argv = argptr;
451 while ((name = *argv++) != NULL) {
452 mklocal(name, 0);
454 return 0;
459 * Make a variable a local variable. When a variable is made local, it's
460 * value and flags are saved in a localvar structure. The saved values
461 * will be restored when the shell function returns. We handle the name
462 * "-" as a special case.
465 void mklocal(char *name, int flags)
467 struct localvar *lvp;
468 struct var *vp;
470 INTOFF;
471 lvp = ckmalloc(sizeof (struct localvar));
472 if (name[0] == '-' && name[1] == '\0') {
473 char *p;
474 p = ckmalloc(sizeof(optlist));
475 lvp->text = memcpy(p, optlist, sizeof(optlist));
476 vp = NULL;
477 } else {
478 char *eq;
480 vp = *findvar(name);
481 eq = strchr(name, '=');
482 if (vp == NULL) {
483 if (eq)
484 vp = setvareq(name, VSTRFIXED | flags);
485 else
486 vp = setvar(name, NULL, VSTRFIXED | flags);
487 lvp->flags = VUNSET;
488 } else {
489 lvp->text = vp->text;
490 lvp->flags = vp->flags;
491 vp->flags |= VSTRFIXED|VTEXTFIXED;
492 if (eq)
493 setvareq(name, flags);
496 lvp->vp = vp;
497 lvp->next = localvar_stack->lv;
498 localvar_stack->lv = lvp;
499 INTON;
504 * Called after a function returns.
505 * Interrupts must be off.
508 static void
509 poplocalvars(void)
511 struct localvar_list *ll;
512 struct localvar *lvp, *next;
513 struct var *vp;
515 INTOFF;
516 ll = localvar_stack;
517 localvar_stack = ll->next;
519 next = ll->lv;
520 ckfree(ll);
522 while ((lvp = next) != NULL) {
523 next = lvp->next;
524 vp = lvp->vp;
525 TRACE(("poplocalvar %s\n", vp ? vp->text : "-"));
526 if (vp == NULL) { /* $- saved */
527 memcpy(optlist, lvp->text, sizeof(optlist));
528 ckfree(lvp->text);
529 optschanged();
530 } else if (lvp->flags == VUNSET) {
531 vp->flags &= ~(VSTRFIXED|VREADONLY);
532 unsetvar(vp->text);
533 } else {
534 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
535 ckfree(vp->text);
536 vp->flags = lvp->flags;
537 vp->text = lvp->text;
538 if (vp->func && !(vp->flags & VNOFUNC))
539 (*vp->func)(varnull(vp->text));
541 ckfree(lvp);
543 INTON;
548 * Create a new localvar environment.
550 struct localvar_list *pushlocalvars(int push)
552 struct localvar_list *ll;
553 struct localvar_list *top;
555 top = localvar_stack;
556 if (!push)
557 goto out;
559 INTOFF;
560 ll = ckmalloc(sizeof(*ll));
561 ll->lv = NULL;
562 ll->next = top;
563 localvar_stack = ll;
564 INTON;
566 out:
567 return top;
571 void unwindlocalvars(struct localvar_list *stop)
573 while (localvar_stack != stop)
574 poplocalvars();
579 * The unset builtin command. We unset the function before we unset the
580 * variable to allow a function to be unset when there is a readonly variable
581 * with the same name.
585 unsetcmd(int argc, char **argv)
587 char **ap;
588 int i;
589 int flag = 0;
591 while ((i = nextopt("vf")) != '\0') {
592 flag = i;
595 for (ap = argptr; *ap ; ap++) {
596 if (flag != 'f') {
597 unsetvar(*ap);
598 continue;
600 if (flag != 'v')
601 unsetfunc(*ap);
603 return 0;
608 * Unset the specified variable.
611 void unsetvar(const char *s)
613 setvar(s, 0, 0);
619 * Find the appropriate entry in the hash table from the name.
622 STATIC struct var **
623 hashvar(const char *p)
625 return &vartab[hashval(p) % VTABSIZE];
631 * Compares two strings up to the first = or '\0'. The first
632 * string must be terminated by '='; the second may be terminated by
633 * either '=' or '\0'.
637 varcmp(const char *p, const char *q)
639 int c = *p, d = *q;
640 while (c == d) {
641 if (!c)
642 break;
643 p++;
644 q++;
645 c = *p;
646 d = *q;
647 if (c == '=')
648 c = '\0';
649 if (d == '=')
650 d = '\0';
652 return c - d;
655 STATIC int
656 vpcmp(const void *a, const void *b)
658 return varcmp(*(const char **)a, *(const char **)b);
661 STATIC struct var **
662 findvar(const char *name)
664 struct var **vpp;
666 for (vpp = hashvar(name); *vpp; vpp = &(*vpp)->next) {
667 if (varequal((*vpp)->text, name)) {
668 break;
671 return vpp;