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