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