Initial import of binutils 2.22 on the new vendor branch
[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.63 2011/06/17 10:21:24 jilles Exp $
38  */
39
40 #include <unistd.h>
41 #include <stdlib.h>
42
43 /*
44  * Shell variables.
45  */
46
47 #include <locale.h>
48 #include <langinfo.h>
49 #include <paths.h>
50
51 #include "shell.h"
52 #include "output.h"
53 #include "expand.h"
54 #include "nodes.h"      /* for other headers */
55 #include "eval.h"       /* defines cmdenviron */
56 #include "exec.h"
57 #include "syntax.h"
58 #include "options.h"
59 #include "mail.h"
60 #include "var.h"
61 #include "memalloc.h"
62 #include "error.h"
63 #include "mystring.h"
64 #include "parser.h"
65 #include "builtins.h"
66 #ifndef NO_HISTORY
67 #include "myhistedit.h"
68 #endif
69
70
71 #define VTABSIZE 39
72
73
74 struct varinit {
75         struct var *var;
76         int flags;
77         const char *text;
78         void (*func)(const char *);
79 };
80
81
82 #ifndef NO_HISTORY
83 struct var vhistsize;
84 struct var vterm;
85 #endif
86 struct var vifs;
87 struct var vmail;
88 struct var vmpath;
89 struct var vpath;
90 struct var vppid;
91 struct var vps1;
92 struct var vps2;
93 struct var vps4;
94 struct var vvers;
95 static struct var voptind;
96
97 int forcelocal;
98
99 static const struct varinit varinit[] = {
100 #ifndef NO_HISTORY
101         { &vhistsize,   VUNSET,                         "HISTSIZE=",
102           sethistsize },
103 #endif
104         { &vifs,        0,                              "IFS= \t\n",
105           NULL },
106         { &vmail,       VUNSET,                         "MAIL=",
107           NULL },
108         { &vmpath,      VUNSET,                         "MAILPATH=",
109           NULL },
110         { &vpath,       0,                              "PATH=" _PATH_DEFPATH,
111           changepath },
112         { &vppid,       VUNSET,                         "PPID=",
113           NULL },
114         /*
115          * vps1 depends on uid
116          */
117         { &vps2,        0,                              "PS2=> ",
118           NULL },
119         { &vps4,        0,                              "PS4=+ ",
120           NULL },
121 #ifndef NO_HISTORY
122         { &vterm,       VUNSET,                         "TERM=",
123           setterm },
124 #endif
125         { &voptind,     0,                              "OPTIND=1",
126           getoptsreset },
127         { NULL, 0,                              NULL,
128           NULL }
129 };
130
131 static struct var *vartab[VTABSIZE];
132
133 static const char *const locale_names[7] = {
134         "LC_COLLATE", "LC_CTYPE", "LC_MONETARY",
135         "LC_NUMERIC", "LC_TIME", "LC_MESSAGES", NULL
136 };
137 static const int locale_categories[7] = {
138         LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME, LC_MESSAGES, 0
139 };
140
141 static int varequal(const char *, const char *);
142 static struct var *find_var(const char *, struct var ***, int *);
143 static int localevar(const char *);
144
145 /*
146  * Initialize the variable symbol tables and import the environment.
147  */
148
149 #ifdef mkinit
150 INCLUDE "var.h"
151 MKINIT char **environ;
152 INIT {
153         char **envp;
154
155         initvar();
156         for (envp = environ ; *envp ; envp++) {
157                 if (strchr(*envp, '=')) {
158                         setvareq(*envp, VEXPORT|VTEXTFIXED);
159                 }
160         }
161 }
162 #endif
163
164
165 /*
166  * This routine initializes the builtin variables.  It is called when the
167  * shell is initialized.
168  */
169
170 void
171 initvar(void)
172 {
173         char ppid[20];
174         const struct varinit *ip;
175         struct var *vp;
176         struct var **vpp;
177
178         for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
179                 if (find_var(ip->text, &vpp, &vp->name_len) != NULL)
180                         continue;
181                 vp->next = *vpp;
182                 *vpp = vp;
183                 vp->text = __DECONST(char *, ip->text);
184                 vp->flags = ip->flags | VSTRFIXED | VTEXTFIXED;
185                 vp->func = ip->func;
186         }
187         /*
188          * PS1 depends on uid
189          */
190         if (find_var("PS1", &vpp, &vps1.name_len) == NULL) {
191                 vps1.next = *vpp;
192                 *vpp = &vps1;
193                 vps1.text = __DECONST(char *, geteuid() ? "PS1=$ " : "PS1=# ");
194                 vps1.flags = VSTRFIXED|VTEXTFIXED;
195         }
196         if ((vppid.flags & VEXPORT) == 0) {
197                 fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
198                 setvarsafe("PPID", ppid, 0);
199         }
200 }
201
202 /*
203  * Safe version of setvar, returns 1 on success 0 on failure.
204  */
205
206 int
207 setvarsafe(const char *name, const char *val, int flags)
208 {
209         struct jmploc jmploc;
210         struct jmploc *const savehandler = handler;
211         int err = 0;
212         int inton;
213
214         inton = is_int_on();
215         if (setjmp(jmploc.loc))
216                 err = 1;
217         else {
218                 handler = &jmploc;
219                 setvar(name, val, flags);
220         }
221         handler = savehandler;
222         SETINTON(inton);
223         return err;
224 }
225
226 /*
227  * Set the value of a variable.  The flags argument is stored with the
228  * flags of the variable.  If val is NULL, the variable is unset.
229  */
230
231 void
232 setvar(const char *name, const char *val, int flags)
233 {
234         const char *p;
235         int len;
236         int namelen;
237         char *nameeq;
238         int isbad;
239
240         isbad = 0;
241         p = name;
242         if (!is_name(*p))
243                 isbad = 1;
244         p++;
245         for (;;) {
246                 if (!is_in_name(*p)) {
247                         if (*p == '\0' || *p == '=')
248                                 break;
249                         isbad = 1;
250                 }
251                 p++;
252         }
253         namelen = p - name;
254         if (isbad)
255                 error("%.*s: bad variable name", namelen, name);
256         len = namelen + 2;              /* 2 is space for '=' and '\0' */
257         if (val == NULL) {
258                 flags |= VUNSET;
259         } else {
260                 len += strlen(val);
261         }
262         nameeq = ckmalloc(len);
263         memcpy(nameeq, name, namelen);
264         nameeq[namelen] = '=';
265         if (val)
266                 scopy(val, nameeq + namelen + 1);
267         else
268                 nameeq[namelen + 1] = '\0';
269         setvareq(nameeq, flags);
270 }
271
272 static int
273 localevar(const char *s)
274 {
275         const char *const *ss;
276
277         if (*s != 'L')
278                 return 0;
279         if (varequal(s + 1, "ANG"))
280                 return 1;
281         if (strncmp(s + 1, "C_", 2) != 0)
282                 return 0;
283         if (varequal(s + 3, "ALL"))
284                 return 1;
285         for (ss = locale_names; *ss ; ss++)
286                 if (varequal(s + 3, *ss + 3))
287                         return 1;
288         return 0;
289 }
290
291 /*
292  * Sets/unsets an environment variable from a pointer that may actually be a
293  * pointer into environ where the string should not be manipulated.
294  */
295 static void
296 change_env(const char *s, int set)
297 {
298         char *eqp;
299         char *ss;
300
301         ss = savestr(s);
302         if ((eqp = strchr(ss, '=')) != NULL)
303                 *eqp = '\0';
304         if (set && eqp != NULL) {
305                 if (setenv(ss, eqp + 1, 1) != 0)
306                         error("setenv: cannot set %s=%s", ss, eqp + 1);
307         } else
308                 unsetenv(ss);
309         ckfree(ss);
310 }
311
312
313 /*
314  * Same as setvar except that the variable and value are passed in
315  * the first argument as name=value.  Since the first argument will
316  * be actually stored in the table, it should not be a string that
317  * will go away.
318  */
319
320 void
321 setvareq(char *s, int flags)
322 {
323         struct var *vp, **vpp;
324         int nlen;
325
326         if (aflag)
327                 flags |= VEXPORT;
328         if (forcelocal && !(flags & (VNOSET | VNOLOCAL)))
329                 mklocal(s);
330         vp = find_var(s, &vpp, &nlen);
331         if (vp != NULL) {
332                 if (vp->flags & VREADONLY)
333                         error("%.*s: is read only", vp->name_len, s);
334                 if (flags & VNOSET)
335                         return;
336                 INTOFF;
337
338                 if (vp->func && (flags & VNOFUNC) == 0)
339                         (*vp->func)(s + vp->name_len + 1);
340
341                 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
342                         ckfree(vp->text);
343
344                 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
345                 vp->flags |= flags;
346                 vp->text = s;
347
348                 /*
349                  * We could roll this to a function, to handle it as
350                  * a regular variable function callback, but why bother?
351                  *
352                  * Note: this assumes iflag is not set to 1 initially.
353                  * As part of init(), this is called before arguments
354                  * are looked at.
355                  */
356                 if ((vp == &vmpath || (vp == &vmail && ! mpathset())) &&
357                     iflag == 1)
358                         chkmail(1);
359                 if ((vp->flags & VEXPORT) && localevar(s)) {
360                         change_env(s, 1);
361                         setlocale(LC_ALL, "");
362                         updatecharset();
363                 }
364                 INTON;
365                 return;
366         }
367         /* not found */
368         if (flags & VNOSET)
369                 return;
370         vp = ckmalloc(sizeof (*vp));
371         vp->flags = flags;
372         vp->text = s;
373         vp->name_len = nlen;
374         vp->next = *vpp;
375         vp->func = NULL;
376         INTOFF;
377         *vpp = vp;
378         if ((vp->flags & VEXPORT) && localevar(s)) {
379                 change_env(s, 1);
380                 setlocale(LC_ALL, "");
381                 updatecharset();
382         }
383         INTON;
384 }
385
386
387
388 /*
389  * Process a linked list of variable assignments.
390  */
391
392 void
393 listsetvar(struct strlist *list, int flags)
394 {
395         struct strlist *lp;
396
397         INTOFF;
398         for (lp = list ; lp ; lp = lp->next) {
399                 setvareq(savestr(lp->text), flags);
400         }
401         INTON;
402 }
403
404
405
406 /*
407  * Find the value of a variable.  Returns NULL if not set.
408  */
409
410 char *
411 lookupvar(const char *name)
412 {
413         struct var *v;
414
415         v = find_var(name, NULL, NULL);
416         if (v == NULL || v->flags & VUNSET)
417                 return NULL;
418         return v->text + v->name_len + 1;
419 }
420
421
422
423 /*
424  * Search the environment of a builtin command.  If the second argument
425  * is nonzero, return the value of a variable even if it hasn't been
426  * exported.
427  */
428
429 char *
430 bltinlookup(const char *name, int doall)
431 {
432         struct strlist *sp;
433         struct var *v;
434         char *result;
435
436         result = NULL;
437         for (sp = cmdenviron ; sp ; sp = sp->next) {
438                 if (varequal(sp->text, name))
439                         result = strchr(sp->text, '=') + 1;
440         }
441         if (result != NULL)
442                 return result;
443
444         v = find_var(name, NULL, NULL);
445         if (v == NULL || v->flags & VUNSET ||
446             (!doall && (v->flags & VEXPORT) == 0))
447                 return NULL;
448         return v->text + v->name_len + 1;
449 }
450
451
452 /*
453  * Set up locale for a builtin (LANG/LC_* assignments).
454  */
455 void
456 bltinsetlocale(void)
457 {
458         struct strlist *lp;
459         int act = 0;
460         char *loc, *locdef;
461         int i;
462
463         for (lp = cmdenviron ; lp ; lp = lp->next) {
464                 if (localevar(lp->text)) {
465                         act = 1;
466                         break;
467                 }
468         }
469         if (!act)
470                 return;
471         loc = bltinlookup("LC_ALL", 0);
472         INTOFF;
473         if (loc != NULL) {
474                 setlocale(LC_ALL, loc);
475                 INTON;
476                 updatecharset();
477                 return;
478         }
479         locdef = bltinlookup("LANG", 0);
480         for (i = 0; locale_names[i] != NULL; i++) {
481                 loc = bltinlookup(locale_names[i], 0);
482                 if (loc == NULL)
483                         loc = locdef;
484                 if (loc != NULL)
485                         setlocale(locale_categories[i], loc);
486         }
487         INTON;
488         updatecharset();
489 }
490
491 /*
492  * Undo the effect of bltinlocaleset().
493  */
494 void
495 bltinunsetlocale(void)
496 {
497         struct strlist *lp;
498
499         INTOFF;
500         for (lp = cmdenviron ; lp ; lp = lp->next) {
501                 if (localevar(lp->text)) {
502                         setlocale(LC_ALL, "");
503                         updatecharset();
504                         return;
505                 }
506         }
507         INTON;
508 }
509
510 /*
511  * Update the localeisutf8 flag.
512  */
513 void
514 updatecharset(void)
515 {
516         char *charset;
517
518         charset = nl_langinfo(CODESET);
519         localeisutf8 = !strcmp(charset, "UTF-8");
520 }
521
522 void
523 initcharset(void)
524 {
525         updatecharset();
526         initial_localeisutf8 = localeisutf8;
527 }
528
529 /*
530  * Generate a list of exported variables.  This routine is used to construct
531  * the third argument to execve when executing a program.
532  */
533
534 char **
535 environment(void)
536 {
537         int nenv;
538         struct var **vpp;
539         struct var *vp;
540         char **env, **ep;
541
542         nenv = 0;
543         for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
544                 for (vp = *vpp ; vp ; vp = vp->next)
545                         if (vp->flags & VEXPORT)
546                                 nenv++;
547         }
548         ep = env = stalloc((nenv + 1) * sizeof *env);
549         for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
550                 for (vp = *vpp ; vp ; vp = vp->next)
551                         if (vp->flags & VEXPORT)
552                                 *ep++ = vp->text;
553         }
554         *ep = NULL;
555         return env;
556 }
557
558
559 static int
560 var_compare(const void *a, const void *b)
561 {
562         const char *const *sa, *const *sb;
563
564         sa = a;
565         sb = b;
566         /*
567          * This compares two var=value strings which creates a different
568          * order from what you would probably expect.  POSIX is somewhat
569          * ambiguous on what should be sorted exactly.
570          */
571         return strcoll(*sa, *sb);
572 }
573
574
575 /*
576  * Command to list all variables which are set.  This is invoked from the
577  * set command when it is called without any options or operands.
578  */
579
580 int
581 showvarscmd(int argc __unused, char **argv __unused)
582 {
583         struct var **vpp;
584         struct var *vp;
585         const char *s;
586         const char **vars;
587         int i, n;
588
589         /*
590          * POSIX requires us to sort the variables.
591          */
592         n = 0;
593         for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
594                 for (vp = *vpp; vp; vp = vp->next) {
595                         if (!(vp->flags & VUNSET))
596                                 n++;
597                 }
598         }
599
600         INTON;
601         vars = ckmalloc(n * sizeof(*vars));
602         i = 0;
603         for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
604                 for (vp = *vpp; vp; vp = vp->next) {
605                         if (!(vp->flags & VUNSET))
606                                 vars[i++] = vp->text;
607                 }
608         }
609
610         qsort(vars, n, sizeof(*vars), var_compare);
611         for (i = 0; i < n; i++) {
612                 /*
613                  * Skip improper variable names so the output remains usable as
614                  * shell input.
615                  */
616                 if (!isassignment(vars[i]))
617                         continue;
618                 s = strchr(vars[i], '=');
619                 s++;
620                 outbin(vars[i], s - vars[i], out1);
621                 out1qstr(s);
622                 out1c('\n');
623         }
624         ckfree(vars);
625         INTOFF;
626
627         return 0;
628 }
629
630
631
632 /*
633  * The export and readonly commands.
634  */
635
636 int
637 exportcmd(int argc, char **argv)
638 {
639         struct var **vpp;
640         struct var *vp;
641         char *name;
642         char *p;
643         char *cmdname;
644         int ch, values;
645         int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
646
647         cmdname = argv[0];
648         optreset = optind = 1;
649         opterr = 0;
650         values = 0;
651         while ((ch = getopt(argc, argv, "p")) != -1) {
652                 switch (ch) {
653                 case 'p':
654                         values = 1;
655                         break;
656                 case '?':
657                 default:
658                         error("unknown option: -%c", optopt);
659                 }
660         }
661         argc -= optind;
662         argv += optind;
663
664         if (values && argc != 0)
665                 error("-p requires no arguments");
666         if (argc != 0) {
667                 while ((name = *argv++) != NULL) {
668                         if ((p = strchr(name, '=')) != NULL) {
669                                 p++;
670                         } else {
671                                 vp = find_var(name, NULL, NULL);
672                                 if (vp != NULL) {
673                                         vp->flags |= flag;
674                                         if ((vp->flags & VEXPORT) && localevar(vp->text)) {
675                                                 change_env(vp->text, 1);
676                                                 setlocale(LC_ALL, "");
677                                                 updatecharset();
678                                         }
679                                         continue;
680                                 }
681                         }
682                         setvar(name, p, flag);
683                 }
684         } else {
685                 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
686                         for (vp = *vpp ; vp ; vp = vp->next) {
687                                 if (vp->flags & flag) {
688                                         if (values) {
689                                                 /*
690                                                  * Skip improper variable names
691                                                  * so the output remains usable
692                                                  * as shell input.
693                                                  */
694                                                 if (!isassignment(vp->text))
695                                                         continue;
696                                                 out1str(cmdname);
697                                                 out1c(' ');
698                                         }
699                                         if (values && !(vp->flags & VUNSET)) {
700                                                 outbin(vp->text,
701                                                     vp->name_len + 1, out1);
702                                                 out1qstr(vp->text +
703                                                     vp->name_len + 1);
704                                         } else
705                                                 outbin(vp->text, vp->name_len,
706                                                     out1);
707                                         out1c('\n');
708                                 }
709                         }
710                 }
711         }
712         return 0;
713 }
714
715
716 /*
717  * The "local" command.
718  */
719
720 int
721 localcmd(int argc __unused, char **argv __unused)
722 {
723         char *name;
724
725         if (! in_function())
726                 error("Not in a function");
727         while ((name = *argptr++) != NULL) {
728                 mklocal(name);
729         }
730         return 0;
731 }
732
733
734 /*
735  * Make a variable a local variable.  When a variable is made local, it's
736  * value and flags are saved in a localvar structure.  The saved values
737  * will be restored when the shell function returns.  We handle the name
738  * "-" as a special case.
739  */
740
741 void
742 mklocal(char *name)
743 {
744         struct localvar *lvp;
745         struct var **vpp;
746         struct var *vp;
747
748         INTOFF;
749         lvp = ckmalloc(sizeof (struct localvar));
750         if (name[0] == '-' && name[1] == '\0') {
751                 lvp->text = ckmalloc(sizeof optlist);
752                 memcpy(lvp->text, optlist, sizeof optlist);
753                 vp = NULL;
754         } else {
755                 vp = find_var(name, &vpp, NULL);
756                 if (vp == NULL) {
757                         if (strchr(name, '='))
758                                 setvareq(savestr(name), VSTRFIXED | VNOLOCAL);
759                         else
760                                 setvar(name, NULL, VSTRFIXED | VNOLOCAL);
761                         vp = *vpp;      /* the new variable */
762                         lvp->text = NULL;
763                         lvp->flags = VUNSET;
764                 } else {
765                         lvp->text = vp->text;
766                         lvp->flags = vp->flags;
767                         vp->flags |= VSTRFIXED|VTEXTFIXED;
768                         if (name[vp->name_len] == '=')
769                                 setvareq(savestr(name), VNOLOCAL);
770                 }
771         }
772         lvp->vp = vp;
773         lvp->next = localvars;
774         localvars = lvp;
775         INTON;
776 }
777
778
779 /*
780  * Called after a function returns.
781  */
782
783 void
784 poplocalvars(void)
785 {
786         struct localvar *lvp;
787         struct var *vp;
788
789         while ((lvp = localvars) != NULL) {
790                 localvars = lvp->next;
791                 vp = lvp->vp;
792                 if (vp == NULL) {       /* $- saved */
793                         memcpy(optlist, lvp->text, sizeof optlist);
794                         ckfree(lvp->text);
795                         optschanged();
796                 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
797                         unsetvar(vp->text);
798                 } else {
799                         if ((vp->flags & VTEXTFIXED) == 0)
800                                 ckfree(vp->text);
801                         vp->flags = lvp->flags;
802                         vp->text = lvp->text;
803                 }
804                 ckfree(lvp);
805         }
806 }
807
808
809 int
810 setvarcmd(int argc, char **argv)
811 {
812         if (argc <= 2)
813                 return unsetcmd(argc, argv);
814         else if (argc == 3)
815                 setvar(argv[1], argv[2], 0);
816         else
817                 error("too many arguments");
818         return 0;
819 }
820
821
822 /*
823  * The unset builtin command.
824  */
825
826 int
827 unsetcmd(int argc __unused, char **argv __unused)
828 {
829         char **ap;
830         int i;
831         int flg_func = 0;
832         int flg_var = 0;
833         int ret = 0;
834
835         while ((i = nextopt("vf")) != '\0') {
836                 if (i == 'f')
837                         flg_func = 1;
838                 else
839                         flg_var = 1;
840         }
841         if (flg_func == 0 && flg_var == 0)
842                 flg_var = 1;
843
844         for (ap = argptr; *ap ; ap++) {
845                 if (flg_func)
846                         ret |= unsetfunc(*ap);
847                 if (flg_var)
848                         ret |= unsetvar(*ap);
849         }
850         return ret;
851 }
852
853
854 /*
855  * Unset the specified variable.
856  */
857
858 int
859 unsetvar(const char *s)
860 {
861         struct var **vpp;
862         struct var *vp;
863
864         vp = find_var(s, &vpp, NULL);
865         if (vp == NULL)
866                 return (0);
867         if (vp->flags & VREADONLY)
868                 return (1);
869         INTOFF;
870         if (vp->text[vp->name_len + 1] != '\0')
871                 setvar(s, nullstr, 0);
872         if ((vp->flags & VEXPORT) && localevar(vp->text)) {
873                 change_env(__DECONST(char *, s), 0);
874                 setlocale(LC_ALL, "");
875                 updatecharset();
876         }
877         vp->flags &= ~VEXPORT;
878         vp->flags |= VUNSET;
879         if ((vp->flags & VSTRFIXED) == 0) {
880                 if ((vp->flags & VTEXTFIXED) == 0)
881                         ckfree(vp->text);
882                 *vpp = vp->next;
883                 ckfree(vp);
884         }
885         INTON;
886         return (0);
887 }
888
889
890
891 /*
892  * Returns true if the two strings specify the same variable.  The first
893  * variable name is terminated by '='; the second may be terminated by
894  * either '=' or '\0'.
895  */
896
897 static int
898 varequal(const char *p, const char *q)
899 {
900         while (*p == *q++) {
901                 if (*p++ == '=')
902                         return 1;
903         }
904         if (*p == '=' && *(q - 1) == '\0')
905                 return 1;
906         return 0;
907 }
908
909 /*
910  * Search for a variable.
911  * 'name' may be terminated by '=' or a NUL.
912  * vppp is set to the pointer to vp, or the list head if vp isn't found
913  * lenp is set to the number of characters in 'name'
914  */
915
916 static struct var *
917 find_var(const char *name, struct var ***vppp, int *lenp)
918 {
919         unsigned int hashval;
920         int len;
921         struct var *vp, **vpp;
922         const char *p = name;
923
924         hashval = 0;
925         while (*p && *p != '=')
926                 hashval = 2 * hashval + (unsigned char)*p++;
927         len = p - name;
928
929         if (lenp)
930                 *lenp = len;
931         vpp = &vartab[hashval % VTABSIZE];
932         if (vppp)
933                 *vppp = vpp;
934
935         for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
936                 if (vp->name_len != len)
937                         continue;
938                 if (memcmp(vp->text, name, len) != 0)
939                         continue;
940                 if (vppp)
941                         *vppp = vpp;
942                 return vp;
943         }
944         return NULL;
945 }