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