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