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