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