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