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