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