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