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