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