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