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