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