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