Fixed reference of memory after free.
[dragonfly.git] / usr.bin / make / var.c
1 /*-
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1989 by Berkeley Softworks
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
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. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * @(#)var.c    8.3 (Berkeley) 3/19/94
39  * $FreeBSD: src/usr.bin/make/var.c,v 1.83 2005/02/11 10:49:01 harti Exp $
40  * $DragonFly: src/usr.bin/make/var.c,v 1.180 2005/03/23 05:02:37 okumoto Exp $
41  */
42
43 /*-
44  * var.c --
45  *      Variable-handling functions
46  *
47  * Interface:
48  *      Var_Set         Set the value of a variable in the given
49  *                      context. The variable is created if it doesn't
50  *                      yet exist. The value and variable name need not
51  *                      be preserved.
52  *
53  *      Var_Append      Append more characters to an existing variable
54  *                      in the given context. The variable needn't
55  *                      exist already -- it will be created if it doesn't.
56  *                      A space is placed between the old value and the
57  *                      new one.
58  *
59  *      Var_Exists      See if a variable exists.
60  *
61  *      Var_Value       Return the value of a variable in a context or
62  *                      NULL if the variable is undefined.
63  *
64  *      Var_Subst       Substitute named variable, or all variables if
65  *                      NULL in a string using
66  *                      the given context as the top-most one. If the
67  *                      third argument is non-zero, Parse_Error is
68  *                      called if any variables are undefined.
69  *
70  *      Var_Parse       Parse a variable expansion from a string and
71  *                      return the result and the number of characters
72  *                      consumed.
73  *
74  *      Var_Delete      Delete a variable in a context.
75  *
76  *      Var_Init        Initialize this module.
77  *
78  * Debugging:
79  *      Var_Dump        Print out all variables defined in the given
80  *                      context.
81  *
82  * XXX: There's a lot of duplication in these functions.
83  */
84
85 #include <assert.h>
86 #include <ctype.h>
87 #include <stdlib.h>
88 #include <string.h>
89
90 #include "buf.h"
91 #include "config.h"
92 #include "globals.h"
93 #include "GNode.h"
94 #include "make.h"
95 #include "nonints.h"
96 #include "parse.h"
97 #include "str.h"
98 #include "targ.h"
99 #include "util.h"
100 #include "var.h"
101
102 /**
103  *
104  */
105 typedef struct VarParser {
106         const char      *const input;   /* pointer to input string */
107         const char      *ptr;           /* current parser pos in input str */
108         GNode           *ctxt;
109         Boolean         err;
110 } VarParser;
111 static char *VarParse(VarParser *, Boolean *);
112
113 /*
114  * This is a harmless return value for Var_Parse that can be used by Var_Subst
115  * to determine if there was an error in parsing -- easier than returning
116  * a flag, as things outside this module don't give a hoot.
117  */
118 char    var_Error[] = "";
119
120 /*
121  * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
122  * set false. Why not just use a constant? Well, gcc likes to condense
123  * identical string instances...
124  */
125 static char     varNoError[] = "";
126
127 /*
128  * Internally, variables are contained in four different contexts.
129  *      1) the environment. They may not be changed. If an environment
130  *         variable is appended-to, the result is placed in the global
131  *         context.
132  *      2) the global context. Variables set in the Makefile are located in
133  *         the global context. It is the penultimate context searched when
134  *         substituting.
135  *      3) the command-line context. All variables set on the command line
136  *         are placed in this context. They are UNALTERABLE once placed here.
137  *      4) the local context. Each target has associated with it a context
138  *         list. On this list are located the structures describing such
139  *         local variables as $(@) and $(*)
140  * The four contexts are searched in the reverse order from which they are
141  * listed.
142  */
143 GNode   *VAR_GLOBAL;    /* variables from the makefile */
144 GNode   *VAR_CMD;       /* variables defined on the command-line */
145
146 #define FIND_CMD        0x1   /* look in VAR_CMD when searching */
147 #define FIND_GLOBAL     0x2   /* look in VAR_GLOBAL as well */
148 #define FIND_ENV        0x4   /* look in the environment also */
149
150 #define OPEN_PAREN              '('
151 #define CLOSE_PAREN             ')'
152 #define OPEN_BRACE              '{'
153 #define CLOSE_BRACE             '}'
154
155 /*
156  * Create a Var object.
157  *
158  * @param name          Name of variable.
159  * @param value         Value of variable.
160  * @param flags         Flags set on variable.
161  */
162 static Var *
163 VarCreate(const char name[], const char value[], int flags)
164 {
165         Var *v;
166
167         v = emalloc(sizeof(Var));
168         v->name = estrdup(name);
169         v->val  = Buf_Init(0);
170         v->flags        = flags;
171
172         if (value != NULL) {
173                 Buf_Append(v->val, value);
174         }
175         return (v);
176 }
177
178 /*
179  * Destroy a Var object.
180  *
181  * @param v     Object to destroy.
182  * @param f     true if internal buffer in Buffer object is to be
183  *              removed.
184  */
185 static void
186 VarDestroy(Var *v, Boolean f)
187 {
188
189         Buf_Destroy(v->val, f);
190         free(v->name);
191         free(v);
192 }
193
194 /*-
195  *-----------------------------------------------------------------------
196  * VarCmp  --
197  *      See if the given variable matches the named one. Called from
198  *      Lst_Find when searching for a variable of a given name.
199  *
200  * Results:
201  *      0 if they match. non-zero otherwise.
202  *
203  * Side Effects:
204  *      none
205  *-----------------------------------------------------------------------
206  */
207 static int
208 VarCmp(const void *v, const void *name)
209 {
210
211         return (strcmp(name, ((const Var *)v)->name));
212 }
213
214 /*-
215  *-----------------------------------------------------------------------
216  * VarPossiblyExpand --
217  *      Expand a variable name's embedded variables in the given context.
218  *
219  * Results:
220  *      The contents of name, possibly expanded.
221  *-----------------------------------------------------------------------
222  */
223 static char *
224 VarPossiblyExpand(const char *name, GNode *ctxt)
225 {
226         Buffer  *buf;
227
228         if (strchr(name, '$') != NULL) {
229                 buf = Var_Subst(NULL, name, ctxt, 0);
230                 return (Buf_Peel(buf));
231         } else {
232                 return estrdup(name);
233         }
234 }
235
236 /*-
237  *-----------------------------------------------------------------------
238  * VarFind --
239  *      Find the given variable in the given context and any other contexts
240  *      indicated.
241  *
242  *      Flags:
243  *              FIND_GLOBAL     set means look in the VAR_GLOBAL context too
244  *              FIND_CMD        set means to look in the VAR_CMD context too
245  *              FIND_ENV        set means to look in the environment
246  *
247  * Results:
248  *      A pointer to the structure describing the desired variable or
249  *      NULL if the variable does not exist.
250  *
251  * Side Effects:
252  *      None
253  *-----------------------------------------------------------------------
254  */
255 static Var *
256 VarFind(const char *name, GNode *ctxt, int flags)
257 {
258         Boolean localCheckEnvFirst;
259         LstNode *var;
260         char    *env;
261
262         /*
263          * If the variable name begins with a '.', it could very well be one of
264          * the local ones.  We check the name against all the local variables
265          * and substitute the short version in for 'name' if it matches one of
266          * them.
267          */
268         if (name[0] == '.') {
269                 switch (name[1]) {
270                 case 'A':
271                         if (!strcmp(name, ".ALLSRC"))
272                                 name = ALLSRC;
273                         if (!strcmp(name, ".ARCHIVE"))
274                                 name = ARCHIVE;
275                         break;
276                 case 'I':
277                         if (!strcmp(name, ".IMPSRC"))
278                                 name = IMPSRC;
279                         break;
280                 case 'M':
281                         if (!strcmp(name, ".MEMBER"))
282                                 name = MEMBER;
283                         break;
284                 case 'O':
285                         if (!strcmp(name, ".OODATE"))
286                                 name = OODATE;
287                         break;
288                 case 'P':
289                         if (!strcmp(name, ".PREFIX"))
290                                 name = PREFIX;
291                         break;
292                 case 'T':
293                         if (!strcmp(name, ".TARGET"))
294                                 name = TARGET;
295                         break;
296                 default:
297                         break;
298                 }
299         }
300
301         /*
302          * Note whether this is one of the specific variables we were told
303          * through the -E flag to use environment-variable-override for.
304          */
305         if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
306                 localCheckEnvFirst = TRUE;
307         } else {
308                 localCheckEnvFirst = FALSE;
309         }
310
311         /*
312          * First look for the variable in the given context. If it's not there,
313          * look for it in VAR_CMD, VAR_GLOBAL and the environment,
314          * in that order, depending on the FIND_* flags in 'flags'
315          */
316         var = Lst_Find(&ctxt->context, name, VarCmp);
317         if (var != NULL) {
318                 /* got it */
319                 return (Lst_Datum(var));
320         }
321
322         /* not there - try command line context */
323         if ((flags & FIND_CMD) && (ctxt != VAR_CMD)) {
324                 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
325                 if (var != NULL)
326                         return (Lst_Datum(var));
327         }
328
329         /* not there - try global context, but only if not -e/-E */
330         if ((flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
331             !checkEnvFirst && !localCheckEnvFirst) {
332                 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
333                 if (var != NULL)
334                         return (Lst_Datum(var));
335         }
336
337         if (!(flags & FIND_ENV))
338                 /* we were not told to look into the environment */
339                 return (NULL);
340
341         /* look in the environment */
342         if ((env = getenv(name)) != NULL) {
343                 /* craft this variable from the environment value */
344                 return (VarCreate(name, env, VAR_FROM_ENV));
345         }
346
347         /* deferred check for the environment (in case of -e/-E) */
348         if ((checkEnvFirst || localCheckEnvFirst) &&
349             (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL)) {
350                 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
351                 if (var != NULL)
352                         return (Lst_Datum(var));
353         }
354         return (NULL);
355 }
356
357 /*-
358  *-----------------------------------------------------------------------
359  * VarAdd  --
360  *      Add a new variable of name name and value val to the given context.
361  *
362  * Results:
363  *      None
364  *
365  * Side Effects:
366  *      The new variable is placed at the front of the given context
367  *      The name and val arguments are duplicated so they may
368  *      safely be freed.
369  *-----------------------------------------------------------------------
370  */
371 static void
372 VarAdd(const char *name, const char *val, GNode *ctxt)
373 {
374
375         Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
376         DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
377 }
378
379 /*-
380  *-----------------------------------------------------------------------
381  * Var_Delete --
382  *      Remove a variable from a context.
383  *
384  * Results:
385  *      None.
386  *
387  * Side Effects:
388  *      The Var structure is removed and freed.
389  *
390  *-----------------------------------------------------------------------
391  */
392 void
393 Var_Delete(const char *name, GNode *ctxt)
394 {
395         LstNode *ln;
396
397         DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
398         ln = Lst_Find(&ctxt->context, name, VarCmp);
399         if (ln != NULL) {
400                 VarDestroy(Lst_Datum(ln), TRUE);
401                 Lst_Remove(&ctxt->context, ln);
402         }
403 }
404
405 /*-
406  *-----------------------------------------------------------------------
407  * Var_Set --
408  *      Set the variable name to the value val in the given context.
409  *
410  * Results:
411  *      None.
412  *
413  * Side Effects:
414  *      If the variable doesn't yet exist, a new record is created for it.
415  *      Else the old value is freed and the new one stuck in its place
416  *
417  * Notes:
418  *      The variable is searched for only in its context before being
419  *      created in that context. I.e. if the context is VAR_GLOBAL,
420  *      only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
421  *      VAR_CMD->context is searched. This is done to avoid the literally
422  *      thousands of unnecessary strcmp's that used to be done to
423  *      set, say, $(@) or $(<).
424  *-----------------------------------------------------------------------
425  */
426 void
427 Var_Set(const char *name, const char *val, GNode *ctxt)
428 {
429         Var    *v;
430         char   *n;
431
432         /*
433          * We only look for a variable in the given context since anything
434          * set here will override anything in a lower context, so there's not
435          * much point in searching them all just to save a bit of memory...
436          */
437         n = VarPossiblyExpand(name, ctxt);
438         v = VarFind(n, ctxt, 0);
439         if (v == NULL) {
440                 VarAdd(n, val, ctxt);
441         } else {
442                 Buf_Clear(v->val);
443                 Buf_Append(v->val, val);
444
445                 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
446         }
447         /*
448          * Any variables given on the command line are automatically exported
449          * to the environment (as per POSIX standard)
450          */
451         if (ctxt == VAR_CMD || (v != NULL && (v->flags & VAR_TO_ENV))) {
452                 setenv(n, val, 1);
453         }
454         free(n);
455 }
456
457 /*
458  * Var_SetEnv --
459  *      Set the VAR_TO_ENV flag on a variable
460  */
461 void
462 Var_SetEnv(const char *name, GNode *ctxt)
463 {
464         Var    *v;
465
466         v = VarFind(name, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
467         if (v == NULL) {
468                 Error("Cannot set environment flag on non-existant variable %s", name);
469         } else {
470                 if ((v->flags & VAR_TO_ENV) == 0) {
471                         v->flags |= VAR_TO_ENV;
472                         setenv(v->name, Buf_Data(v->val), 1);
473                 }
474         }
475 }
476
477 /*-
478  *-----------------------------------------------------------------------
479  * Var_Append --
480  *      The variable of the given name has the given value appended to it in
481  *      the given context.
482  *
483  * Results:
484  *      None
485  *
486  * Side Effects:
487  *      If the variable doesn't exist, it is created. Else the strings
488  *      are concatenated (with a space in between).
489  *
490  * Notes:
491  *      Only if the variable is being sought in the global context is the
492  *      environment searched.
493  *      XXX: Knows its calling circumstances in that if called with ctxt
494  *      an actual target, it will only search that context since only
495  *      a local variable could be being appended to. This is actually
496  *      a big win and must be tolerated.
497  *-----------------------------------------------------------------------
498  */
499 void
500 Var_Append(const char *name, const char *val, GNode *ctxt)
501 {
502         Var     *v;
503         char    *n;
504
505         n = VarPossiblyExpand(name, ctxt);
506         v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
507         if (v == NULL) {
508                 VarAdd(n, val, ctxt);
509
510         } else if (v->flags & VAR_FROM_ENV) {
511                 Buf_AddByte(v->val, (Byte)' ');
512                 Buf_Append(v->val, val);
513                 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
514                 /*
515                  * If the original variable came from the
516                  * environment, we have to install it in the global
517                  * context (we could place it in the environment, but
518                  * then we should provide a way to export other
519                  * variables...)
520                  */
521                 v->flags &= ~VAR_FROM_ENV;
522                 Lst_AtFront(&ctxt->context, v);
523
524         } else {
525                 Buf_AddByte(v->val, (Byte)' ');
526                 Buf_Append(v->val, val);
527                 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
528         }
529         free(n);
530 }
531
532 /*-
533  *-----------------------------------------------------------------------
534  * Var_Exists --
535  *      See if the given variable exists.
536  *
537  * Results:
538  *      TRUE if it does, FALSE if it doesn't
539  *
540  * Side Effects:
541  *      None.
542  *
543  *-----------------------------------------------------------------------
544  */
545 Boolean
546 Var_Exists(const char *name, GNode *ctxt)
547 {
548         Var     *v;
549         char    *n;
550
551         n = VarPossiblyExpand(name, ctxt);
552         v = VarFind(n, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
553         if (v == NULL) {
554                 free(n);
555                 return (FALSE);
556         } else if (v->flags & VAR_FROM_ENV) {
557                 VarDestroy(v, TRUE);
558                 free(n);
559                 return (TRUE);
560         } else {
561                 free(n);
562                 return (TRUE);
563         }
564 }
565
566 /*-
567  *-----------------------------------------------------------------------
568  * Var_Value --
569  *      Return the value of the named variable in the given context
570  *
571  * Results:
572  *      The value if the variable exists, NULL if it doesn't
573  *
574  * Side Effects:
575  *      None
576  *-----------------------------------------------------------------------
577  */
578 char *
579 Var_Value(const char *name, GNode *ctxt, char **frp)
580 {
581         Var     *v;
582         char    *n;
583         char    *p;
584
585         n = VarPossiblyExpand(name, ctxt);
586         v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
587         if (v == NULL) {
588                 p = NULL;
589                 *frp = NULL;
590         } else if (v->flags & VAR_FROM_ENV) {
591                 p = estrdup(Buf_Data(v->val));
592                 *frp = p;
593                 VarDestroy(v, FALSE);
594         } else {
595                 p = Buf_Data(v->val);
596                 *frp = NULL;
597         }
598         free(n);
599         return (p);
600 }
601
602 /*-
603  *-----------------------------------------------------------------------
604  * VarModify --
605  *      Modify each of the words of the passed string using the given
606  *      function. Used to implement all modifiers.
607  *
608  * Results:
609  *      A string of all the words modified appropriately.
610  *
611  * Side Effects:
612  *      Uses brk_string() so it invalidates any previous call to
613  *      brk_string().
614  *
615  *-----------------------------------------------------------------------
616  */
617 static char *
618 VarModify(const char *str, VarModifyProc *modProc, void *datum)
619 {
620         char    **av;           /* word list [first word does not count] */
621         int     ac;
622         Buffer  *buf;           /* Buffer for the new string */
623         Boolean addSpace;       /* TRUE if need to add a space to the buffer
624                                  * before adding the trimmed word */
625         int     i;
626
627         av = brk_string(str, &ac, FALSE);
628
629         buf = Buf_Init(0);
630
631         addSpace = FALSE;
632         for (i = 1; i < ac; i++)
633                 addSpace = (*modProc)(av[i], addSpace, buf, datum);
634
635         return (Buf_Peel(buf));
636 }
637
638 /*-
639  *-----------------------------------------------------------------------
640  * VarSortWords --
641  *      Sort the words in the string.
642  *
643  * Input:
644  *      str             String whose words should be sorted
645  *      cmp             A comparison function to control the ordering
646  *
647  * Results:
648  *      A string containing the words sorted
649  *
650  * Side Effects:
651  *      Uses brk_string() so it invalidates any previous call to
652  *      brk_string().
653  *
654  *-----------------------------------------------------------------------
655  */
656 static char *
657 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
658 {
659         char    **av;
660         int     ac;
661         Buffer  *buf;
662         int     i;
663
664         av = brk_string(str, &ac, FALSE);
665         qsort(av + 1, ac - 1, sizeof(char *), cmp);
666
667         buf = Buf_Init(0);
668         for (i = 1; i < ac; i++) {
669                 Buf_Append(buf, av[i]);
670                 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
671         }
672
673         return (Buf_Peel(buf));
674 }
675
676 static int
677 SortIncreasing(const void *l, const void *r)
678 {
679
680         return (strcmp(*(const char* const*)l, *(const char* const*)r));
681 }
682
683 /*-
684  *-----------------------------------------------------------------------
685  * VarGetPattern --
686  *      Pass through the tstr looking for 1) escaped delimiters,
687  *      '$'s and backslashes (place the escaped character in
688  *      uninterpreted) and 2) unescaped $'s that aren't before
689  *      the delimiter (expand the variable substitution).
690  *      Return the expanded string or NULL if the delimiter was missing
691  *      If pattern is specified, handle escaped ampersands, and replace
692  *      unescaped ampersands with the lhs of the pattern.
693  *
694  * Results:
695  *      A string of all the words modified appropriately.
696  *      If length is specified, return the string length of the buffer
697  *      If flags is specified and the last character of the pattern is a
698  *      $ set the VAR_MATCH_END bit of flags.
699  *
700  * Side Effects:
701  *      None.
702  *-----------------------------------------------------------------------
703  */
704 static Buffer *
705 VarGetPattern(VarParser *vp, int delim, int *flags, VarPattern *patt)
706 {
707         Buffer          *buf;
708
709         buf = Buf_Init(0);
710
711         /*
712          * Skim through until the matching delimiter is found; pick up
713          * variable substitutions on the way. Also allow backslashes to quote
714          * the delimiter, $, and \, but don't touch other backslashes.
715          */
716         while (*vp->ptr != '\0') {
717                 if (*vp->ptr == delim) {
718                         return (buf);
719
720                 } else if ((vp->ptr[0] == '\\') &&
721                     ((vp->ptr[1] == delim) ||
722                      (vp->ptr[1] == '\\') ||
723                      (vp->ptr[1] == '$') ||
724                      (vp->ptr[1] == '&' && patt != NULL))) {
725                         vp->ptr++;              /* consume backslash */
726                         Buf_AddByte(buf, (Byte)vp->ptr[0]);
727                         vp->ptr++;
728
729                 } else if (vp->ptr[0] == '$') {
730                         if (vp->ptr[1] == delim) {
731                                 if (flags == NULL) {
732                                         Buf_AddByte(buf, (Byte)vp->ptr[0]);
733                                         vp->ptr++;
734                                 } else {
735                                         /*
736                                          * Unescaped $ at end of patt =>
737                                          * anchor patt at end.
738                                          */
739                                         *flags |= VAR_MATCH_END;
740                                         vp->ptr++;
741                                 }
742                         } else {
743                                 VarParser       subvp = {
744                                         vp->ptr,
745                                         vp->ptr,
746                                         vp->ctxt,
747                                         vp->err
748                                 };
749                                 char   *rval;
750                                 Boolean rfree;
751
752                                 /*
753                                  * If unescaped dollar sign not
754                                  * before the delimiter, assume it's
755                                  * a variable substitution and
756                                  * recurse.
757                                  */
758                                 rval = VarParse(&subvp, &rfree);
759                                 Buf_Append(buf, rval);
760                                 if (rfree)
761                                         free(rval);
762                                 vp->ptr = subvp.ptr;
763                         }
764                 } else if (vp->ptr[0] == '&' && patt != NULL) {
765                         Buf_AppendBuf(buf, patt->lhs);
766                         vp->ptr++;
767                 } else {
768                         Buf_AddByte(buf, (Byte)vp->ptr[0]);
769                         vp->ptr++;
770                 }
771         }
772
773         Buf_Destroy(buf, TRUE);
774         return (NULL);
775 }
776
777 /*-
778  *-----------------------------------------------------------------------
779  * Var_Quote --
780  *      Quote shell meta-characters in the string
781  *
782  * Results:
783  *      The quoted string
784  *
785  * Side Effects:
786  *      None.
787  *
788  *-----------------------------------------------------------------------
789  */
790 char *
791 Var_Quote(const char *str)
792 {
793         Buffer *buf;
794         /* This should cover most shells :-( */
795         static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
796
797         buf = Buf_Init(MAKE_BSIZE);
798         for (; *str; str++) {
799                 if (strchr(meta, *str) != NULL)
800                         Buf_AddByte(buf, (Byte)'\\');
801                 Buf_AddByte(buf, (Byte)*str);
802         }
803
804         return (Buf_Peel(buf));
805 }
806
807 /*-
808  *-----------------------------------------------------------------------
809  * VarREError --
810  *      Print the error caused by a regcomp or regexec call.
811  *
812  * Results:
813  *      None.
814  *
815  * Side Effects:
816  *      An error gets printed.
817  *
818  *-----------------------------------------------------------------------
819  */
820 void
821 VarREError(int err, regex_t *pat, const char *str)
822 {
823         char   *errbuf;
824         int     errlen;
825
826         errlen = regerror(err, pat, 0, 0);
827         errbuf = emalloc(errlen);
828         regerror(err, pat, errbuf, errlen);
829         Error("%s: %s", str, errbuf);
830         free(errbuf);
831 }
832
833 /**
834  * Make sure this variable is fully expanded.
835  */
836 static char *
837 VarExpand(Var *v, VarParser *vp)
838 {
839         char    *value;
840         char    *result;
841
842         if (v->flags & VAR_IN_USE) {
843                 Fatal("Variable %s is recursive.", v->name);
844                 /* NOTREACHED */
845         }
846
847         v->flags |= VAR_IN_USE;
848
849         /*
850          * Before doing any modification, we have to make sure the
851          * value has been fully expanded. If it looks like recursion
852          * might be necessary (there's a dollar sign somewhere in the
853          * variable's value) we just call Var_Subst to do any other
854          * substitutions that are necessary. Note that the value
855          * returned by Var_Subst will have been
856          * dynamically-allocated, so it will need freeing when we
857          * return.
858          */
859         value = Buf_Data(v->val);
860         if (strchr(value, '$') == NULL) {
861                 result = strdup(value);
862         } else {
863                 Buffer  *buf;
864
865                 buf = Var_Subst(NULL, value, vp->ctxt, vp->err);
866                 result = Buf_Peel(buf);
867         }
868
869         v->flags &= ~VAR_IN_USE;
870
871         return (result);
872 }
873
874 /**
875  * Select only those words in value that match the modifier.
876  */
877 static char *
878 modifier_M(VarParser *vp, const char value[], char endc)
879 {
880         char    *patt;
881         char    *ptr;
882         char    *newValue;
883         char    modifier;
884
885         modifier = vp->ptr[0];
886         vp->ptr++;      /* consume 'M' or 'N' */
887
888         /*
889          * Compress the \:'s out of the pattern, so allocate enough
890          * room to hold the uncompressed pattern and compress the
891          * pattern into that space.
892          */
893         patt = estrdup(vp->ptr);
894         ptr = patt;
895         while (vp->ptr[0] != '\0') {
896                 if (vp->ptr[0] == endc || vp->ptr[0] == ':') {
897                         break;
898                 }
899                 if (vp->ptr[0] == '\\' &&
900                     (vp->ptr[1] == endc || vp->ptr[1] == ':')) {
901                         vp->ptr++;      /* consume backslash */
902                 }
903                 *ptr = vp->ptr[0];
904                 ptr++;
905                 vp->ptr++;
906         }
907         *ptr = '\0';
908
909         if (modifier == 'M') {
910                 newValue = VarModify(value, VarMatch, patt);
911         } else {
912                 newValue = VarModify(value, VarNoMatch, patt);
913         }
914         free(patt);
915
916         return (newValue);
917 }
918
919 /**
920  * Substitute the replacement string for the pattern.  The substitution
921  * is applied to each word in value.
922  */
923 static char *
924 modifier_S(VarParser *vp, const char value[], Var *v)
925 {
926         VarPattern      patt;
927         char            delim;
928         char            *newValue;
929
930         patt.flags = 0;
931
932         vp->ptr++;              /* consume 'S' */
933
934         delim = *vp->ptr;       /* used to find end of pattern */
935         vp->ptr++;              /* consume 1st delim */
936
937         /*
938          * If pattern begins with '^', it is anchored to the start of the
939          * word -- skip over it and flag pattern.
940          */
941         if (*vp->ptr == '^') {
942                 patt.flags |= VAR_MATCH_START;
943                 vp->ptr++;
944         }
945
946         patt.lhs = VarGetPattern(vp, delim, &patt.flags, NULL);
947         if (patt.lhs == NULL) {
948                 /*
949                  * LHS didn't end with the delim, complain and exit.
950                  */
951                 Fatal("Unclosed substitution for %s (%c missing)",
952                     v->name, delim);
953         }
954
955         vp->ptr++;      /* consume 2nd delim */
956
957         patt.rhs = VarGetPattern(vp, delim, NULL, &patt);
958         if (patt.rhs == NULL) {
959                 /*
960                  * RHS didn't end with the delim, complain and exit.
961                  */
962                 Fatal("Unclosed substitution for %s (%c missing)",
963                     v->name, delim);
964         }
965
966         vp->ptr++;      /* consume last delim */
967
968         /*
969          * Check for global substitution. If 'g' after the final delimiter,
970          * substitution is global and is marked that way.
971          */
972         if (vp->ptr[0] == 'g') {
973                 patt.flags |= VAR_SUB_GLOBAL;
974                 vp->ptr++;
975         }
976
977         /*
978          * Global substitution of the empty string causes an infinite number
979          * of matches, unless anchored by '^' (start of string) or '$' (end
980          * of string). Catch the infinite substitution here. Note that flags
981          * can only contain the 3 bits we're interested in so we don't have
982          * to mask unrelated bits. We can test for equality.
983          */
984         if (Buf_Size(patt.lhs) == 0 && patt.flags == VAR_SUB_GLOBAL)
985                 Fatal("Global substitution of the empty string");
986
987         newValue = VarModify(value, VarSubstitute, &patt);
988
989         /*
990          * Free the two strings.
991          */
992         free(patt.lhs);
993         free(patt.rhs);
994
995         return (newValue);
996 }
997
998 static char *
999 modifier_C(VarParser *vp, char value[], Var *v)
1000 {
1001         VarPattern      patt;
1002         char            delim;
1003         int             error;
1004         char            *newValue;
1005
1006         patt.flags = 0;
1007
1008         vp->ptr++;              /* consume 'C' */
1009
1010         delim = *vp->ptr;       /* delimiter between sections */
1011
1012         vp->ptr++;              /* consume 1st delim */
1013
1014         patt.lhs = VarGetPattern(vp, delim, NULL, NULL);
1015         if (patt.lhs == NULL) {
1016                 Fatal("Unclosed substitution for %s (%c missing)",
1017                      v->name, delim);
1018         }
1019
1020         vp->ptr++;              /* consume 2st delim */
1021
1022         patt.rhs = VarGetPattern(vp, delim, NULL, NULL);
1023         if (patt.rhs == NULL) {
1024                 Fatal("Unclosed substitution for %s (%c missing)",
1025                      v->name, delim);
1026         }
1027
1028         vp->ptr++;              /* consume last delim */
1029
1030         switch (*vp->ptr) {
1031         case 'g':
1032                 patt.flags |= VAR_SUB_GLOBAL;
1033                 vp->ptr++;              /* consume 'g' */
1034                 break;
1035         case '1':
1036                 patt.flags |= VAR_SUB_ONE;
1037                 vp->ptr++;              /* consume '1' */
1038                 break;
1039         default:
1040                 break;
1041         }
1042
1043         error = regcomp(&patt.re, Buf_Data(patt.lhs), REG_EXTENDED);
1044         if (error) {
1045                 VarREError(error, &patt.re, "RE substitution error");
1046                 free(patt.rhs);
1047                 free(patt.lhs);
1048                 return (var_Error);
1049         }
1050
1051         patt.nsub = patt.re.re_nsub + 1;
1052         if (patt.nsub < 1)
1053                 patt.nsub = 1;
1054         if (patt.nsub > 10)
1055                 patt.nsub = 10;
1056         patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1057
1058         newValue = VarModify(value, VarRESubstitute, &patt);
1059
1060         regfree(&patt.re);
1061         free(patt.matches);
1062         free(patt.rhs);
1063         free(patt.lhs);
1064
1065         return (newValue);
1066 }
1067
1068 static char *
1069 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1070 {
1071 #ifdef SYSVVARSUB
1072         /*
1073          * This can either be a bogus modifier or a System-V substitution
1074          * command.
1075          */
1076         char            endc;
1077         VarPattern      patt;
1078         Boolean         eqFound;
1079         int             cnt;
1080         char            *newStr;
1081         const char      *cp;
1082
1083         endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1084
1085         patt.flags = 0;
1086
1087         /*
1088          * First we make a pass through the string trying to verify it is a
1089          * SYSV-make-style translation: it must be: <string1>=<string2>)
1090          */
1091         eqFound = FALSE;
1092         cp = vp->ptr;
1093         cnt = 1;
1094         while (*cp != '\0' && cnt) {
1095                 if (*cp == '=') {
1096                         eqFound = TRUE;
1097                         /* continue looking for endc */
1098                 } else if (*cp == endc)
1099                         cnt--;
1100                 else if (*cp == startc)
1101                         cnt++;
1102                 if (cnt)
1103                         cp++;
1104         }
1105
1106         if (*cp == endc && eqFound) {
1107                 /*
1108                  * Now we break this sucker into the lhs and rhs.
1109                  */
1110                 patt.lhs = VarGetPattern(vp, '=', &patt.flags, NULL);
1111                 if (patt.lhs == NULL) {
1112                         Fatal("Unclosed substitution for %s (%c missing)",
1113                               v->name, '=');
1114                 }
1115                 vp->ptr++;      /* consume '=' */
1116
1117                 patt.rhs = VarGetPattern(vp, endc, NULL, &patt);
1118                 if (patt.rhs == NULL) {
1119                         Fatal("Unclosed substitution for %s (%c missing)",
1120                               v->name, endc);
1121                 }
1122
1123                 /*
1124                  * SYSV modifications happen through the whole string. Note
1125                  * the pattern is anchored at the end.
1126                  */
1127                 newStr = VarModify(value, VarSYSVMatch, &patt);
1128
1129                 free(patt.lhs);
1130                 free(patt.rhs);
1131         } else
1132 #endif
1133         {
1134                 Error("Unknown modifier '%c'\n", *vp->ptr);
1135                 vp->ptr++;
1136                 while (*vp->ptr != '\0') {
1137                         if (*vp->ptr == endc && *vp->ptr == ':') {
1138                                 break;
1139                         }
1140                         vp->ptr++;
1141                 }
1142                 newStr = var_Error;
1143         }
1144
1145         return (newStr);
1146 }
1147
1148 /*
1149  * Now we need to apply any modifiers the user wants applied.
1150  * These are:
1151  *      :M<pattern>
1152  *              words which match the given <pattern>.
1153  *              <pattern> is of the standard file
1154  *              wildcarding form.
1155  *      :S<d><pat1><d><pat2><d>[g]
1156  *              Substitute <pat2> for <pat1> in the value
1157  *      :C<d><pat1><d><pat2><d>[g]
1158  *              Substitute <pat2> for regex <pat1> in the value
1159  *      :H      Substitute the head of each word
1160  *      :T      Substitute the tail of each word
1161  *      :E      Substitute the extension (minus '.') of
1162  *              each word
1163  *      :R      Substitute the root of each word
1164  *              (pathname minus the suffix).
1165  *      :lhs=rhs
1166  *              Like :S, but the rhs goes to the end of
1167  *              the invocation.
1168  *      :U      Converts variable to upper-case.
1169  *      :L      Converts variable to lower-case.
1170  *
1171  * XXXHB update this comment or remove it and point to the man page.
1172  */
1173 static char *
1174 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1175 {
1176         char    *value;
1177         char    endc;
1178
1179         value = VarExpand(v, vp);
1180         *freeResult = TRUE;
1181
1182         endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1183
1184         vp->ptr++;      /* consume first colon */
1185
1186         while (*vp->ptr != '\0') {
1187                 char    *newStr;        /* New value to return */
1188
1189                 if (*vp->ptr == endc) {
1190                         return (value);
1191                 }
1192
1193                 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1194                 switch (*vp->ptr) {
1195                 case 'N':
1196                 case 'M':
1197                         newStr = modifier_M(vp, value, endc);
1198                         break;
1199                 case 'S':
1200                         newStr = modifier_S(vp, value, v);
1201                         break;
1202                 case 'C':
1203                         newStr = modifier_C(vp, value, v);
1204                         break;
1205                 default:
1206                         if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1207 #ifdef SUNSHCMD
1208                                 if ((vp->ptr[0] == 's') &&
1209                                     (vp->ptr[1] == 'h') &&
1210                                     (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1211                                         const char      *error;
1212                                         Buffer          *buf;
1213
1214                                         buf = Cmd_Exec(value, &error);
1215                                         newStr = Buf_Peel(buf);
1216
1217                                         if (error)
1218                                                 Error(error, value);
1219                                         vp->ptr += 2;
1220                                 } else
1221 #endif
1222                                 {
1223                                         newStr = sysVvarsub(vp, startc, v, value);
1224                                 }
1225                                 break;
1226                         }
1227
1228                         switch (vp->ptr[0]) {
1229                         case 'L':
1230                                 {
1231                                 const char      *cp;
1232                                 Buffer          *buf;
1233                                 buf = Buf_Init(MAKE_BSIZE);
1234                                 for (cp = value; *cp; cp++)
1235                                         Buf_AddByte(buf, (Byte)tolower(*cp));
1236
1237                                 newStr = Buf_Peel(buf);
1238
1239                                 vp->ptr++;
1240                                 break;
1241                                 }
1242                         case 'O':
1243                                 newStr = VarSortWords(value, SortIncreasing);
1244                                 vp->ptr++;
1245                                 break;
1246                         case 'Q':
1247                                 newStr = Var_Quote(value);
1248                                 vp->ptr++;
1249                                 break;
1250                         case 'T':
1251                                 newStr = VarModify(value, VarTail, NULL);
1252                                 vp->ptr++;
1253                                 break;
1254                         case 'U':
1255                                 {
1256                                 const char      *cp;
1257                                 Buffer          *buf;
1258                                 buf = Buf_Init(MAKE_BSIZE);
1259                                 for (cp = value; *cp; cp++)
1260                                         Buf_AddByte(buf, (Byte)toupper(*cp));
1261
1262                                 newStr = Buf_Peel(buf);
1263
1264                                 vp->ptr++;
1265                                 break;
1266                                 }
1267                         case 'H':
1268                                 newStr = VarModify(value, VarHead, NULL);
1269                                 vp->ptr++;
1270                                 break;
1271                         case 'E':
1272                                 newStr = VarModify(value, VarSuffix, NULL);
1273                                 vp->ptr++;
1274                                 break;
1275                         case 'R':
1276                                 newStr = VarModify(value, VarRoot, NULL);
1277                                 vp->ptr++;
1278                                 break;
1279                         default:
1280                                 newStr = sysVvarsub(vp, startc, v, value);
1281                                 break;
1282                         }
1283                         break;
1284                 }
1285
1286                 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1287                 if (*freeResult) {
1288                         free(value);
1289                 }
1290
1291                 value = newStr;
1292                 *freeResult = (value == var_Error) ? FALSE : TRUE;
1293
1294                 if (vp->ptr[0] == ':') {
1295                         vp->ptr++;      /* consume colon */
1296                 }
1297         }
1298
1299         return (value);
1300 }
1301
1302 static char *
1303 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1304 {
1305         const char      *vname;
1306         size_t          vlen;
1307         Var             *v;
1308         char            *value;
1309
1310         vname = Buf_GetAll(buf, &vlen);
1311
1312         v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1313         if (v != NULL) {
1314                 value = ParseModifier(vp, startc, v, freeResult);
1315
1316                 if (v->flags & VAR_FROM_ENV) {
1317                         VarDestroy(v, TRUE);
1318                 }
1319                 return (value);
1320         }
1321
1322         if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1323                 size_t  consumed = vp->ptr - vp->input + 1;
1324
1325                 /*
1326                  * If substituting a local variable in a non-local context,
1327                  * assume it's for dynamic source stuff. We have to handle
1328                  * this specially and return the longhand for the variable
1329                  * with the dollar sign escaped so it makes it back to the
1330                  * caller. Only four of the local variables are treated
1331                  * specially as they are the only four that will be set when
1332                  * dynamic sources are expanded.
1333                  */
1334                 if (vlen == 1 ||
1335                     (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1336                         if (strchr("!%*@", vname[0]) != NULL) {
1337                                 value = emalloc(consumed + 1);
1338                                 strncpy(value, vp->input, consumed);
1339                                 value[consumed] = '\0';
1340
1341                                 *freeResult = TRUE;
1342                                 return (value);
1343                         }
1344                 }
1345                 if (vlen > 2 &&
1346                     vname[0] == '.' &&
1347                     isupper((unsigned char)vname[1])) {
1348                         if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1349                             (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1350                             (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1351                             (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1352                                 value = emalloc(consumed + 1);
1353                                 strncpy(value, vp->input, consumed);
1354                                 value[consumed] = '\0';
1355
1356                                 *freeResult = TRUE;
1357                                 return (value);
1358                         }
1359                 }
1360         } else {
1361                 /*
1362                  * Check for D and F forms of local variables since we're in
1363                  * a local context and the name is the right length.
1364                  */
1365                 if (vlen == 2 &&
1366                     (vname[1] == 'F' || vname[1] == 'D') &&
1367                     (strchr("!%*<>@", vname[0]) != NULL)) {
1368                         char    name[2];
1369
1370                         name[0] = vname[0];
1371                         name[1] = '\0';
1372
1373                         v = VarFind(name, vp->ctxt, 0);
1374                         if (v != NULL) {
1375                                 value = ParseModifier(vp, startc, v, freeResult);
1376                                 return (value);
1377                         }
1378                 }
1379         }
1380
1381         /*
1382          * Still need to get to the end of the variable
1383          * specification, so kludge up a Var structure for the
1384          * modifications
1385          */
1386         v = VarCreate(vname, NULL, VAR_JUNK);
1387         value = ParseModifier(vp, startc, v, freeResult);
1388         if (*freeResult) {
1389                 free(value);
1390         }
1391         VarDestroy(v, TRUE);
1392
1393         *freeResult = FALSE;
1394         return (vp->err ? var_Error : varNoError);
1395 }
1396
1397 static char *
1398 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1399 {
1400         const char      *vname;
1401         size_t          vlen;
1402         Var             *v;
1403         char            *value;
1404
1405         vname = Buf_GetAll(buf, &vlen);
1406
1407         v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1408         if (v != NULL) {
1409                 value = VarExpand(v, vp);
1410
1411                 if (v->flags & VAR_FROM_ENV) {
1412                         VarDestroy(v, TRUE);
1413                 }
1414
1415                 *freeResult = TRUE;
1416                 return (value);
1417         }
1418
1419         if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1420                 size_t  consumed = vp->ptr - vp->input + 1;
1421
1422                 /*
1423                  * If substituting a local variable in a non-local context,
1424                  * assume it's for dynamic source stuff. We have to handle
1425                  * this specially and return the longhand for the variable
1426                  * with the dollar sign escaped so it makes it back to the
1427                  * caller. Only four of the local variables are treated
1428                  * specially as they are the only four that will be set when
1429                  * dynamic sources are expanded.
1430                  */
1431                 if (vlen == 1 ||
1432                     (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1433                         if (strchr("!%*@", vname[0]) != NULL) {
1434                                 value = emalloc(consumed + 1);
1435                                 strncpy(value, vp->input, consumed);
1436                                 value[consumed] = '\0';
1437
1438                                 *freeResult = TRUE;
1439                                 return (value);
1440                         }
1441                 }
1442                 if (vlen > 2 &&
1443                     vname[0] == '.' &&
1444                     isupper((unsigned char)vname[1])) {
1445                         if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1446                             (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1447                             (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1448                             (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1449                                 value = emalloc(consumed + 1);
1450                                 strncpy(value, vp->input, consumed);
1451                                 value[consumed] = '\0';
1452
1453                                 *freeResult = TRUE;
1454                                 return (value);
1455                         }
1456                 }
1457         } else {
1458                 /*
1459                  * Check for D and F forms of local variables since we're in
1460                  * a local context and the name is the right length.
1461                  */
1462                 if (vlen == 2 &&
1463                     (vname[1] == 'F' || vname[1] == 'D') &&
1464                     (strchr("!%*<>@", vname[0]) != NULL)) {
1465                         char    name[2];
1466
1467                         name[0] = vname[0];
1468                         name[1] = '\0';
1469
1470                         v = VarFind(name, vp->ctxt, 0);
1471                         if (v != NULL) {
1472                                 char    *val;
1473                                 /*
1474                                  * No need for nested expansion or anything,
1475                                  * as we're the only one who sets these
1476                                  * things and we sure don't put nested
1477                                  * invocations in them...
1478                                  */
1479                                 val = Buf_Data(v->val);
1480
1481                                 if (vname[1] == 'D') {
1482                                         val = VarModify(val, VarHead, NULL);
1483                                 } else {
1484                                         val = VarModify(val, VarTail, NULL);
1485                                 }
1486
1487                                 *freeResult = TRUE;
1488                                 return (val);
1489                         }
1490                 }
1491         }
1492
1493         *freeResult = FALSE;
1494         return (vp->err ? var_Error : varNoError);
1495 }
1496
1497 /**
1498  * Parse a multi letter variable name, and return it's value.
1499  */
1500 static char *
1501 VarParseLong(VarParser *vp, Boolean *freeResult)
1502 {
1503         Buffer          *buf;
1504         char            startc;
1505         char            endc;
1506         char            *value;
1507
1508         buf = Buf_Init(MAKE_BSIZE);
1509
1510         startc = vp->ptr[0];
1511         vp->ptr++;              /* consume opening paren or brace */
1512
1513         endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1514
1515         /*
1516          * Process characters until we reach an end character or a colon,
1517          * replacing embedded variables as we go.
1518          */
1519         while (*vp->ptr != '\0') {
1520                 if (*vp->ptr == endc) {
1521                         value = ParseRestEnd(vp, buf, freeResult);
1522                         vp->ptr++;      /* consume closing paren or brace */
1523                         Buf_Destroy(buf, TRUE);
1524                         return (value);
1525
1526                 } else if (*vp->ptr == ':') {
1527                         value = ParseRestModifier(vp, startc, buf, freeResult);
1528                         vp->ptr++;      /* consume closing paren or brace */
1529                         Buf_Destroy(buf, TRUE);
1530                         return (value);
1531
1532                 } else if (*vp->ptr == '$') {
1533                         VarParser       subvp = {
1534                                 vp->ptr,
1535                                 vp->ptr,
1536                                 vp->ctxt,
1537                                 vp->err
1538                         };
1539                         char    *rval;
1540                         Boolean rfree;
1541
1542                         rval = VarParse(&subvp, &rfree);
1543                         if (rval == var_Error) {
1544                                 Fatal("Error expanding embedded variable.");
1545                         }
1546                         Buf_Append(buf, rval);
1547                         if (rfree)
1548                                 free(rval);
1549                         vp->ptr = subvp.ptr;
1550                 } else {
1551                         Buf_AddByte(buf, (Byte)*vp->ptr);
1552                         vp->ptr++;
1553                 }
1554         }
1555
1556         /* If we did not find the end character, return var_Error */
1557         Buf_Destroy(buf, TRUE);
1558         *freeResult = FALSE;
1559         return (var_Error);
1560 }
1561
1562 /**
1563  * Parse a single letter variable name, and return it's value.
1564  */
1565 static char *
1566 VarParseShort(VarParser *vp, Boolean *freeResult)
1567 {
1568         char    vname[2];
1569         Var     *v;
1570         char    *value;
1571
1572         vname[0] = vp->ptr[0];
1573         vname[1] = '\0';
1574
1575         vp->ptr++;      /* consume single letter */
1576
1577         v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1578         if (v != NULL) {
1579                 value = VarExpand(v, vp);
1580
1581                 if (v->flags & VAR_FROM_ENV) {
1582                         VarDestroy(v, TRUE);
1583                 }
1584
1585                 *freeResult = TRUE;
1586                 return (value);
1587         }
1588
1589         /*
1590          * If substituting a local variable in a non-local context, assume
1591          * it's for dynamic source stuff. We have to handle this specially
1592          * and return the longhand for the variable with the dollar sign
1593          * escaped so it makes it back to the caller. Only four of the local
1594          * variables are treated specially as they are the only four that
1595          * will be set when dynamic sources are expanded.
1596          */
1597         if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1598
1599                 /* XXX: It looks like $% and $! are reversed here */
1600                 switch (vname[0]) {
1601                 case '@':
1602                         *freeResult = TRUE;
1603                         return (estrdup("$(.TARGET)"));
1604                 case '%':
1605                         *freeResult = TRUE;
1606                         return (estrdup("$(.ARCHIVE)"));
1607                 case '*':
1608                         *freeResult = TRUE;
1609                         return (estrdup("$(.PREFIX)"));
1610                 case '!':
1611                         *freeResult = TRUE;
1612                         return (estrdup("$(.MEMBER)"));
1613                 default:
1614                         *freeResult = FALSE;
1615                         return (vp->err ? var_Error : varNoError);
1616                 }
1617         }
1618
1619         /* Variable name was not found. */
1620         *freeResult = FALSE;
1621         return (vp->err ? var_Error : varNoError);
1622 }
1623
1624 static char *
1625 VarParse(VarParser *vp, Boolean *freeResult)
1626 {
1627
1628         vp->ptr++;      /* consume '$' or last letter of conditional */
1629
1630         if (vp->ptr[0] == '\0') {
1631                 /* Error, there is only a dollar sign in the input string. */
1632                 *freeResult = FALSE;
1633                 return (vp->err ? var_Error : varNoError);
1634
1635         } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
1636                 /* multi letter variable name */
1637                 return (VarParseLong(vp, freeResult));
1638
1639         } else {
1640                 /* single letter variable name */
1641                 return (VarParseShort(vp, freeResult));
1642         }
1643 }
1644
1645 /*-
1646  *-----------------------------------------------------------------------
1647  * Var_Parse --
1648  *      Given the start of a variable invocation, extract the variable
1649  *      name and find its value, then modify it according to the
1650  *      specification.
1651  *
1652  * Results:
1653  *      The value of the variable or var_Error if the specification
1654  *      is invalid.  The number of characters in the specification
1655  *      is placed in the variable pointed to by consumed.  (for
1656  *      invalid specifications, this is just 2 to skip the '$' and
1657  *      the following letter, or 1 if '$' was the last character
1658  *      in the string).  A Boolean in *freeResult telling whether the
1659  *      returned string should be freed by the caller.
1660  *
1661  * Side Effects:
1662  *      None.
1663  *-----------------------------------------------------------------------
1664  */
1665 char *
1666 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1667         size_t *consumed, Boolean *freeResult)
1668 {
1669         VarParser       vp = {
1670                 input,
1671                 input,
1672                 ctxt,
1673                 err
1674         };
1675         char            *value;
1676
1677         value = VarParse(&vp, freeResult);
1678         *consumed += vp.ptr - vp.input;
1679         return (value);
1680 }
1681
1682 /*-
1683  *-----------------------------------------------------------------------
1684  * Var_Subst  --
1685  *      Substitute for all variables in the given string in the given context
1686  *      If err is TRUE, Parse_Error will be called when an undefined
1687  *      variable is encountered.
1688  *
1689  * Results:
1690  *      The resulting string.
1691  *
1692  * Side Effects:
1693  *      None. The old string must be freed by the caller
1694  *-----------------------------------------------------------------------
1695  */
1696 Buffer *
1697 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean err)
1698 {
1699         Boolean errorReported;
1700         Buffer *buf;            /* Buffer for forming things */
1701
1702         /*
1703          * Set TRUE if an error has already been reported to prevent a
1704          * plethora of messages when recursing. XXXHB this comment sounds
1705          * wrong.
1706          */
1707         errorReported = FALSE;
1708
1709         buf = Buf_Init(0);
1710         while (*str) {
1711                 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1712                         /*
1713                          * A dollar sign may be escaped either with another
1714                          * dollar sign. In such a case, we skip over the
1715                          * escape character and store the dollar sign into
1716                          * the buffer directly.
1717                          */
1718                         Buf_AddByte(buf, (Byte)str[0]);
1719                         str += 2;
1720
1721                 } else if (str[0] == '$') {
1722                         /*
1723                          * Variable invocation.
1724                          */
1725                         if (var != NULL) {
1726                                 int     expand;
1727                                 for (;;) {
1728                                         if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1729                                                 size_t  ln;
1730                                                 const char *p = str + 2;
1731
1732                                                 /*
1733                                                  * Scan up to the end of the
1734                                                  * variable name.
1735                                                  */
1736                                                 while (*p != '\0' &&
1737                                                        *p != ':' &&
1738                                                        *p != CLOSE_PAREN &&
1739                                                        *p != CLOSE_BRACE &&
1740                                                        *p != '$') {
1741                                                         ++p;
1742                                                 }
1743
1744                                                 /*
1745                                                  * A variable inside the
1746                                                  * variable. We cannot expand
1747                                                  * the external variable yet,
1748                                                  * so we try again with the
1749                                                  * nested one
1750                                                  */
1751                                                 if (*p == '$') {
1752                                                         Buf_AppendRange(buf, str, p);
1753                                                         str = p;
1754                                                         continue;
1755                                                 }
1756                                                 ln = p - (str + 2);
1757                                                 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1758                                                         expand = TRUE;
1759                                                 } else {
1760                                                         /*
1761                                                          * Not the variable
1762                                                          * we want to expand,
1763                                                          * scan until the
1764                                                          * next variable
1765                                                          */
1766                                                         while (*p != '$' && *p != '\0')
1767                                                                 p++;
1768
1769                                                         Buf_AppendRange(buf, str, p);
1770                                                         str = p;
1771                                                         expand = FALSE;
1772                                                 }
1773                                         } else {
1774                                                 /*
1775                                                  * Single letter variable
1776                                                  * name
1777                                                  */
1778                                                 if (var[1] == '\0' && var[0] == str[1]) {
1779                                                         expand = TRUE;
1780                                                 } else {
1781                                                         Buf_AddBytes(buf, 2, (const Byte *) str);
1782                                                         str += 2;
1783                                                         expand = FALSE;
1784                                                 }
1785                                         }
1786                                         break;
1787                                 }
1788                                 if (!expand)
1789                                         continue;
1790                         }
1791                     {
1792                         VarParser       subvp = {
1793                                 str,
1794                                 str,
1795                                 ctxt,
1796                                 err
1797                         };
1798                         char    *rval;
1799                         Boolean rfree;
1800
1801                         rval = VarParse(&subvp, &rfree);
1802
1803                         /*
1804                          * When we come down here, val should either point to
1805                          * the value of this variable, suitably modified, or
1806                          * be NULL. Length should be the total length of the
1807                          * potential variable invocation (from $ to end
1808                          * character...)
1809                          */
1810                         if (rval == var_Error || rval == varNoError) {
1811                                 /*
1812                                  * If performing old-time variable
1813                                  * substitution, skip over the variable and
1814                                  * continue with the substitution. Otherwise,
1815                                  * store the dollar sign and advance str so
1816                                  * we continue with the string...
1817                                  */
1818                                 if (oldVars) {
1819                                         str = subvp.ptr;
1820                                 } else if (err) {
1821                                         /*
1822                                          * If variable is undefined, complain
1823                                          * and skip the variable. The
1824                                          * complaint will stop us from doing
1825                                          * anything when the file is parsed.
1826                                          */
1827                                         if (!errorReported) {
1828                                                 Parse_Error(PARSE_FATAL,
1829                                                             "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
1830                                         }
1831                                         str = subvp.ptr;
1832                                         errorReported = TRUE;
1833                                 } else {
1834                                         Buf_AddByte(buf, (Byte)*str);
1835                                         str += 1;
1836                                 }
1837                         } else {
1838                                 /*
1839                                  * We've now got a variable structure to
1840                                  * store in. But first, advance the string
1841                                  * pointer.
1842                                  */
1843                                 str = subvp.ptr;
1844
1845                                 /*
1846                                  * Copy all the characters from the variable
1847                                  * value straight into the new string.
1848                                  */
1849                                 Buf_Append(buf, rval);
1850                                 if (rfree) {
1851                                         free(rval);
1852                                 }
1853                         }
1854                     }
1855                 } else {
1856                         /*
1857                          * Skip as many characters as possible -- either to
1858                          * the end of the string or to the next dollar sign
1859                          * (variable invocation).
1860                          */
1861                         const char *cp = str;
1862
1863                         do {
1864                                 str++;
1865                         } while (str[0] != '$' && str[0] != '\0');
1866
1867                         Buf_AppendRange(buf, cp, str);
1868                 }
1869         }
1870
1871         return (buf);
1872 }
1873
1874 /*-
1875  *-----------------------------------------------------------------------
1876  * Var_GetTail --
1877  *      Return the tail from each of a list of words. Used to set the
1878  *      System V local variables.
1879  *
1880  * Results:
1881  *      The resulting string.
1882  *
1883  * Side Effects:
1884  *      None.
1885  *
1886  *-----------------------------------------------------------------------
1887  */
1888 char *
1889 Var_GetTail(char *file)
1890 {
1891
1892         return (VarModify(file, VarTail, (void *)NULL));
1893 }
1894
1895 /*-
1896  *-----------------------------------------------------------------------
1897  * Var_GetHead --
1898  *      Find the leading components of a (list of) filename(s).
1899  *      XXX: VarHead does not replace foo by ., as (sun) System V make
1900  *      does.
1901  *
1902  * Results:
1903  *      The leading components.
1904  *
1905  * Side Effects:
1906  *      None.
1907  *
1908  *-----------------------------------------------------------------------
1909  */
1910 char *
1911 Var_GetHead(char *file)
1912 {
1913
1914         return (VarModify(file, VarHead, (void *)NULL));
1915 }
1916
1917 /*-
1918  *-----------------------------------------------------------------------
1919  * Var_Init --
1920  *      Initialize the module
1921  *
1922  * Results:
1923  *      None
1924  *
1925  * Side Effects:
1926  *      The VAR_CMD and VAR_GLOBAL contexts are created
1927  *-----------------------------------------------------------------------
1928  */
1929 void
1930 Var_Init(void)
1931 {
1932
1933         VAR_GLOBAL = Targ_NewGN("Global");
1934         VAR_CMD = Targ_NewGN("Command");
1935 }
1936
1937 /*-
1938  *-----------------------------------------------------------------------
1939  * Var_Dump --
1940  *      print all variables in a context
1941  *-----------------------------------------------------------------------
1942  */
1943 void
1944 Var_Dump(const GNode *ctxt)
1945 {
1946         const LstNode   *ln;
1947         const Var       *v;
1948
1949         LST_FOREACH(ln, &ctxt->context) {
1950                 v = Lst_Datum(ln);
1951                 printf("%-16s = %s\n", v->name, Buf_Data(v->val));
1952         }
1953 }