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