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