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