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