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