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