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