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