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