Changed renamed macros *_BRACKET to *_BRACE.
[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.74 2005/02/09 20:55:15 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  *-----------------------------------------------------------------------
883  */
884 char *
885 Var_Parse(char *str, GNode *ctxt, Boolean err, size_t *lengthPtr,
886     Boolean *freePtr)
887 {
888     char            *tstr;      /* Pointer into str */
889     Var             *v;         /* Variable in invocation */
890     char            *cp;        /* Secondary pointer into str (place marker
891                                  * for tstr) */
892     Boolean         haveModifier;/* TRUE if have modifiers for the variable */
893     char            endc;       /* Ending character when variable in parens
894                                  * or braces */
895     char            startc;     /* Starting character when variable in parens
896                                  * or braces */
897     char            *start;
898     char             delim;
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     int         vlen;           /* length of variable name, after embedded variable
904                                  * expansion */
905
906     *freePtr = FALSE;
907     dynamic = FALSE;
908     start = str;
909
910     /*
911      * It is assumed that Var_Parse() is called with str[0] == '$'
912      */
913
914     if (str[1] == '\0') {
915         /*
916          * Error, there is only a dollar sign in the input string.
917          */
918         *lengthPtr = 1;
919         return (err ? var_Error : varNoError);
920
921     } else if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
922         /*
923          * Check if brackets contain a variable name.
924          */
925
926         /* build up expanded variable name in this buffer */
927         Buffer  *buf = Buf_Init(MAKE_BSIZE);
928
929         /*
930          * Skip to the end character or a colon, whichever comes first,
931          * replacing embedded variables as we go.
932          */
933         startc = str[1];
934         endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
935         tstr = str + 2;
936
937         while (*tstr != '\0' && *tstr != endc && *tstr != ':') {
938             if (*tstr == '$') {
939                 size_t  rlen;
940                 Boolean rfree;
941                 char    *rval;
942
943                 rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
944                 if (rval == var_Error) {
945                         Fatal("Error expanding embedded variable.");
946                 } else if (rval != NULL) {
947                         Buf_Append(buf, rval);
948                         if (rfree)
949                                 free(rval);
950                 }
951                 tstr += rlen - 1;
952             } else {
953                 Buf_AddByte(buf, (Byte)*tstr);
954             }
955             tstr++;
956         }
957
958         if (*tstr == '\0') {
959             /*
960              * If we never did find the end character, return NULL
961              * right now, setting the length to be the distance to
962              * the end of the string, since that's what make does.
963              */
964             *lengthPtr = tstr - str;
965             return (var_Error);
966         }
967
968         haveModifier = (*tstr == ':');
969         *tstr = '\0';                   /* modify input string */
970
971         Buf_AddByte(buf, (Byte)'\0');
972         str = Buf_GetAll(buf, (size_t *)NULL);  /* REPLACE str */ 
973         vlen = strlen(str);
974
975         v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
976         if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
977             (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
978         {
979             /*
980              * Check for bogus D and F forms of local variables since we're
981              * in a local context and the name is the right length.
982              */
983             switch (str[0]) {
984                 case '@':
985                 case '%':
986                 case '*':
987                 case '!':
988                 case '>':
989                 case '<':
990                 {
991                     char    vname[2];
992                     char    *val;
993
994                     /*
995                      * Well, it's local -- go look for it.
996                      */
997                     vname[0] = str[0];
998                     vname[1] = '\0';
999                     v = VarFind(vname, ctxt, 0);
1000
1001                     if (v != NULL && !haveModifier) {
1002                         /*
1003                          * No need for nested expansion or anything, as we're
1004                          * the only one who sets these things and we sure don't
1005                          * put nested invocations in them...
1006                          */
1007                         val = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1008
1009                         if (str[1] == 'D') {
1010                             val = VarModify(val, VarHead, (void *)NULL);
1011                         } else {
1012                             val = VarModify(val, VarTail, (void *)NULL);
1013                         }
1014                         /*
1015                          * Resulting string is dynamically allocated, so
1016                          * tell caller to free it.
1017                          */
1018                         *freePtr = TRUE;
1019                         *lengthPtr = tstr-start+1;
1020                         *tstr = endc;
1021                         Buf_Destroy(buf, TRUE);
1022                         return (val);
1023                     }
1024                     break;
1025                 default:
1026                     break;
1027                 }
1028             }
1029         }
1030
1031         if (v == (Var *)NULL) {
1032             if (((vlen == 1) ||
1033                  (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
1034                 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1035             {
1036                 /*
1037                  * If substituting a local variable in a non-local context,
1038                  * assume it's for dynamic source stuff. We have to handle
1039                  * this specially and return the longhand for the variable
1040                  * with the dollar sign escaped so it makes it back to the
1041                  * caller. Only four of the local variables are treated
1042                  * specially as they are the only four that will be set
1043                  * when dynamic sources are expanded.
1044                  */
1045                 switch (str[0]) {
1046                     case '@':
1047                     case '%':
1048                     case '*':
1049                     case '!':
1050                         dynamic = TRUE;
1051                         break;
1052                     default:
1053                         break;
1054                 }
1055             } else if ((vlen > 2) && (str[0] == '.') &&
1056                        isupper((unsigned char)str[1]) &&
1057                        ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1058             {
1059                 int     len;
1060
1061                 len = vlen - 1;
1062                 if ((strncmp(str, ".TARGET", len) == 0) ||
1063                     (strncmp(str, ".ARCHIVE", len) == 0) ||
1064                     (strncmp(str, ".PREFIX", len) == 0) ||
1065                     (strncmp(str, ".MEMBER", len) == 0))
1066                 {
1067                     dynamic = TRUE;
1068                 }
1069             }
1070
1071             if (haveModifier) {
1072                 /*
1073                  * Still need to get to the end of the variable specification,
1074                  * so kludge up a Var structure for the modifications
1075                  */
1076                 v = VarCreate(str, NULL, VAR_JUNK);
1077
1078             } else {
1079                 /*
1080                  * No modifiers -- have specification length so we can return
1081                  * now.
1082                  */
1083                 *lengthPtr = tstr - start + 1;
1084                 *tstr = endc;
1085                 if (dynamic) {
1086                     str = emalloc(*lengthPtr + 1);
1087                     strncpy(str, start, *lengthPtr);
1088                     str[*lengthPtr] = '\0';
1089                     *freePtr = TRUE;
1090                     Buf_Destroy(buf, TRUE);
1091                     return (str);
1092                 } else {
1093                     Buf_Destroy(buf, TRUE);
1094                     return (err ? var_Error : varNoError);
1095                 }
1096             }
1097         }
1098         Buf_Destroy(buf, TRUE);
1099
1100     } else {
1101         /*
1102          * If it's not bounded by braces of some sort, life is much simpler.
1103          * We just need to check for the first character and return the
1104          * value if it exists.
1105          */
1106         char      name[2];
1107
1108         *lengthPtr = 2;
1109
1110         name[0] = str[1];
1111         name[1] = '\0';
1112         v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1113         if (v == NULL) {
1114             if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1115                 /*
1116                  * If substituting a local variable in a non-local context,
1117                  * assume it's for dynamic source stuff. We have to handle
1118                  * this specially and return the longhand for the variable
1119                  * with the dollar sign escaped so it makes it back to the
1120                  * caller. Only four of the local variables are treated
1121                  * specially as they are the only four that will be set
1122                  * when dynamic sources are expanded.
1123                  */
1124                 /* XXX: It looks like $% and $! are reversed here */
1125                 switch (str[1]) {
1126                     case '@':
1127                         return ("$(.TARGET)");
1128                     case '%':
1129                         return ("$(.ARCHIVE)");
1130                     case '*':
1131                         return ("$(.PREFIX)");
1132                     case '!':
1133                         return ("$(.MEMBER)");
1134                     default:
1135                         return (err ? var_Error : varNoError);
1136                 }
1137             } else {
1138                 return (err ? var_Error : varNoError);
1139             }
1140         } else {
1141             haveModifier = FALSE;
1142             startc = 0;
1143             endc = str[1];
1144             tstr = &str[1];
1145         }
1146     }
1147
1148     if (v->flags & VAR_IN_USE) {
1149         Fatal("Variable %s is recursive.", v->name);
1150         /*NOTREACHED*/
1151     } else {
1152         v->flags |= VAR_IN_USE;
1153     }
1154
1155     /*
1156      * Before doing any modification, we have to make sure the value
1157      * has been fully expanded. If it looks like recursion might be
1158      * necessary (there's a dollar sign somewhere in the variable's value)
1159      * we just call Var_Subst to do any other substitutions that are
1160      * necessary. Note that the value returned by Var_Subst will have
1161      * been dynamically-allocated, so it will need freeing when we
1162      * return.
1163      */
1164     str = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1165     if (strchr(str, '$') != NULL) {
1166         Buffer  *buf;
1167
1168         buf = Var_Subst(NULL, str, ctxt, err);
1169         str = Buf_GetAll(buf, NULL);
1170         Buf_Destroy(buf, FALSE);
1171
1172         *freePtr = TRUE;
1173     }
1174
1175     v->flags &= ~VAR_IN_USE;
1176
1177     /*
1178      * Now we need to apply any modifiers the user wants applied.
1179      * These are:
1180      *            :M<pattern>   words which match the given <pattern>.
1181      *                          <pattern> is of the standard file
1182      *                          wildcarding form.
1183      *            :S<d><pat1><d><pat2><d>[g]
1184      *                          Substitute <pat2> for <pat1> in the value
1185      *            :C<d><pat1><d><pat2><d>[g]
1186      *                          Substitute <pat2> for regex <pat1> in the value
1187      *            :H            Substitute the head of each word
1188      *            :T            Substitute the tail of each word
1189      *            :E            Substitute the extension (minus '.') of
1190      *                          each word
1191      *            :R            Substitute the root of each word
1192      *                          (pathname minus the suffix).
1193      *            :lhs=rhs      Like :S, but the rhs goes to the end of
1194      *                          the invocation.
1195      *            :U            Converts variable to upper-case.
1196      *            :L            Converts variable to lower-case.
1197      */
1198     if ((str != NULL) && haveModifier) {
1199         /*
1200          * Skip initial colon while putting it back.
1201          */
1202         *tstr++ = ':';
1203         while (*tstr != endc) {
1204             char        *newStr;    /* New value to return */
1205             char        termc;      /* Character which terminated scan */
1206
1207             DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1208             switch (*tstr) {
1209                 case 'N':
1210                 case 'M':
1211                 {
1212                     char    *pattern;
1213                     char    *cp2;
1214                     Boolean copy;
1215
1216                     copy = FALSE;
1217                     for (cp = tstr + 1;
1218                          *cp != '\0' && *cp != ':' && *cp != endc;
1219                          cp++)
1220                     {
1221                         if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
1222                             copy = TRUE;
1223                             cp++;
1224                         }
1225                     }
1226                     termc = *cp;
1227                     *cp = '\0';
1228                     if (copy) {
1229                         /*
1230                          * Need to compress the \:'s out of the pattern, so
1231                          * allocate enough room to hold the uncompressed
1232                          * pattern (note that cp started at tstr+1, so
1233                          * cp - tstr takes the null byte into account) and
1234                          * compress the pattern into the space.
1235                          */
1236                         pattern = emalloc(cp - tstr);
1237                         for (cp2 = pattern, cp = tstr + 1;
1238                              *cp != '\0';
1239                              cp++, cp2++)
1240                         {
1241                             if ((*cp == '\\') &&
1242                                 (cp[1] == ':' || cp[1] == endc)) {
1243                                     cp++;
1244                             }
1245                             *cp2 = *cp;
1246                         }
1247                         *cp2 = '\0';
1248                     } else {
1249                         pattern = &tstr[1];
1250                     }
1251                     if (*tstr == 'M' || *tstr == 'm') {
1252                         newStr = VarModify(str, VarMatch, pattern);
1253                     } else {
1254                         newStr = VarModify(str, VarNoMatch, pattern);
1255                     }
1256                     if (copy) {
1257                         free(pattern);
1258                     }
1259                     break;
1260                 }
1261                 case 'S':
1262                 {
1263                     VarPattern      pattern;
1264                     char            del;
1265                     Buffer          *buf;       /* Buffer for patterns */
1266
1267                     pattern.flags = 0;
1268                     del = tstr[1];
1269                     tstr += 2;
1270
1271                     /*
1272                      * If pattern begins with '^', it is anchored to the
1273                      * start of the word -- skip over it and flag pattern.
1274                      */
1275                     if (*tstr == '^') {
1276                         pattern.flags |= VAR_MATCH_START;
1277                         tstr += 1;
1278                     }
1279
1280                     buf = Buf_Init(0);
1281
1282                     /*
1283                      * Pass through the lhs looking for 1) escaped delimiters,
1284                      * '$'s and backslashes (place the escaped character in
1285                      * uninterpreted) and 2) unescaped $'s that aren't before
1286                      * the delimiter (expand the variable substitution).
1287                      * The result is left in the Buffer buf.
1288                      */
1289                     for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1290                         if ((*cp == '\\') &&
1291                             ((cp[1] == del) ||
1292                              (cp[1] == '$') ||
1293                              (cp[1] == '\\')))
1294                         {
1295                             Buf_AddByte(buf, (Byte)cp[1]);
1296                             cp++;
1297                         } else if (*cp == '$') {
1298                             if (cp[1] != del) {
1299                                 /*
1300                                  * If unescaped dollar sign not before the
1301                                  * delimiter, assume it's a variable
1302                                  * substitution and recurse.
1303                                  */
1304                                 char        *cp2;
1305                                 size_t len;
1306                                 Boolean     freeIt;
1307
1308                                 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1309                                 Buf_Append(buf, cp2);
1310                                 if (freeIt) {
1311                                     free(cp2);
1312                                 }
1313                                 cp += len - 1;
1314                             } else {
1315                                 /*
1316                                  * Unescaped $ at end of pattern => anchor
1317                                  * pattern at end.
1318                                  */
1319                                 pattern.flags |= VAR_MATCH_END;
1320                             }
1321                         } else {
1322                             Buf_AddByte(buf, (Byte)*cp);
1323                         }
1324                     }
1325
1326                     Buf_AddByte(buf, (Byte)'\0');
1327
1328                     /*
1329                      * If lhs didn't end with the delimiter, complain and
1330                      * exit.
1331                      */
1332                     if (*cp != del) {
1333                         Fatal("Unclosed substitution for %s (%c missing)",
1334                               v->name, del);
1335                     }
1336
1337                     /*
1338                      * Fetch pattern and destroy buffer, but preserve the data
1339                      * in it, since that's our lhs. Note that Buf_GetAll
1340                      * will return the actual number of bytes, which includes
1341                      * the null byte, so we have to decrement the length by
1342                      * one.
1343                      */
1344                     pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1345                     pattern.leftLen--;
1346                     Buf_Destroy(buf, FALSE);
1347
1348                     /*
1349                      * Now comes the replacement string. Three things need to
1350                      * be done here: 1) need to compress escaped delimiters and
1351                      * ampersands and 2) need to replace unescaped ampersands
1352                      * with the l.h.s. (since this isn't regexp, we can do
1353                      * it right here) and 3) expand any variable substitutions.
1354                      */
1355                     buf = Buf_Init(0);
1356
1357                     tstr = cp + 1;
1358                     for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1359                         if ((*cp == '\\') &&
1360                             ((cp[1] == del) ||
1361                              (cp[1] == '&') ||
1362                              (cp[1] == '\\') ||
1363                              (cp[1] == '$')))
1364                         {
1365                             Buf_AddByte(buf, (Byte)cp[1]);
1366                             cp++;
1367                         } else if ((*cp == '$') && (cp[1] != del)) {
1368                             char    *cp2;
1369                             size_t len;
1370                             Boolean freeIt;
1371
1372                             cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1373                             Buf_Append(buf, cp2);
1374                             cp += len - 1;
1375                             if (freeIt) {
1376                                 free(cp2);
1377                             }
1378                         } else if (*cp == '&') {
1379                             Buf_AddBytes(buf, pattern.leftLen,
1380                                          (Byte *)pattern.lhs);
1381                         } else {
1382                             Buf_AddByte(buf, (Byte)*cp);
1383                         }
1384                     }
1385
1386                     Buf_AddByte(buf, (Byte)'\0');
1387
1388                     /*
1389                      * If didn't end in delimiter character, complain
1390                      */
1391                     if (*cp != del) {
1392                         Fatal("Unclosed substitution for %s (%c missing)",
1393                               v->name, del);
1394                     }
1395
1396                     pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1397                     pattern.rightLen--;
1398                     Buf_Destroy(buf, FALSE);
1399
1400                     /*
1401                      * Check for global substitution. If 'g' after the final
1402                      * delimiter, substitution is global and is marked that
1403                      * way.
1404                      */
1405                     cp++;
1406                     if (*cp == 'g') {
1407                         pattern.flags |= VAR_SUB_GLOBAL;
1408                         cp++;
1409                     }
1410
1411                     /*
1412                      * Global substitution of the empty string causes an
1413                      * infinite number of matches, unless anchored by '^'
1414                      * (start of string) or '$' (end of string). Catch the
1415                      * infinite substitution here.
1416                      * Note that flags can only contain the 3 bits we're
1417                      * interested in so we don't have to mask unrelated
1418                      * bits. We can test for equality.
1419                      */
1420                     if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1421                         Fatal("Global substitution of the empty string");
1422
1423                     termc = *cp;
1424                     newStr = VarModify(str, VarSubstitute, &pattern);
1425                     /*
1426                      * Free the two strings.
1427                      */
1428                     free(pattern.lhs);
1429                     free(pattern.rhs);
1430                     break;
1431                 }
1432                 case 'C':
1433                 {
1434                     VarREPattern    pattern;
1435                     char           *re;
1436                     int             error;
1437
1438                     pattern.flags = 0;
1439                     delim = tstr[1];
1440                     tstr += 2;
1441
1442                     cp = tstr;
1443
1444                     if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1445                         NULL, NULL)) == NULL) {
1446                         /* was: goto cleanup */
1447                         *lengthPtr = cp - start + 1;
1448                         if (*freePtr)
1449                             free(str);
1450                         if (delim != '\0')
1451                             Fatal("Unclosed substitution for %s (%c missing)",
1452                                   v->name, delim);
1453                         return (var_Error);
1454                     }
1455
1456                     if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1457                         delim, NULL, NULL, NULL)) == NULL){
1458                         free(re);
1459
1460                         /* was: goto cleanup */
1461                         *lengthPtr = cp - start + 1;
1462                         if (*freePtr)
1463                             free(str);
1464                         if (delim != '\0')
1465                             Fatal("Unclosed substitution for %s (%c missing)",
1466                                   v->name, delim);
1467                         return (var_Error);
1468                     }
1469
1470                     for (;; cp++) {
1471                         switch (*cp) {
1472                         case 'g':
1473                             pattern.flags |= VAR_SUB_GLOBAL;
1474                             continue;
1475                         case '1':
1476                             pattern.flags |= VAR_SUB_ONE;
1477                             continue;
1478                         default:
1479                             break;
1480                         }
1481                         break;
1482                     }
1483
1484                     termc = *cp;
1485
1486                     error = regcomp(&pattern.re, re, REG_EXTENDED);
1487                     free(re);
1488                     if (error)  {
1489                         *lengthPtr = cp - start + 1;
1490                         VarREError(error, &pattern.re, "RE substitution error");
1491                         free(pattern.replace);
1492                         return (var_Error);
1493                     }
1494
1495                     pattern.nsub = pattern.re.re_nsub + 1;
1496                     if (pattern.nsub < 1)
1497                         pattern.nsub = 1;
1498                     if (pattern.nsub > 10)
1499                         pattern.nsub = 10;
1500                     pattern.matches = emalloc(pattern.nsub *
1501                                               sizeof(regmatch_t));
1502                     newStr = VarModify(str, VarRESubstitute, &pattern);
1503                     regfree(&pattern.re);
1504                     free(pattern.replace);
1505                     free(pattern.matches);
1506                     break;
1507                 }
1508                 case 'L':
1509                     if (tstr[1] == endc || tstr[1] == ':') {
1510                         Buffer *buf;
1511                         buf = Buf_Init(MAKE_BSIZE);
1512                         for (cp = str; *cp ; cp++)
1513                             Buf_AddByte(buf, (Byte)tolower(*cp));
1514
1515                         Buf_AddByte(buf, (Byte)'\0');
1516                         newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1517                         Buf_Destroy(buf, FALSE);
1518
1519                         cp = tstr + 1;
1520                         termc = *cp;
1521                         break;
1522                     }
1523                     /* FALLTHROUGH */
1524                 case 'O':
1525                     if (tstr[1] == endc || tstr[1] == ':') {
1526                         newStr = VarSortWords(str, SortIncreasing);
1527                         cp = tstr + 1;
1528                         termc = *cp;
1529                         break;
1530                     }
1531                     /* FALLTHROUGH */
1532                 case 'Q':
1533                     if (tstr[1] == endc || tstr[1] == ':') {
1534                         newStr = Var_Quote(str);
1535                         cp = tstr + 1;
1536                         termc = *cp;
1537                         break;
1538                     }
1539                     /*FALLTHRU*/
1540                 case 'T':
1541                     if (tstr[1] == endc || tstr[1] == ':') {
1542                         newStr = VarModify(str, VarTail, (void *)NULL);
1543                         cp = tstr + 1;
1544                         termc = *cp;
1545                         break;
1546                     }
1547                     /*FALLTHRU*/
1548                 case 'U':
1549                     if (tstr[1] == endc || tstr[1] == ':') {
1550                         Buffer *buf;
1551                         buf = Buf_Init(MAKE_BSIZE);
1552                         for (cp = str; *cp ; cp++)
1553                             Buf_AddByte(buf, (Byte)toupper(*cp));
1554
1555                         Buf_AddByte(buf, (Byte)'\0');
1556                         newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1557                         Buf_Destroy(buf, FALSE);
1558
1559                         cp = tstr + 1;
1560                         termc = *cp;
1561                         break;
1562                     }
1563                     /* FALLTHROUGH */
1564                 case 'H':
1565                     if (tstr[1] == endc || tstr[1] == ':') {
1566                         newStr = VarModify(str, VarHead, (void *)NULL);
1567                         cp = tstr + 1;
1568                         termc = *cp;
1569                         break;
1570                     }
1571                     /*FALLTHRU*/
1572                 case 'E':
1573                     if (tstr[1] == endc || tstr[1] == ':') {
1574                         newStr = VarModify(str, VarSuffix, (void *)NULL);
1575                         cp = tstr + 1;
1576                         termc = *cp;
1577                         break;
1578                     }
1579                     /*FALLTHRU*/
1580                 case 'R':
1581                     if (tstr[1] == endc || tstr[1] == ':') {
1582                         newStr = VarModify(str, VarRoot, (void *)NULL);
1583                         cp = tstr + 1;
1584                         termc = *cp;
1585                         break;
1586                     }
1587                     /*FALLTHRU*/
1588 #ifdef SUNSHCMD
1589                 case 's':
1590                     if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1591                         const char *error;
1592                         Buffer *buf;
1593
1594                         buf = Cmd_Exec(str, &error);
1595                         newStr = Buf_GetAll(buf, NULL);
1596                         Buf_Destroy(buf, FALSE);
1597
1598                         if (error)
1599                             Error(error, str);
1600                         cp = tstr + 2;
1601                         termc = *cp;
1602                         break;
1603                     }
1604                     /*FALLTHRU*/
1605 #endif
1606                 default:
1607                 {
1608 #ifdef SYSVVARSUB
1609                     /*
1610                      * This can either be a bogus modifier or a System-V
1611                      * substitution command.
1612                      */
1613                     VarPattern  pattern;
1614                     Boolean     eqFound;
1615                     int         cnt;
1616
1617                     pattern.flags = 0;
1618                     eqFound = FALSE;
1619                     /*
1620                      * First we make a pass through the string trying
1621                      * to verify it is a SYSV-make-style translation:
1622                      * it must be: <string1>=<string2>)
1623                      */
1624                     cp = tstr;
1625                     cnt = 1;
1626                     while (*cp != '\0' && cnt) {
1627                         if (*cp == '=') {
1628                             eqFound = TRUE;
1629                             /* continue looking for endc */
1630                         }
1631                         else if (*cp == endc)
1632                             cnt--;
1633                         else if (*cp == startc)
1634                             cnt++;
1635                         if (cnt)
1636                             cp++;
1637                     }
1638                     if (*cp == endc && eqFound) {
1639
1640                         /*
1641                          * Now we break this sucker into the lhs and
1642                          * rhs. We must null terminate them of course.
1643                          */
1644                         cp = tstr;
1645
1646                         delim = '=';
1647                         if ((pattern.lhs = VarGetPattern(ctxt,
1648                             err, &cp, delim, &pattern.flags, &pattern.leftLen,
1649                             NULL)) == NULL) {
1650                                 /* was: goto cleanup */
1651                                 *lengthPtr = cp - start + 1;
1652                                 if (*freePtr)
1653                                     free(str);
1654                                 if (delim != '\0')
1655                                     Fatal("Unclosed substitution for %s (%c missing)",
1656                                           v->name, delim);
1657                                 return (var_Error);
1658                         }
1659
1660                         delim = endc;
1661                         if ((pattern.rhs = VarGetPattern(ctxt,
1662                             err, &cp, delim, NULL, &pattern.rightLen,
1663                             &pattern)) == NULL) {
1664                                 /* was: goto cleanup */
1665                                 *lengthPtr = cp - start + 1;
1666                                 if (*freePtr)
1667                                     free(str);
1668                                 if (delim != '\0')
1669                                     Fatal("Unclosed substitution for %s (%c missing)",
1670                                           v->name, delim);
1671                                 return (var_Error);
1672                         }
1673
1674                         /*
1675                          * SYSV modifications happen through the whole
1676                          * string. Note the pattern is anchored at the end.
1677                          */
1678                         termc = *--cp;
1679                         delim = '\0';
1680                         newStr = VarModify(str, VarSYSVMatch, &pattern);
1681
1682                         free(pattern.lhs);
1683                         free(pattern.rhs);
1684
1685                         termc = endc;
1686                     } else
1687 #endif
1688                     {
1689                         Error("Unknown modifier '%c'\n", *tstr);
1690                         for (cp = tstr+1;
1691                              *cp != ':' && *cp != endc && *cp != '\0';
1692                              cp++)
1693                                  continue;
1694                         termc = *cp;
1695                         newStr = var_Error;
1696                     }
1697                 }
1698             }
1699             DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1700
1701             if (*freePtr) {
1702                 free(str);
1703             }
1704             str = newStr;
1705             if (str != var_Error) {
1706                 *freePtr = TRUE;
1707             } else {
1708                 *freePtr = FALSE;
1709             }
1710             if (termc == '\0') {
1711                 Error("Unclosed variable specification for %s", v->name);
1712             } else if (termc == ':') {
1713                 *cp++ = termc;
1714             } else {
1715                 *cp = termc;
1716             }
1717             tstr = cp;
1718         }
1719         *lengthPtr = tstr - start + 1;
1720     } else {
1721         *lengthPtr = tstr - start + 1;
1722         *tstr = endc;
1723     }
1724
1725     if (v->flags & VAR_FROM_ENV) {
1726         Boolean   destroy = FALSE;
1727
1728         if (str != (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1729             destroy = TRUE;
1730         } else {
1731             /*
1732              * Returning the value unmodified, so tell the caller to free
1733              * the thing.
1734              */
1735             *freePtr = TRUE;
1736         }
1737         VarDestroy(v, destroy);
1738     } else if (v->flags & VAR_JUNK) {
1739         /*
1740          * Perform any free'ing needed and set *freePtr to FALSE so the caller
1741          * doesn't try to free a static pointer.
1742          */
1743         if (*freePtr) {
1744             free(str);
1745         }
1746         *freePtr = FALSE;
1747         VarDestroy(v, TRUE);
1748         if (dynamic) {
1749             str = emalloc(*lengthPtr + 1);
1750             strncpy(str, start, *lengthPtr);
1751             str[*lengthPtr] = '\0';
1752             *freePtr = TRUE;
1753         } else {
1754             str = err ? var_Error : varNoError;
1755         }
1756     }
1757     return (str);
1758 }
1759
1760 /*-
1761  *-----------------------------------------------------------------------
1762  * Var_Subst  --
1763  *      Substitute for all variables in the given string in the given context
1764  *      If undefErr is TRUE, Parse_Error will be called when an undefined
1765  *      variable is encountered.
1766  *
1767  * Results:
1768  *      The resulting string.
1769  *
1770  * Side Effects:
1771  *      None. The old string must be freed by the caller
1772  *-----------------------------------------------------------------------
1773  */
1774 Buffer *
1775 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1776 {
1777     Boolean     errorReported;
1778     Buffer      *buf;           /* Buffer for forming things */
1779
1780     /*
1781      * Set TRUE if an error has already been reported to prevent a
1782      * plethora of messages when recursing.
1783      */
1784     errorReported = FALSE;
1785
1786     buf = Buf_Init(0);
1787     while (*str) {
1788         if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1789             /*
1790              * A dollar sign may be escaped either with another dollar sign.
1791              * In such a case, we skip over the escape character and store the
1792              * dollar sign into the buffer directly.
1793              */
1794             Buf_AddByte(buf, (Byte)str[0]);
1795             str += 2;
1796
1797         } else if (str[0] == '$') {
1798             char        *val;   /* Value to substitute for a variable */
1799             size_t      length; /* Length of the variable invocation */
1800             Boolean     doFree; /* Set true if val should be freed */
1801             /*
1802              * Variable invocation.
1803              */
1804             if (var != NULL) {
1805                 int expand;
1806                 for (;;) {
1807                     if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1808                         size_t          l;
1809                         const char      *p = str + 2;
1810
1811                         /*
1812                          * Scan up to the end of the variable name.
1813                          */
1814                         while (*p != '\0' &&
1815                                *p != ':' &&
1816                                *p != CLOSE_PAREN &&
1817                                *p != CLOSE_BRACE &&
1818                                *p != '$') {
1819                             ++p;
1820                         }
1821
1822                         /*
1823                          * A variable inside the variable. We cannot expand
1824                          * the external variable yet, so we try again with
1825                          * the nested one
1826                          */
1827                         if (*p == '$') {
1828                             Buf_AppendRange(buf, str, p);
1829                             str = p;
1830                             continue;
1831                         }
1832
1833                         l = p - (str + 2);
1834                         if (var[l] == '\0' && strncmp(var, str + 2, l) == 0) {
1835                             expand = TRUE;
1836                         } else {
1837                             /*
1838                              * Not the variable we want to expand, scan
1839                              * until the next variable
1840                              */
1841                             while (*p != '$' && *p != '\0')
1842                                 ++p;
1843
1844                             Buf_AppendRange(buf, str, p);
1845                             str = p;
1846                             expand = FALSE;
1847                         }
1848                     } else {
1849                         /*
1850                          * Single letter variable name.
1851                          */
1852                         if (var[1] == '\0' && var[0] == str[1]) {
1853                             expand = TRUE;
1854                         } else {
1855                             Buf_AddBytes(buf, 2, (const Byte *)str);
1856                             str += 2;
1857                             expand = FALSE;
1858                         }
1859                     }
1860                     break;
1861                 }
1862                 if (!expand)
1863                     continue;
1864             }
1865
1866             val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1867
1868             /*
1869              * When we come down here, val should either point to the
1870              * value of this variable, suitably modified, or be NULL.
1871              * Length should be the total length of the potential
1872              * variable invocation (from $ to end character...)
1873              */
1874             if (val == var_Error || val == varNoError) {
1875                 /*
1876                  * If performing old-time variable substitution, skip over
1877                  * the variable and continue with the substitution. Otherwise,
1878                  * store the dollar sign and advance str so we continue with
1879                  * the string...
1880                  */
1881                 if (oldVars) {
1882                     str += length;
1883                 } else if (undefErr) {
1884                     /*
1885                      * If variable is undefined, complain and skip the
1886                      * variable. The complaint will stop us from doing anything
1887                      * when the file is parsed.
1888                      */
1889                     if (!errorReported) {
1890                         Parse_Error(PARSE_FATAL,
1891                                      "Undefined variable \"%.*s\"",length,str);
1892                     }
1893                     str += length;
1894                     errorReported = TRUE;
1895                 } else {
1896                     Buf_AddByte(buf, (Byte)*str);
1897                     str += 1;
1898                 }
1899             } else {
1900                 /*
1901                  * We've now got a variable structure to store in. But first,
1902                  * advance the string pointer.
1903                  */
1904                 str += length;
1905
1906                 /*
1907                  * Copy all the characters from the variable value straight
1908                  * into the new string.
1909                  */
1910                 Buf_Append(buf, val);
1911                 if (doFree) {
1912                     free(val);
1913                 }
1914             }
1915         } else {
1916             /*
1917              * Skip as many characters as possible -- either to the end of
1918              * the string or to the next dollar sign (variable invocation).
1919              */
1920             const char  *cp = str;
1921
1922             do {
1923                 str++;
1924             } while (str[0] != '$' && str[0] != '\0');
1925
1926             Buf_AppendRange(buf, cp, str);
1927         }
1928     }
1929
1930     return (buf);
1931 }
1932
1933 /*-
1934  *-----------------------------------------------------------------------
1935  * Var_GetTail --
1936  *      Return the tail from each of a list of words. Used to set the
1937  *      System V local variables.
1938  *
1939  * Results:
1940  *      The resulting string.
1941  *
1942  * Side Effects:
1943  *      None.
1944  *
1945  *-----------------------------------------------------------------------
1946  */
1947 char *
1948 Var_GetTail(char *file)
1949 {
1950
1951     return (VarModify(file, VarTail, (void *)NULL));
1952 }
1953
1954 /*-
1955  *-----------------------------------------------------------------------
1956  * Var_GetHead --
1957  *      Find the leading components of a (list of) filename(s).
1958  *      XXX: VarHead does not replace foo by ., as (sun) System V make
1959  *      does.
1960  *
1961  * Results:
1962  *      The leading components.
1963  *
1964  * Side Effects:
1965  *      None.
1966  *
1967  *-----------------------------------------------------------------------
1968  */
1969 char *
1970 Var_GetHead(char *file)
1971 {
1972
1973     return (VarModify(file, VarHead, (void *)NULL));
1974 }
1975
1976 /*-
1977  *-----------------------------------------------------------------------
1978  * Var_Init --
1979  *      Initialize the module
1980  *
1981  * Results:
1982  *      None
1983  *
1984  * Side Effects:
1985  *      The VAR_CMD and VAR_GLOBAL contexts are created
1986  *-----------------------------------------------------------------------
1987  */
1988 void
1989 Var_Init(void)
1990 {
1991
1992     VAR_GLOBAL = Targ_NewGN("Global");
1993     VAR_CMD = Targ_NewGN("Command");
1994 }
1995
1996 /****************** PRINT DEBUGGING INFO *****************/
1997 static int
1998 VarPrintVar(void *vp, void *dummy __unused)
1999 {
2000     Var    *v = (Var *) vp;
2001
2002     printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
2003     return (0);
2004 }
2005
2006 /*-
2007  *-----------------------------------------------------------------------
2008  * Var_Dump --
2009  *      print all variables in a context
2010  *-----------------------------------------------------------------------
2011  */
2012 void
2013 Var_Dump(GNode *ctxt)
2014 {
2015
2016     Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);
2017 }