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