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