Home | History | Annotate | Line # | Download | only in make
var.c revision 1.264
      1 /*	$NetBSD: var.c,v 1.264 2020/07/19 15:51:51 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.264 2020/07/19 15:51:51 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.264 2020/07/19 15:51:51 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     /*
   2064      * Skim through until the matching delimiter is found;
   2065      * pick up variable substitutions on the way. Also allow
   2066      * backslashes to quote the delimiter, $, and \, but don't
   2067      * touch other backslashes.
   2068      */
   2069     for (cp = *tstr; *cp && (*cp != delim); cp++) {
   2070 	Boolean is_escaped = cp[0] == '\\' && (cp[1] == delim ||
   2071 	    cp[1] == '\\' || cp[1] == '$' || (pattern && cp[1] == '&'));
   2072 	if (is_escaped) {
   2073 	    Buf_AddByte(&buf, cp[1]);
   2074 	    cp++;
   2075 	} else if (*cp == '$') {
   2076 	    if (cp[1] == delim) {
   2077 		if (mpflags == NULL)
   2078 		    Buf_AddByte(&buf, *cp);
   2079 		else
   2080 		    /*
   2081 		     * Unescaped $ at end of pattern => anchor
   2082 		     * pattern at end.
   2083 		     */
   2084 		    *mpflags |= VARP_MATCH_END;
   2085 	    } else {
   2086 		/* FIXME: mismatch between mpflags and VAR_NOSUBST */
   2087 		if (mpflags == NULL || !(*mpflags & VAR_NOSUBST)) {
   2088 		    char   *cp2;
   2089 		    int     len;
   2090 		    void   *freeIt;
   2091 
   2092 		    /*
   2093 		     * If unescaped dollar sign not before the
   2094 		     * delimiter, assume it's a variable
   2095 		     * substitution and recurse.
   2096 		     */
   2097 		    cp2 = Var_Parse(cp, ctxt, errnum | (eflags & VARE_WANTRES),
   2098 				    &len, &freeIt);
   2099 		    Buf_AddBytes(&buf, strlen(cp2), cp2);
   2100 		    free(freeIt);
   2101 		    cp += len - 1;
   2102 		} else {
   2103 		    const char *cp2 = &cp[1];
   2104 
   2105 		    if (*cp2 == PROPEN || *cp2 == BROPEN) {
   2106 			/*
   2107 			 * Find the end of this variable reference
   2108 			 * and suck it in without further ado.
   2109 			 * It will be interpreted later.
   2110 			 */
   2111 			int have = *cp2;
   2112 			int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
   2113 			int depth = 1;
   2114 
   2115 			for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
   2116 			    if (cp2[-1] != '\\') {
   2117 				if (*cp2 == have)
   2118 				    ++depth;
   2119 				if (*cp2 == want)
   2120 				    --depth;
   2121 			    }
   2122 			}
   2123 			Buf_AddBytes(&buf, cp2 - cp, cp);
   2124 			cp = --cp2;
   2125 		    } else
   2126 			Buf_AddByte(&buf, *cp);
   2127 		}
   2128 	    }
   2129 	} else if (pattern && *cp == '&')
   2130 	    Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
   2131 	else
   2132 	    Buf_AddByte(&buf, *cp);
   2133     }
   2134 
   2135     if (*cp != delim) {
   2136 	*tstr = cp;
   2137 	*length = 0;
   2138 	return NULL;
   2139     }
   2140 
   2141     *tstr = ++cp;
   2142     *length = Buf_Size(&buf);
   2143     rstr = Buf_Destroy(&buf, FALSE);
   2144     if (DEBUG(VAR))
   2145 	fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
   2146     return rstr;
   2147 }
   2148 
   2149 /*-
   2150  *-----------------------------------------------------------------------
   2151  * VarQuote --
   2152  *	Quote shell meta-characters and space characters in the string
   2153  *	if quoteDollar is set, also quote and double any '$' characters.
   2154  *
   2155  * Results:
   2156  *	The quoted string
   2157  *
   2158  * Side Effects:
   2159  *	None.
   2160  *
   2161  *-----------------------------------------------------------------------
   2162  */
   2163 static char *
   2164 VarQuote(char *str, Boolean quoteDollar)
   2165 {
   2166 
   2167     Buffer  	  buf;
   2168     const char	*newline;
   2169     size_t nlen;
   2170 
   2171     if ((newline = Shell_GetNewline()) == NULL)
   2172 	newline = "\\\n";
   2173     nlen = strlen(newline);
   2174 
   2175     Buf_Init(&buf, 0);
   2176 
   2177     for (; *str != '\0'; str++) {
   2178 	if (*str == '\n') {
   2179 	    Buf_AddBytes(&buf, nlen, newline);
   2180 	    continue;
   2181 	}
   2182 	if (isspace((unsigned char)*str) || ismeta((unsigned char)*str))
   2183 	    Buf_AddByte(&buf, '\\');
   2184 	Buf_AddByte(&buf, *str);
   2185 	if (quoteDollar && *str == '$')
   2186 	    Buf_AddBytes(&buf, 2, "\\$");
   2187     }
   2188 
   2189     str = Buf_Destroy(&buf, FALSE);
   2190     if (DEBUG(VAR))
   2191 	fprintf(debug_file, "QuoteMeta: [%s]\n", str);
   2192     return str;
   2193 }
   2194 
   2195 /*-
   2196  *-----------------------------------------------------------------------
   2197  * VarHash --
   2198  *      Hash the string using the MurmurHash3 algorithm.
   2199  *      Output is computed using 32bit Little Endian arithmetic.
   2200  *
   2201  * Input:
   2202  *	str		String to modify
   2203  *
   2204  * Results:
   2205  *      Hash value of str, encoded as 8 hex digits.
   2206  *
   2207  * Side Effects:
   2208  *      None.
   2209  *
   2210  *-----------------------------------------------------------------------
   2211  */
   2212 static char *
   2213 VarHash(const char *str)
   2214 {
   2215     static const char    hexdigits[16] = "0123456789abcdef";
   2216     Buffer         buf;
   2217     size_t         len, len2;
   2218     const unsigned char *ustr = (const unsigned char *)str;
   2219     uint32_t       h, k, c1, c2;
   2220 
   2221     h  = 0x971e137bU;
   2222     c1 = 0x95543787U;
   2223     c2 = 0x2ad7eb25U;
   2224     len2 = strlen(str);
   2225 
   2226     for (len = len2; len; ) {
   2227 	k = 0;
   2228 	switch (len) {
   2229 	default:
   2230 	    k = ((uint32_t)ustr[3] << 24) |
   2231 		((uint32_t)ustr[2] << 16) |
   2232 		((uint32_t)ustr[1] << 8) |
   2233 		(uint32_t)ustr[0];
   2234 	    len -= 4;
   2235 	    ustr += 4;
   2236 	    break;
   2237 	case 3:
   2238 	    k |= (uint32_t)ustr[2] << 16;
   2239 	    /* FALLTHROUGH */
   2240 	case 2:
   2241 	    k |= (uint32_t)ustr[1] << 8;
   2242 	    /* FALLTHROUGH */
   2243 	case 1:
   2244 	    k |= (uint32_t)ustr[0];
   2245 	    len = 0;
   2246 	}
   2247 	c1 = c1 * 5 + 0x7b7d159cU;
   2248 	c2 = c2 * 5 + 0x6bce6396U;
   2249 	k *= c1;
   2250 	k = (k << 11) ^ (k >> 21);
   2251 	k *= c2;
   2252 	h = (h << 13) ^ (h >> 19);
   2253 	h = h * 5 + 0x52dce729U;
   2254 	h ^= k;
   2255     }
   2256     h ^= len2;
   2257     h *= 0x85ebca6b;
   2258     h ^= h >> 13;
   2259     h *= 0xc2b2ae35;
   2260     h ^= h >> 16;
   2261 
   2262     Buf_Init(&buf, 0);
   2263     for (len = 0; len < 8; ++len) {
   2264 	Buf_AddByte(&buf, hexdigits[h & 15]);
   2265 	h >>= 4;
   2266     }
   2267 
   2268     return Buf_Destroy(&buf, FALSE);
   2269 }
   2270 
   2271 static char *
   2272 VarStrftime(const char *fmt, int zulu, time_t utc)
   2273 {
   2274     char buf[BUFSIZ];
   2275 
   2276     if (!utc)
   2277 	time(&utc);
   2278     if (!*fmt)
   2279 	fmt = "%c";
   2280     strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
   2281 
   2282     buf[sizeof(buf) - 1] = '\0';
   2283     return bmake_strdup(buf);
   2284 }
   2285 
   2286 typedef struct {
   2287     /* const parameters */
   2288     int startc;
   2289     int endc;
   2290     Var *v;
   2291     GNode *ctxt;
   2292     int flags;
   2293     int *lengthPtr;
   2294     void **freePtr;
   2295 
   2296     /* read-write */
   2297     char *nstr;
   2298     const char *tstr;
   2299     const char *start;
   2300     const char *cp;		/* Secondary pointer into str (place marker
   2301 				 * for tstr) */
   2302     char termc;			/* Character which terminated scan */
   2303     char delim;
   2304     int modifier;		/* that we are processing */
   2305     Var_Parse_State parsestate;	/* Flags passed to helper functions */
   2306 
   2307     /* result */
   2308     char *newStr;		/* New value to return */
   2309 } ApplyModifiersState;
   2310 
   2311 /* we now have some modifiers with long names */
   2312 #define STRMOD_MATCH(s, want, n) \
   2313     (strncmp(s, want, n) == 0 && (s[n] == st->endc || s[n] == ':'))
   2314 #define STRMOD_MATCHX(s, want, n) \
   2315     (strncmp(s, want, n) == 0 && \
   2316      (s[n] == st->endc || s[n] == ':' || s[n] == '='))
   2317 #define CHARMOD_MATCH(c) (c == st->endc || c == ':')
   2318 
   2319 /* :@var (at) ...${var}...@ */
   2320 static Boolean
   2321 ApplyModifier_At(ApplyModifiersState *st) {
   2322     VarLoop loop;
   2323     VarPatternFlags pflags = VAR_NOSUBST; /* FIXME: mismatch between pflags and VAR_NOSUBST */
   2324 
   2325     st->cp = ++st->tstr;
   2326     st->delim = '@';
   2327     loop.tvar = VarGetPattern(
   2328 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   2329 	&pflags, &loop.tvarLen, NULL);
   2330     if (loop.tvar == NULL)
   2331 	return FALSE;
   2332 
   2333     loop.str = VarGetPattern(
   2334 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   2335 	&pflags, &loop.strLen, NULL);
   2336     if (loop.str == NULL)
   2337 	return FALSE;
   2338 
   2339     st->termc = *st->cp;
   2340     st->delim = '\0';
   2341 
   2342     loop.flags = st->flags & (VARE_UNDEFERR | VARE_WANTRES);
   2343     loop.ctxt = st->ctxt;
   2344     st->newStr = VarModify(
   2345 	st->ctxt, &st->parsestate, st->nstr, VarLoopExpand, &loop);
   2346     Var_Delete(loop.tvar, st->ctxt);
   2347     free(loop.tvar);
   2348     free(loop.str);
   2349     return TRUE;
   2350 }
   2351 
   2352 /* :Ddefined or :Uundefined */
   2353 static void
   2354 ApplyModifier_Defined(ApplyModifiersState *st)
   2355 {
   2356     Buffer buf;			/* Buffer for patterns */
   2357     int nflags;
   2358 
   2359     if (st->flags & VARE_WANTRES) {
   2360 	int wantres;
   2361 	if (*st->tstr == 'U')
   2362 	    wantres = ((st->v->flags & VAR_JUNK) != 0);
   2363 	else
   2364 	    wantres = ((st->v->flags & VAR_JUNK) == 0);
   2365 	nflags = st->flags & ~VARE_WANTRES;
   2366 	if (wantres)
   2367 	    nflags |= VARE_WANTRES;
   2368     } else
   2369 	nflags = st->flags;
   2370 
   2371     /*
   2372      * Pass through tstr looking for 1) escaped delimiters,
   2373      * '$'s and backslashes (place the escaped character in
   2374      * uninterpreted) and 2) unescaped $'s that aren't before
   2375      * the delimiter (expand the variable substitution).
   2376      * The result is left in the Buffer buf.
   2377      */
   2378     Buf_Init(&buf, 0);
   2379     for (st->cp = st->tstr + 1;
   2380 	 *st->cp != st->endc && *st->cp != ':' && *st->cp != '\0';
   2381 	 st->cp++) {
   2382 	if (*st->cp == '\\' &&
   2383 	    (st->cp[1] == ':' || st->cp[1] == '$' || st->cp[1] == st->endc ||
   2384 	     st->cp[1] == '\\')) {
   2385 	    Buf_AddByte(&buf, st->cp[1]);
   2386 	    st->cp++;
   2387 	} else if (*st->cp == '$') {
   2388 	    /*
   2389 	     * If unescaped dollar sign, assume it's a
   2390 	     * variable substitution and recurse.
   2391 	     */
   2392 	    char    *cp2;
   2393 	    int	    len;
   2394 	    void    *freeIt;
   2395 
   2396 	    cp2 = Var_Parse(st->cp, st->ctxt, nflags, &len, &freeIt);
   2397 	    Buf_AddBytes(&buf, strlen(cp2), cp2);
   2398 	    free(freeIt);
   2399 	    st->cp += len - 1;
   2400 	} else {
   2401 	    Buf_AddByte(&buf, *st->cp);
   2402 	}
   2403     }
   2404 
   2405     st->termc = *st->cp;
   2406 
   2407     if (st->v->flags & VAR_JUNK)
   2408 	st->v->flags |= VAR_KEEP;
   2409     if (nflags & VARE_WANTRES) {
   2410 	st->newStr = Buf_Destroy(&buf, FALSE);
   2411     } else {
   2412 	st->newStr = st->nstr;
   2413 	Buf_Destroy(&buf, TRUE);
   2414     }
   2415 }
   2416 
   2417 /* :gmtime */
   2418 static Boolean
   2419 ApplyModifier_Gmtime(ApplyModifiersState *st)
   2420 {
   2421     time_t utc;
   2422     char *ep;
   2423 
   2424     st->cp = st->tstr + 1;	/* make sure it is set */
   2425     if (!STRMOD_MATCHX(st->tstr, "gmtime", 6))
   2426 	return FALSE;
   2427     if (st->tstr[6] == '=') {
   2428 	utc = strtoul(&st->tstr[7], &ep, 10);
   2429 	st->cp = ep;
   2430     } else {
   2431 	utc = 0;
   2432 	st->cp = st->tstr + 6;
   2433     }
   2434     st->newStr = VarStrftime(st->nstr, 1, utc);
   2435     st->termc = *st->cp;
   2436     return TRUE;
   2437 }
   2438 
   2439 /* :localtime */
   2440 static Boolean
   2441 ApplyModifier_Localtime(ApplyModifiersState *st)
   2442 {
   2443     time_t utc;
   2444     char *ep;
   2445 
   2446     st->cp = st->tstr + 1;	/* make sure it is set */
   2447     if (!STRMOD_MATCHX(st->tstr, "localtime", 9))
   2448 	return FALSE;
   2449 
   2450     if (st->tstr[9] == '=') {
   2451 	utc = strtoul(&st->tstr[10], &ep, 10);
   2452 	st->cp = ep;
   2453     } else {
   2454 	utc = 0;
   2455 	st->cp = st->tstr + 9;
   2456     }
   2457     st->newStr = VarStrftime(st->nstr, 0, utc);
   2458     st->termc = *st->cp;
   2459     return TRUE;
   2460 }
   2461 
   2462 /* :hash */
   2463 static Boolean
   2464 ApplyModifier_Hash(ApplyModifiersState *st)
   2465 {
   2466     st->cp = st->tstr + 1;	/* make sure it is set */
   2467     if (!STRMOD_MATCH(st->tstr, "hash", 4))
   2468 	return FALSE;
   2469     st->newStr = VarHash(st->nstr);
   2470     st->cp = st->tstr + 4;
   2471     st->termc = *st->cp;
   2472     return TRUE;
   2473 }
   2474 
   2475 /* :P */
   2476 static void
   2477 ApplyModifier_Path(ApplyModifiersState *st)
   2478 {
   2479     GNode *gn;
   2480 
   2481     if ((st->v->flags & VAR_JUNK) != 0)
   2482 	st->v->flags |= VAR_KEEP;
   2483     gn = Targ_FindNode(st->v->name, TARG_NOCREATE);
   2484     if (gn == NULL || gn->type & OP_NOPATH) {
   2485 	st->newStr = NULL;
   2486     } else if (gn->path) {
   2487 	st->newStr = bmake_strdup(gn->path);
   2488     } else {
   2489 	st->newStr = Dir_FindFile(st->v->name, Suff_FindPath(gn));
   2490     }
   2491     if (!st->newStr)
   2492 	st->newStr = bmake_strdup(st->v->name);
   2493     st->cp = ++st->tstr;
   2494     st->termc = *st->tstr;
   2495 }
   2496 
   2497 /* :!cmd! */
   2498 static Boolean
   2499 ApplyModifier_Exclam(ApplyModifiersState *st)
   2500 {
   2501     const char *emsg;
   2502     VarPattern pattern;
   2503 
   2504     pattern.pflags = 0;
   2505 
   2506     st->delim = '!';
   2507     emsg = NULL;
   2508     st->cp = ++st->tstr;
   2509     pattern.rhs = VarGetPattern(
   2510 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   2511 	NULL, &pattern.rightLen, NULL);
   2512     if (pattern.rhs == NULL)
   2513 	return FALSE;
   2514     if (st->flags & VARE_WANTRES)
   2515 	st->newStr = Cmd_Exec(pattern.rhs, &emsg);
   2516     else
   2517 	st->newStr = varNoError;
   2518     free(UNCONST(pattern.rhs));
   2519     if (emsg)
   2520 	Error(emsg, st->nstr);
   2521     st->termc = *st->cp;
   2522     st->delim = '\0';
   2523     if (st->v->flags & VAR_JUNK)
   2524 	st->v->flags |= VAR_KEEP;
   2525     return TRUE;
   2526 }
   2527 
   2528 /* :range */
   2529 static Boolean
   2530 ApplyModifier_Range(ApplyModifiersState *st)
   2531 {
   2532     int n;
   2533     char *ep;
   2534 
   2535     st->cp = st->tstr + 1;	/* make sure it is set */
   2536     if (!STRMOD_MATCHX(st->tstr, "range", 5))
   2537 	return FALSE;
   2538 
   2539     if (st->tstr[5] == '=') {
   2540 	n = strtoul(&st->tstr[6], &ep, 10);
   2541 	st->cp = ep;
   2542     } else {
   2543 	n = 0;
   2544 	st->cp = st->tstr + 5;
   2545     }
   2546     st->newStr = VarRange(st->nstr, n);
   2547     st->termc = *st->cp;
   2548     return TRUE;
   2549 }
   2550 
   2551 /* :Mpattern or :Npattern */
   2552 static void
   2553 ApplyModifier_Match(ApplyModifiersState *st)
   2554 {
   2555     char    *pattern;
   2556     const char *endpat;		/* points just after end of pattern */
   2557     char    *cp2;
   2558     Boolean copy;		/* pattern should be, or has been, copied */
   2559     Boolean needSubst;
   2560     int nest;
   2561 
   2562     copy = FALSE;
   2563     needSubst = FALSE;
   2564     nest = 1;
   2565     /*
   2566      * In the loop below, ignore ':' unless we are at
   2567      * (or back to) the original brace level.
   2568      * XXX This will likely not work right if $() and ${}
   2569      * are intermixed.
   2570      */
   2571     for (st->cp = st->tstr + 1;
   2572 	 *st->cp != '\0' && !(*st->cp == ':' && nest == 1);
   2573 	 st->cp++) {
   2574 	if (*st->cp == '\\' &&
   2575 	    (st->cp[1] == ':' || st->cp[1] == st->endc ||
   2576 	     st->cp[1] == st->startc)) {
   2577 	    if (!needSubst)
   2578 		copy = TRUE;
   2579 	    st->cp++;
   2580 	    continue;
   2581 	}
   2582 	if (*st->cp == '$')
   2583 	    needSubst = TRUE;
   2584 	if (*st->cp == '(' || *st->cp == '{')
   2585 	    ++nest;
   2586 	if (*st->cp == ')' || *st->cp == '}') {
   2587 	    --nest;
   2588 	    if (nest == 0)
   2589 		break;
   2590 	}
   2591     }
   2592     st->termc = *st->cp;
   2593     endpat = st->cp;
   2594     if (copy) {
   2595 	/*
   2596 	 * Need to compress the \:'s out of the pattern, so
   2597 	 * allocate enough room to hold the uncompressed
   2598 	 * pattern (note that st->cp started at st->tstr+1, so
   2599 	 * st->cp - st->tstr takes the null byte into account) and
   2600 	 * compress the pattern into the space.
   2601 	 */
   2602 	pattern = bmake_malloc(st->cp - st->tstr);
   2603 	for (cp2 = pattern, st->cp = st->tstr + 1;
   2604 	     st->cp < endpat;
   2605 	     st->cp++, cp2++) {
   2606 	    if ((*st->cp == '\\') && (st->cp+1 < endpat) &&
   2607 		(st->cp[1] == ':' || st->cp[1] == st->endc))
   2608 		st->cp++;
   2609 	    *cp2 = *st->cp;
   2610 	}
   2611 	*cp2 = '\0';
   2612 	endpat = cp2;
   2613     } else {
   2614 	/*
   2615 	 * Either Var_Subst or VarModify will need a
   2616 	 * nul-terminated string soon, so construct one now.
   2617 	 */
   2618 	pattern = bmake_strndup(st->tstr+1, endpat - (st->tstr + 1));
   2619     }
   2620     if (needSubst) {
   2621 	/* pattern contains embedded '$', so use Var_Subst to expand it. */
   2622 	cp2 = pattern;
   2623 	pattern = Var_Subst(NULL, cp2, st->ctxt, st->flags);
   2624 	free(cp2);
   2625     }
   2626     if (DEBUG(VAR))
   2627 	fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
   2628 	    st->v->name, st->nstr, pattern);
   2629     if (*st->tstr == 'M') {
   2630 	st->newStr = VarModify(st->ctxt, &st->parsestate, st->nstr, VarMatch,
   2631 			       pattern);
   2632     } else {
   2633 	st->newStr = VarModify(st->ctxt, &st->parsestate, st->nstr, VarNoMatch,
   2634 			       pattern);
   2635     }
   2636     free(pattern);
   2637 }
   2638 
   2639 /* :S,from,to, */
   2640 static Boolean
   2641 ApplyModifier_Subst(ApplyModifiersState *st)
   2642 {
   2643     VarPattern 	    pattern;
   2644     Var_Parse_State tmpparsestate;
   2645 
   2646     pattern.pflags = 0;
   2647     tmpparsestate = st->parsestate;
   2648     st->delim = st->tstr[1];
   2649     st->tstr += 2;
   2650 
   2651     /*
   2652      * If pattern begins with '^', it is anchored to the
   2653      * start of the word -- skip over it and flag pattern.
   2654      */
   2655     if (*st->tstr == '^') {
   2656 	pattern.pflags |= VARP_MATCH_START;
   2657 	st->tstr++;
   2658     }
   2659 
   2660     st->cp = st->tstr;
   2661     pattern.lhs = VarGetPattern(
   2662 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   2663 	&pattern.pflags, &pattern.leftLen, NULL);
   2664     if (pattern.lhs == NULL)
   2665 	return FALSE;
   2666 
   2667     pattern.rhs = VarGetPattern(
   2668 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   2669 	NULL, &pattern.rightLen, &pattern);
   2670     if (pattern.rhs == NULL)
   2671 	return FALSE;
   2672 
   2673     /*
   2674      * Check for global substitution. If 'g' after the final
   2675      * delimiter, substitution is global and is marked that
   2676      * way.
   2677      */
   2678     for (;; st->cp++) {
   2679 	switch (*st->cp) {
   2680 	case 'g':
   2681 	    pattern.pflags |= VARP_SUB_GLOBAL;
   2682 	    continue;
   2683 	case '1':
   2684 	    pattern.pflags |= VARP_SUB_ONE;
   2685 	    continue;
   2686 	case 'W':
   2687 	    tmpparsestate.oneBigWord = TRUE;
   2688 	    continue;
   2689 	}
   2690 	break;
   2691     }
   2692 
   2693     st->termc = *st->cp;
   2694     st->newStr = VarModify(
   2695 	st->ctxt, &tmpparsestate, st->nstr, VarSubstitute, &pattern);
   2696 
   2697     /* Free the two strings. */
   2698     free(UNCONST(pattern.lhs));
   2699     free(UNCONST(pattern.rhs));
   2700     st->delim = '\0';
   2701     return TRUE;
   2702 }
   2703 
   2704 #ifndef NO_REGEX
   2705 /* :C,from,to, */
   2706 static Boolean
   2707 ApplyModifier_Regex(ApplyModifiersState *st)
   2708 {
   2709     VarREPattern    pattern;
   2710     char           *re;
   2711     int             error;
   2712     Var_Parse_State tmpparsestate;
   2713 
   2714     pattern.pflags = 0;
   2715     tmpparsestate = st->parsestate;
   2716     st->delim = st->tstr[1];
   2717     st->tstr += 2;
   2718 
   2719     st->cp = st->tstr;
   2720 
   2721     re = VarGetPattern(
   2722 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   2723 	NULL, NULL, NULL);
   2724     if (re == NULL)
   2725 	return FALSE;
   2726 
   2727     pattern.replace = VarGetPattern(
   2728 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   2729 	NULL, NULL, NULL);
   2730     if (pattern.replace == NULL) {
   2731 	free(re);
   2732 	return FALSE;
   2733     }
   2734 
   2735     for (;; st->cp++) {
   2736 	switch (*st->cp) {
   2737 	case 'g':
   2738 	    pattern.pflags |= VARP_SUB_GLOBAL;
   2739 	    continue;
   2740 	case '1':
   2741 	    pattern.pflags |= VARP_SUB_ONE;
   2742 	    continue;
   2743 	case 'W':
   2744 	    tmpparsestate.oneBigWord = TRUE;
   2745 	    continue;
   2746 	}
   2747 	break;
   2748     }
   2749 
   2750     st->termc = *st->cp;
   2751 
   2752     error = regcomp(&pattern.re, re, REG_EXTENDED);
   2753     free(re);
   2754     if (error) {
   2755 	*st->lengthPtr = st->cp - st->start + 1;
   2756 	VarREError(error, &pattern.re, "RE substitution error");
   2757 	free(pattern.replace);
   2758 	return FALSE;
   2759     }
   2760 
   2761     pattern.nsub = pattern.re.re_nsub + 1;
   2762     if (pattern.nsub < 1)
   2763 	pattern.nsub = 1;
   2764     if (pattern.nsub > 10)
   2765 	pattern.nsub = 10;
   2766     pattern.matches = bmake_malloc(pattern.nsub * sizeof(regmatch_t));
   2767     st->newStr = VarModify(
   2768 	st->ctxt, &tmpparsestate, st->nstr, VarRESubstitute, &pattern);
   2769     regfree(&pattern.re);
   2770     free(pattern.replace);
   2771     free(pattern.matches);
   2772     st->delim = '\0';
   2773     return TRUE;
   2774 }
   2775 #endif
   2776 
   2777 /* :tA, :tu, :tl, etc. */
   2778 static Boolean
   2779 ApplyModifier_To(ApplyModifiersState *st)
   2780 {
   2781     st->cp = st->tstr + 1;	/* make sure it is set */
   2782     if (st->tstr[1] != st->endc && st->tstr[1] != ':') {
   2783 	if (st->tstr[1] == 's') {
   2784 	    /* Use the char (if any) at st->tstr[2] as the word separator. */
   2785 	    VarPattern pattern;
   2786 
   2787 	    if (st->tstr[2] != st->endc &&
   2788 		(st->tstr[3] == st->endc || st->tstr[3] == ':')) {
   2789 		/* ":ts<unrecognised><endc>" or
   2790 		 * ":ts<unrecognised>:" */
   2791 		st->parsestate.varSpace = st->tstr[2];
   2792 		st->cp = st->tstr + 3;
   2793 	    } else if (st->tstr[2] == st->endc || st->tstr[2] == ':') {
   2794 		/* ":ts<endc>" or ":ts:" */
   2795 		st->parsestate.varSpace = 0;	/* no separator */
   2796 		st->cp = st->tstr + 2;
   2797 	    } else if (st->tstr[2] == '\\') {
   2798 		const char *xp = &st->tstr[3];
   2799 		int base = 8;	/* assume octal */
   2800 
   2801 		switch (st->tstr[3]) {
   2802 		case 'n':
   2803 		    st->parsestate.varSpace = '\n';
   2804 		    st->cp = st->tstr + 4;
   2805 		    break;
   2806 		case 't':
   2807 		    st->parsestate.varSpace = '\t';
   2808 		    st->cp = st->tstr + 4;
   2809 		    break;
   2810 		case 'x':
   2811 		    base = 16;
   2812 		    xp++;
   2813 		    goto get_numeric;
   2814 		case '0':
   2815 		    base = 0;
   2816 		    goto get_numeric;
   2817 		default:
   2818 		    if (isdigit((unsigned char)st->tstr[3])) {
   2819 			char *ep;
   2820 		    get_numeric:
   2821 			st->parsestate.varSpace = strtoul(xp, &ep, base);
   2822 			if (*ep != ':' && *ep != st->endc)
   2823 			    return FALSE;
   2824 			st->cp = ep;
   2825 		    } else {
   2826 			/* ":ts<backslash><unrecognised>". */
   2827 			return FALSE;
   2828 		    }
   2829 		    break;
   2830 		}
   2831 	    } else {
   2832 		/* Found ":ts<unrecognised><unrecognised>". */
   2833 		return FALSE;
   2834 	    }
   2835 
   2836 	    st->termc = *st->cp;
   2837 
   2838 	    /*
   2839 	     * We cannot be certain that VarModify will be used - even if there
   2840 	     * is a subsequent modifier, so do a no-op VarSubstitute now to for
   2841 	     * str to be re-expanded without the spaces.
   2842 	     */
   2843 	    pattern.pflags = VARP_SUB_ONE;
   2844 	    pattern.lhs = pattern.rhs = "\032";
   2845 	    pattern.leftLen = pattern.rightLen = 1;
   2846 
   2847 	    st->newStr = VarModify(
   2848 		st->ctxt, &st->parsestate, st->nstr, VarSubstitute, &pattern);
   2849 	} else if (st->tstr[2] == st->endc || st->tstr[2] == ':') {
   2850 	    /* Check for two-character options: ":tu", ":tl" */
   2851 	    if (st->tstr[1] == 'A') {	/* absolute path */
   2852 		st->newStr = VarModify(
   2853 			st->ctxt, &st->parsestate, st->nstr, VarRealpath, NULL);
   2854 		st->cp = st->tstr + 2;
   2855 		st->termc = *st->cp;
   2856 	    } else if (st->tstr[1] == 'u') {
   2857 		char *dp = bmake_strdup(st->nstr);
   2858 		for (st->newStr = dp; *dp; dp++)
   2859 		    *dp = toupper((unsigned char)*dp);
   2860 		st->cp = st->tstr + 2;
   2861 		st->termc = *st->cp;
   2862 	    } else if (st->tstr[1] == 'l') {
   2863 		char *dp = bmake_strdup(st->nstr);
   2864 		for (st->newStr = dp; *dp; dp++)
   2865 		    *dp = tolower((unsigned char)*dp);
   2866 		st->cp = st->tstr + 2;
   2867 		st->termc = *st->cp;
   2868 	    } else if (st->tstr[1] == 'W' || st->tstr[1] == 'w') {
   2869 		st->parsestate.oneBigWord = (st->tstr[1] == 'W');
   2870 		st->newStr = st->nstr;
   2871 		st->cp = st->tstr + 2;
   2872 		st->termc = *st->cp;
   2873 	    } else {
   2874 		/* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
   2875 		return FALSE;
   2876 	    }
   2877 	} else {
   2878 	    /* Found ":t<unrecognised><unrecognised>". */
   2879 	    return FALSE;
   2880 	}
   2881     } else {
   2882 	/* Found ":t<endc>" or ":t:". */
   2883 	return FALSE;
   2884     }
   2885     return TRUE;
   2886 }
   2887 
   2888 /* :[#], :[1], etc. */
   2889 static int
   2890 ApplyModifier_Words(ApplyModifiersState *st)
   2891 {
   2892     /*
   2893      * Look for the closing ']', recursively
   2894      * expanding any embedded variables.
   2895      *
   2896      * estr is a pointer to the expanded result,
   2897      * which we must free().
   2898      */
   2899     char *estr;
   2900 
   2901     st->cp = st->tstr + 1;	/* point to char after '[' */
   2902     st->delim = ']';		/* look for closing ']' */
   2903     estr = VarGetPattern(
   2904 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   2905 	NULL, NULL, NULL);
   2906     if (estr == NULL)
   2907 	return 'c';		/* report missing ']' */
   2908     /* now st->cp points just after the closing ']' */
   2909     st->delim = '\0';
   2910     if (st->cp[0] != ':' && st->cp[0] != st->endc) {
   2911 	/* Found junk after ']' */
   2912 	free(estr);
   2913 	return 'b';
   2914     }
   2915     if (estr[0] == '\0') {
   2916 	/* Found empty square brackets in ":[]". */
   2917 	free(estr);
   2918 	return 'b';
   2919     } else if (estr[0] == '#' && estr[1] == '\0') {
   2920 	/* Found ":[#]" */
   2921 
   2922 	/*
   2923 	 * We will need enough space for the decimal
   2924 	 * representation of an int.  We calculate the
   2925 	 * space needed for the octal representation,
   2926 	 * and add enough slop to cope with a '-' sign
   2927 	 * (which should never be needed) and a '\0'
   2928 	 * string terminator.
   2929 	 */
   2930 	int newStrSize = (sizeof(int) * CHAR_BIT + 2) / 3 + 2;
   2931 
   2932 	st->newStr = bmake_malloc(newStrSize);
   2933 	if (st->parsestate.oneBigWord) {
   2934 	    strncpy(st->newStr, "1", newStrSize);
   2935 	} else {
   2936 	    /* XXX: brk_string() is a rather expensive
   2937 	     * way of counting words. */
   2938 	    char **av;
   2939 	    char *as;
   2940 	    int ac;
   2941 
   2942 	    av = brk_string(st->nstr, &ac, FALSE, &as);
   2943 	    snprintf(st->newStr, newStrSize, "%d", ac);
   2944 	    free(as);
   2945 	    free(av);
   2946 	}
   2947 	st->termc = *st->cp;
   2948 	free(estr);
   2949 	return 0;
   2950     } else if (estr[0] == '*' && estr[1] == '\0') {
   2951 	/* Found ":[*]" */
   2952 	st->parsestate.oneBigWord = TRUE;
   2953 	st->newStr = st->nstr;
   2954 	st->termc = *st->cp;
   2955 	free(estr);
   2956 	return 0;
   2957     } else if (estr[0] == '@' && estr[1] == '\0') {
   2958 	/* Found ":[@]" */
   2959 	st->parsestate.oneBigWord = FALSE;
   2960 	st->newStr = st->nstr;
   2961 	st->termc = *st->cp;
   2962 	free(estr);
   2963 	return 0;
   2964     } else {
   2965 	char *ep;
   2966 	/*
   2967 	 * We expect estr to contain a single
   2968 	 * integer for :[N], or two integers
   2969 	 * separated by ".." for :[start..end].
   2970 	 */
   2971 	VarSelectWords_t seldata = { 0, 0 };
   2972 
   2973 	seldata.start = strtol(estr, &ep, 0);
   2974 	if (ep == estr) {
   2975 	    /* Found junk instead of a number */
   2976 	    free(estr);
   2977 	    return 'b';
   2978 	} else if (ep[0] == '\0') {
   2979 	    /* Found only one integer in :[N] */
   2980 	    seldata.end = seldata.start;
   2981 	} else if (ep[0] == '.' && ep[1] == '.' && ep[2] != '\0') {
   2982 	    /* Expecting another integer after ".." */
   2983 	    ep += 2;
   2984 	    seldata.end = strtol(ep, &ep, 0);
   2985 	    if (ep[0] != '\0') {
   2986 		/* Found junk after ".." */
   2987 		free(estr);
   2988 		return 'b';
   2989 	    }
   2990 	} else {
   2991 	    /* Found junk instead of ".." */
   2992 	    free(estr);
   2993 	    return 'b';
   2994 	}
   2995 	/*
   2996 	 * Now seldata is properly filled in,
   2997 	 * but we still have to check for 0 as
   2998 	 * a special case.
   2999 	 */
   3000 	if (seldata.start == 0 && seldata.end == 0) {
   3001 	    /* ":[0]" or perhaps ":[0..0]" */
   3002 	    st->parsestate.oneBigWord = TRUE;
   3003 	    st->newStr = st->nstr;
   3004 	    st->termc = *st->cp;
   3005 	    free(estr);
   3006 	    return 0;
   3007 	} else if (seldata.start == 0 || seldata.end == 0) {
   3008 	    /* ":[0..N]" or ":[N..0]" */
   3009 	    free(estr);
   3010 	    return 'b';
   3011 	}
   3012 	/* Normal case: select the words described by seldata. */
   3013 	st->newStr = VarSelectWords(
   3014 	    st->ctxt, &st->parsestate, st->nstr, &seldata);
   3015 
   3016 	st->termc = *st->cp;
   3017 	free(estr);
   3018 	return 0;
   3019     }
   3020 }
   3021 
   3022 /* :O or :Ox */
   3023 static Boolean
   3024 ApplyModifier_Order(ApplyModifiersState *st)
   3025 {
   3026     char otype;
   3027 
   3028     st->cp = st->tstr + 1;	/* skip to the rest in any case */
   3029     if (st->tstr[1] == st->endc || st->tstr[1] == ':') {
   3030 	otype = 's';
   3031 	st->termc = *st->cp;
   3032     } else if ((st->tstr[1] == 'r' || st->tstr[1] == 'x') &&
   3033 	       (st->tstr[2] == st->endc || st->tstr[2] == ':')) {
   3034 	otype = st->tstr[1];
   3035 	st->cp = st->tstr + 2;
   3036 	st->termc = *st->cp;
   3037     } else {
   3038 	return FALSE;
   3039     }
   3040     st->newStr = VarOrder(st->nstr, otype);
   3041     return TRUE;
   3042 }
   3043 
   3044 /* :? then : else */
   3045 static Boolean
   3046 ApplyModifier_IfElse(ApplyModifiersState *st)
   3047 {
   3048     Boolean value;
   3049     int cond_rc;
   3050     VarPatternFlags then_flags, else_flags;
   3051     /* FIXME: IfElse has nothing to do with VarPatternFlags */
   3052 
   3053     /* find ':', and then substitute accordingly */
   3054     if (st->flags & VARE_WANTRES) {
   3055 	cond_rc = Cond_EvalExpression(NULL, st->v->name, &value, 0, FALSE);
   3056 	then_flags = cond_rc != COND_INVALID && value ? 0 : VAR_NOSUBST;
   3057 	else_flags = cond_rc != COND_INVALID && !value ? 0 : VAR_NOSUBST;
   3058     } else {
   3059 	/* we are just consuming and discarding */
   3060 	cond_rc = value = 0;
   3061 	then_flags = else_flags = VAR_NOSUBST;
   3062     }
   3063 
   3064     st->cp = ++st->tstr;
   3065     st->delim = ':';
   3066     char *then_expr = VarGetPattern(
   3067 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   3068 	&then_flags, NULL, NULL);
   3069     if (then_expr == NULL)
   3070 	return FALSE;
   3071 
   3072     /* BROPEN or PROPEN */
   3073     st->delim = st->endc;
   3074     char *else_expr = VarGetPattern(
   3075 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   3076 	&else_flags, NULL, NULL);
   3077     if (else_expr == NULL)
   3078 	return FALSE;
   3079 
   3080     st->termc = *--st->cp;
   3081     st->delim = '\0';
   3082     if (cond_rc == COND_INVALID) {
   3083 	Error("Bad conditional expression `%s' in %s?%s:%s",
   3084 	    st->v->name, st->v->name, then_expr, else_expr);
   3085 	return FALSE;
   3086     }
   3087 
   3088     if (value) {
   3089 	st->newStr = then_expr;
   3090 	free(else_expr);
   3091     } else {
   3092 	st->newStr = else_expr;
   3093 	free(else_expr);
   3094     }
   3095     if (st->v->flags & VAR_JUNK)
   3096 	st->v->flags |= VAR_KEEP;
   3097     return TRUE;
   3098 }
   3099 
   3100 /* "::=", "::!=", "::+=", or "::?=" */
   3101 static int
   3102 ApplyModifier_Assign(ApplyModifiersState *st)
   3103 {
   3104     if (st->tstr[1] == '=' ||
   3105 	(st->tstr[2] == '=' &&
   3106 	 (st->tstr[1] == '!' || st->tstr[1] == '+' || st->tstr[1] == '?'))) {
   3107 	GNode *v_ctxt;		/* context where v belongs */
   3108 	const char *emsg;
   3109 	char *sv_name;
   3110 	VarPattern pattern;
   3111 	int how;
   3112 	VarPatternFlags pflags;
   3113 	/* FIXME: Assign has nothing to do with VarPatternFlags */
   3114 
   3115 	if (st->v->name[0] == 0)
   3116 	    return 'b';
   3117 
   3118 	v_ctxt = st->ctxt;
   3119 	sv_name = NULL;
   3120 	++st->tstr;
   3121 	if (st->v->flags & VAR_JUNK) {
   3122 	    /*
   3123 	     * We need to bmake_strdup() it incase
   3124 	     * VarGetPattern() recurses.
   3125 	     */
   3126 	    sv_name = st->v->name;
   3127 	    st->v->name = bmake_strdup(st->v->name);
   3128 	} else if (st->ctxt != VAR_GLOBAL) {
   3129 	    Var *gv = VarFind(st->v->name, st->ctxt, 0);
   3130 	    if (gv == NULL)
   3131 		v_ctxt = VAR_GLOBAL;
   3132 	    else
   3133 		VarFreeEnv(gv, TRUE);
   3134 	}
   3135 
   3136 	switch ((how = *st->tstr)) {
   3137 	case '+':
   3138 	case '?':
   3139 	case '!':
   3140 	    st->cp = &st->tstr[2];
   3141 	    break;
   3142 	default:
   3143 	    st->cp = ++st->tstr;
   3144 	    break;
   3145 	}
   3146 	st->delim = st->startc == PROPEN ? PRCLOSE : BRCLOSE;
   3147 	pattern.pflags = 0;
   3148 
   3149 	pflags = (st->flags & VARE_WANTRES) ? 0 : VAR_NOSUBST;
   3150 	pattern.rhs = VarGetPattern(
   3151 	    st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   3152 	    &pflags, &pattern.rightLen, NULL);
   3153 	if (st->v->flags & VAR_JUNK) {
   3154 	    /* restore original name */
   3155 	    free(st->v->name);
   3156 	    st->v->name = sv_name;
   3157 	}
   3158 	if (pattern.rhs == NULL)
   3159 	    return 'c';
   3160 
   3161 	st->termc = *--st->cp;
   3162 	st->delim = '\0';
   3163 
   3164 	if (st->flags & VARE_WANTRES) {
   3165 	    switch (how) {
   3166 	    case '+':
   3167 		Var_Append(st->v->name, pattern.rhs, v_ctxt);
   3168 		break;
   3169 	    case '!':
   3170 		st->newStr = Cmd_Exec(pattern.rhs, &emsg);
   3171 		if (emsg)
   3172 		    Error(emsg, st->nstr);
   3173 		else
   3174 		    Var_Set(st->v->name, st->newStr, v_ctxt);
   3175 		free(st->newStr);
   3176 		break;
   3177 	    case '?':
   3178 		if ((st->v->flags & VAR_JUNK) == 0)
   3179 		    break;
   3180 		/* FALLTHROUGH */
   3181 	    default:
   3182 		Var_Set(st->v->name, pattern.rhs, v_ctxt);
   3183 		break;
   3184 	    }
   3185 	}
   3186 	free(UNCONST(pattern.rhs));
   3187 	st->newStr = varNoError;
   3188 	return 0;
   3189     }
   3190     return 'd';			/* "::<unrecognised>" */
   3191 }
   3192 
   3193 /* remember current value */
   3194 static Boolean
   3195 ApplyModifier_Remember(ApplyModifiersState *st)
   3196 {
   3197     st->cp = st->tstr + 1;	/* make sure it is set */
   3198     if (!STRMOD_MATCHX(st->tstr, "_", 1))
   3199 	return FALSE;
   3200 
   3201     if (st->tstr[1] == '=') {
   3202 	char *np;
   3203 	int n;
   3204 
   3205 	st->cp++;
   3206 	n = strcspn(st->cp, ":)}");
   3207 	np = bmake_strndup(st->cp, n + 1);
   3208 	np[n] = '\0';
   3209 	st->cp = st->tstr + 2 + n;
   3210 	Var_Set(np, st->nstr, st->ctxt);
   3211 	free(np);
   3212     } else {
   3213 	Var_Set("_", st->nstr, st->ctxt);
   3214     }
   3215     st->newStr = st->nstr;
   3216     st->termc = *st->cp;
   3217     return TRUE;
   3218 }
   3219 
   3220 #ifdef SYSVVARSUB
   3221 /* :from=to */
   3222 static int
   3223 ApplyModifier_SysV(ApplyModifiersState *st)
   3224 {
   3225     /*
   3226      * This can either be a bogus modifier or a System-V
   3227      * substitution command.
   3228      */
   3229     VarPattern      pattern;
   3230     /* FIXME: SysV modifiers have nothing to do with :S or :C pattern matching */
   3231     Boolean         eqFound = FALSE;
   3232 
   3233     pattern.pflags = 0;
   3234 
   3235     /*
   3236      * First we make a pass through the string trying
   3237      * to verify it is a SYSV-make-style translation:
   3238      * it must be: <string1>=<string2>)
   3239      */
   3240     st->cp = st->tstr;
   3241     int nest = 1;
   3242     while (*st->cp != '\0' && nest > 0) {
   3243 	if (*st->cp == '=') {
   3244 	    eqFound = TRUE;
   3245 	    /* continue looking for st->endc */
   3246 	} else if (*st->cp == st->endc)
   3247 	    nest--;
   3248 	else if (*st->cp == st->startc)
   3249 	    nest++;
   3250 	if (nest > 0)
   3251 	    st->cp++;
   3252     }
   3253     if (*st->cp != st->endc || !eqFound)
   3254 	return 0;
   3255 
   3256     st->delim = '=';
   3257     st->cp = st->tstr;
   3258     /* FIXME: There's no point in having a single $ at the end of a
   3259      * SysV substitution since that will not be interpreted as an
   3260      * anchor anyway. */
   3261     pattern.lhs = VarGetPattern(
   3262 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   3263 	&pattern.pflags, &pattern.leftLen, NULL);
   3264     if (pattern.lhs == NULL)
   3265 	return 'c';
   3266 
   3267     st->delim = st->endc;
   3268     pattern.rhs = VarGetPattern(
   3269 	st->ctxt, &st->parsestate, st->flags, &st->cp, st->delim,
   3270 	NULL, &pattern.rightLen, &pattern);
   3271     if (pattern.rhs == NULL)
   3272 	return 'c';
   3273 
   3274     /*
   3275      * SYSV modifications happen through the whole
   3276      * string. Note the pattern is anchored at the end.
   3277      */
   3278     st->termc = *--st->cp;
   3279     st->delim = '\0';
   3280     if (pattern.leftLen == 0 && *st->nstr == '\0') {
   3281 	st->newStr = st->nstr;	/* special case */
   3282     } else {
   3283 	st->newStr = VarModify(
   3284 	    st->ctxt, &st->parsestate, st->nstr, VarSYSVMatch, &pattern);
   3285     }
   3286     free(UNCONST(pattern.lhs));
   3287     free(UNCONST(pattern.rhs));
   3288     return '=';
   3289 }
   3290 #endif
   3291 
   3292 /*
   3293  * Now we need to apply any modifiers the user wants applied.
   3294  * These are:
   3295  *  	  :M<pattern>	words which match the given <pattern>.
   3296  *  			<pattern> is of the standard file
   3297  *  			wildcarding form.
   3298  *  	  :N<pattern>	words which do not match the given <pattern>.
   3299  *  	  :S<d><pat1><d><pat2><d>[1gW]
   3300  *  			Substitute <pat2> for <pat1> in the value
   3301  *  	  :C<d><pat1><d><pat2><d>[1gW]
   3302  *  			Substitute <pat2> for regex <pat1> in the value
   3303  *  	  :H		Substitute the head of each word
   3304  *  	  :T		Substitute the tail of each word
   3305  *  	  :E		Substitute the extension (minus '.') of
   3306  *  			each word
   3307  *  	  :R		Substitute the root of each word
   3308  *  			(pathname minus the suffix).
   3309  *	  :O		("Order") Alphabeticaly sort words in variable.
   3310  *	  :Ox		("intermiX") Randomize words in variable.
   3311  *	  :u		("uniq") Remove adjacent duplicate words.
   3312  *	  :tu		Converts the variable contents to uppercase.
   3313  *	  :tl		Converts the variable contents to lowercase.
   3314  *	  :ts[c]	Sets varSpace - the char used to
   3315  *			separate words to 'c'. If 'c' is
   3316  *			omitted then no separation is used.
   3317  *	  :tW		Treat the variable contents as a single
   3318  *			word, even if it contains spaces.
   3319  *			(Mnemonic: one big 'W'ord.)
   3320  *	  :tw		Treat the variable contents as multiple
   3321  *			space-separated words.
   3322  *			(Mnemonic: many small 'w'ords.)
   3323  *	  :[index]	Select a single word from the value.
   3324  *	  :[start..end]	Select multiple words from the value.
   3325  *	  :[*] or :[0]	Select the entire value, as a single
   3326  *			word.  Equivalent to :tW.
   3327  *	  :[@]		Select the entire value, as multiple
   3328  *			words.	Undoes the effect of :[*].
   3329  *			Equivalent to :tw.
   3330  *	  :[#]		Returns the number of words in the value.
   3331  *
   3332  *	  :?<true-value>:<false-value>
   3333  *			If the variable evaluates to true, return
   3334  *			true value, else return the second value.
   3335  *    	  :lhs=rhs  	Like :S, but the rhs goes to the end of
   3336  *    			the invocation.
   3337  *	  :sh		Treat the current value as a command
   3338  *			to be run, new value is its output.
   3339  * The following added so we can handle ODE makefiles.
   3340  *	  :@<tmpvar>@<newval>@
   3341  *			Assign a temporary local variable <tmpvar>
   3342  *			to the current value of each word in turn
   3343  *			and replace each word with the result of
   3344  *			evaluating <newval>
   3345  *	  :D<newval>	Use <newval> as value if variable defined
   3346  *	  :U<newval>	Use <newval> as value if variable undefined
   3347  *	  :L		Use the name of the variable as the value.
   3348  *	  :P		Use the path of the node that has the same
   3349  *			name as the variable as the value.  This
   3350  *			basically includes an implied :L so that
   3351  *			the common method of refering to the path
   3352  *			of your dependent 'x' in a rule is to use
   3353  *			the form '${x:P}'.
   3354  *	  :!<cmd>!	Run cmd much the same as :sh run's the
   3355  *			current value of the variable.
   3356  * The ::= modifiers, actually assign a value to the variable.
   3357  * Their main purpose is in supporting modifiers of .for loop
   3358  * iterators and other obscure uses.  They always expand to
   3359  * nothing.  In a target rule that would otherwise expand to an
   3360  * empty line they can be preceded with @: to keep make happy.
   3361  * Eg.
   3362  *
   3363  * foo:	.USE
   3364  * .for i in ${.TARGET} ${.TARGET:R}.gz
   3365  * 	@: ${t::=$i}
   3366  *	@echo blah ${t:T}
   3367  * .endfor
   3368  *
   3369  *	  ::=<str>	Assigns <str> as the new value of variable.
   3370  *	  ::?=<str>	Assigns <str> as value of variable if
   3371  *			it was not already set.
   3372  *	  ::+=<str>	Appends <str> to variable.
   3373  *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
   3374  *			variable.
   3375  */
   3376 static char *
   3377 ApplyModifiers(char *nstr, const char *tstr,
   3378 	       int const startc, int const endc,
   3379 	       Var * const v, GNode * const ctxt, int const flags,
   3380 	       int * const lengthPtr, void ** const freePtr)
   3381 {
   3382     ApplyModifiersState st = {
   3383 	startc, endc, v, ctxt, flags, lengthPtr, freePtr,
   3384 	nstr, tstr, tstr, tstr,
   3385 	'\0', '\0', 0, {' ', FALSE}, NULL
   3386     };
   3387 
   3388     while (*st.tstr && *st.tstr != st.endc) {
   3389 
   3390 	if (*st.tstr == '$') {
   3391 	    /*
   3392 	     * We may have some complex modifiers in a variable.
   3393 	     */
   3394 	    void *freeIt;
   3395 	    char *rval;
   3396 	    int rlen;
   3397 	    int c;
   3398 
   3399 	    rval = Var_Parse(st.tstr, st.ctxt, st.flags, &rlen, &freeIt);
   3400 
   3401 	    /*
   3402 	     * If we have not parsed up to st.endc or ':',
   3403 	     * we are not interested.
   3404 	     */
   3405 	    if (rval != NULL && *rval &&
   3406 		(c = st.tstr[rlen]) != '\0' &&
   3407 		c != ':' &&
   3408 		c != st.endc) {
   3409 		free(freeIt);
   3410 		goto apply_mods;
   3411 	    }
   3412 
   3413 	    if (DEBUG(VAR)) {
   3414 		fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
   3415 		       rval, rlen, st.tstr, rlen, st.tstr + rlen);
   3416 	    }
   3417 
   3418 	    st.tstr += rlen;
   3419 
   3420 	    if (rval != NULL && *rval) {
   3421 		int used;
   3422 
   3423 		st.nstr = ApplyModifiers(st.nstr, rval, 0, 0, st.v,
   3424 				      st.ctxt, st.flags, &used, st.freePtr);
   3425 		if (st.nstr == var_Error
   3426 		    || (st.nstr == varNoError && (st.flags & VARE_UNDEFERR) == 0)
   3427 		    || strlen(rval) != (size_t) used) {
   3428 		    free(freeIt);
   3429 		    goto out;	/* error already reported */
   3430 		}
   3431 	    }
   3432 	    free(freeIt);
   3433 	    if (*st.tstr == ':')
   3434 		st.tstr++;
   3435 	    else if (!*st.tstr && st.endc) {
   3436 		Error("Unclosed variable specification after complex "
   3437 		    "modifier (expecting '%c') for %s", st.endc, st.v->name);
   3438 		goto out;
   3439 	    }
   3440 	    continue;
   3441 	}
   3442     apply_mods:
   3443 	if (DEBUG(VAR)) {
   3444 	    fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", st.v->name,
   3445 		*st.tstr, st.nstr);
   3446 	}
   3447 	st.newStr = var_Error;
   3448 	switch ((st.modifier = *st.tstr)) {
   3449 	case ':':
   3450 	    {
   3451 		int res = ApplyModifier_Assign(&st);
   3452 		if (res == 'b')
   3453 		    goto bad_modifier;
   3454 		if (res == 'c')
   3455 		    goto cleanup;
   3456 		if (res == 'd')
   3457 		    goto default_case;
   3458 		break;
   3459 	    }
   3460 	case '@':
   3461 	    ApplyModifier_At(&st);
   3462 	    break;
   3463 	case '_':
   3464 	    if (!ApplyModifier_Remember(&st))
   3465 		goto default_case;
   3466 	    break;
   3467 	case 'D':
   3468 	case 'U':
   3469 	    ApplyModifier_Defined(&st);
   3470 	    break;
   3471 	case 'L':
   3472 	    {
   3473 		if ((st.v->flags & VAR_JUNK) != 0)
   3474 		    st.v->flags |= VAR_KEEP;
   3475 		st.newStr = bmake_strdup(st.v->name);
   3476 		st.cp = ++st.tstr;
   3477 		st.termc = *st.tstr;
   3478 		break;
   3479 	    }
   3480 	case 'P':
   3481 	    ApplyModifier_Path(&st);
   3482 	    break;
   3483 	case '!':
   3484 	    if (!ApplyModifier_Exclam(&st))
   3485 		goto cleanup;
   3486 	    break;
   3487 	case '[':
   3488 	    {
   3489 		int res = ApplyModifier_Words(&st);
   3490 		if (res == 'b')
   3491 		    goto bad_modifier;
   3492 		if (res == 'c')
   3493 		    goto cleanup;
   3494 		break;
   3495 	    }
   3496 	case 'g':
   3497 	    if (!ApplyModifier_Gmtime(&st))
   3498 		goto default_case;
   3499 	    break;
   3500 	case 'h':
   3501 	    if (!ApplyModifier_Hash(&st))
   3502 		goto default_case;
   3503 	    break;
   3504 	case 'l':
   3505 	    if (!ApplyModifier_Localtime(&st))
   3506 		goto default_case;
   3507 	    break;
   3508 	case 't':
   3509 	    if (!ApplyModifier_To(&st))
   3510 		goto bad_modifier;
   3511 	    break;
   3512 	case 'N':
   3513 	case 'M':
   3514 	    ApplyModifier_Match(&st);
   3515 	    break;
   3516 	case 'S':
   3517 	    if (!ApplyModifier_Subst(&st))
   3518 		goto cleanup;
   3519 	    break;
   3520 	case '?':
   3521 	    if (!ApplyModifier_IfElse(&st))
   3522 		goto cleanup;
   3523 	    break;
   3524 #ifndef NO_REGEX
   3525 	case 'C':
   3526 	    if (!ApplyModifier_Regex(&st))
   3527 		goto cleanup;
   3528 	    break;
   3529 #endif
   3530 	case 'q':
   3531 	case 'Q':
   3532 	    if (st.tstr[1] == st.endc || st.tstr[1] == ':') {
   3533 		st.newStr = VarQuote(st.nstr, st.modifier == 'q');
   3534 		st.cp = st.tstr + 1;
   3535 		st.termc = *st.cp;
   3536 		break;
   3537 	    }
   3538 	    goto default_case;
   3539 	case 'T':
   3540 	    if (st.tstr[1] == st.endc || st.tstr[1] == ':') {
   3541 		st.newStr = VarModify(st.ctxt, &st.parsestate, st.nstr, VarTail,
   3542 				   NULL);
   3543 		st.cp = st.tstr + 1;
   3544 		st.termc = *st.cp;
   3545 		break;
   3546 	    }
   3547 	    goto default_case;
   3548 	case 'H':
   3549 	    if (st.tstr[1] == st.endc || st.tstr[1] == ':') {
   3550 		st.newStr = VarModify(st.ctxt, &st.parsestate, st.nstr, VarHead,
   3551 				   NULL);
   3552 		st.cp = st.tstr + 1;
   3553 		st.termc = *st.cp;
   3554 		break;
   3555 	    }
   3556 	    goto default_case;
   3557 	case 'E':
   3558 	    if (st.tstr[1] == st.endc || st.tstr[1] == ':') {
   3559 		st.newStr = VarModify(st.ctxt, &st.parsestate, st.nstr, VarSuffix,
   3560 				   NULL);
   3561 		st.cp = st.tstr + 1;
   3562 		st.termc = *st.cp;
   3563 		break;
   3564 	    }
   3565 	    goto default_case;
   3566 	case 'R':
   3567 	    if (st.tstr[1] == st.endc || st.tstr[1] == ':') {
   3568 		st.newStr = VarModify(st.ctxt, &st.parsestate, st.nstr, VarRoot,
   3569 				   NULL);
   3570 		st.cp = st.tstr + 1;
   3571 		st.termc = *st.cp;
   3572 		break;
   3573 	    }
   3574 	    goto default_case;
   3575 	case 'r':
   3576 	    if (!ApplyModifier_Range(&st))
   3577 		goto default_case;
   3578 	    break;
   3579 	case 'O':
   3580 	    if (!ApplyModifier_Order(&st))
   3581 		goto bad_modifier;
   3582 	    break;
   3583 	case 'u':
   3584 	    if (st.tstr[1] == st.endc || st.tstr[1] == ':') {
   3585 		st.newStr = VarUniq(st.nstr);
   3586 		st.cp = st.tstr + 1;
   3587 		st.termc = *st.cp;
   3588 		break;
   3589 	    }
   3590 	    goto default_case;
   3591 #ifdef SUNSHCMD
   3592 	case 's':
   3593 	    if (st.tstr[1] == 'h' && (st.tstr[2] == st.endc || st.tstr[2] == ':')) {
   3594 		const char *emsg;
   3595 		if (st.flags & VARE_WANTRES) {
   3596 		    st.newStr = Cmd_Exec(st.nstr, &emsg);
   3597 		    if (emsg)
   3598 			Error(emsg, st.nstr);
   3599 		} else
   3600 		    st.newStr = varNoError;
   3601 		st.cp = st.tstr + 2;
   3602 		st.termc = *st.cp;
   3603 		break;
   3604 	    }
   3605 	    goto default_case;
   3606 #endif
   3607 	default:
   3608 	default_case:
   3609 	    {
   3610 #ifdef SYSVVARSUB
   3611 		int res = ApplyModifier_SysV(&st);
   3612 		if (res == 'c')
   3613 		    goto cleanup;
   3614 		if (res != '=')
   3615 #endif
   3616 		{
   3617 		    Error("Unknown modifier '%c'", *st.tstr);
   3618 		    for (st.cp = st.tstr+1;
   3619 			 *st.cp != ':' && *st.cp != st.endc && *st.cp != '\0';
   3620 			 st.cp++)
   3621 			continue;
   3622 		    st.termc = *st.cp;
   3623 		    st.newStr = var_Error;
   3624 		}
   3625 	    }
   3626 	}
   3627 	if (DEBUG(VAR)) {
   3628 	    fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
   3629 		st.v->name, st.modifier, st.newStr);
   3630 	}
   3631 
   3632 	if (st.newStr != st.nstr) {
   3633 	    if (*st.freePtr) {
   3634 		free(st.nstr);
   3635 		*st.freePtr = NULL;
   3636 	    }
   3637 	    st.nstr = st.newStr;
   3638 	    if (st.nstr != var_Error && st.nstr != varNoError) {
   3639 		*st.freePtr = st.nstr;
   3640 	    }
   3641 	}
   3642 	if (st.termc == '\0' && st.endc != '\0') {
   3643 	    Error("Unclosed variable specification (expecting '%c') "
   3644 		"for \"%s\" (value \"%s\") modifier %c",
   3645 		st.endc, st.v->name, st.nstr, st.modifier);
   3646 	} else if (st.termc == ':') {
   3647 	    st.cp++;
   3648 	}
   3649 	st.tstr = st.cp;
   3650     }
   3651 out:
   3652     *st.lengthPtr = st.tstr - st.start;
   3653     return st.nstr;
   3654 
   3655 bad_modifier:
   3656     /* "{(" */
   3657     Error("Bad modifier `:%.*s' for %s", (int)strcspn(st.tstr, ":)}"), st.tstr,
   3658 	  st.v->name);
   3659 
   3660 cleanup:
   3661     *st.lengthPtr = st.cp - st.start;
   3662     if (st.delim != '\0')
   3663 	Error("Unclosed substitution for %s (%c missing)",
   3664 	      st.v->name, st.delim);
   3665     free(*st.freePtr);
   3666     *st.freePtr = NULL;
   3667     return var_Error;
   3668 }
   3669 
   3670 /*-
   3671  *-----------------------------------------------------------------------
   3672  * Var_Parse --
   3673  *	Given the start of a variable invocation, extract the variable
   3674  *	name and find its value, then modify it according to the
   3675  *	specification.
   3676  *
   3677  * Input:
   3678  *	str		The string to parse
   3679  *	ctxt		The context for the variable
   3680  *	flags		VARE_UNDEFERR	if undefineds are an error
   3681  *			VARE_WANTRES	if we actually want the result
   3682  *			VARE_ASSIGN	if we are in a := assignment
   3683  *	lengthPtr	OUT: The length of the specification
   3684  *	freePtr		OUT: Non-NULL if caller should free *freePtr
   3685  *
   3686  * Results:
   3687  *	The (possibly-modified) value of the variable or var_Error if the
   3688  *	specification is invalid. The length of the specification is
   3689  *	placed in *lengthPtr (for invalid specifications, this is just
   3690  *	2...?).
   3691  *	If *freePtr is non-NULL then it's a pointer that the caller
   3692  *	should pass to free() to free memory used by the result.
   3693  *
   3694  * Side Effects:
   3695  *	None.
   3696  *
   3697  *-----------------------------------------------------------------------
   3698  */
   3699 /* coverity[+alloc : arg-*4] */
   3700 char *
   3701 Var_Parse(const char *str, GNode *ctxt, VarEvalFlags flags,
   3702 	  int *lengthPtr, void **freePtr)
   3703 {
   3704     const char	*tstr;		/* Pointer into str */
   3705     Var		*v;		/* Variable in invocation */
   3706     Boolean 	 haveModifier;	/* TRUE if have modifiers for the variable */
   3707     char	 endc;		/* Ending character when variable in parens
   3708 				 * or braces */
   3709     char	 startc;	/* Starting character when variable in parens
   3710 				 * or braces */
   3711     int		 vlen;		/* Length of variable name */
   3712     const char 	*start;		/* Points to original start of str */
   3713     char	*nstr;		/* New string, used during expansion */
   3714     Boolean	 dynamic;	/* TRUE if the variable is local and we're
   3715 				 * expanding it in a non-local context. This
   3716 				 * is done to support dynamic sources. The
   3717 				 * result is just the invocation, unaltered */
   3718     const char	*extramodifiers; /* extra modifiers to apply first */
   3719     char	 name[2];
   3720 
   3721     *freePtr = NULL;
   3722     extramodifiers = NULL;
   3723     dynamic = FALSE;
   3724     start = str;
   3725 
   3726     startc = str[1];
   3727     if (startc != PROPEN && startc != BROPEN) {
   3728 	/*
   3729 	 * If it's not bounded by braces of some sort, life is much simpler.
   3730 	 * We just need to check for the first character and return the
   3731 	 * value if it exists.
   3732 	 */
   3733 
   3734 	/* Error out some really stupid names */
   3735 	if (startc == '\0' || strchr(")}:$", startc)) {
   3736 	    *lengthPtr = 1;
   3737 	    return var_Error;
   3738 	}
   3739 	name[0] = startc;
   3740 	name[1] = '\0';
   3741 
   3742 	v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   3743 	if (v == NULL) {
   3744 	    *lengthPtr = 2;
   3745 
   3746 	    if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
   3747 		/*
   3748 		 * If substituting a local variable in a non-local context,
   3749 		 * assume it's for dynamic source stuff. We have to handle
   3750 		 * this specially and return the longhand for the variable
   3751 		 * with the dollar sign escaped so it makes it back to the
   3752 		 * caller. Only four of the local variables are treated
   3753 		 * specially as they are the only four that will be set
   3754 		 * when dynamic sources are expanded.
   3755 		 */
   3756 		switch (str[1]) {
   3757 		case '@':
   3758 		    return UNCONST("$(.TARGET)");
   3759 		case '%':
   3760 		    return UNCONST("$(.MEMBER)");
   3761 		case '*':
   3762 		    return UNCONST("$(.PREFIX)");
   3763 		case '!':
   3764 		    return UNCONST("$(.ARCHIVE)");
   3765 		}
   3766 	    }
   3767 	    return (flags & VARE_UNDEFERR) ? var_Error : varNoError;
   3768 	} else {
   3769 	    haveModifier = FALSE;
   3770 	    tstr = &str[1];
   3771 	    endc = str[1];
   3772 	}
   3773     } else {
   3774 	Buffer buf;		/* Holds the variable name */
   3775 	int depth = 1;
   3776 
   3777 	endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
   3778 	Buf_Init(&buf, 0);
   3779 
   3780 	/*
   3781 	 * Skip to the end character or a colon, whichever comes first.
   3782 	 */
   3783 	for (tstr = str + 2; *tstr != '\0'; tstr++) {
   3784 	    /* Track depth so we can spot parse errors. */
   3785 	    if (*tstr == startc)
   3786 		depth++;
   3787 	    if (*tstr == endc) {
   3788 		if (--depth == 0)
   3789 		    break;
   3790 	    }
   3791 	    if (depth == 1 && *tstr == ':')
   3792 		break;
   3793 	    /* A variable inside a variable, expand. */
   3794 	    if (*tstr == '$') {
   3795 		int rlen;
   3796 		void *freeIt;
   3797 		char *rval = Var_Parse(tstr, ctxt, flags, &rlen, &freeIt);
   3798 		if (rval != NULL)
   3799 		    Buf_AddBytes(&buf, strlen(rval), rval);
   3800 		free(freeIt);
   3801 		tstr += rlen - 1;
   3802 	    } else
   3803 		Buf_AddByte(&buf, *tstr);
   3804 	}
   3805 	if (*tstr == ':') {
   3806 	    haveModifier = TRUE;
   3807 	} else if (*tstr == endc) {
   3808 	    haveModifier = FALSE;
   3809 	} else {
   3810 	    /*
   3811 	     * If we never did find the end character, return NULL
   3812 	     * right now, setting the length to be the distance to
   3813 	     * the end of the string, since that's what make does.
   3814 	     */
   3815 	    *lengthPtr = tstr - str;
   3816 	    Buf_Destroy(&buf, TRUE);
   3817 	    return var_Error;
   3818 	}
   3819 	str = Buf_GetAll(&buf, &vlen);
   3820 
   3821 	/*
   3822 	 * At this point, str points into newly allocated memory from
   3823 	 * buf, containing only the name of the variable.
   3824 	 *
   3825 	 * start and tstr point into the const string that was pointed
   3826 	 * to by the original value of the str parameter.  start points
   3827 	 * to the '$' at the beginning of the string, while tstr points
   3828 	 * to the char just after the end of the variable name -- this
   3829 	 * will be '\0', ':', PRCLOSE, or BRCLOSE.
   3830 	 */
   3831 
   3832 	v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   3833 	/*
   3834 	 * Check also for bogus D and F forms of local variables since we're
   3835 	 * in a local context and the name is the right length.
   3836 	 */
   3837 	if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
   3838 		(vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
   3839 		strchr("@%?*!<>", str[0]) != NULL) {
   3840 	    /*
   3841 	     * Well, it's local -- go look for it.
   3842 	     */
   3843 	    name[0] = *str;
   3844 	    name[1] = '\0';
   3845 	    v = VarFind(name, ctxt, 0);
   3846 
   3847 	    if (v != NULL) {
   3848 		if (str[1] == 'D') {
   3849 		    extramodifiers = "H:";
   3850 		} else { /* F */
   3851 		    extramodifiers = "T:";
   3852 		}
   3853 	    }
   3854 	}
   3855 
   3856 	if (v == NULL) {
   3857 	    if (((vlen == 1) ||
   3858 		 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
   3859 		((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
   3860 	    {
   3861 		/*
   3862 		 * If substituting a local variable in a non-local context,
   3863 		 * assume it's for dynamic source stuff. We have to handle
   3864 		 * this specially and return the longhand for the variable
   3865 		 * with the dollar sign escaped so it makes it back to the
   3866 		 * caller. Only four of the local variables are treated
   3867 		 * specially as they are the only four that will be set
   3868 		 * when dynamic sources are expanded.
   3869 		 */
   3870 		switch (*str) {
   3871 		case '@':
   3872 		case '%':
   3873 		case '*':
   3874 		case '!':
   3875 		    dynamic = TRUE;
   3876 		    break;
   3877 		}
   3878 	    } else if (vlen > 2 && *str == '.' &&
   3879 		       isupper((unsigned char) str[1]) &&
   3880 		       (ctxt == VAR_CMD || ctxt == VAR_GLOBAL))
   3881 	    {
   3882 		int len = vlen - 1;
   3883 		if ((strncmp(str, ".TARGET", len) == 0) ||
   3884 		    (strncmp(str, ".ARCHIVE", len) == 0) ||
   3885 		    (strncmp(str, ".PREFIX", len) == 0) ||
   3886 		    (strncmp(str, ".MEMBER", len) == 0))
   3887 		{
   3888 		    dynamic = TRUE;
   3889 		}
   3890 	    }
   3891 
   3892 	    if (!haveModifier) {
   3893 		/*
   3894 		 * No modifiers -- have specification length so we can return
   3895 		 * now.
   3896 		 */
   3897 		*lengthPtr = tstr - start + 1;
   3898 		if (dynamic) {
   3899 		    char *pstr = bmake_strndup(start, *lengthPtr);
   3900 		    *freePtr = pstr;
   3901 		    Buf_Destroy(&buf, TRUE);
   3902 		    return pstr;
   3903 		} else {
   3904 		    Buf_Destroy(&buf, TRUE);
   3905 		    return (flags & VARE_UNDEFERR) ? var_Error : varNoError;
   3906 		}
   3907 	    } else {
   3908 		/*
   3909 		 * Still need to get to the end of the variable specification,
   3910 		 * so kludge up a Var structure for the modifications
   3911 		 */
   3912 		v = bmake_malloc(sizeof(Var));
   3913 		v->name = UNCONST(str);
   3914 		Buf_Init(&v->val, 1);
   3915 		v->flags = VAR_JUNK;
   3916 		Buf_Destroy(&buf, FALSE);
   3917 	    }
   3918 	} else
   3919 	    Buf_Destroy(&buf, TRUE);
   3920     }
   3921 
   3922     if (v->flags & VAR_IN_USE) {
   3923 	Fatal("Variable %s is recursive.", v->name);
   3924 	/*NOTREACHED*/
   3925     } else {
   3926 	v->flags |= VAR_IN_USE;
   3927     }
   3928     /*
   3929      * Before doing any modification, we have to make sure the value
   3930      * has been fully expanded. If it looks like recursion might be
   3931      * necessary (there's a dollar sign somewhere in the variable's value)
   3932      * we just call Var_Subst to do any other substitutions that are
   3933      * necessary. Note that the value returned by Var_Subst will have
   3934      * been dynamically-allocated, so it will need freeing when we
   3935      * return.
   3936      */
   3937     nstr = Buf_GetAll(&v->val, NULL);
   3938     if (strchr(nstr, '$') != NULL && (flags & VARE_WANTRES) != 0) {
   3939 	nstr = Var_Subst(NULL, nstr, ctxt, flags);
   3940 	*freePtr = nstr;
   3941     }
   3942 
   3943     v->flags &= ~VAR_IN_USE;
   3944 
   3945     if (nstr != NULL && (haveModifier || extramodifiers != NULL)) {
   3946 	void *extraFree;
   3947 	int used;
   3948 
   3949 	extraFree = NULL;
   3950 	if (extramodifiers != NULL) {
   3951 	    nstr = ApplyModifiers(nstr, extramodifiers, '(', ')',
   3952 				  v, ctxt, flags, &used, &extraFree);
   3953 	}
   3954 
   3955 	if (haveModifier) {
   3956 	    /* Skip initial colon. */
   3957 	    tstr++;
   3958 
   3959 	    nstr = ApplyModifiers(nstr, tstr, startc, endc,
   3960 				  v, ctxt, flags, &used, freePtr);
   3961 	    tstr += used;
   3962 	    free(extraFree);
   3963 	} else {
   3964 	    *freePtr = extraFree;
   3965 	}
   3966     }
   3967     *lengthPtr = tstr - start + (*tstr ? 1 : 0);
   3968 
   3969     if (v->flags & VAR_FROM_ENV) {
   3970 	Boolean destroy = FALSE;
   3971 
   3972 	if (nstr != Buf_GetAll(&v->val, NULL)) {
   3973 	    destroy = TRUE;
   3974 	} else {
   3975 	    /*
   3976 	     * Returning the value unmodified, so tell the caller to free
   3977 	     * the thing.
   3978 	     */
   3979 	    *freePtr = nstr;
   3980 	}
   3981 	VarFreeEnv(v, destroy);
   3982     } else if (v->flags & VAR_JUNK) {
   3983 	/*
   3984 	 * Perform any free'ing needed and set *freePtr to NULL so the caller
   3985 	 * doesn't try to free a static pointer.
   3986 	 * If VAR_KEEP is also set then we want to keep str as is.
   3987 	 */
   3988 	if (!(v->flags & VAR_KEEP)) {
   3989 	    if (*freePtr) {
   3990 		free(nstr);
   3991 		*freePtr = NULL;
   3992 	    }
   3993 	    if (dynamic) {
   3994 		nstr = bmake_strndup(start, *lengthPtr);
   3995 		*freePtr = nstr;
   3996 	    } else {
   3997 		nstr = (flags & VARE_UNDEFERR) ? var_Error : varNoError;
   3998 	    }
   3999 	}
   4000 	if (nstr != Buf_GetAll(&v->val, NULL))
   4001 	    Buf_Destroy(&v->val, TRUE);
   4002 	free(v->name);
   4003 	free(v);
   4004     }
   4005     return nstr;
   4006 }
   4007 
   4008 /*-
   4009  *-----------------------------------------------------------------------
   4010  * Var_Subst  --
   4011  *	Substitute for all variables in the given string in the given context.
   4012  *	If flags & VARE_UNDEFERR, Parse_Error will be called when an undefined
   4013  *	variable is encountered.
   4014  *
   4015  * Input:
   4016  *	var		Named variable || NULL for all
   4017  *	str		the string which to substitute
   4018  *	ctxt		the context wherein to find variables
   4019  *	flags		VARE_UNDEFERR	if undefineds are an error
   4020  *			VARE_WANTRES	if we actually want the result
   4021  *			VARE_ASSIGN	if we are in a := assignment
   4022  *
   4023  * Results:
   4024  *	The resulting string.
   4025  *
   4026  * Side Effects:
   4027  *	None.
   4028  *-----------------------------------------------------------------------
   4029  */
   4030 char *
   4031 Var_Subst(const char *var, const char *str, GNode *ctxt, VarEvalFlags flags)
   4032 {
   4033     Buffer	buf;		/* Buffer for forming things */
   4034     char	*val;		/* Value to substitute for a variable */
   4035     int		length;		/* Length of the variable invocation */
   4036     Boolean	trailingBslash;	/* variable ends in \ */
   4037     void	*freeIt = NULL;	/* Set if it should be freed */
   4038     static Boolean errorReported; /* Set true if an error has already
   4039 				 * been reported to prevent a plethora
   4040 				 * of messages when recursing */
   4041 
   4042     Buf_Init(&buf, 0);
   4043     errorReported = FALSE;
   4044     trailingBslash = FALSE;
   4045 
   4046     while (*str) {
   4047 	if (*str == '\n' && trailingBslash)
   4048 	    Buf_AddByte(&buf, ' ');
   4049 	if (var == NULL && (*str == '$') && (str[1] == '$')) {
   4050 	    /*
   4051 	     * A dollar sign may be escaped either with another dollar sign.
   4052 	     * In such a case, we skip over the escape character and store the
   4053 	     * dollar sign into the buffer directly.
   4054 	     */
   4055 	    if (save_dollars && (flags & VARE_ASSIGN))
   4056 		Buf_AddByte(&buf, *str);
   4057 	    str++;
   4058 	    Buf_AddByte(&buf, *str);
   4059 	    str++;
   4060 	} else if (*str != '$') {
   4061 	    /*
   4062 	     * Skip as many characters as possible -- either to the end of
   4063 	     * the string or to the next dollar sign (variable invocation).
   4064 	     */
   4065 	    const char *cp;
   4066 
   4067 	    for (cp = str++; *str != '$' && *str != '\0'; str++)
   4068 		continue;
   4069 	    Buf_AddBytes(&buf, str - cp, cp);
   4070 	} else {
   4071 	    if (var != NULL) {
   4072 		int expand;
   4073 		for (;;) {
   4074 		    if (str[1] == '\0') {
   4075 			/* A trailing $ is kind of a special case */
   4076 			Buf_AddByte(&buf, str[0]);
   4077 			str++;
   4078 			expand = FALSE;
   4079 		    } else if (str[1] != PROPEN && str[1] != BROPEN) {
   4080 			if (str[1] != *var || strlen(var) > 1) {
   4081 			    Buf_AddBytes(&buf, 2, str);
   4082 			    str += 2;
   4083 			    expand = FALSE;
   4084 			} else
   4085 			    expand = TRUE;
   4086 			break;
   4087 		    } else {
   4088 			const char *p;
   4089 
   4090 			/* Scan up to the end of the variable name. */
   4091 			for (p = &str[2]; *p &&
   4092 			     *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
   4093 			    if (*p == '$')
   4094 				break;
   4095 			/*
   4096 			 * A variable inside the variable. We cannot expand
   4097 			 * the external variable yet, so we try again with
   4098 			 * the nested one
   4099 			 */
   4100 			if (*p == '$') {
   4101 			    Buf_AddBytes(&buf, p - str, str);
   4102 			    str = p;
   4103 			    continue;
   4104 			}
   4105 
   4106 			if (strncmp(var, str + 2, p - str - 2) != 0 ||
   4107 			    var[p - str - 2] != '\0') {
   4108 			    /*
   4109 			     * Not the variable we want to expand, scan
   4110 			     * until the next variable
   4111 			     */
   4112 			    for (; *p != '$' && *p != '\0'; p++)
   4113 				continue;
   4114 			    Buf_AddBytes(&buf, p - str, str);
   4115 			    str = p;
   4116 			    expand = FALSE;
   4117 			} else
   4118 			    expand = TRUE;
   4119 			break;
   4120 		    }
   4121 		}
   4122 		if (!expand)
   4123 		    continue;
   4124 	    }
   4125 
   4126 	    val = Var_Parse(str, ctxt, flags, &length, &freeIt);
   4127 
   4128 	    /*
   4129 	     * When we come down here, val should either point to the
   4130 	     * value of this variable, suitably modified, or be NULL.
   4131 	     * Length should be the total length of the potential
   4132 	     * variable invocation (from $ to end character...)
   4133 	     */
   4134 	    if (val == var_Error || val == varNoError) {
   4135 		/*
   4136 		 * If performing old-time variable substitution, skip over
   4137 		 * the variable and continue with the substitution. Otherwise,
   4138 		 * store the dollar sign and advance str so we continue with
   4139 		 * the string...
   4140 		 */
   4141 		if (oldVars) {
   4142 		    str += length;
   4143 		} else if ((flags & VARE_UNDEFERR) || val == var_Error) {
   4144 		    /*
   4145 		     * If variable is undefined, complain and skip the
   4146 		     * variable. The complaint will stop us from doing anything
   4147 		     * when the file is parsed.
   4148 		     */
   4149 		    if (!errorReported) {
   4150 			Parse_Error(PARSE_FATAL, "Undefined variable \"%.*s\"",
   4151 				    length, str);
   4152 		    }
   4153 		    str += length;
   4154 		    errorReported = TRUE;
   4155 		} else {
   4156 		    Buf_AddByte(&buf, *str);
   4157 		    str += 1;
   4158 		}
   4159 	    } else {
   4160 		/*
   4161 		 * We've now got a variable structure to store in. But first,
   4162 		 * advance the string pointer.
   4163 		 */
   4164 		str += length;
   4165 
   4166 		/*
   4167 		 * Copy all the characters from the variable value straight
   4168 		 * into the new string.
   4169 		 */
   4170 		length = strlen(val);
   4171 		Buf_AddBytes(&buf, length, val);
   4172 		trailingBslash = length > 0 && val[length - 1] == '\\';
   4173 	    }
   4174 	    free(freeIt);
   4175 	    freeIt = NULL;
   4176 	}
   4177     }
   4178 
   4179     return Buf_DestroyCompact(&buf);
   4180 }
   4181 
   4182 /* Initialize the module. */
   4183 void
   4184 Var_Init(void)
   4185 {
   4186     VAR_INTERNAL = Targ_NewGN("Internal");
   4187     VAR_GLOBAL = Targ_NewGN("Global");
   4188     VAR_CMD = Targ_NewGN("Command");
   4189 }
   4190 
   4191 
   4192 void
   4193 Var_End(void)
   4194 {
   4195 }
   4196 
   4197 
   4198 /****************** PRINT DEBUGGING INFO *****************/
   4199 static void
   4200 VarPrintVar(void *vp, void *data MAKE_ATTR_UNUSED)
   4201 {
   4202     Var *v = (Var *)vp;
   4203     fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
   4204 }
   4205 
   4206 /*-
   4207  *-----------------------------------------------------------------------
   4208  * Var_Dump --
   4209  *	print all variables in a context
   4210  *-----------------------------------------------------------------------
   4211  */
   4212 void
   4213 Var_Dump(GNode *ctxt)
   4214 {
   4215     Hash_ForEach(&ctxt->context, VarPrintVar, NULL);
   4216 }
   4217