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