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