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