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