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