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