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