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