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