]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bmake/var.c
Merge OpenSSL 1.0.2d.
[FreeBSD/FreeBSD.git] / contrib / bmake / var.c
1 /*      $NetBSD: var.c,v 1.199 2015/10/20 21:30:57 sjg Exp $    */
2
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *      The Regents of the University of California.  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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *      This product includes software developed by the University of
53  *      California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: var.c,v 1.199 2015/10/20 21:30:57 sjg Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 #if 0
77 static char sccsid[] = "@(#)var.c       8.3 (Berkeley) 3/19/94";
78 #else
79 __RCSID("$NetBSD: var.c,v 1.199 2015/10/20 21:30:57 sjg Exp $");
80 #endif
81 #endif /* not lint */
82 #endif
83
84 /*-
85  * var.c --
86  *      Variable-handling functions
87  *
88  * Interface:
89  *      Var_Set             Set the value of a variable in the given
90  *                          context. The variable is created if it doesn't
91  *                          yet exist. The value and variable name need not
92  *                          be preserved.
93  *
94  *      Var_Append          Append more characters to an existing variable
95  *                          in the given context. The variable needn't
96  *                          exist already -- it will be created if it doesn't.
97  *                          A space is placed between the old value and the
98  *                          new one.
99  *
100  *      Var_Exists          See if a variable exists.
101  *
102  *      Var_Value           Return the value of a variable in a context or
103  *                          NULL if the variable is undefined.
104  *
105  *      Var_Subst           Substitute named variable, or all variables if
106  *                          NULL in a string using
107  *                          the given context as the top-most one. If the
108  *                          third argument is non-zero, Parse_Error is
109  *                          called if any variables are undefined.
110  *
111  *      Var_Parse           Parse a variable expansion from a string and
112  *                          return the result and the number of characters
113  *                          consumed.
114  *
115  *      Var_Delete          Delete a variable in a context.
116  *
117  *      Var_Init            Initialize this module.
118  *
119  * Debugging:
120  *      Var_Dump            Print out all variables defined in the given
121  *                          context.
122  *
123  * XXX: There's a lot of duplication in these functions.
124  */
125
126 #include    <sys/stat.h>
127 #ifndef NO_REGEX
128 #include    <sys/types.h>
129 #include    <regex.h>
130 #endif
131 #include    <ctype.h>
132 #include    <inttypes.h>
133 #include    <stdlib.h>
134 #include    <limits.h>
135 #include    <time.h>
136
137 #include    "make.h"
138 #include    "buf.h"
139 #include    "dir.h"
140 #include    "job.h"
141 #include    "metachar.h"
142
143 extern int makelevel;
144 /*
145  * This lets us tell if we have replaced the original environ
146  * (which we cannot free).
147  */
148 char **savedEnv = NULL;
149
150 /*
151  * This is a harmless return value for Var_Parse that can be used by Var_Subst
152  * to determine if there was an error in parsing -- easier than returning
153  * a flag, as things outside this module don't give a hoot.
154  */
155 char    var_Error[] = "";
156
157 /*
158  * Similar to var_Error, but returned when the 'errnum' flag for Var_Parse is
159  * set false. Why not just use a constant? Well, gcc likes to condense
160  * identical string instances...
161  */
162 static char     varNoError[] = "";
163
164 /*
165  * Internally, variables are contained in four different contexts.
166  *      1) the environment. They may not be changed. If an environment
167  *          variable is appended-to, the result is placed in the global
168  *          context.
169  *      2) the global context. Variables set in the Makefile are located in
170  *          the global context. It is the penultimate context searched when
171  *          substituting.
172  *      3) the command-line context. All variables set on the command line
173  *         are placed in this context. They are UNALTERABLE once placed here.
174  *      4) the local context. Each target has associated with it a context
175  *         list. On this list are located the structures describing such
176  *         local variables as $(@) and $(*)
177  * The four contexts are searched in the reverse order from which they are
178  * listed.
179  */
180 GNode          *VAR_INTERNAL; /* variables from make itself */
181 GNode          *VAR_GLOBAL;   /* variables from the makefile */
182 GNode          *VAR_CMD;      /* variables defined on the command-line */
183
184 #define FIND_CMD        0x1   /* look in VAR_CMD when searching */
185 #define FIND_GLOBAL     0x2   /* look in VAR_GLOBAL as well */
186 #define FIND_ENV        0x4   /* look in the environment also */
187
188 typedef struct Var {
189     char          *name;        /* the variable's name */
190     Buffer        val;          /* its value */
191     int           flags;        /* miscellaneous status flags */
192 #define VAR_IN_USE      1           /* Variable's value currently being used.
193                                      * Used to avoid recursion */
194 #define VAR_FROM_ENV    2           /* Variable comes from the environment */
195 #define VAR_JUNK        4           /* Variable is a junk variable that
196                                      * should be destroyed when done with
197                                      * it. Used by Var_Parse for undefined,
198                                      * modified variables */
199 #define VAR_KEEP        8           /* Variable is VAR_JUNK, but we found
200                                      * a use for it in some modifier and
201                                      * the value is therefore valid */
202 #define VAR_EXPORTED    16          /* Variable is exported */
203 #define VAR_REEXPORT    32          /* Indicate if var needs re-export.
204                                      * This would be true if it contains $'s
205                                      */
206 #define VAR_FROM_CMD    64          /* Variable came from command line */
207 }  Var;
208
209 /*
210  * Exporting vars is expensive so skip it if we can
211  */
212 #define VAR_EXPORTED_NONE       0
213 #define VAR_EXPORTED_YES        1
214 #define VAR_EXPORTED_ALL        2
215 static int var_exportedVars = VAR_EXPORTED_NONE;
216 /*
217  * We pass this to Var_Export when doing the initial export
218  * or after updating an exported var.
219  */
220 #define VAR_EXPORT_PARENT 1
221
222 /* Var*Pattern flags */
223 #define VAR_SUB_GLOBAL  0x01    /* Apply substitution globally */
224 #define VAR_SUB_ONE     0x02    /* Apply substitution to one word */
225 #define VAR_SUB_MATCHED 0x04    /* There was a match */
226 #define VAR_MATCH_START 0x08    /* Match at start of word */
227 #define VAR_MATCH_END   0x10    /* Match at end of word */
228 #define VAR_NOSUBST     0x20    /* don't expand vars in VarGetPattern */
229
230 /* Var_Set flags */
231 #define VAR_NO_EXPORT   0x01    /* do not export */
232
233 typedef struct {
234     /*
235      * The following fields are set by Var_Parse() when it
236      * encounters modifiers that need to keep state for use by
237      * subsequent modifiers within the same variable expansion.
238      */
239     Byte        varSpace;       /* Word separator in expansions */
240     Boolean     oneBigWord;     /* TRUE if we will treat the variable as a
241                                  * single big word, even if it contains
242                                  * embedded spaces (as opposed to the
243                                  * usual behaviour of treating it as
244                                  * several space-separated words). */
245 } Var_Parse_State;
246
247 /* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/",
248  * to VarSYSVMatch() for ":lhs=rhs". */
249 typedef struct {
250     const char   *lhs;      /* String to match */
251     int           leftLen; /* Length of string */
252     const char   *rhs;      /* Replacement string (w/ &'s removed) */
253     int           rightLen; /* Length of replacement */
254     int           flags;
255 } VarPattern;
256
257 /* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */
258 typedef struct {
259     GNode       *ctxt;          /* variable context */
260     char        *tvar;          /* name of temp var */
261     int         tvarLen;
262     char        *str;           /* string to expand */
263     int         strLen;
264     int         errnum;         /* errnum for not defined */
265 } VarLoop_t;
266
267 #ifndef NO_REGEX
268 /* struct passed as 'void *' to VarRESubstitute() for ":C///" */
269 typedef struct {
270     regex_t        re;
271     int            nsub;
272     regmatch_t    *matches;
273     char          *replace;
274     int            flags;
275 } VarREPattern;
276 #endif
277
278 /* struct passed to VarSelectWords() for ":[start..end]" */
279 typedef struct {
280     int         start;          /* first word to select */
281     int         end;            /* last word to select */
282 } VarSelectWords_t;
283
284 static Var *VarFind(const char *, GNode *, int);
285 static void VarAdd(const char *, const char *, GNode *);
286 static Boolean VarHead(GNode *, Var_Parse_State *,
287                         char *, Boolean, Buffer *, void *);
288 static Boolean VarTail(GNode *, Var_Parse_State *,
289                         char *, Boolean, Buffer *, void *);
290 static Boolean VarSuffix(GNode *, Var_Parse_State *,
291                         char *, Boolean, Buffer *, void *);
292 static Boolean VarRoot(GNode *, Var_Parse_State *,
293                         char *, Boolean, Buffer *, void *);
294 static Boolean VarMatch(GNode *, Var_Parse_State *,
295                         char *, Boolean, Buffer *, void *);
296 #ifdef SYSVVARSUB
297 static Boolean VarSYSVMatch(GNode *, Var_Parse_State *,
298                         char *, Boolean, Buffer *, void *);
299 #endif
300 static Boolean VarNoMatch(GNode *, Var_Parse_State *,
301                         char *, Boolean, Buffer *, void *);
302 #ifndef NO_REGEX
303 static void VarREError(int, regex_t *, const char *);
304 static Boolean VarRESubstitute(GNode *, Var_Parse_State *,
305                         char *, Boolean, Buffer *, void *);
306 #endif
307 static Boolean VarSubstitute(GNode *, Var_Parse_State *,
308                         char *, Boolean, Buffer *, void *);
309 static Boolean VarLoopExpand(GNode *, Var_Parse_State *,
310                         char *, Boolean, Buffer *, void *);
311 static char *VarGetPattern(GNode *, Var_Parse_State *,
312                            int, const char **, int, int *, int *,
313                            VarPattern *);
314 static char *VarQuote(char *);
315 static char *VarHash(char *);
316 static char *VarModify(GNode *, Var_Parse_State *,
317     const char *,
318     Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *),
319     void *);
320 static char *VarOrder(const char *, const char);
321 static char *VarUniq(const char *);
322 static int VarWordCompare(const void *, const void *);
323 static void VarPrintVar(void *);
324
325 #define BROPEN  '{'
326 #define BRCLOSE '}'
327 #define PROPEN  '('
328 #define PRCLOSE ')'
329
330 /*-
331  *-----------------------------------------------------------------------
332  * VarFind --
333  *      Find the given variable in the given context and any other contexts
334  *      indicated.
335  *
336  * Input:
337  *      name            name to find
338  *      ctxt            context in which to find it
339  *      flags           FIND_GLOBAL set means to look in the
340  *                      VAR_GLOBAL context as well. FIND_CMD set means
341  *                      to look in the VAR_CMD context also. FIND_ENV
342  *                      set means to look in the environment
343  *
344  * Results:
345  *      A pointer to the structure describing the desired variable or
346  *      NULL if the variable does not exist.
347  *
348  * Side Effects:
349  *      None
350  *-----------------------------------------------------------------------
351  */
352 static Var *
353 VarFind(const char *name, GNode *ctxt, int flags)
354 {
355     Hash_Entry          *var;
356     Var                 *v;
357
358         /*
359          * If the variable name begins with a '.', it could very well be one of
360          * the local ones.  We check the name against all the local variables
361          * and substitute the short version in for 'name' if it matches one of
362          * them.
363          */
364         if (*name == '.' && isupper((unsigned char) name[1]))
365                 switch (name[1]) {
366                 case 'A':
367                         if (!strcmp(name, ".ALLSRC"))
368                                 name = ALLSRC;
369                         if (!strcmp(name, ".ARCHIVE"))
370                                 name = ARCHIVE;
371                         break;
372                 case 'I':
373                         if (!strcmp(name, ".IMPSRC"))
374                                 name = IMPSRC;
375                         break;
376                 case 'M':
377                         if (!strcmp(name, ".MEMBER"))
378                                 name = MEMBER;
379                         break;
380                 case 'O':
381                         if (!strcmp(name, ".OODATE"))
382                                 name = OODATE;
383                         break;
384                 case 'P':
385                         if (!strcmp(name, ".PREFIX"))
386                                 name = PREFIX;
387                         break;
388                 case 'T':
389                         if (!strcmp(name, ".TARGET"))
390                                 name = TARGET;
391                         break;
392                 }
393 #ifdef notyet
394     /* for compatibility with gmake */
395     if (name[0] == '^' && name[1] == '\0')
396             name = ALLSRC;
397 #endif
398
399     /*
400      * First look for the variable in the given context. If it's not there,
401      * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
402      * depending on the FIND_* flags in 'flags'
403      */
404     var = Hash_FindEntry(&ctxt->context, name);
405
406     if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
407         var = Hash_FindEntry(&VAR_CMD->context, name);
408     }
409     if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
410         (ctxt != VAR_GLOBAL))
411     {
412         var = Hash_FindEntry(&VAR_GLOBAL->context, name);
413         if ((var == NULL) && (ctxt != VAR_INTERNAL)) {
414             /* VAR_INTERNAL is subordinate to VAR_GLOBAL */
415             var = Hash_FindEntry(&VAR_INTERNAL->context, name);
416         }
417     }
418     if ((var == NULL) && (flags & FIND_ENV)) {
419         char *env;
420
421         if ((env = getenv(name)) != NULL) {
422             int         len;
423
424             v = bmake_malloc(sizeof(Var));
425             v->name = bmake_strdup(name);
426
427             len = strlen(env);
428
429             Buf_Init(&v->val, len + 1);
430             Buf_AddBytes(&v->val, len, env);
431
432             v->flags = VAR_FROM_ENV;
433             return (v);
434         } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
435                    (ctxt != VAR_GLOBAL))
436         {
437             var = Hash_FindEntry(&VAR_GLOBAL->context, name);
438             if ((var == NULL) && (ctxt != VAR_INTERNAL)) {
439                 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
440             }
441             if (var == NULL) {
442                 return NULL;
443             } else {
444                 return ((Var *)Hash_GetValue(var));
445             }
446         } else {
447             return NULL;
448         }
449     } else if (var == NULL) {
450         return NULL;
451     } else {
452         return ((Var *)Hash_GetValue(var));
453     }
454 }
455
456 /*-
457  *-----------------------------------------------------------------------
458  * VarFreeEnv  --
459  *      If the variable is an environment variable, free it
460  *
461  * Input:
462  *      v               the variable
463  *      destroy         true if the value buffer should be destroyed.
464  *
465  * Results:
466  *      1 if it is an environment variable 0 ow.
467  *
468  * Side Effects:
469  *      The variable is free'ed if it is an environent variable.
470  *-----------------------------------------------------------------------
471  */
472 static Boolean
473 VarFreeEnv(Var *v, Boolean destroy)
474 {
475     if ((v->flags & VAR_FROM_ENV) == 0)
476         return FALSE;
477     free(v->name);
478     Buf_Destroy(&v->val, destroy);
479     free(v);
480     return TRUE;
481 }
482
483 /*-
484  *-----------------------------------------------------------------------
485  * VarAdd  --
486  *      Add a new variable of name name and value val to the given context
487  *
488  * Input:
489  *      name            name of variable to add
490  *      val             value to set it to
491  *      ctxt            context in which to set it
492  *
493  * Results:
494  *      None
495  *
496  * Side Effects:
497  *      The new variable is placed at the front of the given context
498  *      The name and val arguments are duplicated so they may
499  *      safely be freed.
500  *-----------------------------------------------------------------------
501  */
502 static void
503 VarAdd(const char *name, const char *val, GNode *ctxt)
504 {
505     Var           *v;
506     int           len;
507     Hash_Entry    *h;
508
509     v = bmake_malloc(sizeof(Var));
510
511     len = val ? strlen(val) : 0;
512     Buf_Init(&v->val, len+1);
513     Buf_AddBytes(&v->val, len, val);
514
515     v->flags = 0;
516
517     h = Hash_CreateEntry(&ctxt->context, name, NULL);
518     Hash_SetValue(h, v);
519     v->name = h->name;
520     if (DEBUG(VAR)) {
521         fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
522     }
523 }
524
525 /*-
526  *-----------------------------------------------------------------------
527  * Var_Delete --
528  *      Remove a variable from a context.
529  *
530  * Results:
531  *      None.
532  *
533  * Side Effects:
534  *      The Var structure is removed and freed.
535  *
536  *-----------------------------------------------------------------------
537  */
538 void
539 Var_Delete(const char *name, GNode *ctxt)
540 {
541     Hash_Entry    *ln;
542     char *cp;
543     
544     if (strchr(name, '$')) {
545         cp = Var_Subst(NULL, name, VAR_GLOBAL, FALSE, TRUE);
546     } else {
547         cp = (char *)name;
548     }
549     ln = Hash_FindEntry(&ctxt->context, cp);
550     if (DEBUG(VAR)) {
551         fprintf(debug_file, "%s:delete %s%s\n",
552             ctxt->name, cp, ln ? "" : " (not found)");
553     }
554     if (cp != name) {
555         free(cp);
556     }
557     if (ln != NULL) {
558         Var       *v;
559
560         v = (Var *)Hash_GetValue(ln);
561         if ((v->flags & VAR_EXPORTED)) {
562             unsetenv(v->name);
563         }
564         if (strcmp(MAKE_EXPORTED, v->name) == 0) {
565             var_exportedVars = VAR_EXPORTED_NONE;
566         }
567         if (v->name != ln->name)
568                 free(v->name);
569         Hash_DeleteEntry(&ctxt->context, ln);
570         Buf_Destroy(&v->val, TRUE);
571         free(v);
572     }
573 }
574
575
576 /*
577  * Export a var.
578  * We ignore make internal variables (those which start with '.')
579  * Also we jump through some hoops to avoid calling setenv
580  * more than necessary since it can leak.
581  * We only manipulate flags of vars if 'parent' is set.
582  */
583 static int
584 Var_Export1(const char *name, int parent)
585 {
586     char tmp[BUFSIZ];
587     Var *v;
588     char *val = NULL;
589     int n;
590
591     if (*name == '.')
592         return 0;                       /* skip internals */
593     if (!name[1]) {
594         /*
595          * A single char.
596          * If it is one of the vars that should only appear in
597          * local context, skip it, else we can get Var_Subst
598          * into a loop.
599          */
600         switch (name[0]) {
601         case '@':
602         case '%':
603         case '*':
604         case '!':
605             return 0;
606         }
607     }
608     v = VarFind(name, VAR_GLOBAL, 0);
609     if (v == NULL) {
610         return 0;
611     }
612     if (!parent &&
613         (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
614         return 0;                       /* nothing to do */
615     }
616     val = Buf_GetAll(&v->val, NULL);
617     if (strchr(val, '$')) {
618         if (parent) {
619             /*
620              * Flag this as something we need to re-export.
621              * No point actually exporting it now though,
622              * the child can do it at the last minute.
623              */
624             v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
625             return 1;
626         }
627         if (v->flags & VAR_IN_USE) {
628             /*
629              * We recursed while exporting in a child.
630              * This isn't going to end well, just skip it.
631              */
632             return 0;
633         }
634         n = snprintf(tmp, sizeof(tmp), "${%s}", name);
635         if (n < (int)sizeof(tmp)) {
636             val = Var_Subst(NULL, tmp, VAR_GLOBAL, FALSE, TRUE);
637             setenv(name, val, 1);
638             free(val);
639         }
640     } else {
641         if (parent) {
642             v->flags &= ~VAR_REEXPORT;  /* once will do */
643         }
644         if (parent || !(v->flags & VAR_EXPORTED)) {
645             setenv(name, val, 1);
646         }
647     }
648     /*
649      * This is so Var_Set knows to call Var_Export again...
650      */
651     if (parent) {
652         v->flags |= VAR_EXPORTED;
653     }
654     return 1;
655 }
656
657 /*
658  * This gets called from our children.
659  */
660 void
661 Var_ExportVars(void)
662 {
663     char tmp[BUFSIZ];
664     Hash_Entry          *var;
665     Hash_Search         state;
666     Var *v;
667     char *val;
668     int n;
669
670     /*
671      * Several make's support this sort of mechanism for tracking
672      * recursion - but each uses a different name.
673      * We allow the makefiles to update MAKELEVEL and ensure
674      * children see a correctly incremented value.
675      */
676     snprintf(tmp, sizeof(tmp), "%d", makelevel + 1);
677     setenv(MAKE_LEVEL_ENV, tmp, 1);
678
679     if (VAR_EXPORTED_NONE == var_exportedVars)
680         return;
681
682     if (VAR_EXPORTED_ALL == var_exportedVars) {
683         /*
684          * Ouch! This is crazy...
685          */
686         for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
687              var != NULL;
688              var = Hash_EnumNext(&state)) {
689             v = (Var *)Hash_GetValue(var);
690             Var_Export1(v->name, 0);
691         }
692         return;
693     }
694     /*
695      * We have a number of exported vars,
696      */
697     n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
698     if (n < (int)sizeof(tmp)) {
699         char **av;
700         char *as;
701         int ac;
702         int i;
703
704         val = Var_Subst(NULL, tmp, VAR_GLOBAL, FALSE, TRUE);
705         av = brk_string(val, &ac, FALSE, &as);
706         for (i = 0; i < ac; i++) {
707             Var_Export1(av[i], 0);
708         }
709         free(val);
710         free(as);
711         free(av);
712     }
713 }
714
715 /*
716  * This is called when .export is seen or
717  * .MAKE.EXPORTED is modified.
718  * It is also called when any exported var is modified.
719  */
720 void
721 Var_Export(char *str, int isExport)
722 {
723     char *name;
724     char *val;
725     char **av;
726     char *as;
727     int track;
728     int ac;
729     int i;
730
731     if (isExport && (!str || !str[0])) {
732         var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
733         return;
734     }
735
736     if (strncmp(str, "-env", 4) == 0) {
737         track = 0;
738         str += 4;
739     } else {
740         track = VAR_EXPORT_PARENT;
741     }
742     val = Var_Subst(NULL, str, VAR_GLOBAL, FALSE, TRUE);
743     av = brk_string(val, &ac, FALSE, &as);
744     for (i = 0; i < ac; i++) {
745         name = av[i];
746         if (!name[1]) {
747             /*
748              * A single char.
749              * If it is one of the vars that should only appear in
750              * local context, skip it, else we can get Var_Subst
751              * into a loop.
752              */
753             switch (name[0]) {
754             case '@':
755             case '%':
756             case '*':
757             case '!':
758                 continue;
759             }
760         }
761         if (Var_Export1(name, track)) {
762             if (VAR_EXPORTED_ALL != var_exportedVars)
763                 var_exportedVars = VAR_EXPORTED_YES;
764             if (isExport && track) {
765                 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
766             }
767         }
768     }
769     free(val);
770     free(as);
771     free(av);
772 }
773
774
775 /*
776  * This is called when .unexport[-env] is seen.
777  */
778 extern char **environ;
779
780 void
781 Var_UnExport(char *str)
782 {
783     char tmp[BUFSIZ];
784     char *vlist;
785     char *cp;
786     Boolean unexport_env;
787     int n;
788
789     if (!str || !str[0]) {
790         return;                         /* assert? */
791     }
792
793     vlist = NULL;
794
795     str += 8;
796     unexport_env = (strncmp(str, "-env", 4) == 0);
797     if (unexport_env) {
798         char **newenv;
799
800         cp = getenv(MAKE_LEVEL_ENV);    /* we should preserve this */
801         if (environ == savedEnv) {
802             /* we have been here before! */
803             newenv = bmake_realloc(environ, 2 * sizeof(char *));
804         } else {
805             if (savedEnv) {
806                 free(savedEnv);
807                 savedEnv = NULL;
808             }
809             newenv = bmake_malloc(2 * sizeof(char *));
810         }
811         if (!newenv)
812             return;
813         /* Note: we cannot safely free() the original environ. */
814         environ = savedEnv = newenv;
815         newenv[0] = NULL;
816         newenv[1] = NULL;
817         setenv(MAKE_LEVEL_ENV, cp, 1);
818     } else {
819         for (; *str != '\n' && isspace((unsigned char) *str); str++)
820             continue;
821         if (str[0] && str[0] != '\n') {
822             vlist = str;
823         }
824     }
825
826     if (!vlist) {
827         /* Using .MAKE.EXPORTED */
828         n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
829         if (n < (int)sizeof(tmp)) {
830             vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, FALSE, TRUE);
831         }
832     }
833     if (vlist) {
834         Var *v;
835         char **av;
836         char *as;
837         int ac;
838         int i;
839
840         av = brk_string(vlist, &ac, FALSE, &as);
841         for (i = 0; i < ac; i++) {
842             v = VarFind(av[i], VAR_GLOBAL, 0);
843             if (!v)
844                 continue;
845             if (!unexport_env &&
846                 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
847                 unsetenv(v->name);
848             }
849             v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT);
850             /*
851              * If we are unexporting a list,
852              * remove each one from .MAKE.EXPORTED.
853              * If we are removing them all,
854              * just delete .MAKE.EXPORTED below.
855              */
856             if (vlist == str) {
857                 n = snprintf(tmp, sizeof(tmp),
858                              "${" MAKE_EXPORTED ":N%s}", v->name);
859                 if (n < (int)sizeof(tmp)) {
860                     cp = Var_Subst(NULL, tmp, VAR_GLOBAL, FALSE, TRUE);
861                     Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0);
862                     free(cp);
863                 }
864             }
865         }
866         free(as);
867         free(av);
868         if (vlist != str) {
869             Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
870             free(vlist);
871         }
872     }
873 }
874
875 /*-
876  *-----------------------------------------------------------------------
877  * Var_Set --
878  *      Set the variable name to the value val in the given context.
879  *
880  * Input:
881  *      name            name of variable to set
882  *      val             value to give to the variable
883  *      ctxt            context in which to set it
884  *
885  * Results:
886  *      None.
887  *
888  * Side Effects:
889  *      If the variable doesn't yet exist, a new record is created for it.
890  *      Else the old value is freed and the new one stuck in its place
891  *
892  * Notes:
893  *      The variable is searched for only in its context before being
894  *      created in that context. I.e. if the context is VAR_GLOBAL,
895  *      only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
896  *      VAR_CMD->context is searched. This is done to avoid the literally
897  *      thousands of unnecessary strcmp's that used to be done to
898  *      set, say, $(@) or $(<).
899  *      If the context is VAR_GLOBAL though, we check if the variable
900  *      was set in VAR_CMD from the command line and skip it if so.
901  *-----------------------------------------------------------------------
902  */
903 void
904 Var_Set(const char *name, const char *val, GNode *ctxt, int flags)
905 {
906     Var   *v;
907     char *expanded_name = NULL;
908
909     /*
910      * We only look for a variable in the given context since anything set
911      * here will override anything in a lower context, so there's not much
912      * point in searching them all just to save a bit of memory...
913      */
914     if (strchr(name, '$') != NULL) {
915         expanded_name = Var_Subst(NULL, name, ctxt, FALSE, TRUE);
916         if (expanded_name[0] == 0) {
917             if (DEBUG(VAR)) {
918                 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
919                         "name expands to empty string - ignored\n",
920                         name, val);
921             }
922             free(expanded_name);
923             return;
924         }
925         name = expanded_name;
926     }
927     if (ctxt == VAR_GLOBAL) {
928         v = VarFind(name, VAR_CMD, 0);
929         if (v != NULL) {
930             if ((v->flags & VAR_FROM_CMD)) {
931                 if (DEBUG(VAR)) {
932                     fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
933                 }
934                 goto out;
935             }
936             VarFreeEnv(v, TRUE);
937         }
938     }
939     v = VarFind(name, ctxt, 0);
940     if (v == NULL) {
941         if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
942             /*
943              * This var would normally prevent the same name being added
944              * to VAR_GLOBAL, so delete it from there if needed.
945              * Otherwise -V name may show the wrong value.
946              */
947             Var_Delete(name, VAR_GLOBAL);
948         }
949         VarAdd(name, val, ctxt);
950     } else {
951         Buf_Empty(&v->val);
952         Buf_AddBytes(&v->val, strlen(val), val);
953
954         if (DEBUG(VAR)) {
955             fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
956         }
957         if ((v->flags & VAR_EXPORTED)) {
958             Var_Export1(name, VAR_EXPORT_PARENT);
959         }
960     }
961     /*
962      * Any variables given on the command line are automatically exported
963      * to the environment (as per POSIX standard)
964      */
965     if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
966         if (v == NULL) {
967             /* we just added it */
968             v = VarFind(name, ctxt, 0);
969         }
970         if (v != NULL)
971             v->flags |= VAR_FROM_CMD;
972         /*
973          * If requested, don't export these in the environment
974          * individually.  We still put them in MAKEOVERRIDES so
975          * that the command-line settings continue to override
976          * Makefile settings.
977          */
978         if (varNoExportEnv != TRUE)
979             setenv(name, val, 1);
980
981         Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
982     }
983
984
985  out:
986     free(expanded_name);
987     if (v != NULL)
988         VarFreeEnv(v, TRUE);
989 }
990
991 /*-
992  *-----------------------------------------------------------------------
993  * Var_Append --
994  *      The variable of the given name has the given value appended to it in
995  *      the given context.
996  *
997  * Input:
998  *      name            name of variable to modify
999  *      val             String to append to it
1000  *      ctxt            Context in which this should occur
1001  *
1002  * Results:
1003  *      None
1004  *
1005  * Side Effects:
1006  *      If the variable doesn't exist, it is created. Else the strings
1007  *      are concatenated (with a space in between).
1008  *
1009  * Notes:
1010  *      Only if the variable is being sought in the global context is the
1011  *      environment searched.
1012  *      XXX: Knows its calling circumstances in that if called with ctxt
1013  *      an actual target, it will only search that context since only
1014  *      a local variable could be being appended to. This is actually
1015  *      a big win and must be tolerated.
1016  *-----------------------------------------------------------------------
1017  */
1018 void
1019 Var_Append(const char *name, const char *val, GNode *ctxt)
1020 {
1021     Var            *v;
1022     Hash_Entry     *h;
1023     char *expanded_name = NULL;
1024
1025     if (strchr(name, '$') != NULL) {
1026         expanded_name = Var_Subst(NULL, name, ctxt, FALSE, TRUE);
1027         if (expanded_name[0] == 0) {
1028             if (DEBUG(VAR)) {
1029                 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
1030                         "name expands to empty string - ignored\n",
1031                         name, val);
1032             }
1033             free(expanded_name);
1034             return;
1035         }
1036         name = expanded_name;
1037     }
1038
1039     v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
1040
1041     if (v == NULL) {
1042         VarAdd(name, val, ctxt);
1043     } else {
1044         Buf_AddByte(&v->val, ' ');
1045         Buf_AddBytes(&v->val, strlen(val), val);
1046
1047         if (DEBUG(VAR)) {
1048             fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
1049                    Buf_GetAll(&v->val, NULL));
1050         }
1051
1052         if (v->flags & VAR_FROM_ENV) {
1053             /*
1054              * If the original variable came from the environment, we
1055              * have to install it in the global context (we could place
1056              * it in the environment, but then we should provide a way to
1057              * export other variables...)
1058              */
1059             v->flags &= ~VAR_FROM_ENV;
1060             h = Hash_CreateEntry(&ctxt->context, name, NULL);
1061             Hash_SetValue(h, v);
1062         }
1063     }
1064     free(expanded_name);
1065 }
1066
1067 /*-
1068  *-----------------------------------------------------------------------
1069  * Var_Exists --
1070  *      See if the given variable exists.
1071  *
1072  * Input:
1073  *      name            Variable to find
1074  *      ctxt            Context in which to start search
1075  *
1076  * Results:
1077  *      TRUE if it does, FALSE if it doesn't
1078  *
1079  * Side Effects:
1080  *      None.
1081  *
1082  *-----------------------------------------------------------------------
1083  */
1084 Boolean
1085 Var_Exists(const char *name, GNode *ctxt)
1086 {
1087     Var           *v;
1088     char          *cp;
1089
1090     if ((cp = strchr(name, '$')) != NULL) {
1091         cp = Var_Subst(NULL, name, ctxt, FALSE, TRUE);
1092     }
1093     v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
1094     free(cp);
1095     if (v == NULL) {
1096         return(FALSE);
1097     } else {
1098         (void)VarFreeEnv(v, TRUE);
1099     }
1100     return(TRUE);
1101 }
1102
1103 /*-
1104  *-----------------------------------------------------------------------
1105  * Var_Value --
1106  *      Return the value of the named variable in the given context
1107  *
1108  * Input:
1109  *      name            name to find
1110  *      ctxt            context in which to search for it
1111  *
1112  * Results:
1113  *      The value if the variable exists, NULL if it doesn't
1114  *
1115  * Side Effects:
1116  *      None
1117  *-----------------------------------------------------------------------
1118  */
1119 char *
1120 Var_Value(const char *name, GNode *ctxt, char **frp)
1121 {
1122     Var            *v;
1123
1124     v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1125     *frp = NULL;
1126     if (v != NULL) {
1127         char *p = (Buf_GetAll(&v->val, NULL));
1128         if (VarFreeEnv(v, FALSE))
1129             *frp = p;
1130         return p;
1131     } else {
1132         return NULL;
1133     }
1134 }
1135
1136 /*-
1137  *-----------------------------------------------------------------------
1138  * VarHead --
1139  *      Remove the tail of the given word and place the result in the given
1140  *      buffer.
1141  *
1142  * Input:
1143  *      word            Word to trim
1144  *      addSpace        True if need to add a space to the buffer
1145  *                      before sticking in the head
1146  *      buf             Buffer in which to store it
1147  *
1148  * Results:
1149  *      TRUE if characters were added to the buffer (a space needs to be
1150  *      added to the buffer before the next word).
1151  *
1152  * Side Effects:
1153  *      The trimmed word is added to the buffer.
1154  *
1155  *-----------------------------------------------------------------------
1156  */
1157 static Boolean
1158 VarHead(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1159         char *word, Boolean addSpace, Buffer *buf,
1160         void *dummy)
1161 {
1162     char *slash;
1163
1164     slash = strrchr(word, '/');
1165     if (slash != NULL) {
1166         if (addSpace && vpstate->varSpace) {
1167             Buf_AddByte(buf, vpstate->varSpace);
1168         }
1169         *slash = '\0';
1170         Buf_AddBytes(buf, strlen(word), word);
1171         *slash = '/';
1172         return (TRUE);
1173     } else {
1174         /*
1175          * If no directory part, give . (q.v. the POSIX standard)
1176          */
1177         if (addSpace && vpstate->varSpace)
1178             Buf_AddByte(buf, vpstate->varSpace);
1179         Buf_AddByte(buf, '.');
1180     }
1181     return(dummy ? TRUE : TRUE);
1182 }
1183
1184 /*-
1185  *-----------------------------------------------------------------------
1186  * VarTail --
1187  *      Remove the head of the given word and place the result in the given
1188  *      buffer.
1189  *
1190  * Input:
1191  *      word            Word to trim
1192  *      addSpace        True if need to add a space to the buffer
1193  *                      before adding the tail
1194  *      buf             Buffer in which to store it
1195  *
1196  * Results:
1197  *      TRUE if characters were added to the buffer (a space needs to be
1198  *      added to the buffer before the next word).
1199  *
1200  * Side Effects:
1201  *      The trimmed word is added to the buffer.
1202  *
1203  *-----------------------------------------------------------------------
1204  */
1205 static Boolean
1206 VarTail(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1207         char *word, Boolean addSpace, Buffer *buf,
1208         void *dummy)
1209 {
1210     char *slash;
1211
1212     if (addSpace && vpstate->varSpace) {
1213         Buf_AddByte(buf, vpstate->varSpace);
1214     }
1215
1216     slash = strrchr(word, '/');
1217     if (slash != NULL) {
1218         *slash++ = '\0';
1219         Buf_AddBytes(buf, strlen(slash), slash);
1220         slash[-1] = '/';
1221     } else {
1222         Buf_AddBytes(buf, strlen(word), word);
1223     }
1224     return (dummy ? TRUE : TRUE);
1225 }
1226
1227 /*-
1228  *-----------------------------------------------------------------------
1229  * VarSuffix --
1230  *      Place the suffix of the given word in the given buffer.
1231  *
1232  * Input:
1233  *      word            Word to trim
1234  *      addSpace        TRUE if need to add a space before placing the
1235  *                      suffix in the buffer
1236  *      buf             Buffer in which to store it
1237  *
1238  * Results:
1239  *      TRUE if characters were added to the buffer (a space needs to be
1240  *      added to the buffer before the next word).
1241  *
1242  * Side Effects:
1243  *      The suffix from the word is placed in the buffer.
1244  *
1245  *-----------------------------------------------------------------------
1246  */
1247 static Boolean
1248 VarSuffix(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1249           char *word, Boolean addSpace, Buffer *buf,
1250           void *dummy)
1251 {
1252     char *dot;
1253
1254     dot = strrchr(word, '.');
1255     if (dot != NULL) {
1256         if (addSpace && vpstate->varSpace) {
1257             Buf_AddByte(buf, vpstate->varSpace);
1258         }
1259         *dot++ = '\0';
1260         Buf_AddBytes(buf, strlen(dot), dot);
1261         dot[-1] = '.';
1262         addSpace = TRUE;
1263     }
1264     return (dummy ? addSpace : addSpace);
1265 }
1266
1267 /*-
1268  *-----------------------------------------------------------------------
1269  * VarRoot --
1270  *      Remove the suffix of the given word and place the result in the
1271  *      buffer.
1272  *
1273  * Input:
1274  *      word            Word to trim
1275  *      addSpace        TRUE if need to add a space to the buffer
1276  *                      before placing the root in it
1277  *      buf             Buffer in which to store it
1278  *
1279  * Results:
1280  *      TRUE if characters were added to the buffer (a space needs to be
1281  *      added to the buffer before the next word).
1282  *
1283  * Side Effects:
1284  *      The trimmed word is added to the buffer.
1285  *
1286  *-----------------------------------------------------------------------
1287  */
1288 static Boolean
1289 VarRoot(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1290         char *word, Boolean addSpace, Buffer *buf,
1291         void *dummy)
1292 {
1293     char *dot;
1294
1295     if (addSpace && vpstate->varSpace) {
1296         Buf_AddByte(buf, vpstate->varSpace);
1297     }
1298
1299     dot = strrchr(word, '.');
1300     if (dot != NULL) {
1301         *dot = '\0';
1302         Buf_AddBytes(buf, strlen(word), word);
1303         *dot = '.';
1304     } else {
1305         Buf_AddBytes(buf, strlen(word), word);
1306     }
1307     return (dummy ? TRUE : TRUE);
1308 }
1309
1310 /*-
1311  *-----------------------------------------------------------------------
1312  * VarMatch --
1313  *      Place the word in the buffer if it matches the given pattern.
1314  *      Callback function for VarModify to implement the :M modifier.
1315  *
1316  * Input:
1317  *      word            Word to examine
1318  *      addSpace        TRUE if need to add a space to the buffer
1319  *                      before adding the word, if it matches
1320  *      buf             Buffer in which to store it
1321  *      pattern         Pattern the word must match
1322  *
1323  * Results:
1324  *      TRUE if a space should be placed in the buffer before the next
1325  *      word.
1326  *
1327  * Side Effects:
1328  *      The word may be copied to the buffer.
1329  *
1330  *-----------------------------------------------------------------------
1331  */
1332 static Boolean
1333 VarMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1334          char *word, Boolean addSpace, Buffer *buf,
1335          void *pattern)
1336 {
1337     if (DEBUG(VAR))
1338         fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
1339     if (Str_Match(word, (char *)pattern)) {
1340         if (addSpace && vpstate->varSpace) {
1341             Buf_AddByte(buf, vpstate->varSpace);
1342         }
1343         addSpace = TRUE;
1344         Buf_AddBytes(buf, strlen(word), word);
1345     }
1346     return(addSpace);
1347 }
1348
1349 #ifdef SYSVVARSUB
1350 /*-
1351  *-----------------------------------------------------------------------
1352  * VarSYSVMatch --
1353  *      Place the word in the buffer if it matches the given pattern.
1354  *      Callback function for VarModify to implement the System V %
1355  *      modifiers.
1356  *
1357  * Input:
1358  *      word            Word to examine
1359  *      addSpace        TRUE if need to add a space to the buffer
1360  *                      before adding the word, if it matches
1361  *      buf             Buffer in which to store it
1362  *      patp            Pattern the word must match
1363  *
1364  * Results:
1365  *      TRUE if a space should be placed in the buffer before the next
1366  *      word.
1367  *
1368  * Side Effects:
1369  *      The word may be copied to the buffer.
1370  *
1371  *-----------------------------------------------------------------------
1372  */
1373 static Boolean
1374 VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
1375              char *word, Boolean addSpace, Buffer *buf,
1376              void *patp)
1377 {
1378     int len;
1379     char *ptr;
1380     VarPattern    *pat = (VarPattern *)patp;
1381     char *varexp;
1382
1383     if (addSpace && vpstate->varSpace)
1384         Buf_AddByte(buf, vpstate->varSpace);
1385
1386     addSpace = TRUE;
1387
1388     if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
1389         varexp = Var_Subst(NULL, pat->rhs, ctx, FALSE, TRUE);
1390         Str_SYSVSubst(buf, varexp, ptr, len);
1391         free(varexp);
1392     } else {
1393         Buf_AddBytes(buf, strlen(word), word);
1394     }
1395
1396     return(addSpace);
1397 }
1398 #endif
1399
1400
1401 /*-
1402  *-----------------------------------------------------------------------
1403  * VarNoMatch --
1404  *      Place the word in the buffer if it doesn't match the given pattern.
1405  *      Callback function for VarModify to implement the :N modifier.
1406  *
1407  * Input:
1408  *      word            Word to examine
1409  *      addSpace        TRUE if need to add a space to the buffer
1410  *                      before adding the word, if it matches
1411  *      buf             Buffer in which to store it
1412  *      pattern         Pattern the word must match
1413  *
1414  * Results:
1415  *      TRUE if a space should be placed in the buffer before the next
1416  *      word.
1417  *
1418  * Side Effects:
1419  *      The word may be copied to the buffer.
1420  *
1421  *-----------------------------------------------------------------------
1422  */
1423 static Boolean
1424 VarNoMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1425            char *word, Boolean addSpace, Buffer *buf,
1426            void *pattern)
1427 {
1428     if (!Str_Match(word, (char *)pattern)) {
1429         if (addSpace && vpstate->varSpace) {
1430             Buf_AddByte(buf, vpstate->varSpace);
1431         }
1432         addSpace = TRUE;
1433         Buf_AddBytes(buf, strlen(word), word);
1434     }
1435     return(addSpace);
1436 }
1437
1438
1439 /*-
1440  *-----------------------------------------------------------------------
1441  * VarSubstitute --
1442  *      Perform a string-substitution on the given word, placing the
1443  *      result in the passed buffer.
1444  *
1445  * Input:
1446  *      word            Word to modify
1447  *      addSpace        True if space should be added before
1448  *                      other characters
1449  *      buf             Buffer for result
1450  *      patternp        Pattern for substitution
1451  *
1452  * Results:
1453  *      TRUE if a space is needed before more characters are added.
1454  *
1455  * Side Effects:
1456  *      None.
1457  *
1458  *-----------------------------------------------------------------------
1459  */
1460 static Boolean
1461 VarSubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1462               char *word, Boolean addSpace, Buffer *buf,
1463               void *patternp)
1464 {
1465     int         wordLen;    /* Length of word */
1466     char        *cp;        /* General pointer */
1467     VarPattern  *pattern = (VarPattern *)patternp;
1468
1469     wordLen = strlen(word);
1470     if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
1471         (VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1472         /*
1473          * Still substituting -- break it down into simple anchored cases
1474          * and if none of them fits, perform the general substitution case.
1475          */
1476         if ((pattern->flags & VAR_MATCH_START) &&
1477             (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
1478                 /*
1479                  * Anchored at start and beginning of word matches pattern
1480                  */
1481                 if ((pattern->flags & VAR_MATCH_END) &&
1482                     (wordLen == pattern->leftLen)) {
1483                         /*
1484                          * Also anchored at end and matches to the end (word
1485                          * is same length as pattern) add space and rhs only
1486                          * if rhs is non-null.
1487                          */
1488                         if (pattern->rightLen != 0) {
1489                             if (addSpace && vpstate->varSpace) {
1490                                 Buf_AddByte(buf, vpstate->varSpace);
1491                             }
1492                             addSpace = TRUE;
1493                             Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1494                         }
1495                         pattern->flags |= VAR_SUB_MATCHED;
1496                 } else if (pattern->flags & VAR_MATCH_END) {
1497                     /*
1498                      * Doesn't match to end -- copy word wholesale
1499                      */
1500                     goto nosub;
1501                 } else {
1502                     /*
1503                      * Matches at start but need to copy in trailing characters
1504                      */
1505                     if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1506                         if (addSpace && vpstate->varSpace) {
1507                             Buf_AddByte(buf, vpstate->varSpace);
1508                         }
1509                         addSpace = TRUE;
1510                     }
1511                     Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1512                     Buf_AddBytes(buf, wordLen - pattern->leftLen,
1513                                  (word + pattern->leftLen));
1514                     pattern->flags |= VAR_SUB_MATCHED;
1515                 }
1516         } else if (pattern->flags & VAR_MATCH_START) {
1517             /*
1518              * Had to match at start of word and didn't -- copy whole word.
1519              */
1520             goto nosub;
1521         } else if (pattern->flags & VAR_MATCH_END) {
1522             /*
1523              * Anchored at end, Find only place match could occur (leftLen
1524              * characters from the end of the word) and see if it does. Note
1525              * that because the $ will be left at the end of the lhs, we have
1526              * to use strncmp.
1527              */
1528             cp = word + (wordLen - pattern->leftLen);
1529             if ((cp >= word) &&
1530                 (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
1531                 /*
1532                  * Match found. If we will place characters in the buffer,
1533                  * add a space before hand as indicated by addSpace, then
1534                  * stuff in the initial, unmatched part of the word followed
1535                  * by the right-hand-side.
1536                  */
1537                 if (((cp - word) + pattern->rightLen) != 0) {
1538                     if (addSpace && vpstate->varSpace) {
1539                         Buf_AddByte(buf, vpstate->varSpace);
1540                     }
1541                     addSpace = TRUE;
1542                 }
1543                 Buf_AddBytes(buf, cp - word, word);
1544                 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1545                 pattern->flags |= VAR_SUB_MATCHED;
1546             } else {
1547                 /*
1548                  * Had to match at end and didn't. Copy entire word.
1549                  */
1550                 goto nosub;
1551             }
1552         } else {
1553             /*
1554              * Pattern is unanchored: search for the pattern in the word using
1555              * String_FindSubstring, copying unmatched portions and the
1556              * right-hand-side for each match found, handling non-global
1557              * substitutions correctly, etc. When the loop is done, any
1558              * remaining part of the word (word and wordLen are adjusted
1559              * accordingly through the loop) is copied straight into the
1560              * buffer.
1561              * addSpace is set FALSE as soon as a space is added to the
1562              * buffer.
1563              */
1564             Boolean done;
1565             int origSize;
1566
1567             done = FALSE;
1568             origSize = Buf_Size(buf);
1569             while (!done) {
1570                 cp = Str_FindSubstring(word, pattern->lhs);
1571                 if (cp != NULL) {
1572                     if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1573                         Buf_AddByte(buf, vpstate->varSpace);
1574                         addSpace = FALSE;
1575                     }
1576                     Buf_AddBytes(buf, cp-word, word);
1577                     Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1578                     wordLen -= (cp - word) + pattern->leftLen;
1579                     word = cp + pattern->leftLen;
1580                     if (wordLen == 0) {
1581                         done = TRUE;
1582                     }
1583                     if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
1584                         done = TRUE;
1585                     }
1586                     pattern->flags |= VAR_SUB_MATCHED;
1587                 } else {
1588                     done = TRUE;
1589                 }
1590             }
1591             if (wordLen != 0) {
1592                 if (addSpace && vpstate->varSpace) {
1593                     Buf_AddByte(buf, vpstate->varSpace);
1594                 }
1595                 Buf_AddBytes(buf, wordLen, word);
1596             }
1597             /*
1598              * If added characters to the buffer, need to add a space
1599              * before we add any more. If we didn't add any, just return
1600              * the previous value of addSpace.
1601              */
1602             return ((Buf_Size(buf) != origSize) || addSpace);
1603         }
1604         return (addSpace);
1605     }
1606  nosub:
1607     if (addSpace && vpstate->varSpace) {
1608         Buf_AddByte(buf, vpstate->varSpace);
1609     }
1610     Buf_AddBytes(buf, wordLen, word);
1611     return(TRUE);
1612 }
1613
1614 #ifndef NO_REGEX
1615 /*-
1616  *-----------------------------------------------------------------------
1617  * VarREError --
1618  *      Print the error caused by a regcomp or regexec call.
1619  *
1620  * Results:
1621  *      None.
1622  *
1623  * Side Effects:
1624  *      An error gets printed.
1625  *
1626  *-----------------------------------------------------------------------
1627  */
1628 static void
1629 VarREError(int errnum, regex_t *pat, const char *str)
1630 {
1631     char *errbuf;
1632     int errlen;
1633
1634     errlen = regerror(errnum, pat, 0, 0);
1635     errbuf = bmake_malloc(errlen);
1636     regerror(errnum, pat, errbuf, errlen);
1637     Error("%s: %s", str, errbuf);
1638     free(errbuf);
1639 }
1640
1641
1642 /*-
1643  *-----------------------------------------------------------------------
1644  * VarRESubstitute --
1645  *      Perform a regex substitution on the given word, placing the
1646  *      result in the passed buffer.
1647  *
1648  * Results:
1649  *      TRUE if a space is needed before more characters are added.
1650  *
1651  * Side Effects:
1652  *      None.
1653  *
1654  *-----------------------------------------------------------------------
1655  */
1656 static Boolean
1657 VarRESubstitute(GNode *ctx MAKE_ATTR_UNUSED,
1658                 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1659                 char *word, Boolean addSpace, Buffer *buf,
1660                 void *patternp)
1661 {
1662     VarREPattern *pat;
1663     int xrv;
1664     char *wp;
1665     char *rp;
1666     int added;
1667     int flags = 0;
1668
1669 #define MAYBE_ADD_SPACE()               \
1670         if (addSpace && !added)         \
1671             Buf_AddByte(buf, ' ');      \
1672         added = 1
1673
1674     added = 0;
1675     wp = word;
1676     pat = patternp;
1677
1678     if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1679         (VAR_SUB_ONE|VAR_SUB_MATCHED))
1680         xrv = REG_NOMATCH;
1681     else {
1682     tryagain:
1683         xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1684     }
1685
1686     switch (xrv) {
1687     case 0:
1688         pat->flags |= VAR_SUB_MATCHED;
1689         if (pat->matches[0].rm_so > 0) {
1690             MAYBE_ADD_SPACE();
1691             Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1692         }
1693
1694         for (rp = pat->replace; *rp; rp++) {
1695             if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1696                 MAYBE_ADD_SPACE();
1697                 Buf_AddByte(buf,rp[1]);
1698                 rp++;
1699             }
1700             else if ((*rp == '&') ||
1701                 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1702                 int n;
1703                 const char *subbuf;
1704                 int sublen;
1705                 char errstr[3];
1706
1707                 if (*rp == '&') {
1708                     n = 0;
1709                     errstr[0] = '&';
1710                     errstr[1] = '\0';
1711                 } else {
1712                     n = rp[1] - '0';
1713                     errstr[0] = '\\';
1714                     errstr[1] = rp[1];
1715                     errstr[2] = '\0';
1716                     rp++;
1717                 }
1718
1719                 if (n > pat->nsub) {
1720                     Error("No subexpression %s", &errstr[0]);
1721                     subbuf = "";
1722                     sublen = 0;
1723                 } else if ((pat->matches[n].rm_so == -1) &&
1724                            (pat->matches[n].rm_eo == -1)) {
1725                     Error("No match for subexpression %s", &errstr[0]);
1726                     subbuf = "";
1727                     sublen = 0;
1728                 } else {
1729                     subbuf = wp + pat->matches[n].rm_so;
1730                     sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1731                 }
1732
1733                 if (sublen > 0) {
1734                     MAYBE_ADD_SPACE();
1735                     Buf_AddBytes(buf, sublen, subbuf);
1736                 }
1737             } else {
1738                 MAYBE_ADD_SPACE();
1739                 Buf_AddByte(buf, *rp);
1740             }
1741         }
1742         wp += pat->matches[0].rm_eo;
1743         if (pat->flags & VAR_SUB_GLOBAL) {
1744             flags |= REG_NOTBOL;
1745             if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1746                 MAYBE_ADD_SPACE();
1747                 Buf_AddByte(buf, *wp);
1748                 wp++;
1749
1750             }
1751             if (*wp)
1752                 goto tryagain;
1753         }
1754         if (*wp) {
1755             MAYBE_ADD_SPACE();
1756             Buf_AddBytes(buf, strlen(wp), wp);
1757         }
1758         break;
1759     default:
1760         VarREError(xrv, &pat->re, "Unexpected regex error");
1761        /* fall through */
1762     case REG_NOMATCH:
1763         if (*wp) {
1764             MAYBE_ADD_SPACE();
1765             Buf_AddBytes(buf,strlen(wp),wp);
1766         }
1767         break;
1768     }
1769     return(addSpace||added);
1770 }
1771 #endif
1772
1773
1774
1775 /*-
1776  *-----------------------------------------------------------------------
1777  * VarLoopExpand --
1778  *      Implements the :@<temp>@<string>@ modifier of ODE make.
1779  *      We set the temp variable named in pattern.lhs to word and expand
1780  *      pattern.rhs storing the result in the passed buffer.
1781  *
1782  * Input:
1783  *      word            Word to modify
1784  *      addSpace        True if space should be added before
1785  *                      other characters
1786  *      buf             Buffer for result
1787  *      pattern         Datafor substitution
1788  *
1789  * Results:
1790  *      TRUE if a space is needed before more characters are added.
1791  *
1792  * Side Effects:
1793  *      None.
1794  *
1795  *-----------------------------------------------------------------------
1796  */
1797 static Boolean
1798 VarLoopExpand(GNode *ctx MAKE_ATTR_UNUSED,
1799               Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1800               char *word, Boolean addSpace, Buffer *buf,
1801               void *loopp)
1802 {
1803     VarLoop_t   *loop = (VarLoop_t *)loopp;
1804     char *s;
1805     int slen;
1806
1807     if (word && *word) {
1808         Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
1809         s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum, TRUE);
1810         if (s != NULL && *s != '\0') {
1811             if (addSpace && *s != '\n')
1812                 Buf_AddByte(buf, ' ');
1813             Buf_AddBytes(buf, (slen = strlen(s)), s);
1814             addSpace = (slen > 0 && s[slen - 1] != '\n');
1815             free(s);
1816         }
1817     }
1818     return addSpace;
1819 }
1820
1821
1822 /*-
1823  *-----------------------------------------------------------------------
1824  * VarSelectWords --
1825  *      Implements the :[start..end] modifier.
1826  *      This is a special case of VarModify since we want to be able
1827  *      to scan the list backwards if start > end.
1828  *
1829  * Input:
1830  *      str             String whose words should be trimmed
1831  *      seldata         words to select
1832  *
1833  * Results:
1834  *      A string of all the words selected.
1835  *
1836  * Side Effects:
1837  *      None.
1838  *
1839  *-----------------------------------------------------------------------
1840  */
1841 static char *
1842 VarSelectWords(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1843                const char *str, VarSelectWords_t *seldata)
1844 {
1845     Buffer        buf;              /* Buffer for the new string */
1846     Boolean       addSpace;         /* TRUE if need to add a space to the
1847                                      * buffer before adding the trimmed
1848                                      * word */
1849     char **av;                      /* word list */
1850     char *as;                       /* word list memory */
1851     int ac, i;
1852     int start, end, step;
1853
1854     Buf_Init(&buf, 0);
1855     addSpace = FALSE;
1856
1857     if (vpstate->oneBigWord) {
1858         /* fake what brk_string() would do if there were only one word */
1859         ac = 1;
1860         av = bmake_malloc((ac + 1) * sizeof(char *));
1861         as = bmake_strdup(str);
1862         av[0] = as;
1863         av[1] = NULL;
1864     } else {
1865         av = brk_string(str, &ac, FALSE, &as);
1866     }
1867
1868     /*
1869      * Now sanitize seldata.
1870      * If seldata->start or seldata->end are negative, convert them to
1871      * the positive equivalents (-1 gets converted to argc, -2 gets
1872      * converted to (argc-1), etc.).
1873      */
1874     if (seldata->start < 0)
1875         seldata->start = ac + seldata->start + 1;
1876     if (seldata->end < 0)
1877         seldata->end = ac + seldata->end + 1;
1878
1879     /*
1880      * We avoid scanning more of the list than we need to.
1881      */
1882     if (seldata->start > seldata->end) {
1883         start = MIN(ac, seldata->start) - 1;
1884         end = MAX(0, seldata->end - 1);
1885         step = -1;
1886     } else {
1887         start = MAX(0, seldata->start - 1);
1888         end = MIN(ac, seldata->end);
1889         step = 1;
1890     }
1891
1892     for (i = start;
1893          (step < 0 && i >= end) || (step > 0 && i < end);
1894          i += step) {
1895         if (av[i] && *av[i]) {
1896             if (addSpace && vpstate->varSpace) {
1897                 Buf_AddByte(&buf, vpstate->varSpace);
1898             }
1899             Buf_AddBytes(&buf, strlen(av[i]), av[i]);
1900             addSpace = TRUE;
1901         }
1902     }
1903
1904     free(as);
1905     free(av);
1906
1907     return Buf_Destroy(&buf, FALSE);
1908 }
1909
1910
1911 /*-
1912  * VarRealpath --
1913  *      Replace each word with the result of realpath()
1914  *      if successful.
1915  */
1916 static Boolean
1917 VarRealpath(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1918             char *word, Boolean addSpace, Buffer *buf,
1919             void *patternp MAKE_ATTR_UNUSED)
1920 {
1921         struct stat st;
1922         char rbuf[MAXPATHLEN];
1923         char *rp;
1924                             
1925         if (addSpace && vpstate->varSpace) {
1926             Buf_AddByte(buf, vpstate->varSpace);
1927         }
1928         addSpace = TRUE;
1929         rp = realpath(word, rbuf);
1930         if (rp && *rp == '/' && stat(rp, &st) == 0)
1931                 word = rp;
1932         
1933         Buf_AddBytes(buf, strlen(word), word);
1934         return(addSpace);
1935 }
1936
1937 /*-
1938  *-----------------------------------------------------------------------
1939  * VarModify --
1940  *      Modify each of the words of the passed string using the given
1941  *      function. Used to implement all modifiers.
1942  *
1943  * Input:
1944  *      str             String whose words should be trimmed
1945  *      modProc         Function to use to modify them
1946  *      datum           Datum to pass it
1947  *
1948  * Results:
1949  *      A string of all the words modified appropriately.
1950  *
1951  * Side Effects:
1952  *      None.
1953  *
1954  *-----------------------------------------------------------------------
1955  */
1956 static char *
1957 VarModify(GNode *ctx, Var_Parse_State *vpstate,
1958     const char *str,
1959     Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
1960                        Boolean, Buffer *, void *),
1961     void *datum)
1962 {
1963     Buffer        buf;              /* Buffer for the new string */
1964     Boolean       addSpace;         /* TRUE if need to add a space to the
1965                                      * buffer before adding the trimmed
1966                                      * word */
1967     char **av;                      /* word list */
1968     char *as;                       /* word list memory */
1969     int ac, i;
1970
1971     Buf_Init(&buf, 0);
1972     addSpace = FALSE;
1973
1974     if (vpstate->oneBigWord) {
1975         /* fake what brk_string() would do if there were only one word */
1976         ac = 1;
1977         av = bmake_malloc((ac + 1) * sizeof(char *));
1978         as = bmake_strdup(str);
1979         av[0] = as;
1980         av[1] = NULL;
1981     } else {
1982         av = brk_string(str, &ac, FALSE, &as);
1983     }
1984
1985     for (i = 0; i < ac; i++) {
1986         addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum);
1987     }
1988
1989     free(as);
1990     free(av);
1991
1992     return Buf_Destroy(&buf, FALSE);
1993 }
1994
1995
1996 static int
1997 VarWordCompare(const void *a, const void *b)
1998 {
1999         int r = strcmp(*(const char * const *)a, *(const char * const *)b);
2000         return r;
2001 }
2002
2003 /*-
2004  *-----------------------------------------------------------------------
2005  * VarOrder --
2006  *      Order the words in the string.
2007  *
2008  * Input:
2009  *      str             String whose words should be sorted.
2010  *      otype           How to order: s - sort, x - random.
2011  *
2012  * Results:
2013  *      A string containing the words ordered.
2014  *
2015  * Side Effects:
2016  *      None.
2017  *
2018  *-----------------------------------------------------------------------
2019  */
2020 static char *
2021 VarOrder(const char *str, const char otype)
2022 {
2023     Buffer        buf;              /* Buffer for the new string */
2024     char **av;                      /* word list [first word does not count] */
2025     char *as;                       /* word list memory */
2026     int ac, i;
2027
2028     Buf_Init(&buf, 0);
2029
2030     av = brk_string(str, &ac, FALSE, &as);
2031
2032     if (ac > 0)
2033         switch (otype) {
2034         case 's':       /* sort alphabetically */
2035             qsort(av, ac, sizeof(char *), VarWordCompare);
2036             break;
2037         case 'x':       /* randomize */
2038         {
2039             int rndidx;
2040             char *t;
2041
2042             /*
2043              * We will use [ac..2] range for mod factors. This will produce
2044              * random numbers in [(ac-1)..0] interval, and minimal
2045              * reasonable value for mod factor is 2 (the mod 1 will produce
2046              * 0 with probability 1).
2047              */
2048             for (i = ac-1; i > 0; i--) {
2049                 rndidx = random() % (i + 1);
2050                 if (i != rndidx) {
2051                     t = av[i];
2052                     av[i] = av[rndidx];
2053                     av[rndidx] = t;
2054                 }
2055             }
2056         }
2057         } /* end of switch */
2058
2059     for (i = 0; i < ac; i++) {
2060         Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2061         if (i != ac - 1)
2062             Buf_AddByte(&buf, ' ');
2063     }
2064
2065     free(as);
2066     free(av);
2067
2068     return Buf_Destroy(&buf, FALSE);
2069 }
2070
2071
2072 /*-
2073  *-----------------------------------------------------------------------
2074  * VarUniq --
2075  *      Remove adjacent duplicate words.
2076  *
2077  * Input:
2078  *      str             String whose words should be sorted
2079  *
2080  * Results:
2081  *      A string containing the resulting words.
2082  *
2083  * Side Effects:
2084  *      None.
2085  *
2086  *-----------------------------------------------------------------------
2087  */
2088 static char *
2089 VarUniq(const char *str)
2090 {
2091     Buffer        buf;              /* Buffer for new string */
2092     char        **av;               /* List of words to affect */
2093     char         *as;               /* Word list memory */
2094     int           ac, i, j;
2095
2096     Buf_Init(&buf, 0);
2097     av = brk_string(str, &ac, FALSE, &as);
2098
2099     if (ac > 1) {
2100         for (j = 0, i = 1; i < ac; i++)
2101             if (strcmp(av[i], av[j]) != 0 && (++j != i))
2102                 av[j] = av[i];
2103         ac = j + 1;
2104     }
2105
2106     for (i = 0; i < ac; i++) {
2107         Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2108         if (i != ac - 1)
2109             Buf_AddByte(&buf, ' ');
2110     }
2111
2112     free(as);
2113     free(av);
2114
2115     return Buf_Destroy(&buf, FALSE);
2116 }
2117
2118
2119 /*-
2120  *-----------------------------------------------------------------------
2121  * VarGetPattern --
2122  *      Pass through the tstr looking for 1) escaped delimiters,
2123  *      '$'s and backslashes (place the escaped character in
2124  *      uninterpreted) and 2) unescaped $'s that aren't before
2125  *      the delimiter (expand the variable substitution unless flags
2126  *      has VAR_NOSUBST set).
2127  *      Return the expanded string or NULL if the delimiter was missing
2128  *      If pattern is specified, handle escaped ampersands, and replace
2129  *      unescaped ampersands with the lhs of the pattern.
2130  *
2131  * Results:
2132  *      A string of all the words modified appropriately.
2133  *      If length is specified, return the string length of the buffer
2134  *      If flags is specified and the last character of the pattern is a
2135  *      $ set the VAR_MATCH_END bit of flags.
2136  *
2137  * Side Effects:
2138  *      None.
2139  *-----------------------------------------------------------------------
2140  */
2141 static char *
2142 VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
2143               int errnum, const char **tstr, int delim, int *flags,
2144               int *length, VarPattern *pattern)
2145 {
2146     const char *cp;
2147     char *rstr;
2148     Buffer buf;
2149     int junk;
2150
2151     Buf_Init(&buf, 0);
2152     if (length == NULL)
2153         length = &junk;
2154
2155 #define IS_A_MATCH(cp, delim) \
2156     ((cp[0] == '\\') && ((cp[1] == delim) ||  \
2157      (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
2158
2159     /*
2160      * Skim through until the matching delimiter is found;
2161      * pick up variable substitutions on the way. Also allow
2162      * backslashes to quote the delimiter, $, and \, but don't
2163      * touch other backslashes.
2164      */
2165     for (cp = *tstr; *cp && (*cp != delim); cp++) {
2166         if (IS_A_MATCH(cp, delim)) {
2167             Buf_AddByte(&buf, cp[1]);
2168             cp++;
2169         } else if (*cp == '$') {
2170             if (cp[1] == delim) {
2171                 if (flags == NULL)
2172                     Buf_AddByte(&buf, *cp);
2173                 else
2174                     /*
2175                      * Unescaped $ at end of pattern => anchor
2176                      * pattern at end.
2177                      */
2178                     *flags |= VAR_MATCH_END;
2179             } else {
2180                 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
2181                     char   *cp2;
2182                     int     len;
2183                     void   *freeIt;
2184
2185                     /*
2186                      * If unescaped dollar sign not before the
2187                      * delimiter, assume it's a variable
2188                      * substitution and recurse.
2189                      */
2190                     cp2 = Var_Parse(cp, ctxt, errnum, TRUE, &len, &freeIt);
2191                     Buf_AddBytes(&buf, strlen(cp2), cp2);
2192                     free(freeIt);
2193                     cp += len - 1;
2194                 } else {
2195                     const char *cp2 = &cp[1];
2196
2197                     if (*cp2 == PROPEN || *cp2 == BROPEN) {
2198                         /*
2199                          * Find the end of this variable reference
2200                          * and suck it in without further ado.
2201                          * It will be interperated later.
2202                          */
2203                         int have = *cp2;
2204                         int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
2205                         int depth = 1;
2206
2207                         for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
2208                             if (cp2[-1] != '\\') {
2209                                 if (*cp2 == have)
2210                                     ++depth;
2211                                 if (*cp2 == want)
2212                                     --depth;
2213                             }
2214                         }
2215                         Buf_AddBytes(&buf, cp2 - cp, cp);
2216                         cp = --cp2;
2217                     } else
2218                         Buf_AddByte(&buf, *cp);
2219                 }
2220             }
2221         }
2222         else if (pattern && *cp == '&')
2223             Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
2224         else
2225             Buf_AddByte(&buf, *cp);
2226     }
2227
2228     if (*cp != delim) {
2229         *tstr = cp;
2230         *length = 0;
2231         return NULL;
2232     }
2233
2234     *tstr = ++cp;
2235     *length = Buf_Size(&buf);
2236     rstr = Buf_Destroy(&buf, FALSE);
2237     if (DEBUG(VAR))
2238         fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
2239     return rstr;
2240 }
2241
2242 /*-
2243  *-----------------------------------------------------------------------
2244  * VarQuote --
2245  *      Quote shell meta-characters and space characters in the string
2246  *
2247  * Results:
2248  *      The quoted string
2249  *
2250  * Side Effects:
2251  *      None.
2252  *
2253  *-----------------------------------------------------------------------
2254  */
2255 static char *
2256 VarQuote(char *str)
2257 {
2258
2259     Buffer        buf;
2260     const char  *newline;
2261     size_t nlen;
2262
2263     if ((newline = Shell_GetNewline()) == NULL)
2264             newline = "\\\n";
2265     nlen = strlen(newline);
2266
2267     Buf_Init(&buf, 0);
2268
2269     for (; *str != '\0'; str++) {
2270         if (*str == '\n') {
2271             Buf_AddBytes(&buf, nlen, newline);
2272             continue;
2273         }
2274         if (isspace((unsigned char)*str) || ismeta((unsigned char)*str))
2275             Buf_AddByte(&buf, '\\');
2276         Buf_AddByte(&buf, *str);
2277     }
2278
2279     str = Buf_Destroy(&buf, FALSE);
2280     if (DEBUG(VAR))
2281         fprintf(debug_file, "QuoteMeta: [%s]\n", str);
2282     return str;
2283 }
2284
2285 /*-
2286  *-----------------------------------------------------------------------
2287  * VarHash --
2288  *      Hash the string using the MurmurHash3 algorithm.
2289  *      Output is computed using 32bit Little Endian arithmetic.
2290  *
2291  * Input:
2292  *      str             String to modify
2293  *
2294  * Results:
2295  *      Hash value of str, encoded as 8 hex digits.
2296  *
2297  * Side Effects:
2298  *      None.
2299  *
2300  *-----------------------------------------------------------------------
2301  */
2302 static char *
2303 VarHash(char *str)
2304 {
2305     static const char    hexdigits[16] = "0123456789abcdef";
2306     Buffer         buf;
2307     size_t         len, len2;
2308     unsigned char  *ustr = (unsigned char *)str;
2309     uint32_t       h, k, c1, c2;
2310
2311     h  = 0x971e137bU;
2312     c1 = 0x95543787U;
2313     c2 = 0x2ad7eb25U;
2314     len2 = strlen(str);
2315
2316     for (len = len2; len; ) {
2317         k = 0;
2318         switch (len) {
2319         default:
2320             k = (ustr[3] << 24) | (ustr[2] << 16) | (ustr[1] << 8) | ustr[0];
2321             len -= 4;
2322             ustr += 4;
2323             break;
2324         case 3:
2325             k |= (ustr[2] << 16);
2326         case 2:
2327             k |= (ustr[1] << 8);
2328         case 1:
2329             k |= ustr[0];
2330             len = 0;
2331         }
2332         c1 = c1 * 5 + 0x7b7d159cU;
2333         c2 = c2 * 5 + 0x6bce6396U;
2334         k *= c1;
2335         k = (k << 11) ^ (k >> 21);
2336         k *= c2;
2337         h = (h << 13) ^ (h >> 19);
2338         h = h * 5 + 0x52dce729U;
2339         h ^= k;
2340    }
2341    h ^= len2;
2342    h *= 0x85ebca6b;
2343    h ^= h >> 13;
2344    h *= 0xc2b2ae35;
2345    h ^= h >> 16;
2346
2347    Buf_Init(&buf, 0);
2348    for (len = 0; len < 8; ++len) {
2349        Buf_AddByte(&buf, hexdigits[h & 15]);
2350        h >>= 4;
2351    }
2352
2353    return Buf_Destroy(&buf, FALSE);
2354 }
2355
2356 static char *
2357 VarStrftime(const char *fmt, int zulu)
2358 {
2359     char buf[BUFSIZ];
2360     time_t utc;
2361
2362     time(&utc);
2363     if (!*fmt)
2364         fmt = "%c";
2365     strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2366     
2367     buf[sizeof(buf) - 1] = '\0';
2368     return bmake_strdup(buf);
2369 }
2370
2371 /*
2372  * Now we need to apply any modifiers the user wants applied.
2373  * These are:
2374  *        :M<pattern>   words which match the given <pattern>.
2375  *                      <pattern> is of the standard file
2376  *                      wildcarding form.
2377  *        :N<pattern>   words which do not match the given <pattern>.
2378  *        :S<d><pat1><d><pat2><d>[1gW]
2379  *                      Substitute <pat2> for <pat1> in the value
2380  *        :C<d><pat1><d><pat2><d>[1gW]
2381  *                      Substitute <pat2> for regex <pat1> in the value
2382  *        :H            Substitute the head of each word
2383  *        :T            Substitute the tail of each word
2384  *        :E            Substitute the extension (minus '.') of
2385  *                      each word
2386  *        :R            Substitute the root of each word
2387  *                      (pathname minus the suffix).
2388  *        :O            ("Order") Alphabeticaly sort words in variable.
2389  *        :Ox           ("intermiX") Randomize words in variable.
2390  *        :u            ("uniq") Remove adjacent duplicate words.
2391  *        :tu           Converts the variable contents to uppercase.
2392  *        :tl           Converts the variable contents to lowercase.
2393  *        :ts[c]        Sets varSpace - the char used to
2394  *                      separate words to 'c'. If 'c' is
2395  *                      omitted then no separation is used.
2396  *        :tW           Treat the variable contents as a single
2397  *                      word, even if it contains spaces.
2398  *                      (Mnemonic: one big 'W'ord.)
2399  *        :tw           Treat the variable contents as multiple
2400  *                      space-separated words.
2401  *                      (Mnemonic: many small 'w'ords.)
2402  *        :[index]      Select a single word from the value.
2403  *        :[start..end] Select multiple words from the value.
2404  *        :[*] or :[0]  Select the entire value, as a single
2405  *                      word.  Equivalent to :tW.
2406  *        :[@]          Select the entire value, as multiple
2407  *                      words.  Undoes the effect of :[*].
2408  *                      Equivalent to :tw.
2409  *        :[#]          Returns the number of words in the value.
2410  *
2411  *        :?<true-value>:<false-value>
2412  *                      If the variable evaluates to true, return
2413  *                      true value, else return the second value.
2414  *        :lhs=rhs      Like :S, but the rhs goes to the end of
2415  *                      the invocation.
2416  *        :sh           Treat the current value as a command
2417  *                      to be run, new value is its output.
2418  * The following added so we can handle ODE makefiles.
2419  *        :@<tmpvar>@<newval>@
2420  *                      Assign a temporary local variable <tmpvar>
2421  *                      to the current value of each word in turn
2422  *                      and replace each word with the result of
2423  *                      evaluating <newval>
2424  *        :D<newval>    Use <newval> as value if variable defined
2425  *        :U<newval>    Use <newval> as value if variable undefined
2426  *        :L            Use the name of the variable as the value.
2427  *        :P            Use the path of the node that has the same
2428  *                      name as the variable as the value.  This
2429  *                      basically includes an implied :L so that
2430  *                      the common method of refering to the path
2431  *                      of your dependent 'x' in a rule is to use
2432  *                      the form '${x:P}'.
2433  *        :!<cmd>!      Run cmd much the same as :sh run's the
2434  *                      current value of the variable.
2435  * The ::= modifiers, actually assign a value to the variable.
2436  * Their main purpose is in supporting modifiers of .for loop
2437  * iterators and other obscure uses.  They always expand to
2438  * nothing.  In a target rule that would otherwise expand to an
2439  * empty line they can be preceded with @: to keep make happy.
2440  * Eg.
2441  *
2442  * foo: .USE
2443  * .for i in ${.TARGET} ${.TARGET:R}.gz
2444  *      @: ${t::=$i}
2445  *      @echo blah ${t:T}
2446  * .endfor
2447  *
2448  *        ::=<str>      Assigns <str> as the new value of variable.
2449  *        ::?=<str>     Assigns <str> as value of variable if
2450  *                      it was not already set.
2451  *        ::+=<str>     Appends <str> to variable.
2452  *        ::!=<cmd>     Assigns output of <cmd> as the new value of
2453  *                      variable.
2454  */
2455
2456 /* we now have some modifiers with long names */
2457 #define STRMOD_MATCH(s, want, n) \
2458     (strncmp(s, want, n) == 0 && (s[n] == endc || s[n] == ':'))
2459
2460 static char *
2461 ApplyModifiers(char *nstr, const char *tstr,
2462                int startc, int endc,
2463                Var *v, GNode *ctxt, Boolean errnum, Boolean wantit,
2464                int *lengthPtr, void **freePtr)
2465 {
2466     const char     *start;
2467     const char     *cp;         /* Secondary pointer into str (place marker
2468                                  * for tstr) */
2469     char           *newStr;     /* New value to return */
2470     char            termc;      /* Character which terminated scan */
2471     int             cnt;        /* Used to count brace pairs when variable in
2472                                  * in parens or braces */
2473     char        delim;
2474     int         modifier;       /* that we are processing */
2475     Var_Parse_State parsestate; /* Flags passed to helper functions */
2476
2477     delim = '\0';
2478     parsestate.oneBigWord = FALSE;
2479     parsestate.varSpace = ' ';  /* word separator */
2480
2481     start = cp = tstr;
2482
2483     while (*tstr && *tstr != endc) {
2484
2485         if (*tstr == '$') {
2486             /*
2487              * We may have some complex modifiers in a variable.
2488              */
2489             void *freeIt;
2490             char *rval;
2491             int rlen;
2492             int c;
2493
2494             rval = Var_Parse(tstr, ctxt, errnum, wantit, &rlen, &freeIt);
2495
2496             /*
2497              * If we have not parsed up to endc or ':',
2498              * we are not interested.
2499              */
2500             if (rval != NULL && *rval &&
2501                 (c = tstr[rlen]) != '\0' &&
2502                 c != ':' &&
2503                 c != endc) {
2504                 free(freeIt);
2505                 goto apply_mods;
2506             }
2507
2508             if (DEBUG(VAR)) {
2509                 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
2510                        rval, rlen, tstr, rlen, tstr + rlen);
2511             }
2512
2513             tstr += rlen;
2514
2515             if (rval != NULL && *rval) {
2516                 int used;
2517
2518                 nstr = ApplyModifiers(nstr, rval,
2519                                       0, 0,
2520                                       v, ctxt, errnum, wantit, &used, freePtr);
2521                 if (nstr == var_Error
2522                     || (nstr == varNoError && errnum == 0)
2523                     || strlen(rval) != (size_t) used) {
2524                     free(freeIt);
2525                     goto out;           /* error already reported */
2526                 }
2527             }
2528             free(freeIt);
2529             if (*tstr == ':')
2530                 tstr++;
2531             else if (!*tstr && endc) {
2532                 Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name);
2533                 goto out;
2534             }
2535             continue;
2536         }
2537     apply_mods:
2538         if (DEBUG(VAR)) {
2539             fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", v->name,
2540                 *tstr, nstr);
2541         }
2542         newStr = var_Error;
2543         switch ((modifier = *tstr)) {
2544         case ':':
2545             {
2546                 if (tstr[1] == '=' ||
2547                     (tstr[2] == '=' &&
2548                      (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
2549                     /*
2550                      * "::=", "::!=", "::+=", or "::?="
2551                      */
2552                     GNode *v_ctxt;              /* context where v belongs */
2553                     const char *emsg;
2554                     char *sv_name;
2555                     VarPattern  pattern;
2556                     int how;
2557                     int flags;
2558
2559                     if (v->name[0] == 0)
2560                         goto bad_modifier;
2561
2562                     v_ctxt = ctxt;
2563                     sv_name = NULL;
2564                     ++tstr;
2565                     if (v->flags & VAR_JUNK) {
2566                         /*
2567                          * We need to bmake_strdup() it incase
2568                          * VarGetPattern() recurses.
2569                          */
2570                         sv_name = v->name;
2571                         v->name = bmake_strdup(v->name);
2572                     } else if (ctxt != VAR_GLOBAL) {
2573                         Var *gv = VarFind(v->name, ctxt, 0);
2574                         if (gv == NULL)
2575                             v_ctxt = VAR_GLOBAL;
2576                         else
2577                             VarFreeEnv(gv, TRUE);
2578                     }
2579
2580                     switch ((how = *tstr)) {
2581                     case '+':
2582                     case '?':
2583                     case '!':
2584                         cp = &tstr[2];
2585                         break;
2586                     default:
2587                         cp = ++tstr;
2588                         break;
2589                     }
2590                     delim = startc == PROPEN ? PRCLOSE : BRCLOSE;
2591                     pattern.flags = 0;
2592
2593                     flags = (wantit) ? 0 : VAR_NOSUBST;
2594                     pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2595                                                 &cp, delim, &flags,
2596                                                 &pattern.rightLen,
2597                                                 NULL);
2598                     if (v->flags & VAR_JUNK) {
2599                         /* restore original name */
2600                         free(v->name);
2601                         v->name = sv_name;
2602                     }
2603                     if (pattern.rhs == NULL)
2604                         goto cleanup;
2605
2606                     termc = *--cp;
2607                     delim = '\0';
2608
2609                     if (wantit) {
2610                         switch (how) {
2611                         case '+':
2612                             Var_Append(v->name, pattern.rhs, v_ctxt);
2613                             break;
2614                         case '!':
2615                             newStr = Cmd_Exec(pattern.rhs, &emsg);
2616                             if (emsg)
2617                                 Error(emsg, nstr);
2618                             else
2619                                 Var_Set(v->name, newStr,  v_ctxt, 0);
2620                             free(newStr);
2621                             break;
2622                         case '?':
2623                             if ((v->flags & VAR_JUNK) == 0)
2624                                 break;
2625                             /* FALLTHROUGH */
2626                         default:
2627                             Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2628                             break;
2629                         }
2630                     }
2631                     free(UNCONST(pattern.rhs));
2632                     newStr = varNoError;
2633                     break;
2634                 }
2635                 goto default_case; /* "::<unrecognised>" */
2636             }
2637         case '@':
2638             {
2639                 VarLoop_t       loop;
2640                 int flags = VAR_NOSUBST;
2641
2642                 cp = ++tstr;
2643                 delim = '@';
2644                 if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum,
2645                                                &cp, delim,
2646                                                &flags, &loop.tvarLen,
2647                                                NULL)) == NULL)
2648                     goto cleanup;
2649
2650                 if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum,
2651                                               &cp, delim,
2652                                               &flags, &loop.strLen,
2653                                               NULL)) == NULL)
2654                     goto cleanup;
2655
2656                 termc = *cp;
2657                 delim = '\0';
2658
2659                 loop.errnum = errnum;
2660                 loop.ctxt = ctxt;
2661                 newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
2662                                    &loop);
2663                 free(loop.tvar);
2664                 free(loop.str);
2665                 break;
2666             }
2667         case 'D':
2668         case 'U':
2669             {
2670                 Buffer  buf;            /* Buffer for patterns */
2671                 int         wantit_;    /* want data in buffer */
2672
2673                 if (wantit) {
2674                     if (*tstr == 'U')
2675                         wantit_ = ((v->flags & VAR_JUNK) != 0);
2676                     else
2677                         wantit_ = ((v->flags & VAR_JUNK) == 0);
2678                 } else
2679                     wantit_ = wantit;
2680                 /*
2681                  * Pass through tstr looking for 1) escaped delimiters,
2682                  * '$'s and backslashes (place the escaped character in
2683                  * uninterpreted) and 2) unescaped $'s that aren't before
2684                  * the delimiter (expand the variable substitution).
2685                  * The result is left in the Buffer buf.
2686                  */
2687                 Buf_Init(&buf, 0);
2688                 for (cp = tstr + 1;
2689                      *cp != endc && *cp != ':' && *cp != '\0';
2690                      cp++) {
2691                     if ((*cp == '\\') &&
2692                         ((cp[1] == ':') ||
2693                          (cp[1] == '$') ||
2694                          (cp[1] == endc) ||
2695                          (cp[1] == '\\')))
2696                         {
2697                             Buf_AddByte(&buf, cp[1]);
2698                             cp++;
2699                         } else if (*cp == '$') {
2700                             /*
2701                              * If unescaped dollar sign, assume it's a
2702                              * variable substitution and recurse.
2703                              */
2704                             char    *cp2;
2705                             int     len;
2706                             void    *freeIt;
2707
2708                             cp2 = Var_Parse(cp, ctxt, errnum, wantit_, &len, &freeIt);
2709                             Buf_AddBytes(&buf, strlen(cp2), cp2);
2710                             free(freeIt);
2711                             cp += len - 1;
2712                         } else {
2713                             Buf_AddByte(&buf, *cp);
2714                         }
2715                 }
2716
2717                 termc = *cp;
2718
2719                 if ((v->flags & VAR_JUNK) != 0)
2720                     v->flags |= VAR_KEEP;
2721                 if (wantit_) {
2722                     newStr = Buf_Destroy(&buf, FALSE);
2723                 } else {
2724                     newStr = nstr;
2725                     Buf_Destroy(&buf, TRUE);
2726                 }
2727                 break;
2728             }
2729         case 'L':
2730             {
2731                 if ((v->flags & VAR_JUNK) != 0)
2732                     v->flags |= VAR_KEEP;
2733                 newStr = bmake_strdup(v->name);
2734                 cp = ++tstr;
2735                 termc = *tstr;
2736                 break;
2737             }
2738         case 'P':
2739             {
2740                 GNode *gn;
2741
2742                 if ((v->flags & VAR_JUNK) != 0)
2743                     v->flags |= VAR_KEEP;
2744                 gn = Targ_FindNode(v->name, TARG_NOCREATE);
2745                 if (gn == NULL || gn->type & OP_NOPATH) {
2746                     newStr = NULL;
2747                 } else if (gn->path) {
2748                     newStr = bmake_strdup(gn->path);
2749                 } else {
2750                     newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
2751                 }
2752                 if (!newStr) {
2753                     newStr = bmake_strdup(v->name);
2754                 }
2755                 cp = ++tstr;
2756                 termc = *tstr;
2757                 break;
2758             }
2759         case '!':
2760             {
2761                 const char *emsg;
2762                 VarPattern          pattern;
2763                 pattern.flags = 0;
2764
2765                 delim = '!';
2766                 emsg = NULL;
2767                 cp = ++tstr;
2768                 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2769                                                  &cp, delim,
2770                                                  NULL, &pattern.rightLen,
2771                                                  NULL)) == NULL)
2772                     goto cleanup;
2773                 if (wantit)
2774                     newStr = Cmd_Exec(pattern.rhs, &emsg);
2775                 else
2776                     newStr = varNoError;
2777                 free(UNCONST(pattern.rhs));
2778                 if (emsg)
2779                     Error(emsg, nstr);
2780                 termc = *cp;
2781                 delim = '\0';
2782                 if (v->flags & VAR_JUNK) {
2783                     v->flags |= VAR_KEEP;
2784                 }
2785                 break;
2786             }
2787         case '[':
2788             {
2789                 /*
2790                  * Look for the closing ']', recursively
2791                  * expanding any embedded variables.
2792                  *
2793                  * estr is a pointer to the expanded result,
2794                  * which we must free().
2795                  */
2796                 char *estr;
2797
2798                 cp = tstr+1; /* point to char after '[' */
2799                 delim = ']'; /* look for closing ']' */
2800                 estr = VarGetPattern(ctxt, &parsestate,
2801                                      errnum, &cp, delim,
2802                                      NULL, NULL, NULL);
2803                 if (estr == NULL)
2804                     goto cleanup; /* report missing ']' */
2805                 /* now cp points just after the closing ']' */
2806                 delim = '\0';
2807                 if (cp[0] != ':' && cp[0] != endc) {
2808                     /* Found junk after ']' */
2809                     free(estr);
2810                     goto bad_modifier;
2811                 }
2812                 if (estr[0] == '\0') {
2813                     /* Found empty square brackets in ":[]". */
2814                     free(estr);
2815                     goto bad_modifier;
2816                 } else if (estr[0] == '#' && estr[1] == '\0') {
2817                     /* Found ":[#]" */
2818
2819                     /*
2820                      * We will need enough space for the decimal
2821                      * representation of an int.  We calculate the
2822                      * space needed for the octal representation,
2823                      * and add enough slop to cope with a '-' sign
2824                      * (which should never be needed) and a '\0'
2825                      * string terminator.
2826                      */
2827                     int newStrSize =
2828                         (sizeof(int) * CHAR_BIT + 2) / 3 + 2;
2829
2830                     newStr = bmake_malloc(newStrSize);
2831                     if (parsestate.oneBigWord) {
2832                         strncpy(newStr, "1", newStrSize);
2833                     } else {
2834                         /* XXX: brk_string() is a rather expensive
2835                          * way of counting words. */
2836                         char **av;
2837                         char *as;
2838                         int ac;
2839
2840                         av = brk_string(nstr, &ac, FALSE, &as);
2841                         snprintf(newStr, newStrSize,  "%d", ac);
2842                         free(as);
2843                         free(av);
2844                     }
2845                     termc = *cp;
2846                     free(estr);
2847                     break;
2848                 } else if (estr[0] == '*' && estr[1] == '\0') {
2849                     /* Found ":[*]" */
2850                     parsestate.oneBigWord = TRUE;
2851                     newStr = nstr;
2852                     termc = *cp;
2853                     free(estr);
2854                     break;
2855                 } else if (estr[0] == '@' && estr[1] == '\0') {
2856                     /* Found ":[@]" */
2857                     parsestate.oneBigWord = FALSE;
2858                     newStr = nstr;
2859                     termc = *cp;
2860                     free(estr);
2861                     break;
2862                 } else {
2863                     /*
2864                      * We expect estr to contain a single
2865                      * integer for :[N], or two integers
2866                      * separated by ".." for :[start..end].
2867                      */
2868                     char *ep;
2869
2870                     VarSelectWords_t seldata = { 0, 0 };
2871
2872                     seldata.start = strtol(estr, &ep, 0);
2873                     if (ep == estr) {
2874                         /* Found junk instead of a number */
2875                         free(estr);
2876                         goto bad_modifier;
2877                     } else if (ep[0] == '\0') {
2878                         /* Found only one integer in :[N] */
2879                         seldata.end = seldata.start;
2880                     } else if (ep[0] == '.' && ep[1] == '.' &&
2881                                ep[2] != '\0') {
2882                         /* Expecting another integer after ".." */
2883                         ep += 2;
2884                         seldata.end = strtol(ep, &ep, 0);
2885                         if (ep[0] != '\0') {
2886                             /* Found junk after ".." */
2887                             free(estr);
2888                             goto bad_modifier;
2889                         }
2890                     } else {
2891                         /* Found junk instead of ".." */
2892                         free(estr);
2893                         goto bad_modifier;
2894                     }
2895                     /*
2896                      * Now seldata is properly filled in,
2897                      * but we still have to check for 0 as
2898                      * a special case.
2899                      */
2900                     if (seldata.start == 0 && seldata.end == 0) {
2901                         /* ":[0]" or perhaps ":[0..0]" */
2902                         parsestate.oneBigWord = TRUE;
2903                         newStr = nstr;
2904                         termc = *cp;
2905                         free(estr);
2906                         break;
2907                     } else if (seldata.start == 0 ||
2908                                seldata.end == 0) {
2909                         /* ":[0..N]" or ":[N..0]" */
2910                         free(estr);
2911                         goto bad_modifier;
2912                     }
2913                     /*
2914                      * Normal case: select the words
2915                      * described by seldata.
2916                      */
2917                     newStr = VarSelectWords(ctxt, &parsestate,
2918                                             nstr, &seldata);
2919
2920                     termc = *cp;
2921                     free(estr);
2922                     break;
2923                 }
2924
2925             }
2926         case 'g':
2927             cp = tstr + 1;      /* make sure it is set */
2928             if (STRMOD_MATCH(tstr, "gmtime", 6)) {
2929                 newStr = VarStrftime(nstr, 1);
2930                 cp = tstr + 6;
2931                 termc = *cp;
2932             } else {
2933                 goto default_case;
2934             }
2935             break;
2936         case 'h':
2937             cp = tstr + 1;      /* make sure it is set */
2938             if (STRMOD_MATCH(tstr, "hash", 4)) {
2939                 newStr = VarHash(nstr);
2940                 cp = tstr + 4;
2941                 termc = *cp;
2942             } else {
2943                 goto default_case;
2944             }
2945             break;
2946         case 'l':
2947             cp = tstr + 1;      /* make sure it is set */
2948             if (STRMOD_MATCH(tstr, "localtime", 9)) {
2949                 newStr = VarStrftime(nstr, 0);
2950                 cp = tstr + 9;
2951                 termc = *cp;
2952             } else {
2953                 goto default_case;
2954             }
2955             break;
2956         case 't':
2957             {
2958                 cp = tstr + 1;  /* make sure it is set */
2959                 if (tstr[1] != endc && tstr[1] != ':') {
2960                     if (tstr[1] == 's') {
2961                         /*
2962                          * Use the char (if any) at tstr[2]
2963                          * as the word separator.
2964                          */
2965                         VarPattern pattern;
2966
2967                         if (tstr[2] != endc &&
2968                             (tstr[3] == endc || tstr[3] == ':')) {
2969                             /* ":ts<unrecognised><endc>" or
2970                              * ":ts<unrecognised>:" */
2971                             parsestate.varSpace = tstr[2];
2972                             cp = tstr + 3;
2973                         } else if (tstr[2] == endc || tstr[2] == ':') {
2974                             /* ":ts<endc>" or ":ts:" */
2975                             parsestate.varSpace = 0; /* no separator */
2976                             cp = tstr + 2;
2977                         } else if (tstr[2] == '\\') {
2978                             switch (tstr[3]) {
2979                             case 'n':
2980                                 parsestate.varSpace = '\n';
2981                                 cp = tstr + 4;
2982                                 break;
2983                             case 't':
2984                                 parsestate.varSpace = '\t';
2985                                 cp = tstr + 4;
2986                                 break;
2987                             default:
2988                                 if (isdigit((unsigned char)tstr[3])) {
2989                                     char *ep;
2990
2991                                     parsestate.varSpace =
2992                                         strtoul(&tstr[3], &ep, 0);
2993                                     if (*ep != ':' && *ep != endc)
2994                                         goto bad_modifier;
2995                                     cp = ep;
2996                                 } else {
2997                                     /*
2998                                      * ":ts<backslash><unrecognised>".
2999                                      */
3000                                     goto bad_modifier;
3001                                 }
3002                                 break;
3003                             }
3004                         } else {
3005                             /*
3006                              * Found ":ts<unrecognised><unrecognised>".
3007                              */
3008                             goto bad_modifier;
3009                         }
3010
3011                         termc = *cp;
3012
3013                         /*
3014                          * We cannot be certain that VarModify
3015                          * will be used - even if there is a
3016                          * subsequent modifier, so do a no-op
3017                          * VarSubstitute now to for str to be
3018                          * re-expanded without the spaces.
3019                          */
3020                         pattern.flags = VAR_SUB_ONE;
3021                         pattern.lhs = pattern.rhs = "\032";
3022                         pattern.leftLen = pattern.rightLen = 1;
3023
3024                         newStr = VarModify(ctxt, &parsestate, nstr,
3025                                            VarSubstitute,
3026                                            &pattern);
3027                     } else if (tstr[2] == endc || tstr[2] == ':') {
3028                         /*
3029                          * Check for two-character options:
3030                          * ":tu", ":tl"
3031                          */
3032                         if (tstr[1] == 'A') { /* absolute path */
3033                             newStr = VarModify(ctxt, &parsestate, nstr,
3034                                                VarRealpath, NULL);
3035                             cp = tstr + 2;
3036                             termc = *cp;
3037                         } else if (tstr[1] == 'u') {
3038                             char *dp = bmake_strdup(nstr);
3039                             for (newStr = dp; *dp; dp++)
3040                                 *dp = toupper((unsigned char)*dp);
3041                             cp = tstr + 2;
3042                             termc = *cp;
3043                         } else if (tstr[1] == 'l') {
3044                             char *dp = bmake_strdup(nstr);
3045                             for (newStr = dp; *dp; dp++)
3046                                 *dp = tolower((unsigned char)*dp);
3047                             cp = tstr + 2;
3048                             termc = *cp;
3049                         } else if (tstr[1] == 'W' || tstr[1] == 'w') {
3050                             parsestate.oneBigWord = (tstr[1] == 'W');
3051                             newStr = nstr;
3052                             cp = tstr + 2;
3053                             termc = *cp;
3054                         } else {
3055                             /* Found ":t<unrecognised>:" or
3056                              * ":t<unrecognised><endc>". */
3057                             goto bad_modifier;
3058                         }
3059                     } else {
3060                         /*
3061                          * Found ":t<unrecognised><unrecognised>".
3062                          */
3063                         goto bad_modifier;
3064                     }
3065                 } else {
3066                     /*
3067                      * Found ":t<endc>" or ":t:".
3068                      */
3069                     goto bad_modifier;
3070                 }
3071                 break;
3072             }
3073         case 'N':
3074         case 'M':
3075             {
3076                 char    *pattern;
3077                 const char *endpat; /* points just after end of pattern */
3078                 char    *cp2;
3079                 Boolean copy;   /* pattern should be, or has been, copied */
3080                 Boolean needSubst;
3081                 int nest;
3082
3083                 copy = FALSE;
3084                 needSubst = FALSE;
3085                 nest = 1;
3086                 /*
3087                  * In the loop below, ignore ':' unless we are at
3088                  * (or back to) the original brace level.
3089                  * XXX This will likely not work right if $() and ${}
3090                  * are intermixed.
3091                  */
3092                 for (cp = tstr + 1;
3093                      *cp != '\0' && !(*cp == ':' && nest == 1);
3094                      cp++)
3095                     {
3096                         if (*cp == '\\' &&
3097                             (cp[1] == ':' ||
3098                              cp[1] == endc || cp[1] == startc)) {
3099                             if (!needSubst) {
3100                                 copy = TRUE;
3101                             }
3102                             cp++;
3103                             continue;
3104                         }
3105                         if (*cp == '$') {
3106                             needSubst = TRUE;
3107                         }
3108                         if (*cp == '(' || *cp == '{')
3109                             ++nest;
3110                         if (*cp == ')' || *cp == '}') {
3111                             --nest;
3112                             if (nest == 0)
3113                                 break;
3114                         }
3115                     }
3116                 termc = *cp;
3117                 endpat = cp;
3118                 if (copy) {
3119                     /*
3120                      * Need to compress the \:'s out of the pattern, so
3121                      * allocate enough room to hold the uncompressed
3122                      * pattern (note that cp started at tstr+1, so
3123                      * cp - tstr takes the null byte into account) and
3124                      * compress the pattern into the space.
3125                      */
3126                     pattern = bmake_malloc(cp - tstr);
3127                     for (cp2 = pattern, cp = tstr + 1;
3128                          cp < endpat;
3129                          cp++, cp2++)
3130                         {
3131                             if ((*cp == '\\') && (cp+1 < endpat) &&
3132                                 (cp[1] == ':' || cp[1] == endc)) {
3133                                 cp++;
3134                             }
3135                             *cp2 = *cp;
3136                         }
3137                     *cp2 = '\0';
3138                     endpat = cp2;
3139                 } else {
3140                     /*
3141                      * Either Var_Subst or VarModify will need a
3142                      * nul-terminated string soon, so construct one now.
3143                      */
3144                     pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
3145                 }
3146                 if (needSubst) {
3147                     /*
3148                      * pattern contains embedded '$', so use Var_Subst to
3149                      * expand it.
3150                      */
3151                     cp2 = pattern;
3152                     pattern = Var_Subst(NULL, cp2, ctxt, errnum, TRUE);
3153                     free(cp2);
3154                 }
3155                 if (DEBUG(VAR))
3156                     fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
3157                         v->name, nstr, pattern);
3158                 if (*tstr == 'M') {
3159                     newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
3160                                        pattern);
3161                 } else {
3162                     newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
3163                                        pattern);
3164                 }
3165                 free(pattern);
3166                 break;
3167             }
3168         case 'S':
3169             {
3170                 VarPattern          pattern;
3171                 Var_Parse_State tmpparsestate;
3172
3173                 pattern.flags = 0;
3174                 tmpparsestate = parsestate;
3175                 delim = tstr[1];
3176                 tstr += 2;
3177
3178                 /*
3179                  * If pattern begins with '^', it is anchored to the
3180                  * start of the word -- skip over it and flag pattern.
3181                  */
3182                 if (*tstr == '^') {
3183                     pattern.flags |= VAR_MATCH_START;
3184                     tstr += 1;
3185                 }
3186
3187                 cp = tstr;
3188                 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3189                                                  &cp, delim,
3190                                                  &pattern.flags,
3191                                                  &pattern.leftLen,
3192                                                  NULL)) == NULL)
3193                     goto cleanup;
3194
3195                 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3196                                                  &cp, delim, NULL,
3197                                                  &pattern.rightLen,
3198                                                  &pattern)) == NULL)
3199                     goto cleanup;
3200
3201                 /*
3202                  * Check for global substitution. If 'g' after the final
3203                  * delimiter, substitution is global and is marked that
3204                  * way.
3205                  */
3206                 for (;; cp++) {
3207                     switch (*cp) {
3208                     case 'g':
3209                         pattern.flags |= VAR_SUB_GLOBAL;
3210                         continue;
3211                     case '1':
3212                         pattern.flags |= VAR_SUB_ONE;
3213                         continue;
3214                     case 'W':
3215                         tmpparsestate.oneBigWord = TRUE;
3216                         continue;
3217                     }
3218                     break;
3219                 }
3220
3221                 termc = *cp;
3222                 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3223                                    VarSubstitute,
3224                                    &pattern);
3225
3226                 /*
3227                  * Free the two strings.
3228                  */
3229                 free(UNCONST(pattern.lhs));
3230                 free(UNCONST(pattern.rhs));
3231                 delim = '\0';
3232                 break;
3233             }
3234         case '?':
3235             {
3236                 VarPattern      pattern;
3237                 Boolean value;
3238                 int cond_rc;
3239                 int lhs_flags, rhs_flags;
3240                 
3241                 /* find ':', and then substitute accordingly */
3242                 if (wantit) {
3243                     cond_rc = Cond_EvalExpression(NULL, v->name, &value, 0, FALSE);
3244                     if (cond_rc == COND_INVALID) {
3245                         lhs_flags = rhs_flags = VAR_NOSUBST;
3246                     } else if (value) {
3247                         lhs_flags = 0;
3248                         rhs_flags = VAR_NOSUBST;
3249                     } else {
3250                         lhs_flags = VAR_NOSUBST;
3251                         rhs_flags = 0;
3252                     }
3253                 } else {
3254                     /* we are just consuming and discarding */
3255                     cond_rc = value = 0;
3256                     lhs_flags = rhs_flags = VAR_NOSUBST;
3257                 }
3258                 pattern.flags = 0;
3259
3260                 cp = ++tstr;
3261                 delim = ':';
3262                 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3263                                                  &cp, delim, &lhs_flags,
3264                                                  &pattern.leftLen,
3265                                                  NULL)) == NULL)
3266                     goto cleanup;
3267
3268                 /* BROPEN or PROPEN */
3269                 delim = endc;
3270                 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3271                                                  &cp, delim, &rhs_flags,
3272                                                  &pattern.rightLen,
3273                                                  NULL)) == NULL)
3274                     goto cleanup;
3275
3276                 termc = *--cp;
3277                 delim = '\0';
3278                 if (cond_rc == COND_INVALID) {
3279                     Error("Bad conditional expression `%s' in %s?%s:%s",
3280                           v->name, v->name, pattern.lhs, pattern.rhs);
3281                     goto cleanup;
3282                 }
3283
3284                 if (value) {
3285                     newStr = UNCONST(pattern.lhs);
3286                     free(UNCONST(pattern.rhs));
3287                 } else {
3288                     newStr = UNCONST(pattern.rhs);
3289                     free(UNCONST(pattern.lhs));
3290                 }
3291                 if (v->flags & VAR_JUNK) {
3292                     v->flags |= VAR_KEEP;
3293                 }
3294                 break;
3295             }
3296 #ifndef NO_REGEX
3297         case 'C':
3298             {
3299                 VarREPattern    pattern;
3300                 char           *re;
3301                 int             error;
3302                 Var_Parse_State tmpparsestate;
3303
3304                 pattern.flags = 0;
3305                 tmpparsestate = parsestate;
3306                 delim = tstr[1];
3307                 tstr += 2;
3308
3309                 cp = tstr;
3310
3311                 if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim,
3312                                         NULL, NULL, NULL)) == NULL)
3313                     goto cleanup;
3314
3315                 if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
3316                                                      errnum, &cp, delim, NULL,
3317                                                      NULL, NULL)) == NULL){
3318                     free(re);
3319                     goto cleanup;
3320                 }
3321
3322                 for (;; cp++) {
3323                     switch (*cp) {
3324                     case 'g':
3325                         pattern.flags |= VAR_SUB_GLOBAL;
3326                         continue;
3327                     case '1':
3328                         pattern.flags |= VAR_SUB_ONE;
3329                         continue;
3330                     case 'W':
3331                         tmpparsestate.oneBigWord = TRUE;
3332                         continue;
3333                     }
3334                     break;
3335                 }
3336
3337                 termc = *cp;
3338
3339                 error = regcomp(&pattern.re, re, REG_EXTENDED);
3340                 free(re);
3341                 if (error)  {
3342                     *lengthPtr = cp - start + 1;
3343                     VarREError(error, &pattern.re, "RE substitution error");
3344                     free(pattern.replace);
3345                     goto cleanup;
3346                 }
3347
3348                 pattern.nsub = pattern.re.re_nsub + 1;
3349                 if (pattern.nsub < 1)
3350                     pattern.nsub = 1;
3351                 if (pattern.nsub > 10)
3352                     pattern.nsub = 10;
3353                 pattern.matches = bmake_malloc(pattern.nsub *
3354                                           sizeof(regmatch_t));
3355                 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3356                                    VarRESubstitute,
3357                                    &pattern);
3358                 regfree(&pattern.re);
3359                 free(pattern.replace);
3360                 free(pattern.matches);
3361                 delim = '\0';
3362                 break;
3363             }
3364 #endif
3365         case 'Q':
3366             if (tstr[1] == endc || tstr[1] == ':') {
3367                 newStr = VarQuote(nstr);
3368                 cp = tstr + 1;
3369                 termc = *cp;
3370                 break;
3371             }
3372             goto default_case;
3373         case 'T':
3374             if (tstr[1] == endc || tstr[1] == ':') {
3375                 newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
3376                                    NULL);
3377                 cp = tstr + 1;
3378                 termc = *cp;
3379                 break;
3380             }
3381             goto default_case;
3382         case 'H':
3383             if (tstr[1] == endc || tstr[1] == ':') {
3384                 newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
3385                                    NULL);
3386                 cp = tstr + 1;
3387                 termc = *cp;
3388                 break;
3389             }
3390             goto default_case;
3391         case 'E':
3392             if (tstr[1] == endc || tstr[1] == ':') {
3393                 newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
3394                                    NULL);
3395                 cp = tstr + 1;
3396                 termc = *cp;
3397                 break;
3398             }
3399             goto default_case;
3400         case 'R':
3401             if (tstr[1] == endc || tstr[1] == ':') {
3402                 newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
3403                                    NULL);
3404                 cp = tstr + 1;
3405                 termc = *cp;
3406                 break;
3407             }
3408             goto default_case;
3409         case 'O':
3410             {
3411                 char otype;
3412
3413                 cp = tstr + 1;  /* skip to the rest in any case */
3414                 if (tstr[1] == endc || tstr[1] == ':') {
3415                     otype = 's';
3416                     termc = *cp;
3417                 } else if ( (tstr[1] == 'x') &&
3418                             (tstr[2] == endc || tstr[2] == ':') ) {
3419                     otype = tstr[1];
3420                     cp = tstr + 2;
3421                     termc = *cp;
3422                 } else {
3423                     goto bad_modifier;
3424                 }
3425                 newStr = VarOrder(nstr, otype);
3426                 break;
3427             }
3428         case 'u':
3429             if (tstr[1] == endc || tstr[1] == ':') {
3430                 newStr = VarUniq(nstr);
3431                 cp = tstr + 1;
3432                 termc = *cp;
3433                 break;
3434             }
3435             goto default_case;
3436 #ifdef SUNSHCMD
3437         case 's':
3438             if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
3439                 const char *emsg;
3440                 if (wantit) {
3441                     newStr = Cmd_Exec(nstr, &emsg);
3442                     if (emsg)
3443                         Error(emsg, nstr);
3444                 } else
3445                     newStr = varNoError;
3446                 cp = tstr + 2;
3447                 termc = *cp;
3448                 break;
3449             }
3450             goto default_case;
3451 #endif
3452         default:
3453         default_case:
3454         {
3455 #ifdef SYSVVARSUB
3456             /*
3457              * This can either be a bogus modifier or a System-V
3458              * substitution command.
3459              */
3460             VarPattern      pattern;
3461             Boolean         eqFound;
3462
3463             pattern.flags = 0;
3464             eqFound = FALSE;
3465             /*
3466              * First we make a pass through the string trying
3467              * to verify it is a SYSV-make-style translation:
3468              * it must be: <string1>=<string2>)
3469              */
3470             cp = tstr;
3471             cnt = 1;
3472             while (*cp != '\0' && cnt) {
3473                 if (*cp == '=') {
3474                     eqFound = TRUE;
3475                     /* continue looking for endc */
3476                 }
3477                 else if (*cp == endc)
3478                     cnt--;
3479                 else if (*cp == startc)
3480                     cnt++;
3481                 if (cnt)
3482                     cp++;
3483             }
3484             if (*cp == endc && eqFound) {
3485
3486                 /*
3487                  * Now we break this sucker into the lhs and
3488                  * rhs. We must null terminate them of course.
3489                  */
3490                 delim='=';
3491                 cp = tstr;
3492                 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
3493                                                  errnum, &cp, delim, &pattern.flags,
3494                                                  &pattern.leftLen, NULL)) == NULL)
3495                     goto cleanup;
3496                 delim = endc;
3497                 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
3498                                                  errnum, &cp, delim, NULL, &pattern.rightLen,
3499                                                  &pattern)) == NULL)
3500                     goto cleanup;
3501
3502                 /*
3503                  * SYSV modifications happen through the whole
3504                  * string. Note the pattern is anchored at the end.
3505                  */
3506                 termc = *--cp;
3507                 delim = '\0';
3508                 if (pattern.leftLen == 0 && *nstr == '\0') {
3509                     newStr = nstr;      /* special case */
3510                 } else {
3511                     newStr = VarModify(ctxt, &parsestate, nstr,
3512                                        VarSYSVMatch,
3513                                        &pattern);
3514                 }
3515                 free(UNCONST(pattern.lhs));
3516                 free(UNCONST(pattern.rhs));
3517             } else
3518 #endif
3519                 {
3520                     Error("Unknown modifier '%c'", *tstr);
3521                     for (cp = tstr+1;
3522                          *cp != ':' && *cp != endc && *cp != '\0';
3523                          cp++)
3524                         continue;
3525                     termc = *cp;
3526                     newStr = var_Error;
3527                 }
3528             }
3529         }
3530         if (DEBUG(VAR)) {
3531             fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
3532                 v->name, modifier, newStr);
3533         }
3534
3535         if (newStr != nstr) {
3536             if (*freePtr) {
3537                 free(nstr);
3538                 *freePtr = NULL;
3539             }
3540             nstr = newStr;
3541             if (nstr != var_Error && nstr != varNoError) {
3542                 *freePtr = nstr;
3543             }
3544         }
3545         if (termc == '\0' && endc != '\0') {
3546             Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier);
3547         } else if (termc == ':') {
3548             cp++;
3549         }
3550         tstr = cp;
3551     }
3552  out:
3553     *lengthPtr = tstr - start;
3554     return (nstr);
3555
3556  bad_modifier:
3557     /* "{(" */
3558     Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
3559           v->name);
3560
3561  cleanup:
3562     *lengthPtr = cp - start;
3563     if (delim != '\0')
3564         Error("Unclosed substitution for %s (%c missing)",
3565               v->name, delim);
3566     free(*freePtr);
3567     *freePtr = NULL;
3568     return (var_Error);
3569 }
3570
3571 /*-
3572  *-----------------------------------------------------------------------
3573  * Var_Parse --
3574  *      Given the start of a variable invocation, extract the variable
3575  *      name and find its value, then modify it according to the
3576  *      specification.
3577  *
3578  * Input:
3579  *      str             The string to parse
3580  *      ctxt            The context for the variable
3581  *      errnum          TRUE if undefined variables are an error
3582  *      wantit          TRUE if we actually want the result
3583  *      lengthPtr       OUT: The length of the specification
3584  *      freePtr         OUT: Non-NULL if caller should free *freePtr
3585  *
3586  * Results:
3587  *      The (possibly-modified) value of the variable or var_Error if the
3588  *      specification is invalid. The length of the specification is
3589  *      placed in *lengthPtr (for invalid specifications, this is just
3590  *      2...?).
3591  *      If *freePtr is non-NULL then it's a pointer that the caller
3592  *      should pass to free() to free memory used by the result.
3593  *
3594  * Side Effects:
3595  *      None.
3596  *
3597  *-----------------------------------------------------------------------
3598  */
3599 /* coverity[+alloc : arg-*4] */
3600 char *
3601 Var_Parse(const char *str, GNode *ctxt,
3602            Boolean errnum, Boolean wantit,
3603            int *lengthPtr, void **freePtr)
3604 {
3605     const char     *tstr;       /* Pointer into str */
3606     Var            *v;          /* Variable in invocation */
3607     Boolean         haveModifier;/* TRUE if have modifiers for the variable */
3608     char            endc;       /* Ending character when variable in parens
3609                                  * or braces */
3610     char            startc;     /* Starting character when variable in parens
3611                                  * or braces */
3612     int             vlen;       /* Length of variable name */
3613     const char     *start;      /* Points to original start of str */
3614     char           *nstr;       /* New string, used during expansion */
3615     Boolean         dynamic;    /* TRUE if the variable is local and we're
3616                                  * expanding it in a non-local context. This
3617                                  * is done to support dynamic sources. The
3618                                  * result is just the invocation, unaltered */
3619     const char     *extramodifiers; /* extra modifiers to apply first */
3620     char          name[2];
3621
3622     *freePtr = NULL;
3623     extramodifiers = NULL;
3624     dynamic = FALSE;
3625     start = str;
3626
3627     startc = str[1];
3628     if (startc != PROPEN && startc != BROPEN) {
3629         /*
3630          * If it's not bounded by braces of some sort, life is much simpler.
3631          * We just need to check for the first character and return the
3632          * value if it exists.
3633          */
3634
3635         /* Error out some really stupid names */
3636         if (startc == '\0' || strchr(")}:$", startc)) {
3637             *lengthPtr = 1;
3638             return var_Error;
3639         }
3640         name[0] = startc;
3641         name[1] = '\0';
3642
3643         v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3644         if (v == NULL) {
3645             *lengthPtr = 2;
3646
3647             if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
3648                 /*
3649                  * If substituting a local variable in a non-local context,
3650                  * assume it's for dynamic source stuff. We have to handle
3651                  * this specially and return the longhand for the variable
3652                  * with the dollar sign escaped so it makes it back to the
3653                  * caller. Only four of the local variables are treated
3654                  * specially as they are the only four that will be set
3655                  * when dynamic sources are expanded.
3656                  */
3657                 switch (str[1]) {
3658                     case '@':
3659                         return UNCONST("$(.TARGET)");
3660                     case '%':
3661                         return UNCONST("$(.ARCHIVE)");
3662                     case '*':
3663                         return UNCONST("$(.PREFIX)");
3664                     case '!':
3665                         return UNCONST("$(.MEMBER)");
3666                 }
3667             }
3668             /*
3669              * Error
3670              */
3671             return (errnum ? var_Error : varNoError);
3672         } else {
3673             haveModifier = FALSE;
3674             tstr = &str[1];
3675             endc = str[1];
3676         }
3677     } else {
3678         Buffer buf;     /* Holds the variable name */
3679         int depth = 1;
3680
3681         endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3682         Buf_Init(&buf, 0);
3683
3684         /*
3685          * Skip to the end character or a colon, whichever comes first.
3686          */
3687         for (tstr = str + 2; *tstr != '\0'; tstr++)
3688         {
3689             /*
3690              * Track depth so we can spot parse errors.
3691              */
3692             if (*tstr == startc) {
3693                 depth++;
3694             }
3695             if (*tstr == endc) {
3696                 if (--depth == 0)
3697                     break;
3698             }
3699             if (depth == 1 && *tstr == ':') {
3700                 break;
3701             }
3702             /*
3703              * A variable inside a variable, expand
3704              */
3705             if (*tstr == '$') {
3706                 int rlen;
3707                 void *freeIt;
3708                 char *rval = Var_Parse(tstr, ctxt, errnum, wantit, &rlen, &freeIt);
3709                 if (rval != NULL) {
3710                     Buf_AddBytes(&buf, strlen(rval), rval);
3711                 }
3712                 free(freeIt);
3713                 tstr += rlen - 1;
3714             }
3715             else
3716                 Buf_AddByte(&buf, *tstr);
3717         }
3718         if (*tstr == ':') {
3719             haveModifier = TRUE;
3720         } else if (*tstr == endc) {
3721             haveModifier = FALSE;
3722         } else {
3723             /*
3724              * If we never did find the end character, return NULL
3725              * right now, setting the length to be the distance to
3726              * the end of the string, since that's what make does.
3727              */
3728             *lengthPtr = tstr - str;
3729             Buf_Destroy(&buf, TRUE);
3730             return (var_Error);
3731         }
3732         str = Buf_GetAll(&buf, &vlen);
3733
3734         /*
3735          * At this point, str points into newly allocated memory from
3736          * buf, containing only the name of the variable.
3737          *
3738          * start and tstr point into the const string that was pointed
3739          * to by the original value of the str parameter.  start points
3740          * to the '$' at the beginning of the string, while tstr points
3741          * to the char just after the end of the variable name -- this
3742          * will be '\0', ':', PRCLOSE, or BRCLOSE.
3743          */
3744
3745         v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3746         /*
3747          * Check also for bogus D and F forms of local variables since we're
3748          * in a local context and the name is the right length.
3749          */
3750         if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
3751                 (vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
3752                 strchr("@%?*!<>", str[0]) != NULL) {
3753             /*
3754              * Well, it's local -- go look for it.
3755              */
3756             name[0] = *str;
3757             name[1] = '\0';
3758             v = VarFind(name, ctxt, 0);
3759
3760             if (v != NULL) {
3761                 if (str[1] == 'D') {
3762                         extramodifiers = "H:";
3763                 }
3764                 else { /* F */
3765                         extramodifiers = "T:";
3766                 }
3767             }
3768         }
3769
3770         if (v == NULL) {
3771             if (((vlen == 1) ||
3772                  (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
3773                 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3774             {
3775                 /*
3776                  * If substituting a local variable in a non-local context,
3777                  * assume it's for dynamic source stuff. We have to handle
3778                  * this specially and return the longhand for the variable
3779                  * with the dollar sign escaped so it makes it back to the
3780                  * caller. Only four of the local variables are treated
3781                  * specially as they are the only four that will be set
3782                  * when dynamic sources are expanded.
3783                  */
3784                 switch (*str) {
3785                     case '@':
3786                     case '%':
3787                     case '*':
3788                     case '!':
3789                         dynamic = TRUE;
3790                         break;
3791                 }
3792             } else if ((vlen > 2) && (*str == '.') &&
3793                        isupper((unsigned char) str[1]) &&
3794                        ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3795             {
3796                 int     len;
3797
3798                 len = vlen - 1;
3799                 if ((strncmp(str, ".TARGET", len) == 0) ||
3800                     (strncmp(str, ".ARCHIVE", len) == 0) ||
3801                     (strncmp(str, ".PREFIX", len) == 0) ||
3802                     (strncmp(str, ".MEMBER", len) == 0))
3803                 {
3804                     dynamic = TRUE;
3805                 }
3806             }
3807
3808             if (!haveModifier) {
3809                 /*
3810                  * No modifiers -- have specification length so we can return
3811                  * now.
3812                  */
3813                 *lengthPtr = tstr - start + 1;
3814                 if (dynamic) {
3815                     char *pstr = bmake_strndup(start, *lengthPtr);
3816                     *freePtr = pstr;
3817                     Buf_Destroy(&buf, TRUE);
3818                     return(pstr);
3819                 } else {
3820                     Buf_Destroy(&buf, TRUE);
3821                     return (errnum ? var_Error : varNoError);
3822                 }
3823             } else {
3824                 /*
3825                  * Still need to get to the end of the variable specification,
3826                  * so kludge up a Var structure for the modifications
3827                  */
3828                 v = bmake_malloc(sizeof(Var));
3829                 v->name = UNCONST(str);
3830                 Buf_Init(&v->val, 1);
3831                 v->flags = VAR_JUNK;
3832                 Buf_Destroy(&buf, FALSE);
3833             }
3834         } else
3835             Buf_Destroy(&buf, TRUE);
3836     }
3837
3838     if (v->flags & VAR_IN_USE) {
3839         Fatal("Variable %s is recursive.", v->name);
3840         /*NOTREACHED*/
3841     } else {
3842         v->flags |= VAR_IN_USE;
3843     }
3844     /*
3845      * Before doing any modification, we have to make sure the value
3846      * has been fully expanded. If it looks like recursion might be
3847      * necessary (there's a dollar sign somewhere in the variable's value)
3848      * we just call Var_Subst to do any other substitutions that are
3849      * necessary. Note that the value returned by Var_Subst will have
3850      * been dynamically-allocated, so it will need freeing when we
3851      * return.
3852      */
3853     nstr = Buf_GetAll(&v->val, NULL);
3854     if (strchr(nstr, '$') != NULL) {
3855         nstr = Var_Subst(NULL, nstr, ctxt, errnum, wantit);
3856         *freePtr = nstr;
3857     }
3858
3859     v->flags &= ~VAR_IN_USE;
3860
3861     if ((nstr != NULL) && (haveModifier || extramodifiers != NULL)) {
3862         void *extraFree;
3863         int used;
3864
3865         extraFree = NULL;
3866         if (extramodifiers != NULL) {
3867                 nstr = ApplyModifiers(nstr, extramodifiers, '(', ')',
3868                                       v, ctxt, errnum, wantit, &used, &extraFree);
3869         }
3870
3871         if (haveModifier) {
3872                 /* Skip initial colon. */
3873                 tstr++;
3874
3875                 nstr = ApplyModifiers(nstr, tstr, startc, endc,
3876                                       v, ctxt, errnum, wantit, &used, freePtr);
3877                 tstr += used;
3878                 free(extraFree);
3879         } else {
3880                 *freePtr = extraFree;
3881         }
3882     }
3883     if (*tstr) {
3884         *lengthPtr = tstr - start + 1;
3885     } else {
3886         *lengthPtr = tstr - start;
3887     }
3888
3889     if (v->flags & VAR_FROM_ENV) {
3890         Boolean   destroy = FALSE;
3891
3892         if (nstr != Buf_GetAll(&v->val, NULL)) {
3893             destroy = TRUE;
3894         } else {
3895             /*
3896              * Returning the value unmodified, so tell the caller to free
3897              * the thing.
3898              */
3899             *freePtr = nstr;
3900         }
3901         VarFreeEnv(v, destroy);
3902     } else if (v->flags & VAR_JUNK) {
3903         /*
3904          * Perform any free'ing needed and set *freePtr to NULL so the caller
3905          * doesn't try to free a static pointer.
3906          * If VAR_KEEP is also set then we want to keep str as is.
3907          */
3908         if (!(v->flags & VAR_KEEP)) {
3909             if (*freePtr) {
3910                 free(nstr);
3911                 *freePtr = NULL;
3912             }
3913             if (dynamic) {
3914                 nstr = bmake_strndup(start, *lengthPtr);
3915                 *freePtr = nstr;
3916             } else {
3917                 nstr = errnum ? var_Error : varNoError;
3918             }
3919         }
3920         if (nstr != Buf_GetAll(&v->val, NULL))
3921             Buf_Destroy(&v->val, TRUE);
3922         free(v->name);
3923         free(v);
3924     }
3925     return (nstr);
3926 }
3927
3928 /*-
3929  *-----------------------------------------------------------------------
3930  * Var_Subst  --
3931  *      Substitute for all variables in the given string in the given context
3932  *      If undefErr is TRUE, Parse_Error will be called when an undefined
3933  *      variable is encountered.
3934  *
3935  * Input:
3936  *      var             Named variable || NULL for all
3937  *      str             the string which to substitute
3938  *      ctxt            the context wherein to find variables
3939  *      undefErr        TRUE if undefineds are an error
3940  *      wantit          TRUE if we actually want the result
3941  *
3942  * Results:
3943  *      The resulting string.
3944  *
3945  * Side Effects:
3946  *      None. The old string must be freed by the caller
3947  *-----------------------------------------------------------------------
3948  */
3949 char *
3950 Var_Subst(const char *var, const char *str, GNode *ctxt,
3951            Boolean undefErr, Boolean wantit)
3952 {
3953     Buffer        buf;              /* Buffer for forming things */
3954     char          *val;             /* Value to substitute for a variable */
3955     int           length;           /* Length of the variable invocation */
3956     Boolean       trailingBslash;   /* variable ends in \ */
3957     void          *freeIt = NULL;    /* Set if it should be freed */
3958     static Boolean errorReported;   /* Set true if an error has already
3959                                      * been reported to prevent a plethora
3960                                      * of messages when recursing */
3961
3962     Buf_Init(&buf, 0);
3963     errorReported = FALSE;
3964     trailingBslash = FALSE;
3965
3966     while (*str) {
3967         if (*str == '\n' && trailingBslash)
3968             Buf_AddByte(&buf, ' ');
3969         if (var == NULL && (*str == '$') && (str[1] == '$')) {
3970             /*
3971              * A dollar sign may be escaped either with another dollar sign.
3972              * In such a case, we skip over the escape character and store the
3973              * dollar sign into the buffer directly.
3974              */
3975             str++;
3976             Buf_AddByte(&buf, *str);
3977             str++;
3978         } else if (*str != '$') {
3979             /*
3980              * Skip as many characters as possible -- either to the end of
3981              * the string or to the next dollar sign (variable invocation).
3982              */
3983             const char  *cp;
3984
3985             for (cp = str++; *str != '$' && *str != '\0'; str++)
3986                 continue;
3987             Buf_AddBytes(&buf, str - cp, cp);
3988         } else {
3989             if (var != NULL) {
3990                 int expand;
3991                 for (;;) {
3992                     if (str[1] == '\0') {
3993                         /* A trailing $ is kind of a special case */
3994                         Buf_AddByte(&buf, str[0]);
3995                         str++;
3996                         expand = FALSE;
3997                     } else if (str[1] != PROPEN && str[1] != BROPEN) {
3998                         if (str[1] != *var || strlen(var) > 1) {
3999                             Buf_AddBytes(&buf, 2, str);
4000                             str += 2;
4001                             expand = FALSE;
4002                         }
4003                         else
4004                             expand = TRUE;
4005                         break;
4006                     }
4007                     else {
4008                         const char *p;
4009
4010                         /*
4011                          * Scan up to the end of the variable name.
4012                          */
4013                         for (p = &str[2]; *p &&
4014                              *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
4015                             if (*p == '$')
4016                                 break;
4017                         /*
4018                          * A variable inside the variable. We cannot expand
4019                          * the external variable yet, so we try again with
4020                          * the nested one
4021                          */
4022                         if (*p == '$') {
4023                             Buf_AddBytes(&buf, p - str, str);
4024                             str = p;
4025                             continue;
4026                         }
4027
4028                         if (strncmp(var, str + 2, p - str - 2) != 0 ||
4029                             var[p - str - 2] != '\0') {
4030                             /*
4031                              * Not the variable we want to expand, scan
4032                              * until the next variable
4033                              */
4034                             for (;*p != '$' && *p != '\0'; p++)
4035                                 continue;
4036                             Buf_AddBytes(&buf, p - str, str);
4037                             str = p;
4038                             expand = FALSE;
4039                         }
4040                         else
4041                             expand = TRUE;
4042                         break;
4043                     }
4044                 }
4045                 if (!expand)
4046                     continue;
4047             }
4048
4049             val = Var_Parse(str, ctxt, undefErr, wantit, &length, &freeIt);
4050
4051             /*
4052              * When we come down here, val should either point to the
4053              * value of this variable, suitably modified, or be NULL.
4054              * Length should be the total length of the potential
4055              * variable invocation (from $ to end character...)
4056              */
4057             if (val == var_Error || val == varNoError) {
4058                 /*
4059                  * If performing old-time variable substitution, skip over
4060                  * the variable and continue with the substitution. Otherwise,
4061                  * store the dollar sign and advance str so we continue with
4062                  * the string...
4063                  */
4064                 if (oldVars) {
4065                     str += length;
4066                 } else if (undefErr || val == var_Error) {
4067                     /*
4068                      * If variable is undefined, complain and skip the
4069                      * variable. The complaint will stop us from doing anything
4070                      * when the file is parsed.
4071                      */
4072                     if (!errorReported) {
4073                         Parse_Error(PARSE_FATAL,
4074                                      "Undefined variable \"%.*s\"",length,str);
4075                     }
4076                     str += length;
4077                     errorReported = TRUE;
4078                 } else {
4079                     Buf_AddByte(&buf, *str);
4080                     str += 1;
4081                 }
4082             } else {
4083                 /*
4084                  * We've now got a variable structure to store in. But first,
4085                  * advance the string pointer.
4086                  */
4087                 str += length;
4088
4089                 /*
4090                  * Copy all the characters from the variable value straight
4091                  * into the new string.
4092                  */
4093                 length = strlen(val);
4094                 Buf_AddBytes(&buf, length, val);
4095                 trailingBslash = length > 0 && val[length - 1] == '\\';
4096             }
4097             free(freeIt);
4098             freeIt = NULL;
4099         }
4100     }
4101
4102     return Buf_DestroyCompact(&buf);
4103 }
4104
4105 /*-
4106  *-----------------------------------------------------------------------
4107  * Var_GetTail --
4108  *      Return the tail from each of a list of words. Used to set the
4109  *      System V local variables.
4110  *
4111  * Input:
4112  *      file            Filename to modify
4113  *
4114  * Results:
4115  *      The resulting string.
4116  *
4117  * Side Effects:
4118  *      None.
4119  *
4120  *-----------------------------------------------------------------------
4121  */
4122 #if 0
4123 char *
4124 Var_GetTail(char *file)
4125 {
4126     return(VarModify(file, VarTail, NULL));
4127 }
4128
4129 /*-
4130  *-----------------------------------------------------------------------
4131  * Var_GetHead --
4132  *      Find the leading components of a (list of) filename(s).
4133  *      XXX: VarHead does not replace foo by ., as (sun) System V make
4134  *      does.
4135  *
4136  * Input:
4137  *      file            Filename to manipulate
4138  *
4139  * Results:
4140  *      The leading components.
4141  *
4142  * Side Effects:
4143  *      None.
4144  *
4145  *-----------------------------------------------------------------------
4146  */
4147 char *
4148 Var_GetHead(char *file)
4149 {
4150     return(VarModify(file, VarHead, NULL));
4151 }
4152 #endif
4153
4154 /*-
4155  *-----------------------------------------------------------------------
4156  * Var_Init --
4157  *      Initialize the module
4158  *
4159  * Results:
4160  *      None
4161  *
4162  * Side Effects:
4163  *      The VAR_CMD and VAR_GLOBAL contexts are created
4164  *-----------------------------------------------------------------------
4165  */
4166 void
4167 Var_Init(void)
4168 {
4169     VAR_INTERNAL = Targ_NewGN("Internal");
4170     VAR_GLOBAL = Targ_NewGN("Global");
4171     VAR_CMD = Targ_NewGN("Command");
4172
4173 }
4174
4175
4176 void
4177 Var_End(void)
4178 {
4179 }
4180
4181
4182 /****************** PRINT DEBUGGING INFO *****************/
4183 static void
4184 VarPrintVar(void *vp)
4185 {
4186     Var    *v = (Var *)vp;
4187     fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
4188 }
4189
4190 /*-
4191  *-----------------------------------------------------------------------
4192  * Var_Dump --
4193  *      print all variables in a context
4194  *-----------------------------------------------------------------------
4195  */
4196 void
4197 Var_Dump(GNode *ctxt)
4198 {
4199     Hash_Search search;
4200     Hash_Entry *h;
4201
4202     for (h = Hash_EnumFirst(&ctxt->context, &search);
4203          h != NULL;
4204          h = Hash_EnumNext(&search)) {
4205             VarPrintVar(Hash_GetValue(h));
4206     }
4207 }