Document the recently added WITHOUT_SRCS variable.
[dragonfly.git] / bin / sh / var.c
1 /*-
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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.
23  *
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
34  * SUCH DAMAGE.
35  *
36  * @(#)var.c    8.3 (Berkeley) 5/4/95
37  * $FreeBSD: src/bin/sh/var.c,v 1.15.2.2 2002/08/27 01:36:28 tjr Exp $
38  * $DragonFly: src/bin/sh/var.c,v 1.11 2006/01/12 13:43:10 corecode Exp $
39  */
40
41 #include <unistd.h>
42 #include <stdlib.h>
43
44 /*
45  * Shell variables.
46  */
47
48 #include <locale.h>
49
50 #include "shell.h"
51 #include "output.h"
52 #include "expand.h"
53 #include "nodes.h"      /* for other headers */
54 #include "eval.h"       /* defines cmdenviron */
55 #include "exec.h"
56 #include "syntax.h"
57 #include "options.h"
58 #include "mail.h"
59 #include "var.h"
60 #include "memalloc.h"
61 #include "error.h"
62 #include "mystring.h"
63 #include "parser.h"
64 #ifndef NO_HISTORY
65 #include "myhistedit.h"
66 #endif
67
68
69 #define VTABSIZE 39
70
71
72 struct varinit {
73         struct var *var;
74         int flags;
75         char *text;
76         void (*func)(const char *);
77 };
78
79
80 #ifndef NO_HISTORY
81 struct var vhistsize;
82 #endif
83 struct var vifs;
84 struct var vmail;
85 struct var vmpath;
86 struct var vpath;
87 struct var vppid;
88 struct var vps1;
89 struct var vps2;
90 struct var vvers;
91 STATIC struct var voptind;
92
93 STATIC const struct varinit varinit[] = {
94 #ifndef NO_HISTORY
95         { &vhistsize,   VSTRFIXED|VTEXTFIXED|VUNSET,    "HISTSIZE=",
96           sethistsize },
97 #endif
98         { &vifs,        VSTRFIXED|VTEXTFIXED,           "IFS= \t\n",
99           NULL },
100         { &vmail,       VSTRFIXED|VTEXTFIXED|VUNSET,    "MAIL=",
101           NULL },
102         { &vmpath,      VSTRFIXED|VTEXTFIXED|VUNSET,    "MAILPATH=",
103           NULL },
104         { &vpath,       VSTRFIXED|VTEXTFIXED,           "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/pkg/bin:/usr/pkg/sbin",
105           changepath },
106         { &vppid,       VSTRFIXED|VTEXTFIXED|VUNSET,    "PPID=",
107           NULL },
108         /*
109          * vps1 depends on uid
110          */
111         { &vps2,        VSTRFIXED|VTEXTFIXED,           "PS2=> ",
112           NULL },
113         { &voptind,     VSTRFIXED|VTEXTFIXED,           "OPTIND=1",
114           getoptsreset },
115         { NULL, 0,                              NULL,
116           NULL }
117 };
118
119 STATIC struct var *vartab[VTABSIZE];
120
121 STATIC struct var **hashvar(const char *);
122 STATIC int varequal(const char *, const char *);
123 STATIC int localevar(const char *);
124
125 /*
126  * Initialize the variable symbol tables and import the environment.
127  */
128
129 #ifdef mkinit
130 INCLUDE "var.h"
131 INIT {
132         char **envp;
133         extern char **environ;
134
135         initvar();
136         for (envp = environ ; *envp ; envp++) {
137                 if (strchr(*envp, '=')) {
138                         setvareq(*envp, VEXPORT|VTEXTFIXED);
139                 }
140         }
141 }
142 #endif
143
144
145 /*
146  * This routine initializes the builtin variables.  It is called when the
147  * shell is initialized and again when a shell procedure is spawned.
148  */
149
150 void
151 initvar(void)
152 {
153         char ppid[20];
154         const struct varinit *ip;
155         struct var *vp;
156         struct var **vpp;
157
158         for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
159                 if ((vp->flags & VEXPORT) == 0) {
160                         vpp = hashvar(ip->text);
161                         vp->next = *vpp;
162                         *vpp = vp;
163                         vp->text = ip->text;
164                         vp->flags = ip->flags;
165                         vp->func = ip->func;
166                 }
167         }
168         /*
169          * PS1 depends on uid
170          */
171         if ((vps1.flags & VEXPORT) == 0) {
172                 vpp = hashvar("PS1=");
173                 vps1.next = *vpp;
174                 *vpp = &vps1;
175                 vps1.text = geteuid() ? "PS1=$ " : "PS1=# ";
176                 vps1.flags = VSTRFIXED|VTEXTFIXED;
177         }
178         if ((vppid.flags & VEXPORT) == 0) {
179                 fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
180                 setvarsafe("PPID", ppid, 0);
181         }
182 }
183
184 /*
185  * Safe version of setvar, returns 1 on success 0 on failure.
186  */
187
188 int
189 setvarsafe(const char *name, const char *val, int flags)
190 {
191         struct jmploc jmploc;
192         struct jmploc *volatile savehandler = handler;
193         int err = 0;
194 #if __GNUC__
195         /* Avoid longjmp clobbering */
196         (void) &err;
197 #endif
198
199         if (setjmp(jmploc.loc))
200                 err = 1;
201         else {
202                 handler = &jmploc;
203                 setvar(name, val, flags);
204         }
205         handler = savehandler;
206         return err;
207 }
208
209 /*
210  * Set the value of a variable.  The flags argument is tored with the
211  * flags of the variable.  If val is NULL, the variable is unset.
212  */
213
214 void
215 setvar(const char *name, const char *val, int flags)
216 {
217         const char *cp;
218         char *p;
219         int len;
220         int namelen;
221         char *nameeq;
222         int isbad;
223
224         isbad = 0;
225         cp = name;
226         if (!is_name(*cp))
227                 isbad = 1;
228         cp++;
229         for (;;) {
230                 if (!is_in_name(*cp)) {
231                         if (*cp == '\0' || *cp == '=')
232                                 break;
233                         isbad = 1;
234                 }
235                 cp++;
236         }
237         namelen = cp - name;
238         if (isbad)
239                 error("%.*s: bad variable name", namelen, name);
240         len = namelen + 2;              /* 2 is space for '=' and '\0' */
241         if (val == NULL) {
242                 flags |= VUNSET;
243         } else {
244                 len += strlen(val);
245         }
246         p = nameeq = ckmalloc(len);
247         cp = name;
248         while (--namelen >= 0)
249                 *p++ = *cp++;
250         *p++ = '=';
251         *p = '\0';
252         if (val)
253                 scopy(val, p);
254         setvareq(nameeq, flags);
255 }
256
257 STATIC int
258 localevar(const char *s)
259 {
260         static const char * const lnames[7] = {
261                 "ALL", "COLLATE", "CTYPE", "MONETARY",
262                 "NUMERIC", "TIME", NULL
263         };
264         const char * const *ss;
265
266         if (*s != 'L')
267                 return 0;
268         if (varequal(s + 1, "ANG"))
269                 return 1;
270         if (strncmp(s + 1, "C_", 2) != 0)
271                 return 0;
272         for (ss = lnames; *ss ; ss++)
273                 if (varequal(s + 3, *ss))
274                         return 1;
275         return 0;
276 }
277
278 /*
279  * Same as setvar except that the variable and value are passed in
280  * the first argument as name=value.  Since the first argument will
281  * be actually stored in the table, it should not be a string that
282  * will go away.
283  */
284
285 void
286 setvareq(char *s, int flags)
287 {
288         struct var *vp, **vpp;
289         int len;
290
291         if (aflag)
292                 flags |= VEXPORT;
293         vpp = hashvar(s);
294         for (vp = *vpp ; vp ; vp = vp->next) {
295                 if (varequal(s, vp->text)) {
296                         if (vp->flags & VREADONLY) {
297                                 len = strchr(s, '=') - s;
298                                 error("%.*s: is read only", len, s);
299                         }
300                         INTOFF;
301
302                         if (vp->func && (flags & VNOFUNC) == 0)
303                                 (*vp->func)(strchr(s, '=') + 1);
304
305                         if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
306                                 ckfree(vp->text);
307
308                         vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
309                         vp->flags |= flags;
310                         vp->text = s;
311
312                         /*
313                          * We could roll this to a function, to handle it as
314                          * a regular variable function callback, but why bother?
315                          */
316                         if (vp == &vmpath || (vp == &vmail && ! mpathset()))
317                                 chkmail(1);
318                         if ((vp->flags & VEXPORT) && localevar(s)) {
319                                 if (putenv(s) != 0)
320                                         error("putenv: cannot set %s", s);
321                                 setlocale(LC_ALL, "");
322                         }
323                         INTON;
324                         return;
325                 }
326         }
327         /* not found */
328         vp = ckmalloc(sizeof (*vp));
329         vp->flags = flags;
330         vp->text = s;
331         vp->next = *vpp;
332         vp->func = NULL;
333         INTOFF;
334         *vpp = vp;
335         if ((vp->flags & VEXPORT) && localevar(s)) {
336                 if (putenv(s) != 0)
337                         error("putenv: cannot set %s", s);
338                 setlocale(LC_ALL, "");
339         }
340         INTON;
341 }
342
343
344
345 /*
346  * Process a linked list of variable assignments.
347  */
348
349 void
350 listsetvar(struct strlist *list)
351 {
352         struct strlist *lp;
353
354         INTOFF;
355         for (lp = list ; lp ; lp = lp->next) {
356                 setvareq(savestr(lp->text), 0);
357         }
358         INTON;
359 }
360
361
362
363 /*
364  * Find the value of a variable.  Returns NULL if not set.
365  */
366
367 char *
368 lookupvar(const char *name)
369 {
370         struct var *v;
371
372         for (v = *hashvar(name) ; v ; v = v->next) {
373                 if (varequal(v->text, name)) {
374                         if (v->flags & VUNSET)
375                                 return NULL;
376                         return strchr(v->text, '=') + 1;
377                 }
378         }
379         return NULL;
380 }
381
382
383
384 /*
385  * Search the environment of a builtin command.  If the second argument
386  * is nonzero, return the value of a variable even if it hasn't been
387  * exported.
388  */
389
390 char *
391 bltinlookup(const char *name, int doall)
392 {
393         struct strlist *sp;
394         struct var *v;
395
396         for (sp = cmdenviron ; sp ; sp = sp->next) {
397                 if (varequal(sp->text, name))
398                         return strchr(sp->text, '=') + 1;
399         }
400         for (v = *hashvar(name) ; v ; v = v->next) {
401                 if (varequal(v->text, name)) {
402                         if ((v->flags & VUNSET)
403                          || (!doall && (v->flags & VEXPORT) == 0))
404                                 return NULL;
405                         return strchr(v->text, '=') + 1;
406                 }
407         }
408         return NULL;
409 }
410
411
412
413 /*
414  * Generate a list of exported variables.  This routine is used to construct
415  * the third argument to execve when executing a program.
416  */
417
418 char **
419 environment(void)
420 {
421         int nenv;
422         struct var **vpp;
423         struct var *vp;
424         char **env, **ep;
425
426         nenv = 0;
427         for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
428                 for (vp = *vpp ; vp ; vp = vp->next)
429                         if (vp->flags & VEXPORT)
430                                 nenv++;
431         }
432         ep = env = stalloc((nenv + 1) * sizeof *env);
433         for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
434                 for (vp = *vpp ; vp ; vp = vp->next)
435                         if (vp->flags & VEXPORT)
436                                 *ep++ = vp->text;
437         }
438         *ep = NULL;
439         return env;
440 }
441
442
443 /*
444  * Called when a shell procedure is invoked to clear out nonexported
445  * variables.  It is also necessary to reallocate variables of with
446  * VSTACK set since these are currently allocated on the stack.
447  */
448
449 #ifdef mkinit
450 MKINIT void shprocvar(void);
451
452 SHELLPROC {
453         shprocvar();
454 }
455 #endif
456
457 void
458 shprocvar(void)
459 {
460         struct var **vpp;
461         struct var *vp, **prev;
462
463         for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
464                 for (prev = vpp ; (vp = *prev) != NULL ; ) {
465                         if ((vp->flags & VEXPORT) == 0) {
466                                 *prev = vp->next;
467                                 if ((vp->flags & VTEXTFIXED) == 0)
468                                         ckfree(vp->text);
469                                 if ((vp->flags & VSTRFIXED) == 0)
470                                         ckfree(vp);
471                         } else {
472                                 if (vp->flags & VSTACK) {
473                                         vp->text = savestr(vp->text);
474                                         vp->flags &=~ VSTACK;
475                                 }
476                                 prev = &vp->next;
477                         }
478                 }
479         }
480         initvar();
481 }
482
483
484
485 /*
486  * Command to list all variables which are set.  Currently this command
487  * is invoked from the set command when the set command is called without
488  * any variables.
489  */
490
491 int
492 showvarscmd(int argc __unused, char **argv __unused)
493 {
494         struct var **vpp;
495         struct var *vp;
496         const char *s;
497
498         for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
499                 for (vp = *vpp ; vp ; vp = vp->next) {
500                         if (vp->flags & VUNSET)
501                                 continue;
502                         for (s = vp->text; *s != '='; s++)
503                                 out1c(*s);
504                         out1c('=');
505                         out1qstr(s + 1);
506                         out1c('\n');
507                 }
508         }
509         return 0;
510 }
511
512
513
514 /*
515  * The export and readonly commands.
516  */
517
518 int
519 exportcmd(int argc, char **argv)
520 {
521         struct var **vpp;
522         struct var *vp;
523         char *name;
524         char *p;
525         char *cmdname;
526         int ch, values;
527         int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
528
529         cmdname = argv[0];
530         optreset = optind = 1;
531         opterr = 0;
532         values = 0;
533         while ((ch = getopt(argc, argv, "p")) != -1) {
534                 switch (ch) {
535                 case 'p':
536                         values = 1;
537                         break;
538                 case '?':
539                 default:
540                         error("unknown option: -%c", optopt);
541                 }
542         }
543         argc -= optind;
544         argv += optind;
545
546         listsetvar(cmdenviron);
547         if (argc != 0) {
548                 while ((name = *argptr++) != NULL) {
549                         if ((p = strchr(name, '=')) != NULL) {
550                                 p++;
551                         } else {
552                                 vpp = hashvar(name);
553                                 for (vp = *vpp ; vp ; vp = vp->next) {
554                                         if (varequal(vp->text, name)) {
555
556                                                 vp->flags |= flag;
557                                                 if ((vp->flags & VEXPORT) && localevar(vp->text)) {
558                                                         if (putenv(vp->text) != 0)
559                                                                 error("putenv: cannot set %s", vp->text);
560                                                         setlocale(LC_ALL, "");
561                                                 }
562                                                 goto found;
563                                         }
564                                 }
565                         }
566                         setvar(name, p, flag);
567 found:;
568                 }
569         } else {
570                 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
571                         for (vp = *vpp ; vp ; vp = vp->next) {
572                                 if (vp->flags & flag) {
573                                         if (values) {
574                                                 out1str(cmdname);
575                                                 out1c(' ');
576                                         }
577                                         for (p = vp->text ; *p != '=' ; p++)
578                                                 out1c(*p);
579                                         if (values && !(vp->flags & VUNSET)) {
580                                                 out1c('=');
581                                                 out1qstr(p + 1);
582                                         }
583                                         out1c('\n');
584                                 }
585                         }
586                 }
587         }
588         return 0;
589 }
590
591
592 /*
593  * The "local" command.
594  */
595
596 int
597 localcmd(int argc __unused, char **argv __unused)
598 {
599         char *name;
600
601         if (! in_function())
602                 error("Not in a function");
603         while ((name = *argptr++) != NULL) {
604                 mklocal(name);
605         }
606         return 0;
607 }
608
609
610 /*
611  * Make a variable a local variable.  When a variable is made local, it's
612  * value and flags are saved in a localvar structure.  The saved values
613  * will be restored when the shell function returns.  We handle the name
614  * "-" as a special case.
615  */
616
617 void
618 mklocal(char *name)
619 {
620         struct localvar *lvp;
621         struct var **vpp;
622         struct var *vp;
623
624         INTOFF;
625         lvp = ckmalloc(sizeof (struct localvar));
626         if (name[0] == '-' && name[1] == '\0') {
627                 lvp->text = ckmalloc(sizeof optlist);
628                 memcpy(lvp->text, optlist, sizeof optlist);
629                 vp = NULL;
630         } else {
631                 vpp = hashvar(name);
632                 for (vp = *vpp ; vp && ! varequal(vp->text, name) ; vp = vp->next);
633                 if (vp == NULL) {
634                         if (strchr(name, '='))
635                                 setvareq(savestr(name), VSTRFIXED);
636                         else
637                                 setvar(name, NULL, VSTRFIXED);
638                         vp = *vpp;      /* the new variable */
639                         lvp->text = NULL;
640                         lvp->flags = VUNSET;
641                 } else {
642                         lvp->text = vp->text;
643                         lvp->flags = vp->flags;
644                         vp->flags |= VSTRFIXED|VTEXTFIXED;
645                         if (strchr(name, '='))
646                                 setvareq(savestr(name), 0);
647                 }
648         }
649         lvp->vp = vp;
650         lvp->next = localvars;
651         localvars = lvp;
652         INTON;
653 }
654
655
656 /*
657  * Called after a function returns.
658  */
659
660 void
661 poplocalvars(void)
662 {
663         struct localvar *lvp;
664         struct var *vp;
665
666         while ((lvp = localvars) != NULL) {
667                 localvars = lvp->next;
668                 vp = lvp->vp;
669                 if (vp == NULL) {       /* $- saved */
670                         memcpy(optlist, lvp->text, sizeof optlist);
671                         ckfree(lvp->text);
672                 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
673                         unsetvar(vp->text);
674                 } else {
675                         if ((vp->flags & VTEXTFIXED) == 0)
676                                 ckfree(vp->text);
677                         vp->flags = lvp->flags;
678                         vp->text = lvp->text;
679                 }
680                 ckfree(lvp);
681         }
682 }
683
684
685 int
686 setvarcmd(int argc, char **argv)
687 {
688         if (argc <= 2)
689                 return unsetcmd(argc, argv);
690         else if (argc == 3)
691                 setvar(argv[1], argv[2], 0);
692         else
693                 error("List assignment not implemented");
694         return 0;
695 }
696
697
698 /*
699  * The unset builtin command.  We unset the function before we unset the
700  * variable to allow a function to be unset when there is a readonly variable
701  * with the same name.
702  */
703
704 int
705 unsetcmd(int argc __unused, char **argv __unused)
706 {
707         char **ap;
708         int i;
709         int flg_func = 0;
710         int flg_var = 0;
711         int ret = 0;
712
713         while ((i = nextopt("vf")) != '\0') {
714                 if (i == 'f')
715                         flg_func = 1;
716                 else
717                         flg_var = 1;
718         }
719         if (flg_func == 0 && flg_var == 0)
720                 flg_var = 1;
721
722         for (ap = argptr; *ap ; ap++) {
723                 if (flg_func)
724                         ret |= unsetfunc(*ap);
725                 if (flg_var)
726                         ret |= unsetvar(*ap);
727         }
728         return ret;
729 }
730
731
732 /*
733  * Unset the specified variable.
734  */
735
736 int
737 unsetvar(const char *s)
738 {
739         struct var **vpp;
740         struct var *vp;
741
742         vpp = hashvar(s);
743         for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
744                 if (varequal(vp->text, s)) {
745                         if (vp->flags & VREADONLY)
746                                 return (1);
747                         INTOFF;
748                         if (*(strchr(vp->text, '=') + 1) != '\0')
749                                 setvar(s, nullstr, 0);
750                         if ((vp->flags & VEXPORT) && localevar(vp->text)) {
751                                 unsetenv(s);
752                                 setlocale(LC_ALL, "");
753                         }
754                         vp->flags &= ~VEXPORT;
755                         vp->flags |= VUNSET;
756                         if ((vp->flags & VSTRFIXED) == 0) {
757                                 if ((vp->flags & VTEXTFIXED) == 0)
758                                         ckfree(vp->text);
759                                 *vpp = vp->next;
760                                 ckfree(vp);
761                         }
762                         INTON;
763                         return (0);
764                 }
765         }
766         return (0);
767 }
768
769
770
771 /*
772  * Find the appropriate entry in the hash table from the name.
773  */
774
775 STATIC struct var **
776 hashvar(const char *p)
777 {
778         unsigned int hashval;
779
780         hashval = ((unsigned char) *p) << 4;
781         while (*p && *p != '=')
782                 hashval += (unsigned char) *p++;
783         return &vartab[hashval % VTABSIZE];
784 }
785
786
787
788 /*
789  * Returns true if the two strings specify the same varable.  The first
790  * variable name is terminated by '='; the second may be terminated by
791  * either '=' or '\0'.
792  */
793
794 STATIC int
795 varequal(const char *p, const char *q)
796 {
797         while (*p == *q++) {
798                 if (*p++ == '=')
799                         return 1;
800         }
801         if (*p == '=' && *(q - 1) == '\0')
802                 return 1;
803         return 0;
804 }