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