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