Home | History | Annotate | Line # | Download | only in make
var.c revision 1.1000
      1 /*	$NetBSD: var.c,v 1.1000 2022/01/09 18:49:28 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
     84  *	Var_SetExpand
     85  *			Set the value of the variable, creating it if
     86  *			necessary.
     87  *
     88  *	Var_Append
     89  *	Var_AppendExpand
     90  *			Append more characters to the variable, creating it if
     91  *			necessary. A space is placed between the old value and
     92  *			the new one.
     93  *
     94  *	Var_Exists
     95  *	Var_ExistsExpand
     96  *			See if a variable exists.
     97  *
     98  *	Var_Value	Return the unexpanded value of a variable, or NULL if
     99  *			the variable is undefined.
    100  *
    101  *	Var_Subst	Substitute all variable expressions in a string.
    102  *
    103  *	Var_Parse	Parse a variable expression such as ${VAR:Mpattern}.
    104  *
    105  *	Var_Delete
    106  *	Var_DeleteExpand
    107  *			Delete a variable.
    108  *
    109  *	Var_ReexportVars
    110  *			Export some or even all variables to the environment
    111  *			of this process and its child processes.
    112  *
    113  *	Var_Export	Export the variable to the environment of this process
    114  *			and its child processes.
    115  *
    116  *	Var_UnExport	Don't export the variable anymore.
    117  *
    118  * Debugging:
    119  *	Var_Stats	Print out hashing statistics if in -dh mode.
    120  *
    121  *	Var_Dump	Print out all variables defined in the given scope.
    122  *
    123  * XXX: There's a lot of almost duplicate code in these functions that only
    124  *  differs in subtle details that are not mentioned in the manual page.
    125  */
    126 
    127 #include <sys/stat.h>
    128 #ifndef NO_REGEX
    129 #include <sys/types.h>
    130 #include <regex.h>
    131 #endif
    132 #include <errno.h>
    133 #include <inttypes.h>
    134 #include <limits.h>
    135 #include <time.h>
    136 
    137 #include "make.h"
    138 #include "dir.h"
    139 #include "job.h"
    140 #include "metachar.h"
    141 
    142 /*	"@(#)var.c	8.3 (Berkeley) 3/19/94" */
    143 MAKE_RCSID("$NetBSD: var.c,v 1.1000 2022/01/09 18:49:28 rillig Exp $");
    144 
    145 /*
    146  * Variables are defined using one of the VAR=value assignments.  Their
    147  * value can be queried by expressions such as $V, ${VAR}, or with modifiers
    148  * such as ${VAR:S,from,to,g:Q}.
    149  *
    150  * There are 3 kinds of variables: scope variables, environment variables,
    151  * undefined variables.
    152  *
    153  * Scope variables are stored in a GNode.scope.  The only way to undefine
    154  * a scope variable is using the .undef directive.  In particular, it must
    155  * not be possible to undefine a variable during the evaluation of an
    156  * expression, or Var.name might point nowhere.  (There is another,
    157  * unintended way to undefine a scope variable, see varmod-loop-delete.mk.)
    158  *
    159  * Environment variables are short-lived.  They are returned by VarFind, and
    160  * after using them, they must be freed using VarFreeShortLived.
    161  *
    162  * Undefined variables occur during evaluation of variable expressions such
    163  * as ${UNDEF:Ufallback} in Var_Parse and ApplyModifiers.
    164  */
    165 typedef struct Var {
    166 	/*
    167 	 * The name of the variable, once set, doesn't change anymore.
    168 	 * For scope variables, it aliases the corresponding HashEntry name.
    169 	 * For environment and undefined variables, it is allocated.
    170 	 */
    171 	FStr name;
    172 
    173 	/* The unexpanded value of the variable. */
    174 	Buffer val;
    175 
    176 	/* The variable came from the command line. */
    177 	bool fromCmd:1;
    178 
    179 	/*
    180 	 * The variable is short-lived.
    181 	 * These variables are not registered in any GNode, therefore they
    182 	 * must be freed after use.
    183 	 */
    184 	bool shortLived:1;
    185 
    186 	/*
    187 	 * The variable comes from the environment.
    188 	 * Appending to its value moves the variable to the global scope.
    189 	 */
    190 	bool fromEnvironment:1;
    191 
    192 	/*
    193 	 * The variable value cannot be changed anymore, and the variable
    194 	 * cannot be deleted.  Any attempts to do so are silently ignored,
    195 	 * they are logged with -dv though.
    196 	 *
    197 	 * See VAR_SET_READONLY.
    198 	 */
    199 	bool readOnly:1;
    200 
    201 	/*
    202 	* The variable's value is currently being used by Var_Parse or
    203 	* Var_Subst.  This marker is used to avoid endless recursion.
    204 	*/
    205 	bool inUse:1;
    206 
    207 	/*
    208 	 * The variable is exported to the environment, to be used by child
    209 	 * processes.
    210 	 */
    211 	bool exported:1;
    212 
    213 	/*
    214 	 * At the point where this variable was exported, it contained an
    215 	 * unresolved reference to another variable.  Before any child
    216 	 * process is started, it needs to be exported again, in the hope
    217 	 * that the referenced variable can then be resolved.
    218 	 */
    219 	bool reexport:1;
    220 } Var;
    221 
    222 /*
    223  * Exporting variables is expensive and may leak memory, so skip it if we
    224  * can.
    225  *
    226  * To avoid this, it might be worth encapsulating the environment variables
    227  * in a separate data structure called EnvVars.
    228  */
    229 typedef enum VarExportedMode {
    230 	VAR_EXPORTED_NONE,
    231 	VAR_EXPORTED_SOME,
    232 	VAR_EXPORTED_ALL
    233 } VarExportedMode;
    234 
    235 typedef enum UnexportWhat {
    236 	/* Unexport the variables given by name. */
    237 	UNEXPORT_NAMED,
    238 	/*
    239 	 * Unexport all globals previously exported, but keep the environment
    240 	 * inherited from the parent.
    241 	 */
    242 	UNEXPORT_ALL,
    243 	/*
    244 	 * Unexport all globals previously exported and clear the environment
    245 	 * inherited from the parent.
    246 	 */
    247 	UNEXPORT_ENV
    248 } UnexportWhat;
    249 
    250 /* Flags for pattern matching in the :S and :C modifiers */
    251 typedef struct PatternFlags {
    252 	bool subGlobal:1;	/* 'g': replace as often as possible */
    253 	bool subOnce:1;		/* '1': replace only once */
    254 	bool anchorStart:1;	/* '^': match only at start of word */
    255 	bool anchorEnd:1;	/* '$': match only at end of word */
    256 } PatternFlags;
    257 
    258 /* SepBuf builds a string from words interleaved with separators. */
    259 typedef struct SepBuf {
    260 	Buffer buf;
    261 	bool needSep;
    262 	/* Usually ' ', but see the ':ts' modifier. */
    263 	char sep;
    264 } SepBuf;
    265 
    266 
    267 /*
    268  * This lets us tell if we have replaced the original environ
    269  * (which we cannot free).
    270  */
    271 char **savedEnv = NULL;
    272 
    273 /*
    274  * Special return value for Var_Parse, indicating a parse error.  It may be
    275  * caused by an undefined variable, a syntax error in a modifier or
    276  * something entirely different.
    277  */
    278 char var_Error[] = "";
    279 
    280 /*
    281  * Special return value for Var_Parse, indicating an undefined variable in
    282  * a case where VARE_UNDEFERR is not set.  This undefined variable is
    283  * typically a dynamic variable such as ${.TARGET}, whose expansion needs to
    284  * be deferred until it is defined in an actual target.
    285  *
    286  * See VARE_EVAL_KEEP_UNDEF.
    287  */
    288 static char varUndefined[] = "";
    289 
    290 /*
    291  * Traditionally this make consumed $$ during := like any other expansion.
    292  * Other make's do not, and this make follows straight since 2016-01-09.
    293  *
    294  * This knob allows controlling the behavior:
    295  *	false to consume $$ during := assignment.
    296  *	true to preserve $$ during := assignment.
    297  */
    298 #define MAKE_SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
    299 static bool save_dollars = true;
    300 
    301 /*
    302  * A scope collects variable names and their values.
    303  *
    304  * The main scope is SCOPE_GLOBAL, which contains the variables that are set
    305  * in the makefiles.  SCOPE_INTERNAL acts as a fallback for SCOPE_GLOBAL and
    306  * contains some internal make variables.  These internal variables can thus
    307  * be overridden, they can also be restored by undefining the overriding
    308  * variable.
    309  *
    310  * SCOPE_CMDLINE contains variables from the command line arguments.  These
    311  * override variables from SCOPE_GLOBAL.
    312  *
    313  * There is no scope for environment variables, these are generated on-the-fly
    314  * whenever they are referenced.  If there were such a scope, each change to
    315  * environment variables would have to be reflected in that scope, which may
    316  * be simpler or more complex than the current implementation.
    317  *
    318  * Each target has its own scope, containing the 7 target-local variables
    319  * .TARGET, .ALLSRC, etc.  No other variables are in these scopes.
    320  */
    321 
    322 GNode *SCOPE_CMDLINE;
    323 GNode *SCOPE_GLOBAL;
    324 GNode *SCOPE_INTERNAL;
    325 
    326 static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE;
    327 
    328 static const char VarEvalMode_Name[][32] = {
    329 	"parse-only",
    330 	"eval",
    331 	"eval-defined",
    332 	"eval-keep-dollar",
    333 	"eval-keep-undefined",
    334 	"eval-keep-dollar-and-undefined",
    335 };
    336 
    337 
    338 static Var *
    339 VarNew(FStr name, const char *value,
    340        bool shortLived, bool fromEnvironment, bool readOnly)
    341 {
    342 	size_t value_len = strlen(value);
    343 	Var *var = bmake_malloc(sizeof *var);
    344 	var->name = name;
    345 	Buf_InitSize(&var->val, value_len + 1);
    346 	Buf_AddBytes(&var->val, value, value_len);
    347 	var->fromCmd = false;
    348 	var->shortLived = shortLived;
    349 	var->fromEnvironment = fromEnvironment;
    350 	var->readOnly = readOnly;
    351 	var->inUse = false;
    352 	var->exported = false;
    353 	var->reexport = false;
    354 	return var;
    355 }
    356 
    357 static Substring
    358 CanonicalVarname(Substring name)
    359 {
    360 
    361 	if (!(Substring_Length(name) > 0 && name.start[0] == '.'))
    362 		return name;
    363 
    364 	if (Substring_Equals(name, ".ALLSRC"))
    365 		return Substring_InitStr(ALLSRC);
    366 	if (Substring_Equals(name, ".ARCHIVE"))
    367 		return Substring_InitStr(ARCHIVE);
    368 	if (Substring_Equals(name, ".IMPSRC"))
    369 		return Substring_InitStr(IMPSRC);
    370 	if (Substring_Equals(name, ".MEMBER"))
    371 		return Substring_InitStr(MEMBER);
    372 	if (Substring_Equals(name, ".OODATE"))
    373 		return Substring_InitStr(OODATE);
    374 	if (Substring_Equals(name, ".PREFIX"))
    375 		return Substring_InitStr(PREFIX);
    376 	if (Substring_Equals(name, ".TARGET"))
    377 		return Substring_InitStr(TARGET);
    378 
    379 	if (Substring_Equals(name, ".SHELL") && shellPath == NULL)
    380 		Shell_Init();
    381 
    382 	/* GNU make has an additional alias $^ == ${.ALLSRC}. */
    383 
    384 	return name;
    385 }
    386 
    387 static Var *
    388 GNode_FindVar(GNode *scope, Substring varname, unsigned int hash)
    389 {
    390 	return HashTable_FindValueBySubstringHash(&scope->vars, varname, hash);
    391 }
    392 
    393 /*
    394  * Find the variable in the scope, and maybe in other scopes as well.
    395  *
    396  * Input:
    397  *	name		name to find, is not expanded any further
    398  *	scope		scope in which to look first
    399  *	elsewhere	true to look in other scopes as well
    400  *
    401  * Results:
    402  *	The found variable, or NULL if the variable does not exist.
    403  *	If the variable is short-lived (such as environment variables), it
    404  *	must be freed using VarFreeShortLived after use.
    405  */
    406 static Var *
    407 VarFindSubstring(Substring name, GNode *scope, bool elsewhere)
    408 {
    409 	Var *var;
    410 	unsigned int nameHash;
    411 
    412 	/* Replace '.TARGET' with '@', likewise for other local variables. */
    413 	name = CanonicalVarname(name);
    414 	nameHash = Hash_Substring(name);
    415 
    416 	var = GNode_FindVar(scope, name, nameHash);
    417 	if (!elsewhere)
    418 		return var;
    419 
    420 	if (var == NULL && scope != SCOPE_CMDLINE)
    421 		var = GNode_FindVar(SCOPE_CMDLINE, name, nameHash);
    422 
    423 	if (!opts.checkEnvFirst && var == NULL && scope != SCOPE_GLOBAL) {
    424 		var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
    425 		if (var == NULL && scope != SCOPE_INTERNAL) {
    426 			/* SCOPE_INTERNAL is subordinate to SCOPE_GLOBAL */
    427 			var = GNode_FindVar(SCOPE_INTERNAL, name, nameHash);
    428 		}
    429 	}
    430 
    431 	if (var == NULL) {
    432 		FStr envName;
    433 		const char *envValue;
    434 
    435 		/*
    436 		 * TODO: try setting an environment variable with the empty
    437 		 *  name, which should be technically possible, just to see
    438 		 *  how make reacts.  All .for loops should be broken then.
    439 		 */
    440 		envName = Substring_Str(name);
    441 		envValue = getenv(envName.str);
    442 		if (envValue != NULL)
    443 			return VarNew(envName, envValue, true, true, false);
    444 		FStr_Done(&envName);
    445 
    446 		if (opts.checkEnvFirst && scope != SCOPE_GLOBAL) {
    447 			var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
    448 			if (var == NULL && scope != SCOPE_INTERNAL)
    449 				var = GNode_FindVar(SCOPE_INTERNAL, name,
    450 				    nameHash);
    451 			return var;
    452 		}
    453 
    454 		return NULL;
    455 	}
    456 
    457 	return var;
    458 }
    459 
    460 /* TODO: Replace these calls with VarFindSubstring, as far as possible. */
    461 static Var *
    462 VarFind(const char *name, GNode *scope, bool elsewhere)
    463 {
    464 	return VarFindSubstring(Substring_InitStr(name), scope, elsewhere);
    465 }
    466 
    467 /* If the variable is short-lived, free it, including its value. */
    468 static void
    469 VarFreeShortLived(Var *v)
    470 {
    471 	if (!v->shortLived)
    472 		return;
    473 
    474 	FStr_Done(&v->name);
    475 	Buf_Done(&v->val);
    476 	free(v);
    477 }
    478 
    479 /* Add a new variable of the given name and value to the given scope. */
    480 static Var *
    481 VarAdd(const char *name, const char *value, GNode *scope, VarSetFlags flags)
    482 {
    483 	HashEntry *he = HashTable_CreateEntry(&scope->vars, name, NULL);
    484 	Var *v = VarNew(FStr_InitRefer(/* aliased to */ he->key), value,
    485 	    false, false, (flags & VAR_SET_READONLY) != 0);
    486 	HashEntry_Set(he, v);
    487 	DEBUG3(VAR, "%s: %s = %s\n", scope->name, name, value);
    488 	return v;
    489 }
    490 
    491 /*
    492  * Remove a variable from a scope, freeing all related memory as well.
    493  * The variable name is kept as-is, it is not expanded.
    494  */
    495 void
    496 Var_Delete(GNode *scope, const char *varname)
    497 {
    498 	HashEntry *he = HashTable_FindEntry(&scope->vars, varname);
    499 	Var *v;
    500 
    501 	if (he == NULL) {
    502 		DEBUG2(VAR, "%s:delete %s (not found)\n", scope->name, varname);
    503 		return;
    504 	}
    505 
    506 	DEBUG2(VAR, "%s:delete %s\n", scope->name, varname);
    507 	v = he->value;
    508 	if (v->inUse) {
    509 		Parse_Error(PARSE_FATAL,
    510 		    "Cannot delete variable \"%s\" while it is used",
    511 		    v->name.str);
    512 		return;
    513 	}
    514 	if (v->exported)
    515 		unsetenv(v->name.str);
    516 	if (strcmp(v->name.str, MAKE_EXPORTED) == 0)
    517 		var_exportedVars = VAR_EXPORTED_NONE;
    518 	assert(v->name.freeIt == NULL);
    519 	HashTable_DeleteEntry(&scope->vars, he);
    520 	Buf_Done(&v->val);
    521 	free(v);
    522 }
    523 
    524 /*
    525  * Remove a variable from a scope, freeing all related memory as well.
    526  * The variable name is expanded once.
    527  */
    528 void
    529 Var_DeleteExpand(GNode *scope, const char *name)
    530 {
    531 	FStr varname = FStr_InitRefer(name);
    532 
    533 	if (strchr(varname.str, '$') != NULL) {
    534 		char *expanded;
    535 		(void)Var_Subst(varname.str, SCOPE_GLOBAL, VARE_WANTRES,
    536 		    &expanded);
    537 		/* TODO: handle errors */
    538 		varname = FStr_InitOwn(expanded);
    539 	}
    540 
    541 	Var_Delete(scope, varname.str);
    542 	FStr_Done(&varname);
    543 }
    544 
    545 /*
    546  * Undefine one or more variables from the global scope.
    547  * The argument is expanded exactly once and then split into words.
    548  */
    549 void
    550 Var_Undef(const char *arg)
    551 {
    552 	VarParseResult vpr;
    553 	char *expanded;
    554 	Words varnames;
    555 	size_t i;
    556 
    557 	if (arg[0] == '\0') {
    558 		Parse_Error(PARSE_FATAL,
    559 		    "The .undef directive requires an argument");
    560 		return;
    561 	}
    562 
    563 	vpr = Var_Subst(arg, SCOPE_GLOBAL, VARE_WANTRES, &expanded);
    564 	if (vpr != VPR_OK) {
    565 		Parse_Error(PARSE_FATAL,
    566 		    "Error in variable names to be undefined");
    567 		return;
    568 	}
    569 
    570 	varnames = Str_Words(expanded, false);
    571 	if (varnames.len == 1 && varnames.words[0][0] == '\0')
    572 		varnames.len = 0;
    573 
    574 	for (i = 0; i < varnames.len; i++) {
    575 		const char *varname = varnames.words[i];
    576 		Global_Delete(varname);
    577 	}
    578 
    579 	Words_Free(varnames);
    580 	free(expanded);
    581 }
    582 
    583 static bool
    584 MayExport(const char *name)
    585 {
    586 	if (name[0] == '.')
    587 		return false;	/* skip internals */
    588 	if (name[0] == '-')
    589 		return false;	/* skip misnamed variables */
    590 	if (name[1] == '\0') {
    591 		/*
    592 		 * A single char.
    593 		 * If it is one of the variables that should only appear in
    594 		 * local scope, skip it, else we can get Var_Subst
    595 		 * into a loop.
    596 		 */
    597 		switch (name[0]) {
    598 		case '@':
    599 		case '%':
    600 		case '*':
    601 		case '!':
    602 			return false;
    603 		}
    604 	}
    605 	return true;
    606 }
    607 
    608 static bool
    609 ExportVarEnv(Var *v)
    610 {
    611 	const char *name = v->name.str;
    612 	char *val = v->val.data;
    613 	char *expr;
    614 
    615 	if (v->exported && !v->reexport)
    616 		return false;	/* nothing to do */
    617 
    618 	if (strchr(val, '$') == NULL) {
    619 		if (!v->exported)
    620 			setenv(name, val, 1);
    621 		return true;
    622 	}
    623 
    624 	if (v->inUse) {
    625 		/*
    626 		 * We recursed while exporting in a child.
    627 		 * This isn't going to end well, just skip it.
    628 		 */
    629 		return false;
    630 	}
    631 
    632 	/* XXX: name is injected without escaping it */
    633 	expr = str_concat3("${", name, "}");
    634 	(void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &val);
    635 	/* TODO: handle errors */
    636 	setenv(name, val, 1);
    637 	free(val);
    638 	free(expr);
    639 	return true;
    640 }
    641 
    642 static bool
    643 ExportVarPlain(Var *v)
    644 {
    645 	if (strchr(v->val.data, '$') == NULL) {
    646 		setenv(v->name.str, v->val.data, 1);
    647 		v->exported = true;
    648 		v->reexport = false;
    649 		return true;
    650 	}
    651 
    652 	/*
    653 	 * Flag the variable as something we need to re-export.
    654 	 * No point actually exporting it now though,
    655 	 * the child process can do it at the last minute.
    656 	 * Avoid calling setenv more often than necessary since it can leak.
    657 	 */
    658 	v->exported = true;
    659 	v->reexport = true;
    660 	return true;
    661 }
    662 
    663 static bool
    664 ExportVarLiteral(Var *v)
    665 {
    666 	if (v->exported && !v->reexport)
    667 		return false;
    668 
    669 	if (!v->exported)
    670 		setenv(v->name.str, v->val.data, 1);
    671 
    672 	return true;
    673 }
    674 
    675 /*
    676  * Mark a single variable to be exported later for subprocesses.
    677  *
    678  * Internal variables (those starting with '.') are not exported.
    679  */
    680 static bool
    681 ExportVar(const char *name, VarExportMode mode)
    682 {
    683 	Var *v;
    684 
    685 	if (!MayExport(name))
    686 		return false;
    687 
    688 	v = VarFind(name, SCOPE_GLOBAL, false);
    689 	if (v == NULL)
    690 		return false;
    691 
    692 	if (mode == VEM_ENV)
    693 		return ExportVarEnv(v);
    694 	else if (mode == VEM_PLAIN)
    695 		return ExportVarPlain(v);
    696 	else
    697 		return ExportVarLiteral(v);
    698 }
    699 
    700 /*
    701  * Actually export the variables that have been marked as needing to be
    702  * re-exported.
    703  */
    704 void
    705 Var_ReexportVars(void)
    706 {
    707 	char *xvarnames;
    708 
    709 	/*
    710 	 * Several make implementations support this sort of mechanism for
    711 	 * tracking recursion - but each uses a different name.
    712 	 * We allow the makefiles to update MAKELEVEL and ensure
    713 	 * children see a correctly incremented value.
    714 	 */
    715 	char tmp[21];
    716 	snprintf(tmp, sizeof tmp, "%d", makelevel + 1);
    717 	setenv(MAKE_LEVEL_ENV, tmp, 1);
    718 
    719 	if (var_exportedVars == VAR_EXPORTED_NONE)
    720 		return;
    721 
    722 	if (var_exportedVars == VAR_EXPORTED_ALL) {
    723 		HashIter hi;
    724 
    725 		/* Ouch! Exporting all variables at once is crazy. */
    726 		HashIter_Init(&hi, &SCOPE_GLOBAL->vars);
    727 		while (HashIter_Next(&hi) != NULL) {
    728 			Var *var = hi.entry->value;
    729 			ExportVar(var->name.str, VEM_ENV);
    730 		}
    731 		return;
    732 	}
    733 
    734 	(void)Var_Subst("${" MAKE_EXPORTED ":O:u}", SCOPE_GLOBAL, VARE_WANTRES,
    735 	    &xvarnames);
    736 	/* TODO: handle errors */
    737 	if (xvarnames[0] != '\0') {
    738 		Words varnames = Str_Words(xvarnames, false);
    739 		size_t i;
    740 
    741 		for (i = 0; i < varnames.len; i++)
    742 			ExportVar(varnames.words[i], VEM_ENV);
    743 		Words_Free(varnames);
    744 	}
    745 	free(xvarnames);
    746 }
    747 
    748 static void
    749 ExportVars(const char *varnames, bool isExport, VarExportMode mode)
    750 /* TODO: try to combine the parameters 'isExport' and 'mode'. */
    751 {
    752 	Words words = Str_Words(varnames, false);
    753 	size_t i;
    754 
    755 	if (words.len == 1 && words.words[0][0] == '\0')
    756 		words.len = 0;
    757 
    758 	for (i = 0; i < words.len; i++) {
    759 		const char *varname = words.words[i];
    760 		if (!ExportVar(varname, mode))
    761 			continue;
    762 
    763 		if (var_exportedVars == VAR_EXPORTED_NONE)
    764 			var_exportedVars = VAR_EXPORTED_SOME;
    765 
    766 		if (isExport && mode == VEM_PLAIN)
    767 			Global_Append(MAKE_EXPORTED, varname);
    768 	}
    769 	Words_Free(words);
    770 }
    771 
    772 static void
    773 ExportVarsExpand(const char *uvarnames, bool isExport, VarExportMode mode)
    774 {
    775 	char *xvarnames;
    776 
    777 	(void)Var_Subst(uvarnames, SCOPE_GLOBAL, VARE_WANTRES, &xvarnames);
    778 	/* TODO: handle errors */
    779 	ExportVars(xvarnames, isExport, mode);
    780 	free(xvarnames);
    781 }
    782 
    783 /* Export the named variables, or all variables. */
    784 void
    785 Var_Export(VarExportMode mode, const char *varnames)
    786 {
    787 	if (mode == VEM_PLAIN && varnames[0] == '\0') {
    788 		var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
    789 		return;
    790 	}
    791 
    792 	ExportVarsExpand(varnames, true, mode);
    793 }
    794 
    795 void
    796 Var_ExportVars(const char *varnames)
    797 {
    798 	ExportVarsExpand(varnames, false, VEM_PLAIN);
    799 }
    800 
    801 
    802 extern char **environ;
    803 
    804 static void
    805 ClearEnv(void)
    806 {
    807 	const char *cp;
    808 	char **newenv;
    809 
    810 	cp = getenv(MAKE_LEVEL_ENV);	/* we should preserve this */
    811 	if (environ == savedEnv) {
    812 		/* we have been here before! */
    813 		newenv = bmake_realloc(environ, 2 * sizeof(char *));
    814 	} else {
    815 		if (savedEnv != NULL) {
    816 			free(savedEnv);
    817 			savedEnv = NULL;
    818 		}
    819 		newenv = bmake_malloc(2 * sizeof(char *));
    820 	}
    821 
    822 	/* Note: we cannot safely free() the original environ. */
    823 	environ = savedEnv = newenv;
    824 	newenv[0] = NULL;
    825 	newenv[1] = NULL;
    826 	if (cp != NULL && *cp != '\0')
    827 		setenv(MAKE_LEVEL_ENV, cp, 1);
    828 }
    829 
    830 static void
    831 GetVarnamesToUnexport(bool isEnv, const char *arg,
    832 		      FStr *out_varnames, UnexportWhat *out_what)
    833 {
    834 	UnexportWhat what;
    835 	FStr varnames = FStr_InitRefer("");
    836 
    837 	if (isEnv) {
    838 		if (arg[0] != '\0') {
    839 			Parse_Error(PARSE_FATAL,
    840 			    "The directive .unexport-env does not take "
    841 			    "arguments");
    842 			/* continue anyway */
    843 		}
    844 		what = UNEXPORT_ENV;
    845 
    846 	} else {
    847 		what = arg[0] != '\0' ? UNEXPORT_NAMED : UNEXPORT_ALL;
    848 		if (what == UNEXPORT_NAMED)
    849 			varnames = FStr_InitRefer(arg);
    850 	}
    851 
    852 	if (what != UNEXPORT_NAMED) {
    853 		char *expanded;
    854 		/* Using .MAKE.EXPORTED */
    855 		(void)Var_Subst("${" MAKE_EXPORTED ":O:u}", SCOPE_GLOBAL,
    856 		    VARE_WANTRES, &expanded);
    857 		/* TODO: handle errors */
    858 		varnames = FStr_InitOwn(expanded);
    859 	}
    860 
    861 	*out_varnames = varnames;
    862 	*out_what = what;
    863 }
    864 
    865 static void
    866 UnexportVar(Substring varname, UnexportWhat what)
    867 {
    868 	Var *v = VarFindSubstring(varname, SCOPE_GLOBAL, false);
    869 	if (v == NULL) {
    870 		DEBUG2(VAR, "Not unexporting \"%.*s\" (not found)\n",
    871 		    (int)Substring_Length(varname), varname.start);
    872 		return;
    873 	}
    874 
    875 	DEBUG2(VAR, "Unexporting \"%.*s\"\n",
    876 	    (int)Substring_Length(varname), varname.start);
    877 	if (what != UNEXPORT_ENV && v->exported && !v->reexport)
    878 		unsetenv(v->name.str);
    879 	v->exported = false;
    880 	v->reexport = false;
    881 
    882 	if (what == UNEXPORT_NAMED) {
    883 		/* Remove the variable names from .MAKE.EXPORTED. */
    884 		/* XXX: v->name is injected without escaping it */
    885 		char *expr = str_concat3("${" MAKE_EXPORTED ":N",
    886 		    v->name.str, "}");
    887 		char *cp;
    888 		(void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &cp);
    889 		/* TODO: handle errors */
    890 		Global_Set(MAKE_EXPORTED, cp);
    891 		free(cp);
    892 		free(expr);
    893 	}
    894 }
    895 
    896 static void
    897 UnexportVars(FStr *varnames, UnexportWhat what)
    898 {
    899 	size_t i;
    900 	SubstringWords words;
    901 
    902 	if (what == UNEXPORT_ENV)
    903 		ClearEnv();
    904 
    905 	words = Substring_Words(varnames->str, false);
    906 	for (i = 0; i < words.len; i++)
    907 		UnexportVar(words.words[i], what);
    908 	SubstringWords_Free(words);
    909 
    910 	if (what != UNEXPORT_NAMED)
    911 		Global_Delete(MAKE_EXPORTED);
    912 }
    913 
    914 /*
    915  * This is called when .unexport[-env] is seen.
    916  *
    917  * str must have the form "unexport[-env] varname...".
    918  */
    919 void
    920 Var_UnExport(bool isEnv, const char *arg)
    921 {
    922 	UnexportWhat what;
    923 	FStr varnames;
    924 
    925 	GetVarnamesToUnexport(isEnv, arg, &varnames, &what);
    926 	UnexportVars(&varnames, what);
    927 	FStr_Done(&varnames);
    928 }
    929 
    930 /*
    931  * When there is a variable of the same name in the command line scope, the
    932  * global variable would not be visible anywhere.  Therefore there is no
    933  * point in setting it at all.
    934  *
    935  * See 'scope == SCOPE_CMDLINE' in Var_SetWithFlags.
    936  */
    937 static bool
    938 ExistsInCmdline(const char *name, const char *val)
    939 {
    940 	Var *v;
    941 
    942 	v = VarFind(name, SCOPE_CMDLINE, false);
    943 	if (v == NULL)
    944 		return false;
    945 
    946 	if (v->fromCmd) {
    947 		DEBUG3(VAR, "%s: %s = %s ignored!\n",
    948 		    SCOPE_GLOBAL->name, name, val);
    949 		return true;
    950 	}
    951 
    952 	VarFreeShortLived(v);
    953 	return false;
    954 }
    955 
    956 /* Set the variable to the value; the name is not expanded. */
    957 void
    958 Var_SetWithFlags(GNode *scope, const char *name, const char *val,
    959 		 VarSetFlags flags)
    960 {
    961 	Var *v;
    962 
    963 	assert(val != NULL);
    964 	if (name[0] == '\0') {
    965 		DEBUG0(VAR, "SetVar: variable name is empty - ignored\n");
    966 		return;
    967 	}
    968 
    969 	if (scope == SCOPE_GLOBAL && ExistsInCmdline(name, val))
    970 		return;
    971 
    972 	/*
    973 	 * Only look for a variable in the given scope since anything set
    974 	 * here will override anything in a lower scope, so there's not much
    975 	 * point in searching them all.
    976 	 */
    977 	v = VarFind(name, scope, false);
    978 	if (v == NULL) {
    979 		if (scope == SCOPE_CMDLINE && !(flags & VAR_SET_NO_EXPORT)) {
    980 			/*
    981 			 * This var would normally prevent the same name being
    982 			 * added to SCOPE_GLOBAL, so delete it from there if
    983 			 * needed. Otherwise -V name may show the wrong value.
    984 			 *
    985 			 * See ExistsInCmdline.
    986 			 */
    987 			Var_Delete(SCOPE_GLOBAL, name);
    988 		}
    989 		if (strcmp(name, ".SUFFIXES") == 0) {
    990 			/* special: treat as readOnly */
    991 			DEBUG3(VAR, "%s: %s = %s ignored (read-only)\n",
    992 			    scope->name, name, val);
    993 			return;
    994 		}
    995 		v = VarAdd(name, val, scope, flags);
    996 	} else {
    997 		if (v->readOnly && !(flags & VAR_SET_READONLY)) {
    998 			DEBUG3(VAR, "%s: %s = %s ignored (read-only)\n",
    999 			    scope->name, name, val);
   1000 			return;
   1001 		}
   1002 		Buf_Clear(&v->val);
   1003 		Buf_AddStr(&v->val, val);
   1004 
   1005 		DEBUG3(VAR, "%s: %s = %s\n", scope->name, name, val);
   1006 		if (v->exported)
   1007 			ExportVar(name, VEM_PLAIN);
   1008 	}
   1009 
   1010 	/*
   1011 	 * Any variables given on the command line are automatically exported
   1012 	 * to the environment (as per POSIX standard), except for internals.
   1013 	 */
   1014 	if (scope == SCOPE_CMDLINE && !(flags & VAR_SET_NO_EXPORT) &&
   1015 	    name[0] != '.') {
   1016 		v->fromCmd = true;
   1017 
   1018 		/*
   1019 		 * If requested, don't export these in the environment
   1020 		 * individually.  We still put them in MAKEOVERRIDES so
   1021 		 * that the command-line settings continue to override
   1022 		 * Makefile settings.
   1023 		 */
   1024 		if (!opts.varNoExportEnv)
   1025 			setenv(name, val, 1);
   1026 		/* XXX: What about .MAKE.EXPORTED? */
   1027 		/*
   1028 		 * XXX: Why not just mark the variable for needing export, as
   1029 		 * in ExportVarPlain?
   1030 		 */
   1031 
   1032 		Global_Append(MAKEOVERRIDES, name);
   1033 	}
   1034 
   1035 	if (name[0] == '.' && strcmp(name, MAKE_SAVE_DOLLARS) == 0)
   1036 		save_dollars = ParseBoolean(val, save_dollars);
   1037 
   1038 	if (v != NULL)
   1039 		VarFreeShortLived(v);
   1040 }
   1041 
   1042 /* See Var_Set for documentation. */
   1043 void
   1044 Var_SetExpandWithFlags(GNode *scope, const char *name, const char *val,
   1045 		       VarSetFlags flags)
   1046 {
   1047 	const char *unexpanded_name = name;
   1048 	FStr varname = FStr_InitRefer(name);
   1049 
   1050 	assert(val != NULL);
   1051 
   1052 	if (strchr(varname.str, '$') != NULL) {
   1053 		char *expanded;
   1054 		(void)Var_Subst(varname.str, scope, VARE_WANTRES, &expanded);
   1055 		/* TODO: handle errors */
   1056 		varname = FStr_InitOwn(expanded);
   1057 	}
   1058 
   1059 	if (varname.str[0] == '\0') {
   1060 		DEBUG2(VAR,
   1061 		    "Var_SetExpand: variable name \"%s\" expands "
   1062 		    "to empty string, with value \"%s\" - ignored\n",
   1063 		    unexpanded_name, val);
   1064 	} else
   1065 		Var_SetWithFlags(scope, varname.str, val, flags);
   1066 
   1067 	FStr_Done(&varname);
   1068 }
   1069 
   1070 void
   1071 Var_Set(GNode *scope, const char *name, const char *val)
   1072 {
   1073 	Var_SetWithFlags(scope, name, val, VAR_SET_NONE);
   1074 }
   1075 
   1076 /*
   1077  * Set the variable name to the value val in the given scope.
   1078  *
   1079  * If the variable doesn't yet exist, it is created.
   1080  * Otherwise the new value overwrites and replaces the old value.
   1081  *
   1082  * Input:
   1083  *	scope		scope in which to set it
   1084  *	name		name of the variable to set, is expanded once
   1085  *	val		value to give to the variable
   1086  */
   1087 void
   1088 Var_SetExpand(GNode *scope, const char *name, const char *val)
   1089 {
   1090 	Var_SetExpandWithFlags(scope, name, val, VAR_SET_NONE);
   1091 }
   1092 
   1093 void
   1094 Global_Set(const char *name, const char *value)
   1095 {
   1096 	Var_Set(SCOPE_GLOBAL, name, value);
   1097 }
   1098 
   1099 void
   1100 Global_SetExpand(const char *name, const char *value)
   1101 {
   1102 	Var_SetExpand(SCOPE_GLOBAL, name, value);
   1103 }
   1104 
   1105 void
   1106 Global_Delete(const char *name)
   1107 {
   1108 	Var_Delete(SCOPE_GLOBAL, name);
   1109 }
   1110 
   1111 /*
   1112  * Append the value to the named variable.
   1113  *
   1114  * If the variable doesn't exist, it is created.  Otherwise a single space
   1115  * and the given value are appended.
   1116  */
   1117 void
   1118 Var_Append(GNode *scope, const char *name, const char *val)
   1119 {
   1120 	Var *v;
   1121 
   1122 	v = VarFind(name, scope, scope == SCOPE_GLOBAL);
   1123 
   1124 	if (v == NULL) {
   1125 		Var_SetWithFlags(scope, name, val, VAR_SET_NONE);
   1126 	} else if (v->readOnly) {
   1127 		DEBUG1(VAR, "Ignoring append to %s since it is read-only\n",
   1128 		    name);
   1129 	} else if (scope == SCOPE_CMDLINE || !v->fromCmd) {
   1130 		Buf_AddByte(&v->val, ' ');
   1131 		Buf_AddStr(&v->val, val);
   1132 
   1133 		DEBUG3(VAR, "%s: %s = %s\n", scope->name, name, v->val.data);
   1134 
   1135 		if (v->fromEnvironment) {
   1136 			/*
   1137 			 * The variable originally came from the environment.
   1138 			 * Install it in the global scope (we could place it
   1139 			 * in the environment, but then we should provide a
   1140 			 * way to export other variables...)
   1141 			 */
   1142 			v->fromEnvironment = false;
   1143 			v->shortLived = false;
   1144 			/*
   1145 			 * This is the only place where a variable is
   1146 			 * created in a scope, where v->name does not alias
   1147 			 * scope->vars->key.
   1148 			 */
   1149 			HashTable_Set(&scope->vars, name, v);
   1150 		}
   1151 	}
   1152 }
   1153 
   1154 /*
   1155  * The variable of the given name has the given value appended to it in the
   1156  * given scope.
   1157  *
   1158  * If the variable doesn't exist, it is created. Otherwise the strings are
   1159  * concatenated, with a space in between.
   1160  *
   1161  * Input:
   1162  *	scope		scope in which this should occur
   1163  *	name		name of the variable to modify, is expanded once
   1164  *	val		string to append to it
   1165  *
   1166  * Notes:
   1167  *	Only if the variable is being sought in the global scope is the
   1168  *	environment searched.
   1169  *	XXX: Knows its calling circumstances in that if called with scope
   1170  *	an actual target, it will only search that scope since only
   1171  *	a local variable could be being appended to. This is actually
   1172  *	a big win and must be tolerated.
   1173  */
   1174 void
   1175 Var_AppendExpand(GNode *scope, const char *name, const char *val)
   1176 {
   1177 	FStr xname = FStr_InitRefer(name);
   1178 
   1179 	assert(val != NULL);
   1180 
   1181 	if (strchr(name, '$') != NULL) {
   1182 		char *expanded;
   1183 		(void)Var_Subst(name, scope, VARE_WANTRES, &expanded);
   1184 		/* TODO: handle errors */
   1185 		xname = FStr_InitOwn(expanded);
   1186 		if (expanded[0] == '\0') {
   1187 			DEBUG2(VAR,
   1188 			    "Var_AppendExpand: variable name \"%s\" expands "
   1189 			    "to empty string, with value \"%s\" - ignored\n",
   1190 			    name, val);
   1191 			FStr_Done(&xname);
   1192 			return;
   1193 		}
   1194 	}
   1195 
   1196 	Var_Append(scope, xname.str, val);
   1197 
   1198 	FStr_Done(&xname);
   1199 }
   1200 
   1201 void
   1202 Global_Append(const char *name, const char *value)
   1203 {
   1204 	Var_Append(SCOPE_GLOBAL, name, value);
   1205 }
   1206 
   1207 bool
   1208 Var_Exists(GNode *scope, const char *name)
   1209 {
   1210 	Var *v = VarFind(name, scope, true);
   1211 	if (v == NULL)
   1212 		return false;
   1213 
   1214 	VarFreeShortLived(v);
   1215 	return true;
   1216 }
   1217 
   1218 /*
   1219  * See if the given variable exists, in the given scope or in other
   1220  * fallback scopes.
   1221  *
   1222  * Input:
   1223  *	scope		scope in which to start search
   1224  *	name		name of the variable to find, is expanded once
   1225  */
   1226 bool
   1227 Var_ExistsExpand(GNode *scope, const char *name)
   1228 {
   1229 	FStr varname = FStr_InitRefer(name);
   1230 	bool exists;
   1231 
   1232 	if (strchr(varname.str, '$') != NULL) {
   1233 		char *expanded;
   1234 		(void)Var_Subst(varname.str, scope, VARE_WANTRES, &expanded);
   1235 		/* TODO: handle errors */
   1236 		varname = FStr_InitOwn(expanded);
   1237 	}
   1238 
   1239 	exists = Var_Exists(scope, varname.str);
   1240 	FStr_Done(&varname);
   1241 	return exists;
   1242 }
   1243 
   1244 /*
   1245  * Return the unexpanded value of the given variable in the given scope,
   1246  * or the usual scopes.
   1247  *
   1248  * Input:
   1249  *	scope		scope in which to search for it
   1250  *	name		name to find, is not expanded any further
   1251  *
   1252  * Results:
   1253  *	The value if the variable exists, NULL if it doesn't.
   1254  *	The value is valid until the next modification to any variable.
   1255  */
   1256 FStr
   1257 Var_Value(GNode *scope, const char *name)
   1258 {
   1259 	Var *v = VarFind(name, scope, true);
   1260 	char *value;
   1261 
   1262 	if (v == NULL)
   1263 		return FStr_InitRefer(NULL);
   1264 
   1265 	if (!v->shortLived)
   1266 		return FStr_InitRefer(v->val.data);
   1267 
   1268 	value = v->val.data;
   1269 	v->val.data = NULL;
   1270 	VarFreeShortLived(v);
   1271 
   1272 	return FStr_InitOwn(value);
   1273 }
   1274 
   1275 /*
   1276  * Return the unexpanded variable value from this node, without trying to look
   1277  * up the variable in any other scope.
   1278  */
   1279 const char *
   1280 GNode_ValueDirect(GNode *gn, const char *name)
   1281 {
   1282 	Var *v = VarFind(name, gn, false);
   1283 	return v != NULL ? v->val.data : NULL;
   1284 }
   1285 
   1286 static VarEvalMode
   1287 VarEvalMode_WithoutKeepDollar(VarEvalMode emode)
   1288 {
   1289 	if (emode == VARE_KEEP_DOLLAR_UNDEF)
   1290 		return VARE_EVAL_KEEP_UNDEF;
   1291 	if (emode == VARE_EVAL_KEEP_DOLLAR)
   1292 		return VARE_WANTRES;
   1293 	return emode;
   1294 }
   1295 
   1296 static VarEvalMode
   1297 VarEvalMode_UndefOk(VarEvalMode emode)
   1298 {
   1299 	return emode == VARE_UNDEFERR ? VARE_WANTRES : emode;
   1300 }
   1301 
   1302 static bool
   1303 VarEvalMode_ShouldEval(VarEvalMode emode)
   1304 {
   1305 	return emode != VARE_PARSE_ONLY;
   1306 }
   1307 
   1308 static bool
   1309 VarEvalMode_ShouldKeepUndef(VarEvalMode emode)
   1310 {
   1311 	return emode == VARE_EVAL_KEEP_UNDEF ||
   1312 	       emode == VARE_KEEP_DOLLAR_UNDEF;
   1313 }
   1314 
   1315 static bool
   1316 VarEvalMode_ShouldKeepDollar(VarEvalMode emode)
   1317 {
   1318 	return emode == VARE_EVAL_KEEP_DOLLAR ||
   1319 	       emode == VARE_KEEP_DOLLAR_UNDEF;
   1320 }
   1321 
   1322 
   1323 static void
   1324 SepBuf_Init(SepBuf *buf, char sep)
   1325 {
   1326 	Buf_InitSize(&buf->buf, 32);
   1327 	buf->needSep = false;
   1328 	buf->sep = sep;
   1329 }
   1330 
   1331 static void
   1332 SepBuf_Sep(SepBuf *buf)
   1333 {
   1334 	buf->needSep = true;
   1335 }
   1336 
   1337 static void
   1338 SepBuf_AddBytes(SepBuf *buf, const char *mem, size_t mem_size)
   1339 {
   1340 	if (mem_size == 0)
   1341 		return;
   1342 	if (buf->needSep && buf->sep != '\0') {
   1343 		Buf_AddByte(&buf->buf, buf->sep);
   1344 		buf->needSep = false;
   1345 	}
   1346 	Buf_AddBytes(&buf->buf, mem, mem_size);
   1347 }
   1348 
   1349 static void
   1350 SepBuf_AddBytesBetween(SepBuf *buf, const char *start, const char *end)
   1351 {
   1352 	SepBuf_AddBytes(buf, start, (size_t)(end - start));
   1353 }
   1354 
   1355 static void
   1356 SepBuf_AddStr(SepBuf *buf, const char *str)
   1357 {
   1358 	SepBuf_AddBytes(buf, str, strlen(str));
   1359 }
   1360 
   1361 static void
   1362 SepBuf_AddSubstring(SepBuf *buf, Substring sub)
   1363 {
   1364 	SepBuf_AddBytesBetween(buf, sub.start, sub.end);
   1365 }
   1366 
   1367 static char *
   1368 SepBuf_DoneData(SepBuf *buf)
   1369 {
   1370 	return Buf_DoneData(&buf->buf);
   1371 }
   1372 
   1373 
   1374 /*
   1375  * This callback for ModifyWords gets a single word from a variable expression
   1376  * and typically adds a modification of this word to the buffer. It may also
   1377  * do nothing or add several words.
   1378  *
   1379  * For example, when evaluating the modifier ':M*b' in ${:Ua b c:M*b}, the
   1380  * callback is called 3 times, once for "a", "b" and "c".
   1381  *
   1382  * Some ModifyWord functions assume that they are always passed a
   1383  * null-terminated substring, which is currently guaranteed but may change in
   1384  * the future.
   1385  */
   1386 typedef void (*ModifyWordProc)(Substring word, SepBuf *buf, void *data);
   1387 
   1388 
   1389 /*
   1390  * Callback for ModifyWords to implement the :H modifier.
   1391  * Add the dirname of the given word to the buffer.
   1392  */
   1393 /*ARGSUSED*/
   1394 static void
   1395 ModifyWord_Head(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1396 {
   1397 	SepBuf_AddSubstring(buf, Substring_Dirname(word));
   1398 }
   1399 
   1400 /*
   1401  * Callback for ModifyWords to implement the :T modifier.
   1402  * Add the basename of the given word to the buffer.
   1403  */
   1404 /*ARGSUSED*/
   1405 static void
   1406 ModifyWord_Tail(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1407 {
   1408 	SepBuf_AddSubstring(buf, Substring_Basename(word));
   1409 }
   1410 
   1411 /*
   1412  * Callback for ModifyWords to implement the :E modifier.
   1413  * Add the filename suffix of the given word to the buffer, if it exists.
   1414  */
   1415 /*ARGSUSED*/
   1416 static void
   1417 ModifyWord_Suffix(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1418 {
   1419 	const char *lastDot = Substring_LastIndex(word, '.');
   1420 	if (lastDot != NULL)
   1421 		SepBuf_AddBytesBetween(buf, lastDot + 1, word.end);
   1422 }
   1423 
   1424 /*
   1425  * Callback for ModifyWords to implement the :R modifier.
   1426  * Add the filename without extension of the given word to the buffer.
   1427  */
   1428 /*ARGSUSED*/
   1429 static void
   1430 ModifyWord_Root(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1431 {
   1432 	const char *lastDot, *end;
   1433 
   1434 	lastDot = Substring_LastIndex(word, '.');
   1435 	end = lastDot != NULL ? lastDot : word.end;
   1436 	SepBuf_AddBytesBetween(buf, word.start, end);
   1437 }
   1438 
   1439 /*
   1440  * Callback for ModifyWords to implement the :M modifier.
   1441  * Place the word in the buffer if it matches the given pattern.
   1442  */
   1443 static void
   1444 ModifyWord_Match(Substring word, SepBuf *buf, void *data)
   1445 {
   1446 	const char *pattern = data;
   1447 
   1448 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   1449 	if (Str_Match(word.start, pattern))
   1450 		SepBuf_AddSubstring(buf, word);
   1451 }
   1452 
   1453 /*
   1454  * Callback for ModifyWords to implement the :N modifier.
   1455  * Place the word in the buffer if it doesn't match the given pattern.
   1456  */
   1457 static void
   1458 ModifyWord_NoMatch(Substring word, SepBuf *buf, void *data)
   1459 {
   1460 	const char *pattern = data;
   1461 
   1462 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   1463 	if (!Str_Match(word.start, pattern))
   1464 		SepBuf_AddSubstring(buf, word);
   1465 }
   1466 
   1467 #ifdef SYSVVARSUB
   1468 struct ModifyWord_SysVSubstArgs {
   1469 	GNode *scope;
   1470 	Substring lhsPrefix;
   1471 	bool lhsPercent;
   1472 	Substring lhsSuffix;
   1473 	const char *rhs;
   1474 };
   1475 
   1476 /* Callback for ModifyWords to implement the :%.from=%.to modifier. */
   1477 static void
   1478 ModifyWord_SysVSubst(Substring word, SepBuf *buf, void *data)
   1479 {
   1480 	const struct ModifyWord_SysVSubstArgs *args = data;
   1481 	FStr rhs;
   1482 	char *rhsExp;
   1483 	const char *percent;
   1484 
   1485 	if (Substring_IsEmpty(word))
   1486 		return;
   1487 
   1488 	if (!Substring_HasPrefix(word, args->lhsPrefix))
   1489 		goto no_match;
   1490 	if (!Substring_HasSuffix(word, args->lhsSuffix))
   1491 		goto no_match;
   1492 
   1493 	rhs = FStr_InitRefer(args->rhs);
   1494 	if (strchr(rhs.str, '$') != NULL) {
   1495 		(void)Var_Subst(args->rhs, args->scope, VARE_WANTRES, &rhsExp);
   1496 		/* TODO: handle errors */
   1497 		rhs = FStr_InitOwn(rhsExp);
   1498 	}
   1499 
   1500 	percent = args->lhsPercent ? strchr(rhs.str, '%') : NULL;
   1501 
   1502 	if (percent != NULL)
   1503 		SepBuf_AddBytesBetween(buf, rhs.str, percent);
   1504 	if (percent != NULL || !args->lhsPercent)
   1505 		SepBuf_AddBytesBetween(buf,
   1506 		    word.start + Substring_Length(args->lhsPrefix),
   1507 		    word.end - Substring_Length(args->lhsSuffix));
   1508 	SepBuf_AddStr(buf, percent != NULL ? percent + 1 : rhs.str);
   1509 
   1510 	FStr_Done(&rhs);
   1511 	return;
   1512 
   1513 no_match:
   1514 	SepBuf_AddSubstring(buf, word);
   1515 }
   1516 #endif
   1517 
   1518 
   1519 struct ModifyWord_SubstArgs {
   1520 	Substring lhs;
   1521 	Substring rhs;
   1522 	PatternFlags pflags;
   1523 	bool matched;
   1524 };
   1525 
   1526 static const char *
   1527 Substring_Find(Substring haystack, Substring needle)
   1528 {
   1529 	size_t len, needleLen, i;
   1530 
   1531 	len = Substring_Length(haystack);
   1532 	needleLen = Substring_Length(needle);
   1533 	for (i = 0; i + needleLen <= len; i++)
   1534 		if (memcmp(haystack.start + i, needle.start, needleLen) == 0)
   1535 			return haystack.start + i;
   1536 	return NULL;
   1537 }
   1538 
   1539 /*
   1540  * Callback for ModifyWords to implement the :S,from,to, modifier.
   1541  * Perform a string substitution on the given word.
   1542  */
   1543 static void
   1544 ModifyWord_Subst(Substring word, SepBuf *buf, void *data)
   1545 {
   1546 	struct ModifyWord_SubstArgs *args = data;
   1547 	size_t wordLen, lhsLen;
   1548 	const char *wordEnd, *match;
   1549 
   1550 	wordLen = Substring_Length(word);
   1551 	wordEnd = word.end;
   1552 	if (args->pflags.subOnce && args->matched)
   1553 		goto nosub;
   1554 
   1555 	lhsLen = Substring_Length(args->lhs);
   1556 	if (args->pflags.anchorStart) {
   1557 		if (wordLen < lhsLen ||
   1558 		    memcmp(word.start, args->lhs.start, lhsLen) != 0)
   1559 			goto nosub;
   1560 
   1561 		if (args->pflags.anchorEnd && wordLen != lhsLen)
   1562 			goto nosub;
   1563 
   1564 		/* :S,^prefix,replacement, or :S,^whole$,replacement, */
   1565 		SepBuf_AddSubstring(buf, args->rhs);
   1566 		SepBuf_AddBytesBetween(buf, word.start + lhsLen, wordEnd);
   1567 		args->matched = true;
   1568 		return;
   1569 	}
   1570 
   1571 	if (args->pflags.anchorEnd) {
   1572 		if (wordLen < lhsLen)
   1573 			goto nosub;
   1574 		if (memcmp(wordEnd - lhsLen, args->lhs.start, lhsLen) != 0)
   1575 			goto nosub;
   1576 
   1577 		/* :S,suffix$,replacement, */
   1578 		SepBuf_AddBytesBetween(buf, word.start, wordEnd - lhsLen);
   1579 		SepBuf_AddSubstring(buf, args->rhs);
   1580 		args->matched = true;
   1581 		return;
   1582 	}
   1583 
   1584 	if (Substring_IsEmpty(args->lhs))
   1585 		goto nosub;
   1586 
   1587 	/* unanchored case, may match more than once */
   1588 	while ((match = Substring_Find(word, args->lhs)) != NULL) {
   1589 		SepBuf_AddBytesBetween(buf, word.start, match);
   1590 		SepBuf_AddSubstring(buf, args->rhs);
   1591 		args->matched = true;
   1592 		word.start = match + lhsLen;
   1593 		if (Substring_IsEmpty(word) || !args->pflags.subGlobal)
   1594 			break;
   1595 	}
   1596 nosub:
   1597 	SepBuf_AddSubstring(buf, word);
   1598 }
   1599 
   1600 #ifndef NO_REGEX
   1601 /* Print the error caused by a regcomp or regexec call. */
   1602 static void
   1603 VarREError(int reerr, const regex_t *pat, const char *str)
   1604 {
   1605 	size_t errlen = regerror(reerr, pat, NULL, 0);
   1606 	char *errbuf = bmake_malloc(errlen);
   1607 	regerror(reerr, pat, errbuf, errlen);
   1608 	Error("%s: %s", str, errbuf);
   1609 	free(errbuf);
   1610 }
   1611 
   1612 /* In the modifier ':C', replace a backreference from \0 to \9. */
   1613 static void
   1614 RegexReplaceBackref(char ref, SepBuf *buf, const char *wp,
   1615 		    const regmatch_t *m, size_t nsub)
   1616 {
   1617 	unsigned int n = ref - '0';
   1618 
   1619 	if (n >= nsub)
   1620 		Error("No subexpression \\%u", n);
   1621 	else if (m[n].rm_so == -1) {
   1622 		if (opts.strict)
   1623 			Error("No match for subexpression \\%u", n);
   1624 	} else {
   1625 		SepBuf_AddBytesBetween(buf,
   1626 		    wp + (size_t)m[n].rm_so,
   1627 		    wp + (size_t)m[n].rm_eo);
   1628 	}
   1629 }
   1630 
   1631 /*
   1632  * The regular expression matches the word; now add the replacement to the
   1633  * buffer, taking back-references from 'wp'.
   1634  */
   1635 static void
   1636 RegexReplace(Substring replace, SepBuf *buf, const char *wp,
   1637 	     const regmatch_t *m, size_t nsub)
   1638 {
   1639 	const char *rp;
   1640 
   1641 	for (rp = replace.start; rp != replace.end; rp++) {
   1642 		if (*rp == '\\' && rp + 1 != replace.end &&
   1643 		    (rp[1] == '&' || rp[1] == '\\'))
   1644 			SepBuf_AddBytes(buf, ++rp, 1);
   1645 		else if (*rp == '\\' && rp + 1 != replace.end &&
   1646 			 ch_isdigit(rp[1]))
   1647 			RegexReplaceBackref(*++rp, buf, wp, m, nsub);
   1648 		else if (*rp == '&') {
   1649 			SepBuf_AddBytesBetween(buf,
   1650 			    wp + (size_t)m[0].rm_so,
   1651 			    wp + (size_t)m[0].rm_eo);
   1652 		} else
   1653 			SepBuf_AddBytes(buf, rp, 1);
   1654 	}
   1655 }
   1656 
   1657 struct ModifyWord_SubstRegexArgs {
   1658 	regex_t re;
   1659 	size_t nsub;
   1660 	Substring replace;
   1661 	PatternFlags pflags;
   1662 	bool matched;
   1663 };
   1664 
   1665 /*
   1666  * Callback for ModifyWords to implement the :C/from/to/ modifier.
   1667  * Perform a regex substitution on the given word.
   1668  */
   1669 static void
   1670 ModifyWord_SubstRegex(Substring word, SepBuf *buf, void *data)
   1671 {
   1672 	struct ModifyWord_SubstRegexArgs *args = data;
   1673 	int xrv;
   1674 	const char *wp;
   1675 	int flags = 0;
   1676 	regmatch_t m[10];
   1677 
   1678 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   1679 	wp = word.start;
   1680 	if (args->pflags.subOnce && args->matched)
   1681 		goto no_match;
   1682 
   1683 again:
   1684 	xrv = regexec(&args->re, wp, args->nsub, m, flags);
   1685 	if (xrv == 0)
   1686 		goto ok;
   1687 	if (xrv != REG_NOMATCH)
   1688 		VarREError(xrv, &args->re, "Unexpected regex error");
   1689 no_match:
   1690 	SepBuf_AddBytesBetween(buf, wp, word.end);
   1691 	return;
   1692 
   1693 ok:
   1694 	args->matched = true;
   1695 	SepBuf_AddBytes(buf, wp, (size_t)m[0].rm_so);
   1696 
   1697 	RegexReplace(args->replace, buf, wp, m, args->nsub);
   1698 
   1699 	wp += (size_t)m[0].rm_eo;
   1700 	if (args->pflags.subGlobal) {
   1701 		flags |= REG_NOTBOL;
   1702 		if (m[0].rm_so == 0 && m[0].rm_eo == 0) {
   1703 			SepBuf_AddBytes(buf, wp, 1);
   1704 			wp++;
   1705 		}
   1706 		if (*wp != '\0')
   1707 			goto again;
   1708 	}
   1709 	if (*wp != '\0')
   1710 		SepBuf_AddStr(buf, wp);
   1711 }
   1712 #endif
   1713 
   1714 
   1715 struct ModifyWord_LoopArgs {
   1716 	GNode *scope;
   1717 	const char *var;	/* name of the temporary variable */
   1718 	const char *body;	/* string to expand */
   1719 	VarEvalMode emode;
   1720 };
   1721 
   1722 /* Callback for ModifyWords to implement the :@var (at) ...@ modifier of ODE make. */
   1723 static void
   1724 ModifyWord_Loop(Substring word, SepBuf *buf, void *data)
   1725 {
   1726 	const struct ModifyWord_LoopArgs *args;
   1727 	char *s;
   1728 
   1729 	if (Substring_IsEmpty(word))
   1730 		return;
   1731 
   1732 	args = data;
   1733 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   1734 	Var_SetWithFlags(args->scope, args->var, word.start,
   1735 	    VAR_SET_NO_EXPORT);
   1736 	(void)Var_Subst(args->body, args->scope, args->emode, &s);
   1737 	/* TODO: handle errors */
   1738 
   1739 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   1740 	DEBUG4(VAR, "ModifyWord_Loop: "
   1741 		    "in \"%s\", replace \"%s\" with \"%s\" to \"%s\"\n",
   1742 	    word.start, args->var, args->body, s);
   1743 
   1744 	if (s[0] == '\n' || Buf_EndsWith(&buf->buf, '\n'))
   1745 		buf->needSep = false;
   1746 	SepBuf_AddStr(buf, s);
   1747 	free(s);
   1748 }
   1749 
   1750 
   1751 /*
   1752  * The :[first..last] modifier selects words from the expression.
   1753  * It can also reverse the words.
   1754  */
   1755 static char *
   1756 VarSelectWords(const char *str, int first, int last,
   1757 	       char sep, bool oneBigWord)
   1758 {
   1759 	SubstringWords words;
   1760 	int len, start, end, step;
   1761 	int i;
   1762 
   1763 	SepBuf buf;
   1764 	SepBuf_Init(&buf, sep);
   1765 
   1766 	if (oneBigWord) {
   1767 		/* fake what Substring_Words() would do */
   1768 		words.len = 1;
   1769 		words.words = bmake_malloc(sizeof(words.words[0]));
   1770 		words.freeIt = NULL;
   1771 		words.words[0] = Substring_InitStr(str); /* no need to copy */
   1772 	} else {
   1773 		words = Substring_Words(str, false);
   1774 	}
   1775 
   1776 	/*
   1777 	 * Now sanitize the given range.  If first or last are negative,
   1778 	 * convert them to the positive equivalents (-1 gets converted to len,
   1779 	 * -2 gets converted to (len - 1), etc.).
   1780 	 */
   1781 	len = (int)words.len;
   1782 	if (first < 0)
   1783 		first += len + 1;
   1784 	if (last < 0)
   1785 		last += len + 1;
   1786 
   1787 	/* We avoid scanning more of the list than we need to. */
   1788 	if (first > last) {
   1789 		start = (first > len ? len : first) - 1;
   1790 		end = last < 1 ? 0 : last - 1;
   1791 		step = -1;
   1792 	} else {
   1793 		start = first < 1 ? 0 : first - 1;
   1794 		end = last > len ? len : last;
   1795 		step = 1;
   1796 	}
   1797 
   1798 	for (i = start; (step < 0) == (i >= end); i += step) {
   1799 		SepBuf_AddSubstring(&buf, words.words[i]);
   1800 		SepBuf_Sep(&buf);
   1801 	}
   1802 
   1803 	SubstringWords_Free(words);
   1804 
   1805 	return SepBuf_DoneData(&buf);
   1806 }
   1807 
   1808 
   1809 /*
   1810  * Callback for ModifyWords to implement the :tA modifier.
   1811  * Replace each word with the result of realpath() if successful.
   1812  */
   1813 /*ARGSUSED*/
   1814 static void
   1815 ModifyWord_Realpath(Substring word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   1816 {
   1817 	struct stat st;
   1818 	char rbuf[MAXPATHLEN];
   1819 	const char *rp;
   1820 
   1821 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   1822 	rp = cached_realpath(word.start, rbuf);
   1823 	if (rp != NULL && *rp == '/' && stat(rp, &st) == 0)
   1824 		SepBuf_AddStr(buf, rp);
   1825 	else
   1826 		SepBuf_AddSubstring(buf, word);
   1827 }
   1828 
   1829 
   1830 static char *
   1831 SubstringWords_JoinFree(SubstringWords words)
   1832 {
   1833 	Buffer buf;
   1834 	size_t i;
   1835 
   1836 	Buf_Init(&buf);
   1837 
   1838 	for (i = 0; i < words.len; i++) {
   1839 		if (i != 0) {
   1840 			/*
   1841 			 * XXX: Use ch->sep instead of ' ', for consistency.
   1842 			 */
   1843 			Buf_AddByte(&buf, ' ');
   1844 		}
   1845 		Buf_AddBytesBetween(&buf,
   1846 		    words.words[i].start, words.words[i].end);
   1847 	}
   1848 
   1849 	SubstringWords_Free(words);
   1850 
   1851 	return Buf_DoneData(&buf);
   1852 }
   1853 
   1854 
   1855 /*
   1856  * Quote shell meta-characters and space characters in the string.
   1857  * If quoteDollar is set, also quote and double any '$' characters.
   1858  */
   1859 static void
   1860 VarQuote(const char *str, bool quoteDollar, LazyBuf *buf)
   1861 {
   1862 	const char *p;
   1863 
   1864 	LazyBuf_Init(buf, str);
   1865 	for (p = str; *p != '\0'; p++) {
   1866 		if (*p == '\n') {
   1867 			const char *newline = Shell_GetNewline();
   1868 			if (newline == NULL)
   1869 				newline = "\\\n";
   1870 			LazyBuf_AddStr(buf, newline);
   1871 			continue;
   1872 		}
   1873 		if (ch_isspace(*p) || ch_is_shell_meta(*p))
   1874 			LazyBuf_Add(buf, '\\');
   1875 		LazyBuf_Add(buf, *p);
   1876 		if (quoteDollar && *p == '$')
   1877 			LazyBuf_AddStr(buf, "\\$");
   1878 	}
   1879 }
   1880 
   1881 /*
   1882  * Compute the 32-bit hash of the given string, using the MurmurHash3
   1883  * algorithm. Output is encoded as 8 hex digits, in Little Endian order.
   1884  */
   1885 static char *
   1886 VarHash(const char *str)
   1887 {
   1888 	static const char hexdigits[16] = "0123456789abcdef";
   1889 	const unsigned char *ustr = (const unsigned char *)str;
   1890 
   1891 	uint32_t h = 0x971e137bU;
   1892 	uint32_t c1 = 0x95543787U;
   1893 	uint32_t c2 = 0x2ad7eb25U;
   1894 	size_t len2 = strlen(str);
   1895 
   1896 	char *buf;
   1897 	size_t i;
   1898 
   1899 	size_t len;
   1900 	for (len = len2; len != 0;) {
   1901 		uint32_t k = 0;
   1902 		switch (len) {
   1903 		default:
   1904 			k = ((uint32_t)ustr[3] << 24) |
   1905 			    ((uint32_t)ustr[2] << 16) |
   1906 			    ((uint32_t)ustr[1] << 8) |
   1907 			    (uint32_t)ustr[0];
   1908 			len -= 4;
   1909 			ustr += 4;
   1910 			break;
   1911 		case 3:
   1912 			k |= (uint32_t)ustr[2] << 16;
   1913 			/* FALLTHROUGH */
   1914 		case 2:
   1915 			k |= (uint32_t)ustr[1] << 8;
   1916 			/* FALLTHROUGH */
   1917 		case 1:
   1918 			k |= (uint32_t)ustr[0];
   1919 			len = 0;
   1920 		}
   1921 		c1 = c1 * 5 + 0x7b7d159cU;
   1922 		c2 = c2 * 5 + 0x6bce6396U;
   1923 		k *= c1;
   1924 		k = (k << 11) ^ (k >> 21);
   1925 		k *= c2;
   1926 		h = (h << 13) ^ (h >> 19);
   1927 		h = h * 5 + 0x52dce729U;
   1928 		h ^= k;
   1929 	}
   1930 	h ^= (uint32_t)len2;
   1931 	h *= 0x85ebca6b;
   1932 	h ^= h >> 13;
   1933 	h *= 0xc2b2ae35;
   1934 	h ^= h >> 16;
   1935 
   1936 	buf = bmake_malloc(9);
   1937 	for (i = 0; i < 8; i++) {
   1938 		buf[i] = hexdigits[h & 0x0f];
   1939 		h >>= 4;
   1940 	}
   1941 	buf[8] = '\0';
   1942 	return buf;
   1943 }
   1944 
   1945 static char *
   1946 VarStrftime(const char *fmt, time_t t, bool gmt)
   1947 {
   1948 	char buf[BUFSIZ];
   1949 
   1950 	if (t == 0)
   1951 		time(&t);
   1952 	if (*fmt == '\0')
   1953 		fmt = "%c";
   1954 	strftime(buf, sizeof buf, fmt, gmt ? gmtime(&t) : localtime(&t));
   1955 
   1956 	buf[sizeof buf - 1] = '\0';
   1957 	return bmake_strdup(buf);
   1958 }
   1959 
   1960 /*
   1961  * The ApplyModifier functions take an expression that is being evaluated.
   1962  * Their task is to apply a single modifier to the expression.  This involves
   1963  * parsing the modifier, evaluating it and finally updating the value of the
   1964  * expression.
   1965  *
   1966  * Parsing the modifier
   1967  *
   1968  * If parsing succeeds, the parsing position *pp is updated to point to the
   1969  * first character following the modifier, which typically is either ':' or
   1970  * ch->endc.  The modifier doesn't have to check for this delimiter character,
   1971  * this is done by ApplyModifiers.
   1972  *
   1973  * XXX: As of 2020-11-15, some modifiers such as :S, :C, :P, :L do not
   1974  * need to be followed by a ':' or endc; this was an unintended mistake.
   1975  *
   1976  * If parsing fails because of a missing delimiter (as in the :S, :C or :@
   1977  * modifiers), return AMR_CLEANUP.
   1978  *
   1979  * If parsing fails because the modifier is unknown, return AMR_UNKNOWN to
   1980  * try the SysV modifier ${VAR:from=to} as fallback.  This should only be
   1981  * done as long as there have been no side effects from evaluating nested
   1982  * variables, to avoid evaluating them more than once.  In this case, the
   1983  * parsing position may or may not be updated.  (XXX: Why not? The original
   1984  * parsing position is well-known in ApplyModifiers.)
   1985  *
   1986  * If parsing fails and the SysV modifier ${VAR:from=to} should not be used
   1987  * as a fallback, either issue an error message using Error or Parse_Error
   1988  * and then return AMR_CLEANUP, or return AMR_BAD for the default error
   1989  * message.  Both of these return values will stop processing the variable
   1990  * expression.  (XXX: As of 2020-08-23, evaluation of the whole string
   1991  * continues nevertheless after skipping a few bytes, which essentially is
   1992  * undefined behavior.  Not in the sense of C, but still the resulting string
   1993  * is garbage.)
   1994  *
   1995  * Evaluating the modifier
   1996  *
   1997  * After parsing, the modifier is evaluated.  The side effects from evaluating
   1998  * nested variable expressions in the modifier text often already happen
   1999  * during parsing though.  For most modifiers this doesn't matter since their
   2000  * only noticeable effect is that they update the value of the expression.
   2001  * Some modifiers such as ':sh' or '::=' have noticeable side effects though.
   2002  *
   2003  * Evaluating the modifier usually takes the current value of the variable
   2004  * expression from ch->expr->value, or the variable name from ch->var->name
   2005  * and stores the result back in expr->value via Expr_SetValueOwn or
   2006  * Expr_SetValueRefer.
   2007  *
   2008  * If evaluating fails (as of 2020-08-23), an error message is printed using
   2009  * Error.  This function has no side-effects, it really just prints the error
   2010  * message.  Processing the expression continues as if everything were ok.
   2011  * XXX: This should be fixed by adding proper error handling to Var_Subst,
   2012  * Var_Parse, ApplyModifiers and ModifyWords.
   2013  *
   2014  * Housekeeping
   2015  *
   2016  * Some modifiers such as :D and :U turn undefined expressions into defined
   2017  * expressions (see Expr_Define).
   2018  *
   2019  * Some modifiers need to free some memory.
   2020  */
   2021 
   2022 typedef enum ExprDefined {
   2023 	/* The variable expression is based on a regular, defined variable. */
   2024 	DEF_REGULAR,
   2025 	/* The variable expression is based on an undefined variable. */
   2026 	DEF_UNDEF,
   2027 	/*
   2028 	 * The variable expression started as an undefined expression, but one
   2029 	 * of the modifiers (such as ':D' or ':U') has turned the expression
   2030 	 * from undefined to defined.
   2031 	 */
   2032 	DEF_DEFINED
   2033 } ExprDefined;
   2034 
   2035 static const char ExprDefined_Name[][10] = {
   2036 	"regular",
   2037 	"undefined",
   2038 	"defined"
   2039 };
   2040 
   2041 #if __STDC_VERSION__ >= 199901L
   2042 #define const_member		const
   2043 #else
   2044 #define const_member		/* no const possible */
   2045 #endif
   2046 
   2047 /* An expression based on a variable, such as $@ or ${VAR:Mpattern:Q}. */
   2048 typedef struct Expr {
   2049 	const char *name;
   2050 	FStr value;
   2051 	VarEvalMode const_member emode;
   2052 	GNode *const_member scope;
   2053 	ExprDefined defined;
   2054 } Expr;
   2055 
   2056 /*
   2057  * The status of applying a chain of modifiers to an expression.
   2058  *
   2059  * The modifiers of an expression are broken into chains of modifiers,
   2060  * starting a new nested chain whenever an indirect modifier starts.  There
   2061  * are at most 2 nesting levels: the outer one for the direct modifiers, and
   2062  * the inner one for the indirect modifiers.
   2063  *
   2064  * For example, the expression ${VAR:M*:${IND1}:${IND2}:O:u} has 3 chains of
   2065  * modifiers:
   2066  *
   2067  *	Chain 1 starts with the single modifier ':M*'.
   2068  *	  Chain 2 starts with all modifiers from ${IND1}.
   2069  *	  Chain 2 ends at the ':' between ${IND1} and ${IND2}.
   2070  *	  Chain 3 starts with all modifiers from ${IND2}.
   2071  *	  Chain 3 ends at the ':' after ${IND2}.
   2072  *	Chain 1 continues with the 2 modifiers ':O' and ':u'.
   2073  *	Chain 1 ends at the final '}' of the expression.
   2074  *
   2075  * After such a chain ends, its properties no longer have any effect.
   2076  *
   2077  * It may or may not have been intended that 'defined' has scope Expr while
   2078  * 'sep' and 'oneBigWord' have smaller scope.
   2079  *
   2080  * See varmod-indirect.mk.
   2081  */
   2082 typedef struct ModChain {
   2083 	Expr *expr;
   2084 	/* '\0' or '{' or '(' */
   2085 	char const_member startc;
   2086 	/* '\0' or '}' or ')' */
   2087 	char const_member endc;
   2088 	/* Word separator in expansions (see the :ts modifier). */
   2089 	char sep;
   2090 	/*
   2091 	 * True if some modifiers that otherwise split the variable value
   2092 	 * into words, like :S and :C, treat the variable value as a single
   2093 	 * big word, possibly containing spaces.
   2094 	 */
   2095 	bool oneBigWord;
   2096 } ModChain;
   2097 
   2098 static void
   2099 Expr_Define(Expr *expr)
   2100 {
   2101 	if (expr->defined == DEF_UNDEF)
   2102 		expr->defined = DEF_DEFINED;
   2103 }
   2104 
   2105 static const char *
   2106 Expr_Str(const Expr *expr)
   2107 {
   2108 	return expr->value.str;
   2109 }
   2110 
   2111 static SubstringWords
   2112 Expr_Words(const Expr *expr)
   2113 {
   2114 	return Substring_Words(Expr_Str(expr), false);
   2115 }
   2116 
   2117 static void
   2118 Expr_SetValue(Expr *expr, FStr value)
   2119 {
   2120 	FStr_Done(&expr->value);
   2121 	expr->value = value;
   2122 }
   2123 
   2124 static void
   2125 Expr_SetValueOwn(Expr *expr, char *value)
   2126 {
   2127 	Expr_SetValue(expr, FStr_InitOwn(value));
   2128 }
   2129 
   2130 static void
   2131 Expr_SetValueRefer(Expr *expr, const char *value)
   2132 {
   2133 	Expr_SetValue(expr, FStr_InitRefer(value));
   2134 }
   2135 
   2136 static bool
   2137 Expr_ShouldEval(const Expr *expr)
   2138 {
   2139 	return VarEvalMode_ShouldEval(expr->emode);
   2140 }
   2141 
   2142 static bool
   2143 ModChain_ShouldEval(const ModChain *ch)
   2144 {
   2145 	return Expr_ShouldEval(ch->expr);
   2146 }
   2147 
   2148 
   2149 typedef enum ApplyModifierResult {
   2150 	/* Continue parsing */
   2151 	AMR_OK,
   2152 	/* Not a match, try other modifiers as well. */
   2153 	AMR_UNKNOWN,
   2154 	/* Error out with "Bad modifier" message. */
   2155 	AMR_BAD,
   2156 	/* Error out without the standard error message. */
   2157 	AMR_CLEANUP
   2158 } ApplyModifierResult;
   2159 
   2160 /*
   2161  * Allow backslashes to escape the delimiter, $, and \, but don't touch other
   2162  * backslashes.
   2163  */
   2164 static bool
   2165 IsEscapedModifierPart(const char *p, char delim,
   2166 		      struct ModifyWord_SubstArgs *subst)
   2167 {
   2168 	if (p[0] != '\\')
   2169 		return false;
   2170 	if (p[1] == delim || p[1] == '\\' || p[1] == '$')
   2171 		return true;
   2172 	return p[1] == '&' && subst != NULL;
   2173 }
   2174 
   2175 /*
   2176  * In a part of a modifier, parse a subexpression and evaluate it.
   2177  */
   2178 static void
   2179 ParseModifierPartExpr(const char **pp, LazyBuf *part, const ModChain *ch,
   2180 		      VarEvalMode emode)
   2181 {
   2182 	const char *p = *pp;
   2183 	FStr nested_val;
   2184 
   2185 	(void)Var_Parse(&p, ch->expr->scope,
   2186 	    VarEvalMode_WithoutKeepDollar(emode), &nested_val);
   2187 	/* TODO: handle errors */
   2188 	LazyBuf_AddStr(part, nested_val.str);
   2189 	FStr_Done(&nested_val);
   2190 	*pp = p;
   2191 }
   2192 
   2193 /*
   2194  * In a part of a modifier, parse a subexpression but don't evaluate it.
   2195  *
   2196  * XXX: This whole block is very similar to Var_Parse with VARE_PARSE_ONLY.
   2197  * There may be subtle edge cases though that are not yet covered in the unit
   2198  * tests and that are parsed differently, depending on whether they are
   2199  * evaluated or not.
   2200  *
   2201  * This subtle difference is not documented in the manual page, neither is
   2202  * the difference between parsing ':D' and ':M' documented.  No code should
   2203  * ever depend on these details, but who knows.
   2204  */
   2205 static void
   2206 ParseModifierPartDollar(const char **pp, LazyBuf *part)
   2207 {
   2208 	const char *p = *pp;
   2209 	const char *start = *pp;
   2210 
   2211 	if (p[1] == '(' || p[1] == '{') {
   2212 		char startc = p[1];
   2213 		int endc = startc == '(' ? ')' : '}';
   2214 		int depth = 1;
   2215 
   2216 		for (p += 2; *p != '\0' && depth > 0; p++) {
   2217 			if (p[-1] != '\\') {
   2218 				if (*p == startc)
   2219 					depth++;
   2220 				if (*p == endc)
   2221 					depth--;
   2222 			}
   2223 		}
   2224 		LazyBuf_AddBytesBetween(part, start, p);
   2225 		*pp = p;
   2226 	} else {
   2227 		LazyBuf_Add(part, *start);
   2228 		*pp = p + 1;
   2229 	}
   2230 }
   2231 
   2232 /* See ParseModifierPart for the documentation. */
   2233 static VarParseResult
   2234 ParseModifierPartSubst(
   2235     const char **pp,
   2236     char delim,
   2237     VarEvalMode emode,
   2238     ModChain *ch,
   2239     LazyBuf *part,
   2240     /*
   2241      * For the first part of the modifier ':S', set anchorEnd if the last
   2242      * character of the pattern is a $.
   2243      */
   2244     PatternFlags *out_pflags,
   2245     /*
   2246      * For the second part of the :S modifier, allow ampersands to be escaped
   2247      * and replace unescaped ampersands with subst->lhs.
   2248      */
   2249     struct ModifyWord_SubstArgs *subst
   2250 )
   2251 {
   2252 	const char *p;
   2253 
   2254 	p = *pp;
   2255 	LazyBuf_Init(part, p);
   2256 
   2257 	while (*p != '\0' && *p != delim) {
   2258 		if (IsEscapedModifierPart(p, delim, subst)) {
   2259 			LazyBuf_Add(part, p[1]);
   2260 			p += 2;
   2261 		} else if (*p != '$') {	/* Unescaped, simple text */
   2262 			if (subst != NULL && *p == '&')
   2263 				LazyBuf_AddSubstring(part, subst->lhs);
   2264 			else
   2265 				LazyBuf_Add(part, *p);
   2266 			p++;
   2267 		} else if (p[1] == delim) {	/* Unescaped '$' at end */
   2268 			if (out_pflags != NULL)
   2269 				out_pflags->anchorEnd = true;
   2270 			else
   2271 				LazyBuf_Add(part, *p);
   2272 			p++;
   2273 		} else if (VarEvalMode_ShouldEval(emode))
   2274 			ParseModifierPartExpr(&p, part, ch, emode);
   2275 		else
   2276 			ParseModifierPartDollar(&p, part);
   2277 	}
   2278 
   2279 	if (*p != delim) {
   2280 		*pp = p;
   2281 		Error("Unfinished modifier for \"%s\" ('%c' missing)",
   2282 		    ch->expr->name, delim);
   2283 		LazyBuf_Done(part);
   2284 		return VPR_ERR;
   2285 	}
   2286 
   2287 	*pp = p + 1;
   2288 
   2289 	{
   2290 		Substring sub = LazyBuf_Get(part);
   2291 		DEBUG2(VAR, "Modifier part: \"%.*s\"\n",
   2292 		    (int)Substring_Length(sub), sub.start);
   2293 	}
   2294 
   2295 	return VPR_OK;
   2296 }
   2297 
   2298 /*
   2299  * Parse a part of a modifier such as the "from" and "to" in :S/from/to/ or
   2300  * the "var" or "replacement ${var}" in :@var@replacement ${var}@, up to and
   2301  * including the next unescaped delimiter.  The delimiter, as well as the
   2302  * backslash or the dollar, can be escaped with a backslash.
   2303  *
   2304  * Return VPR_OK if parsing succeeded, together with the parsed (and possibly
   2305  * expanded) part.  In that case, pp points right after the delimiter.  The
   2306  * delimiter is not included in the part though.
   2307  */
   2308 static VarParseResult
   2309 ParseModifierPart(
   2310     /* The parsing position, updated upon return */
   2311     const char **pp,
   2312     /* Parsing stops at this delimiter */
   2313     char delim,
   2314     /* Mode for evaluating nested variables. */
   2315     VarEvalMode emode,
   2316     ModChain *ch,
   2317     LazyBuf *part
   2318 )
   2319 {
   2320 	return ParseModifierPartSubst(pp, delim, emode, ch, part, NULL, NULL);
   2321 }
   2322 
   2323 MAKE_INLINE bool
   2324 IsDelimiter(char c, const ModChain *ch)
   2325 {
   2326 	return c == ':' || c == ch->endc;
   2327 }
   2328 
   2329 /* Test whether mod starts with modname, followed by a delimiter. */
   2330 MAKE_INLINE bool
   2331 ModMatch(const char *mod, const char *modname, const ModChain *ch)
   2332 {
   2333 	size_t n = strlen(modname);
   2334 	return strncmp(mod, modname, n) == 0 && IsDelimiter(mod[n], ch);
   2335 }
   2336 
   2337 /* Test whether mod starts with modname, followed by a delimiter or '='. */
   2338 MAKE_INLINE bool
   2339 ModMatchEq(const char *mod, const char *modname, const ModChain *ch)
   2340 {
   2341 	size_t n = strlen(modname);
   2342 	return strncmp(mod, modname, n) == 0 &&
   2343 	       (IsDelimiter(mod[n], ch) || mod[n] == '=');
   2344 }
   2345 
   2346 static bool
   2347 TryParseIntBase0(const char **pp, int *out_num)
   2348 {
   2349 	char *end;
   2350 	long n;
   2351 
   2352 	errno = 0;
   2353 	n = strtol(*pp, &end, 0);
   2354 
   2355 	if (end == *pp)
   2356 		return false;
   2357 	if ((n == LONG_MIN || n == LONG_MAX) && errno == ERANGE)
   2358 		return false;
   2359 	if (n < INT_MIN || n > INT_MAX)
   2360 		return false;
   2361 
   2362 	*pp = end;
   2363 	*out_num = (int)n;
   2364 	return true;
   2365 }
   2366 
   2367 static bool
   2368 TryParseSize(const char **pp, size_t *out_num)
   2369 {
   2370 	char *end;
   2371 	unsigned long n;
   2372 
   2373 	if (!ch_isdigit(**pp))
   2374 		return false;
   2375 
   2376 	errno = 0;
   2377 	n = strtoul(*pp, &end, 10);
   2378 	if (n == ULONG_MAX && errno == ERANGE)
   2379 		return false;
   2380 	if (n > SIZE_MAX)
   2381 		return false;
   2382 
   2383 	*pp = end;
   2384 	*out_num = (size_t)n;
   2385 	return true;
   2386 }
   2387 
   2388 static bool
   2389 TryParseChar(const char **pp, int base, char *out_ch)
   2390 {
   2391 	char *end;
   2392 	unsigned long n;
   2393 
   2394 	if (!ch_isalnum(**pp))
   2395 		return false;
   2396 
   2397 	errno = 0;
   2398 	n = strtoul(*pp, &end, base);
   2399 	if (n == ULONG_MAX && errno == ERANGE)
   2400 		return false;
   2401 	if (n > UCHAR_MAX)
   2402 		return false;
   2403 
   2404 	*pp = end;
   2405 	*out_ch = (char)n;
   2406 	return true;
   2407 }
   2408 
   2409 /*
   2410  * Modify each word of the expression using the given function and place the
   2411  * result back in the expression.
   2412  */
   2413 static void
   2414 ModifyWords(ModChain *ch,
   2415 	    ModifyWordProc modifyWord, void *modifyWord_args,
   2416 	    bool oneBigWord)
   2417 {
   2418 	Expr *expr = ch->expr;
   2419 	const char *val = Expr_Str(expr);
   2420 	SepBuf result;
   2421 	SubstringWords words;
   2422 	size_t i;
   2423 	Substring word;
   2424 
   2425 	if (oneBigWord) {
   2426 		SepBuf_Init(&result, ch->sep);
   2427 		/* XXX: performance: Substring_InitStr calls strlen */
   2428 		word = Substring_InitStr(val);
   2429 		modifyWord(word, &result, modifyWord_args);
   2430 		goto done;
   2431 	}
   2432 
   2433 	words = Substring_Words(val, false);
   2434 
   2435 	DEBUG3(VAR, "ModifyWords: split \"%s\" into %u %s\n",
   2436 	    val, (unsigned)words.len, words.len != 1 ? "words" : "word");
   2437 
   2438 	SepBuf_Init(&result, ch->sep);
   2439 	for (i = 0; i < words.len; i++) {
   2440 		modifyWord(words.words[i], &result, modifyWord_args);
   2441 		if (result.buf.len > 0)
   2442 			SepBuf_Sep(&result);
   2443 	}
   2444 
   2445 	SubstringWords_Free(words);
   2446 
   2447 done:
   2448 	Expr_SetValueOwn(expr, SepBuf_DoneData(&result));
   2449 }
   2450 
   2451 /* :@var (at) ...${var}...@ */
   2452 static ApplyModifierResult
   2453 ApplyModifier_Loop(const char **pp, ModChain *ch)
   2454 {
   2455 	Expr *expr = ch->expr;
   2456 	struct ModifyWord_LoopArgs args;
   2457 	char prev_sep;
   2458 	VarParseResult res;
   2459 	LazyBuf tvarBuf, strBuf;
   2460 	FStr tvar, str;
   2461 
   2462 	args.scope = expr->scope;
   2463 
   2464 	(*pp)++;		/* Skip the first '@' */
   2465 	res = ParseModifierPart(pp, '@', VARE_PARSE_ONLY, ch, &tvarBuf);
   2466 	if (res != VPR_OK)
   2467 		return AMR_CLEANUP;
   2468 	tvar = LazyBuf_DoneGet(&tvarBuf);
   2469 	args.var = tvar.str;
   2470 	if (strchr(args.var, '$') != NULL) {
   2471 		Parse_Error(PARSE_FATAL,
   2472 		    "In the :@ modifier of \"%s\", the variable name \"%s\" "
   2473 		    "must not contain a dollar",
   2474 		    expr->name, args.var);
   2475 		return AMR_CLEANUP;
   2476 	}
   2477 
   2478 	res = ParseModifierPart(pp, '@', VARE_PARSE_ONLY, ch, &strBuf);
   2479 	if (res != VPR_OK)
   2480 		return AMR_CLEANUP;
   2481 	str = LazyBuf_DoneGet(&strBuf);
   2482 	args.body = str.str;
   2483 
   2484 	if (!Expr_ShouldEval(expr))
   2485 		goto done;
   2486 
   2487 	args.emode = VarEvalMode_WithoutKeepDollar(expr->emode);
   2488 	prev_sep = ch->sep;
   2489 	ch->sep = ' ';		/* XXX: should be ch->sep for consistency */
   2490 	ModifyWords(ch, ModifyWord_Loop, &args, ch->oneBigWord);
   2491 	ch->sep = prev_sep;
   2492 	/* XXX: Consider restoring the previous value instead of deleting. */
   2493 	Var_Delete(expr->scope, args.var);
   2494 
   2495 done:
   2496 	FStr_Done(&tvar);
   2497 	FStr_Done(&str);
   2498 	return AMR_OK;
   2499 }
   2500 
   2501 /* :Ddefined or :Uundefined */
   2502 static ApplyModifierResult
   2503 ApplyModifier_Defined(const char **pp, ModChain *ch)
   2504 {
   2505 	Expr *expr = ch->expr;
   2506 	LazyBuf buf;
   2507 	const char *p;
   2508 
   2509 	VarEvalMode emode = VARE_PARSE_ONLY;
   2510 	if (Expr_ShouldEval(expr))
   2511 		if ((**pp == 'D') == (expr->defined == DEF_REGULAR))
   2512 			emode = expr->emode;
   2513 
   2514 	p = *pp + 1;
   2515 	LazyBuf_Init(&buf, p);
   2516 	while (!IsDelimiter(*p, ch) && *p != '\0') {
   2517 
   2518 		/*
   2519 		 * XXX: This code is similar to the one in Var_Parse. See if
   2520 		 * the code can be merged. See also ApplyModifier_Match and
   2521 		 * ParseModifierPart.
   2522 		 */
   2523 
   2524 		/* Escaped delimiter or other special character */
   2525 		/* See Buf_AddEscaped in for.c. */
   2526 		if (*p == '\\') {
   2527 			char c = p[1];
   2528 			if (IsDelimiter(c, ch) || c == '$' || c == '\\') {
   2529 				LazyBuf_Add(&buf, c);
   2530 				p += 2;
   2531 				continue;
   2532 			}
   2533 		}
   2534 
   2535 		/* Nested variable expression */
   2536 		if (*p == '$') {
   2537 			FStr nested_val;
   2538 
   2539 			(void)Var_Parse(&p, expr->scope, emode, &nested_val);
   2540 			/* TODO: handle errors */
   2541 			if (Expr_ShouldEval(expr))
   2542 				LazyBuf_AddStr(&buf, nested_val.str);
   2543 			FStr_Done(&nested_val);
   2544 			continue;
   2545 		}
   2546 
   2547 		/* Ordinary text */
   2548 		LazyBuf_Add(&buf, *p);
   2549 		p++;
   2550 	}
   2551 	*pp = p;
   2552 
   2553 	Expr_Define(expr);
   2554 
   2555 	if (VarEvalMode_ShouldEval(emode))
   2556 		Expr_SetValue(expr, Substring_Str(LazyBuf_Get(&buf)));
   2557 	else
   2558 		LazyBuf_Done(&buf);
   2559 
   2560 	return AMR_OK;
   2561 }
   2562 
   2563 /* :L */
   2564 static ApplyModifierResult
   2565 ApplyModifier_Literal(const char **pp, ModChain *ch)
   2566 {
   2567 	Expr *expr = ch->expr;
   2568 
   2569 	(*pp)++;
   2570 
   2571 	if (Expr_ShouldEval(expr)) {
   2572 		Expr_Define(expr);
   2573 		Expr_SetValueOwn(expr, bmake_strdup(expr->name));
   2574 	}
   2575 
   2576 	return AMR_OK;
   2577 }
   2578 
   2579 static bool
   2580 TryParseTime(const char **pp, time_t *out_time)
   2581 {
   2582 	char *end;
   2583 	unsigned long n;
   2584 
   2585 	if (!ch_isdigit(**pp))
   2586 		return false;
   2587 
   2588 	errno = 0;
   2589 	n = strtoul(*pp, &end, 10);
   2590 	if (n == ULONG_MAX && errno == ERANGE)
   2591 		return false;
   2592 
   2593 	*pp = end;
   2594 	*out_time = (time_t)n;	/* ignore possible truncation for now */
   2595 	return true;
   2596 }
   2597 
   2598 /* :gmtime and :localtime */
   2599 static ApplyModifierResult
   2600 ApplyModifier_Time(const char **pp, ModChain *ch)
   2601 {
   2602 	Expr *expr;
   2603 	time_t t;
   2604 	const char *args;
   2605 	const char *mod = *pp;
   2606 	bool gmt = mod[0] == 'g';
   2607 
   2608 	if (!ModMatchEq(mod, gmt ? "gmtime" : "localtime", ch))
   2609 		return AMR_UNKNOWN;
   2610 	args = mod + (gmt ? 6 : 9);
   2611 
   2612 	if (args[0] == '=') {
   2613 		const char *p = args + 1;
   2614 		if (!TryParseTime(&p, &t)) {
   2615 			Parse_Error(PARSE_FATAL,
   2616 			    "Invalid time value at \"%s\"", p);
   2617 			return AMR_CLEANUP;
   2618 		}
   2619 		*pp = p;
   2620 	} else {
   2621 		t = 0;
   2622 		*pp = args;
   2623 	}
   2624 
   2625 	expr = ch->expr;
   2626 	if (Expr_ShouldEval(expr))
   2627 		Expr_SetValueOwn(expr, VarStrftime(Expr_Str(expr), t, gmt));
   2628 
   2629 	return AMR_OK;
   2630 }
   2631 
   2632 /* :hash */
   2633 static ApplyModifierResult
   2634 ApplyModifier_Hash(const char **pp, ModChain *ch)
   2635 {
   2636 	if (!ModMatch(*pp, "hash", ch))
   2637 		return AMR_UNKNOWN;
   2638 	*pp += 4;
   2639 
   2640 	if (ModChain_ShouldEval(ch))
   2641 		Expr_SetValueOwn(ch->expr, VarHash(Expr_Str(ch->expr)));
   2642 
   2643 	return AMR_OK;
   2644 }
   2645 
   2646 /* :P */
   2647 static ApplyModifierResult
   2648 ApplyModifier_Path(const char **pp, ModChain *ch)
   2649 {
   2650 	Expr *expr = ch->expr;
   2651 	GNode *gn;
   2652 	char *path;
   2653 
   2654 	(*pp)++;
   2655 
   2656 	if (!Expr_ShouldEval(expr))
   2657 		return AMR_OK;
   2658 
   2659 	Expr_Define(expr);
   2660 
   2661 	gn = Targ_FindNode(expr->name);
   2662 	if (gn == NULL || gn->type & OP_NOPATH) {
   2663 		path = NULL;
   2664 	} else if (gn->path != NULL) {
   2665 		path = bmake_strdup(gn->path);
   2666 	} else {
   2667 		SearchPath *searchPath = Suff_FindPath(gn);
   2668 		path = Dir_FindFile(expr->name, searchPath);
   2669 	}
   2670 	if (path == NULL)
   2671 		path = bmake_strdup(expr->name);
   2672 	Expr_SetValueOwn(expr, path);
   2673 
   2674 	return AMR_OK;
   2675 }
   2676 
   2677 /* :!cmd! */
   2678 static ApplyModifierResult
   2679 ApplyModifier_ShellCommand(const char **pp, ModChain *ch)
   2680 {
   2681 	Expr *expr = ch->expr;
   2682 	VarParseResult res;
   2683 	LazyBuf cmdBuf;
   2684 	FStr cmd;
   2685 
   2686 	(*pp)++;
   2687 	res = ParseModifierPart(pp, '!', expr->emode, ch, &cmdBuf);
   2688 	if (res != VPR_OK)
   2689 		return AMR_CLEANUP;
   2690 	cmd = LazyBuf_DoneGet(&cmdBuf);
   2691 
   2692 	if (Expr_ShouldEval(expr)) {
   2693 		char *output, *error;
   2694 		output = Cmd_Exec(cmd.str, &error);
   2695 		Expr_SetValueOwn(expr, output);
   2696 		if (error != NULL) {
   2697 			/* XXX: why still return AMR_OK? */
   2698 			Error("%s", error);
   2699 			free(error);
   2700 		}
   2701 	} else
   2702 		Expr_SetValueRefer(expr, "");
   2703 
   2704 	FStr_Done(&cmd);
   2705 	Expr_Define(expr);
   2706 
   2707 	return AMR_OK;
   2708 }
   2709 
   2710 /*
   2711  * The :range modifier generates an integer sequence as long as the words.
   2712  * The :range=7 modifier generates an integer sequence from 1 to 7.
   2713  */
   2714 static ApplyModifierResult
   2715 ApplyModifier_Range(const char **pp, ModChain *ch)
   2716 {
   2717 	size_t n;
   2718 	Buffer buf;
   2719 	size_t i;
   2720 
   2721 	const char *mod = *pp;
   2722 	if (!ModMatchEq(mod, "range", ch))
   2723 		return AMR_UNKNOWN;
   2724 
   2725 	if (mod[5] == '=') {
   2726 		const char *p = mod + 6;
   2727 		if (!TryParseSize(&p, &n)) {
   2728 			Parse_Error(PARSE_FATAL,
   2729 			    "Invalid number \"%s\" for ':range' modifier",
   2730 			    mod + 6);
   2731 			return AMR_CLEANUP;
   2732 		}
   2733 		*pp = p;
   2734 	} else {
   2735 		n = 0;
   2736 		*pp = mod + 5;
   2737 	}
   2738 
   2739 	if (!ModChain_ShouldEval(ch))
   2740 		return AMR_OK;
   2741 
   2742 	if (n == 0) {
   2743 		SubstringWords words = Expr_Words(ch->expr);
   2744 		n = words.len;
   2745 		SubstringWords_Free(words);
   2746 	}
   2747 
   2748 	Buf_Init(&buf);
   2749 
   2750 	for (i = 0; i < n; i++) {
   2751 		if (i != 0) {
   2752 			/*
   2753 			 * XXX: Use ch->sep instead of ' ', for consistency.
   2754 			 */
   2755 			Buf_AddByte(&buf, ' ');
   2756 		}
   2757 		Buf_AddInt(&buf, 1 + (int)i);
   2758 	}
   2759 
   2760 	Expr_SetValueOwn(ch->expr, Buf_DoneData(&buf));
   2761 	return AMR_OK;
   2762 }
   2763 
   2764 /* Parse a ':M' or ':N' modifier. */
   2765 static void
   2766 ParseModifier_Match(const char **pp, const ModChain *ch,
   2767 		    char **out_pattern)
   2768 {
   2769 	const char *mod = *pp;
   2770 	Expr *expr = ch->expr;
   2771 	bool copy = false;	/* pattern should be, or has been, copied */
   2772 	bool needSubst = false;
   2773 	const char *endpat;
   2774 	char *pattern;
   2775 
   2776 	/*
   2777 	 * In the loop below, ignore ':' unless we are at (or back to) the
   2778 	 * original brace level.
   2779 	 * XXX: This will likely not work right if $() and ${} are intermixed.
   2780 	 */
   2781 	/*
   2782 	 * XXX: This code is similar to the one in Var_Parse.
   2783 	 * See if the code can be merged.
   2784 	 * See also ApplyModifier_Defined.
   2785 	 */
   2786 	int nest = 0;
   2787 	const char *p;
   2788 	for (p = mod + 1; *p != '\0' && !(*p == ':' && nest == 0); p++) {
   2789 		if (*p == '\\' &&
   2790 		    (IsDelimiter(p[1], ch) || p[1] == ch->startc)) {
   2791 			if (!needSubst)
   2792 				copy = true;
   2793 			p++;
   2794 			continue;
   2795 		}
   2796 		if (*p == '$')
   2797 			needSubst = true;
   2798 		if (*p == '(' || *p == '{')
   2799 			nest++;
   2800 		if (*p == ')' || *p == '}') {
   2801 			nest--;
   2802 			if (nest < 0)
   2803 				break;
   2804 		}
   2805 	}
   2806 	*pp = p;
   2807 	endpat = p;
   2808 
   2809 	if (copy) {
   2810 		char *dst;
   2811 		const char *src;
   2812 
   2813 		/* Compress the \:'s out of the pattern. */
   2814 		pattern = bmake_malloc((size_t)(endpat - (mod + 1)) + 1);
   2815 		dst = pattern;
   2816 		src = mod + 1;
   2817 		for (; src < endpat; src++, dst++) {
   2818 			if (src[0] == '\\' && src + 1 < endpat &&
   2819 			    /* XXX: ch->startc is missing here; see above */
   2820 			    IsDelimiter(src[1], ch))
   2821 				src++;
   2822 			*dst = *src;
   2823 		}
   2824 		*dst = '\0';
   2825 	} else {
   2826 		pattern = bmake_strsedup(mod + 1, endpat);
   2827 	}
   2828 
   2829 	if (needSubst) {
   2830 		char *old_pattern = pattern;
   2831 		(void)Var_Subst(pattern, expr->scope, expr->emode, &pattern);
   2832 		/* TODO: handle errors */
   2833 		free(old_pattern);
   2834 	}
   2835 
   2836 	DEBUG2(VAR, "Pattern for ':%c' is \"%s\"\n", mod[0], pattern);
   2837 
   2838 	*out_pattern = pattern;
   2839 }
   2840 
   2841 /* :Mpattern or :Npattern */
   2842 static ApplyModifierResult
   2843 ApplyModifier_Match(const char **pp, ModChain *ch)
   2844 {
   2845 	char mod = **pp;
   2846 	char *pattern;
   2847 
   2848 	ParseModifier_Match(pp, ch, &pattern);
   2849 
   2850 	if (ModChain_ShouldEval(ch)) {
   2851 		ModifyWordProc modifyWord =
   2852 		    mod == 'M' ? ModifyWord_Match : ModifyWord_NoMatch;
   2853 		ModifyWords(ch, modifyWord, pattern, ch->oneBigWord);
   2854 	}
   2855 
   2856 	free(pattern);
   2857 	return AMR_OK;
   2858 }
   2859 
   2860 static void
   2861 ParsePatternFlags(const char **pp, PatternFlags *pflags, bool *oneBigWord)
   2862 {
   2863 	for (;; (*pp)++) {
   2864 		if (**pp == 'g')
   2865 			pflags->subGlobal = true;
   2866 		else if (**pp == '1')
   2867 			pflags->subOnce = true;
   2868 		else if (**pp == 'W')
   2869 			*oneBigWord = true;
   2870 		else
   2871 			break;
   2872 	}
   2873 }
   2874 
   2875 MAKE_INLINE PatternFlags
   2876 PatternFlags_None(void)
   2877 {
   2878 	PatternFlags pflags = { false, false, false, false };
   2879 	return pflags;
   2880 }
   2881 
   2882 /* :S,from,to, */
   2883 static ApplyModifierResult
   2884 ApplyModifier_Subst(const char **pp, ModChain *ch)
   2885 {
   2886 	struct ModifyWord_SubstArgs args;
   2887 	bool oneBigWord;
   2888 	VarParseResult res;
   2889 	LazyBuf lhsBuf, rhsBuf;
   2890 
   2891 	char delim = (*pp)[1];
   2892 	if (delim == '\0') {
   2893 		Error("Missing delimiter for modifier ':S'");
   2894 		(*pp)++;
   2895 		return AMR_CLEANUP;
   2896 	}
   2897 
   2898 	*pp += 2;
   2899 
   2900 	args.pflags = PatternFlags_None();
   2901 	args.matched = false;
   2902 
   2903 	if (**pp == '^') {
   2904 		args.pflags.anchorStart = true;
   2905 		(*pp)++;
   2906 	}
   2907 
   2908 	res = ParseModifierPartSubst(pp, delim, ch->expr->emode, ch, &lhsBuf,
   2909 	    &args.pflags, NULL);
   2910 	if (res != VPR_OK)
   2911 		return AMR_CLEANUP;
   2912 	args.lhs = LazyBuf_Get(&lhsBuf);
   2913 
   2914 	res = ParseModifierPartSubst(pp, delim, ch->expr->emode, ch, &rhsBuf,
   2915 	    NULL, &args);
   2916 	if (res != VPR_OK) {
   2917 		LazyBuf_Done(&lhsBuf);
   2918 		return AMR_CLEANUP;
   2919 	}
   2920 	args.rhs = LazyBuf_Get(&rhsBuf);
   2921 
   2922 	oneBigWord = ch->oneBigWord;
   2923 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   2924 
   2925 	ModifyWords(ch, ModifyWord_Subst, &args, oneBigWord);
   2926 
   2927 	LazyBuf_Done(&lhsBuf);
   2928 	LazyBuf_Done(&rhsBuf);
   2929 	return AMR_OK;
   2930 }
   2931 
   2932 #ifndef NO_REGEX
   2933 
   2934 /* :C,from,to, */
   2935 static ApplyModifierResult
   2936 ApplyModifier_Regex(const char **pp, ModChain *ch)
   2937 {
   2938 	struct ModifyWord_SubstRegexArgs args;
   2939 	bool oneBigWord;
   2940 	int error;
   2941 	VarParseResult res;
   2942 	LazyBuf reBuf, replaceBuf;
   2943 	FStr re;
   2944 
   2945 	char delim = (*pp)[1];
   2946 	if (delim == '\0') {
   2947 		Error("Missing delimiter for :C modifier");
   2948 		(*pp)++;
   2949 		return AMR_CLEANUP;
   2950 	}
   2951 
   2952 	*pp += 2;
   2953 
   2954 	res = ParseModifierPart(pp, delim, ch->expr->emode, ch, &reBuf);
   2955 	if (res != VPR_OK)
   2956 		return AMR_CLEANUP;
   2957 	re = LazyBuf_DoneGet(&reBuf);
   2958 
   2959 	res = ParseModifierPart(pp, delim, ch->expr->emode, ch, &replaceBuf);
   2960 	if (res != VPR_OK) {
   2961 		FStr_Done(&re);
   2962 		return AMR_CLEANUP;
   2963 	}
   2964 	args.replace = LazyBuf_Get(&replaceBuf);
   2965 
   2966 	args.pflags = PatternFlags_None();
   2967 	args.matched = false;
   2968 	oneBigWord = ch->oneBigWord;
   2969 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   2970 
   2971 	if (!ModChain_ShouldEval(ch)) {
   2972 		LazyBuf_Done(&replaceBuf);
   2973 		FStr_Done(&re);
   2974 		return AMR_OK;
   2975 	}
   2976 
   2977 	error = regcomp(&args.re, re.str, REG_EXTENDED);
   2978 	if (error != 0) {
   2979 		VarREError(error, &args.re, "Regex compilation error");
   2980 		LazyBuf_Done(&replaceBuf);
   2981 		FStr_Done(&re);
   2982 		return AMR_CLEANUP;
   2983 	}
   2984 
   2985 	args.nsub = args.re.re_nsub + 1;
   2986 	if (args.nsub > 10)
   2987 		args.nsub = 10;
   2988 
   2989 	ModifyWords(ch, ModifyWord_SubstRegex, &args, oneBigWord);
   2990 
   2991 	regfree(&args.re);
   2992 	LazyBuf_Done(&replaceBuf);
   2993 	FStr_Done(&re);
   2994 	return AMR_OK;
   2995 }
   2996 
   2997 #endif
   2998 
   2999 /* :Q, :q */
   3000 static ApplyModifierResult
   3001 ApplyModifier_Quote(const char **pp, ModChain *ch)
   3002 {
   3003 	LazyBuf buf;
   3004 	bool quoteDollar;
   3005 
   3006 	quoteDollar = **pp == 'q';
   3007 	if (!IsDelimiter((*pp)[1], ch))
   3008 		return AMR_UNKNOWN;
   3009 	(*pp)++;
   3010 
   3011 	if (!ModChain_ShouldEval(ch))
   3012 		return AMR_OK;
   3013 
   3014 	VarQuote(Expr_Str(ch->expr), quoteDollar, &buf);
   3015 	if (buf.data != NULL)
   3016 		Expr_SetValue(ch->expr, LazyBuf_DoneGet(&buf));
   3017 	else
   3018 		LazyBuf_Done(&buf);
   3019 
   3020 	return AMR_OK;
   3021 }
   3022 
   3023 /*ARGSUSED*/
   3024 static void
   3025 ModifyWord_Copy(Substring word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   3026 {
   3027 	SepBuf_AddSubstring(buf, word);
   3028 }
   3029 
   3030 /* :ts<separator> */
   3031 static ApplyModifierResult
   3032 ApplyModifier_ToSep(const char **pp, ModChain *ch)
   3033 {
   3034 	const char *sep = *pp + 2;
   3035 
   3036 	/*
   3037 	 * Even in parse-only mode, proceed as normal since there is
   3038 	 * neither any observable side effect nor a performance penalty.
   3039 	 * Checking for wantRes for every single piece of code in here
   3040 	 * would make the code in this function too hard to read.
   3041 	 */
   3042 
   3043 	/* ":ts<any><endc>" or ":ts<any>:" */
   3044 	if (sep[0] != ch->endc && IsDelimiter(sep[1], ch)) {
   3045 		*pp = sep + 1;
   3046 		ch->sep = sep[0];
   3047 		goto ok;
   3048 	}
   3049 
   3050 	/* ":ts<endc>" or ":ts:" */
   3051 	if (IsDelimiter(sep[0], ch)) {
   3052 		*pp = sep;
   3053 		ch->sep = '\0';	/* no separator */
   3054 		goto ok;
   3055 	}
   3056 
   3057 	/* ":ts<unrecognised><unrecognised>". */
   3058 	if (sep[0] != '\\') {
   3059 		(*pp)++;	/* just for backwards compatibility */
   3060 		return AMR_BAD;
   3061 	}
   3062 
   3063 	/* ":ts\n" */
   3064 	if (sep[1] == 'n') {
   3065 		*pp = sep + 2;
   3066 		ch->sep = '\n';
   3067 		goto ok;
   3068 	}
   3069 
   3070 	/* ":ts\t" */
   3071 	if (sep[1] == 't') {
   3072 		*pp = sep + 2;
   3073 		ch->sep = '\t';
   3074 		goto ok;
   3075 	}
   3076 
   3077 	/* ":ts\x40" or ":ts\100" */
   3078 	{
   3079 		const char *p = sep + 1;
   3080 		int base = 8;	/* assume octal */
   3081 
   3082 		if (sep[1] == 'x') {
   3083 			base = 16;
   3084 			p++;
   3085 		} else if (!ch_isdigit(sep[1])) {
   3086 			(*pp)++;	/* just for backwards compatibility */
   3087 			return AMR_BAD;	/* ":ts<backslash><unrecognised>". */
   3088 		}
   3089 
   3090 		if (!TryParseChar(&p, base, &ch->sep)) {
   3091 			Parse_Error(PARSE_FATAL,
   3092 			    "Invalid character number at \"%s\"", p);
   3093 			return AMR_CLEANUP;
   3094 		}
   3095 		if (!IsDelimiter(*p, ch)) {
   3096 			(*pp)++;	/* just for backwards compatibility */
   3097 			return AMR_BAD;
   3098 		}
   3099 
   3100 		*pp = p;
   3101 	}
   3102 
   3103 ok:
   3104 	ModifyWords(ch, ModifyWord_Copy, NULL, ch->oneBigWord);
   3105 	return AMR_OK;
   3106 }
   3107 
   3108 static char *
   3109 str_toupper(const char *str)
   3110 {
   3111 	char *res;
   3112 	size_t i, len;
   3113 
   3114 	len = strlen(str);
   3115 	res = bmake_malloc(len + 1);
   3116 	for (i = 0; i < len + 1; i++)
   3117 		res[i] = ch_toupper(str[i]);
   3118 
   3119 	return res;
   3120 }
   3121 
   3122 static char *
   3123 str_tolower(const char *str)
   3124 {
   3125 	char *res;
   3126 	size_t i, len;
   3127 
   3128 	len = strlen(str);
   3129 	res = bmake_malloc(len + 1);
   3130 	for (i = 0; i < len + 1; i++)
   3131 		res[i] = ch_tolower(str[i]);
   3132 
   3133 	return res;
   3134 }
   3135 
   3136 /* :tA, :tu, :tl, :ts<separator>, etc. */
   3137 static ApplyModifierResult
   3138 ApplyModifier_To(const char **pp, ModChain *ch)
   3139 {
   3140 	Expr *expr = ch->expr;
   3141 	const char *mod = *pp;
   3142 	assert(mod[0] == 't');
   3143 
   3144 	if (IsDelimiter(mod[1], ch) || mod[1] == '\0') {
   3145 		*pp = mod + 1;
   3146 		return AMR_BAD;	/* Found ":t<endc>" or ":t:". */
   3147 	}
   3148 
   3149 	if (mod[1] == 's')
   3150 		return ApplyModifier_ToSep(pp, ch);
   3151 
   3152 	if (!IsDelimiter(mod[2], ch)) {			/* :t<unrecognized> */
   3153 		*pp = mod + 1;
   3154 		return AMR_BAD;
   3155 	}
   3156 
   3157 	if (mod[1] == 'A') {				/* :tA */
   3158 		*pp = mod + 2;
   3159 		ModifyWords(ch, ModifyWord_Realpath, NULL, ch->oneBigWord);
   3160 		return AMR_OK;
   3161 	}
   3162 
   3163 	if (mod[1] == 'u') {				/* :tu */
   3164 		*pp = mod + 2;
   3165 		if (Expr_ShouldEval(expr))
   3166 			Expr_SetValueOwn(expr, str_toupper(Expr_Str(expr)));
   3167 		return AMR_OK;
   3168 	}
   3169 
   3170 	if (mod[1] == 'l') {				/* :tl */
   3171 		*pp = mod + 2;
   3172 		if (Expr_ShouldEval(expr))
   3173 			Expr_SetValueOwn(expr, str_tolower(Expr_Str(expr)));
   3174 		return AMR_OK;
   3175 	}
   3176 
   3177 	if (mod[1] == 'W' || mod[1] == 'w') {		/* :tW, :tw */
   3178 		*pp = mod + 2;
   3179 		ch->oneBigWord = mod[1] == 'W';
   3180 		return AMR_OK;
   3181 	}
   3182 
   3183 	/* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
   3184 	*pp = mod + 1;		/* XXX: unnecessary but observable */
   3185 	return AMR_BAD;
   3186 }
   3187 
   3188 /* :[#], :[1], :[-1..1], etc. */
   3189 static ApplyModifierResult
   3190 ApplyModifier_Words(const char **pp, ModChain *ch)
   3191 {
   3192 	Expr *expr = ch->expr;
   3193 	const char *estr;
   3194 	int first, last;
   3195 	VarParseResult res;
   3196 	const char *p;
   3197 	LazyBuf estrBuf;
   3198 	FStr festr;
   3199 
   3200 	(*pp)++;		/* skip the '[' */
   3201 	res = ParseModifierPart(pp, ']', expr->emode, ch, &estrBuf);
   3202 	if (res != VPR_OK)
   3203 		return AMR_CLEANUP;
   3204 	festr = LazyBuf_DoneGet(&estrBuf);
   3205 	estr = festr.str;
   3206 
   3207 	if (!IsDelimiter(**pp, ch))
   3208 		goto bad_modifier;		/* Found junk after ']' */
   3209 
   3210 	if (!ModChain_ShouldEval(ch))
   3211 		goto ok;
   3212 
   3213 	if (estr[0] == '\0')
   3214 		goto bad_modifier;			/* Found ":[]". */
   3215 
   3216 	if (estr[0] == '#' && estr[1] == '\0') {	/* Found ":[#]" */
   3217 		if (ch->oneBigWord) {
   3218 			Expr_SetValueRefer(expr, "1");
   3219 		} else {
   3220 			Buffer buf;
   3221 
   3222 			SubstringWords words = Expr_Words(expr);
   3223 			size_t ac = words.len;
   3224 			SubstringWords_Free(words);
   3225 
   3226 			/* 3 digits + '\0' is usually enough */
   3227 			Buf_InitSize(&buf, 4);
   3228 			Buf_AddInt(&buf, (int)ac);
   3229 			Expr_SetValueOwn(expr, Buf_DoneData(&buf));
   3230 		}
   3231 		goto ok;
   3232 	}
   3233 
   3234 	if (estr[0] == '*' && estr[1] == '\0') {	/* Found ":[*]" */
   3235 		ch->oneBigWord = true;
   3236 		goto ok;
   3237 	}
   3238 
   3239 	if (estr[0] == '@' && estr[1] == '\0') {	/* Found ":[@]" */
   3240 		ch->oneBigWord = false;
   3241 		goto ok;
   3242 	}
   3243 
   3244 	/*
   3245 	 * We expect estr to contain a single integer for :[N], or two
   3246 	 * integers separated by ".." for :[start..end].
   3247 	 */
   3248 	p = estr;
   3249 	if (!TryParseIntBase0(&p, &first))
   3250 		goto bad_modifier;	/* Found junk instead of a number */
   3251 
   3252 	if (p[0] == '\0') {		/* Found only one integer in :[N] */
   3253 		last = first;
   3254 	} else if (p[0] == '.' && p[1] == '.' && p[2] != '\0') {
   3255 		/* Expecting another integer after ".." */
   3256 		p += 2;
   3257 		if (!TryParseIntBase0(&p, &last) || *p != '\0')
   3258 			goto bad_modifier; /* Found junk after ".." */
   3259 	} else
   3260 		goto bad_modifier;	/* Found junk instead of ".." */
   3261 
   3262 	/*
   3263 	 * Now first and last are properly filled in, but we still have to
   3264 	 * check for 0 as a special case.
   3265 	 */
   3266 	if (first == 0 && last == 0) {
   3267 		/* ":[0]" or perhaps ":[0..0]" */
   3268 		ch->oneBigWord = true;
   3269 		goto ok;
   3270 	}
   3271 
   3272 	/* ":[0..N]" or ":[N..0]" */
   3273 	if (first == 0 || last == 0)
   3274 		goto bad_modifier;
   3275 
   3276 	/* Normal case: select the words described by first and last. */
   3277 	Expr_SetValueOwn(expr,
   3278 	    VarSelectWords(Expr_Str(expr), first, last,
   3279 	        ch->sep, ch->oneBigWord));
   3280 
   3281 ok:
   3282 	FStr_Done(&festr);
   3283 	return AMR_OK;
   3284 
   3285 bad_modifier:
   3286 	FStr_Done(&festr);
   3287 	return AMR_BAD;
   3288 }
   3289 
   3290 #ifndef NUM_TYPE
   3291 # define NUM_TYPE long long
   3292 #endif
   3293 
   3294 static NUM_TYPE
   3295 num_val(Substring s)
   3296 {
   3297 	NUM_TYPE val;
   3298 	char *ep;
   3299 
   3300 	val = strtoll(s.start, &ep, 0);
   3301 	if (ep != s.start) {
   3302 		switch (*ep) {
   3303 		case 'K':
   3304 		case 'k':
   3305 			val <<= 10;
   3306 			break;
   3307 		case 'M':
   3308 		case 'm':
   3309 			val <<= 20;
   3310 			break;
   3311 		case 'G':
   3312 		case 'g':
   3313 			val <<= 30;
   3314 			break;
   3315 		}
   3316 	}
   3317 	return val;
   3318 }
   3319 
   3320 static int
   3321 SubNumAsc(const void *sa, const void *sb)
   3322 {
   3323 	NUM_TYPE a, b;
   3324 
   3325 	a = num_val(*((const Substring *)sa));
   3326 	b = num_val(*((const Substring *)sb));
   3327 	return (a > b) ? 1 : (b > a) ? -1 : 0;
   3328 }
   3329 
   3330 static int
   3331 SubNumDesc(const void *sa, const void *sb)
   3332 {
   3333 	return SubNumAsc(sb, sa);
   3334 }
   3335 
   3336 static int
   3337 SubStrAsc(const void *sa, const void *sb)
   3338 {
   3339 	return strcmp(
   3340 	    ((const Substring *)sa)->start, ((const Substring *)sb)->start);
   3341 }
   3342 
   3343 static int
   3344 SubStrDesc(const void *sa, const void *sb)
   3345 {
   3346 	return SubStrAsc(sb, sa);
   3347 }
   3348 
   3349 static void
   3350 ShuffleSubstrings(Substring *strs, size_t n)
   3351 {
   3352 	size_t i;
   3353 
   3354 	for (i = n - 1; i > 0; i--) {
   3355 		size_t rndidx = (size_t)random() % (i + 1);
   3356 		Substring t = strs[i];
   3357 		strs[i] = strs[rndidx];
   3358 		strs[rndidx] = t;
   3359 	}
   3360 }
   3361 
   3362 /*
   3363  * :O		order ascending
   3364  * :Or		order descending
   3365  * :Ox		shuffle
   3366  * :On		numeric ascending
   3367  * :Onr, :Orn	numeric descending
   3368  */
   3369 static ApplyModifierResult
   3370 ApplyModifier_Order(const char **pp, ModChain *ch)
   3371 {
   3372 	const char *mod = *pp;
   3373 	SubstringWords words;
   3374 	int (*cmp)(const void *, const void *);
   3375 
   3376 	if (IsDelimiter(mod[1], ch) || mod[1] == '\0') {
   3377 		cmp = SubStrAsc;
   3378 		(*pp)++;
   3379 	} else if (IsDelimiter(mod[2], ch) || mod[2] == '\0') {
   3380 		if (mod[1] == 'n')
   3381 			cmp = SubNumAsc;
   3382 		else if (mod[1] == 'r')
   3383 			cmp = SubStrDesc;
   3384 		else if (mod[1] == 'x')
   3385 			cmp = NULL;
   3386 		else
   3387 			goto bad;
   3388 		*pp += 2;
   3389 	} else if (IsDelimiter(mod[3], ch) || mod[3] == '\0') {
   3390 		if ((mod[1] == 'n' && mod[2] == 'r') ||
   3391 		    (mod[1] == 'r' && mod[2] == 'n'))
   3392 			cmp = SubNumDesc;
   3393 		else
   3394 			goto bad;
   3395 		*pp += 3;
   3396 	} else
   3397 		goto bad;
   3398 
   3399 	if (!ModChain_ShouldEval(ch))
   3400 		return AMR_OK;
   3401 
   3402 	words = Expr_Words(ch->expr);
   3403 	if (cmp == NULL)
   3404 		ShuffleSubstrings(words.words, words.len);
   3405 	else {
   3406 		assert(words.words[0].end[0] == '\0');
   3407 		qsort(words.words, words.len, sizeof(words.words[0]), cmp);
   3408 	}
   3409 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3410 
   3411 	return AMR_OK;
   3412 
   3413 bad:
   3414 	(*pp)++;
   3415 	return AMR_BAD;
   3416 }
   3417 
   3418 /* :? then : else */
   3419 static ApplyModifierResult
   3420 ApplyModifier_IfElse(const char **pp, ModChain *ch)
   3421 {
   3422 	Expr *expr = ch->expr;
   3423 	VarParseResult res;
   3424 	LazyBuf thenBuf;
   3425 	LazyBuf elseBuf;
   3426 
   3427 	VarEvalMode then_emode = VARE_PARSE_ONLY;
   3428 	VarEvalMode else_emode = VARE_PARSE_ONLY;
   3429 
   3430 	CondResult cond_rc = CR_TRUE;	/* just not CR_ERROR */
   3431 	if (Expr_ShouldEval(expr)) {
   3432 		cond_rc = Cond_EvalCondition(expr->name);
   3433 		if (cond_rc == CR_TRUE)
   3434 			then_emode = expr->emode;
   3435 		if (cond_rc == CR_FALSE)
   3436 			else_emode = expr->emode;
   3437 	}
   3438 
   3439 	(*pp)++;		/* skip past the '?' */
   3440 	res = ParseModifierPart(pp, ':', then_emode, ch, &thenBuf);
   3441 	if (res != VPR_OK)
   3442 		return AMR_CLEANUP;
   3443 
   3444 	res = ParseModifierPart(pp, ch->endc, else_emode, ch, &elseBuf);
   3445 	if (res != VPR_OK) {
   3446 		LazyBuf_Done(&thenBuf);
   3447 		return AMR_CLEANUP;
   3448 	}
   3449 
   3450 	(*pp)--;		/* Go back to the ch->endc. */
   3451 
   3452 	if (cond_rc == CR_ERROR) {
   3453 		Substring thenExpr = LazyBuf_Get(&thenBuf);
   3454 		Substring elseExpr = LazyBuf_Get(&elseBuf);
   3455 		Error("Bad conditional expression '%s' in '%s?%.*s:%.*s'",
   3456 		    expr->name, expr->name,
   3457 		    (int)Substring_Length(thenExpr), thenExpr.start,
   3458 		    (int)Substring_Length(elseExpr), elseExpr.start);
   3459 		LazyBuf_Done(&thenBuf);
   3460 		LazyBuf_Done(&elseBuf);
   3461 		return AMR_CLEANUP;
   3462 	}
   3463 
   3464 	if (!Expr_ShouldEval(expr)) {
   3465 		LazyBuf_Done(&thenBuf);
   3466 		LazyBuf_Done(&elseBuf);
   3467 	} else if (cond_rc == CR_TRUE) {
   3468 		Expr_SetValue(expr, LazyBuf_DoneGet(&thenBuf));
   3469 		LazyBuf_Done(&elseBuf);
   3470 	} else {
   3471 		LazyBuf_Done(&thenBuf);
   3472 		Expr_SetValue(expr, LazyBuf_DoneGet(&elseBuf));
   3473 	}
   3474 	Expr_Define(expr);
   3475 	return AMR_OK;
   3476 }
   3477 
   3478 /*
   3479  * The ::= modifiers are special in that they do not read the variable value
   3480  * but instead assign to that variable.  They always expand to an empty
   3481  * string.
   3482  *
   3483  * Their main purpose is in supporting .for loops that generate shell commands
   3484  * since an ordinary variable assignment at that point would terminate the
   3485  * dependency group for these targets.  For example:
   3486  *
   3487  * list-targets: .USE
   3488  * .for i in ${.TARGET} ${.TARGET:R}.gz
   3489  *	@${t::=$i}
   3490  *	@echo 'The target is ${t:T}.'
   3491  * .endfor
   3492  *
   3493  *	  ::=<str>	Assigns <str> as the new value of variable.
   3494  *	  ::?=<str>	Assigns <str> as value of variable if
   3495  *			it was not already set.
   3496  *	  ::+=<str>	Appends <str> to variable.
   3497  *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
   3498  *			variable.
   3499  */
   3500 static ApplyModifierResult
   3501 ApplyModifier_Assign(const char **pp, ModChain *ch)
   3502 {
   3503 	Expr *expr = ch->expr;
   3504 	GNode *scope;
   3505 	FStr val;
   3506 	VarParseResult res;
   3507 	LazyBuf buf;
   3508 
   3509 	const char *mod = *pp;
   3510 	const char *op = mod + 1;
   3511 
   3512 	if (op[0] == '=')
   3513 		goto found_op;
   3514 	if ((op[0] == '+' || op[0] == '?' || op[0] == '!') && op[1] == '=')
   3515 		goto found_op;
   3516 	return AMR_UNKNOWN;	/* "::<unrecognised>" */
   3517 
   3518 found_op:
   3519 	if (expr->name[0] == '\0') {
   3520 		*pp = mod + 1;
   3521 		return AMR_BAD;
   3522 	}
   3523 
   3524 	*pp = mod + (op[0] == '+' || op[0] == '?' || op[0] == '!' ? 3 : 2);
   3525 
   3526 	res = ParseModifierPart(pp, ch->endc, expr->emode, ch, &buf);
   3527 	if (res != VPR_OK)
   3528 		return AMR_CLEANUP;
   3529 	val = LazyBuf_DoneGet(&buf);
   3530 
   3531 	(*pp)--;		/* Go back to the ch->endc. */
   3532 
   3533 	if (!Expr_ShouldEval(expr))
   3534 		goto done;
   3535 
   3536 	scope = expr->scope;	/* scope where v belongs */
   3537 	if (expr->defined == DEF_REGULAR && expr->scope != SCOPE_GLOBAL) {
   3538 		Var *gv = VarFind(expr->name, expr->scope, false);
   3539 		if (gv == NULL)
   3540 			scope = SCOPE_GLOBAL;
   3541 		else
   3542 			VarFreeShortLived(gv);
   3543 	}
   3544 
   3545 	if (op[0] == '+')
   3546 		Var_Append(scope, expr->name, val.str);
   3547 	else if (op[0] == '!') {
   3548 		char *output, *error;
   3549 		output = Cmd_Exec(val.str, &error);
   3550 		if (error != NULL) {
   3551 			Error("%s", error);
   3552 			free(error);
   3553 		} else
   3554 			Var_Set(scope, expr->name, output);
   3555 		free(output);
   3556 	} else if (op[0] == '?' && expr->defined == DEF_REGULAR) {
   3557 		/* Do nothing. */
   3558 	} else
   3559 		Var_Set(scope, expr->name, val.str);
   3560 
   3561 	Expr_SetValueRefer(expr, "");
   3562 
   3563 done:
   3564 	FStr_Done(&val);
   3565 	return AMR_OK;
   3566 }
   3567 
   3568 /*
   3569  * :_=...
   3570  * remember current value
   3571  */
   3572 static ApplyModifierResult
   3573 ApplyModifier_Remember(const char **pp, ModChain *ch)
   3574 {
   3575 	Expr *expr = ch->expr;
   3576 	const char *mod = *pp;
   3577 	FStr name;
   3578 
   3579 	if (!ModMatchEq(mod, "_", ch))
   3580 		return AMR_UNKNOWN;
   3581 
   3582 	name = FStr_InitRefer("_");
   3583 	if (mod[1] == '=') {
   3584 		/*
   3585 		 * XXX: This ad-hoc call to strcspn deviates from the usual
   3586 		 * behavior defined in ParseModifierPart.  This creates an
   3587 		 * unnecessary, undocumented inconsistency in make.
   3588 		 */
   3589 		const char *arg = mod + 2;
   3590 		size_t argLen = strcspn(arg, ":)}");
   3591 		*pp = arg + argLen;
   3592 		name = FStr_InitOwn(bmake_strldup(arg, argLen));
   3593 	} else
   3594 		*pp = mod + 1;
   3595 
   3596 	if (Expr_ShouldEval(expr))
   3597 		Var_Set(expr->scope, name.str, Expr_Str(expr));
   3598 	FStr_Done(&name);
   3599 
   3600 	return AMR_OK;
   3601 }
   3602 
   3603 /*
   3604  * Apply the given function to each word of the variable value,
   3605  * for a single-letter modifier such as :H, :T.
   3606  */
   3607 static ApplyModifierResult
   3608 ApplyModifier_WordFunc(const char **pp, ModChain *ch,
   3609 		       ModifyWordProc modifyWord)
   3610 {
   3611 	if (!IsDelimiter((*pp)[1], ch))
   3612 		return AMR_UNKNOWN;
   3613 	(*pp)++;
   3614 
   3615 	if (ModChain_ShouldEval(ch))
   3616 		ModifyWords(ch, modifyWord, NULL, ch->oneBigWord);
   3617 
   3618 	return AMR_OK;
   3619 }
   3620 
   3621 /* Remove adjacent duplicate words. */
   3622 static ApplyModifierResult
   3623 ApplyModifier_Unique(const char **pp, ModChain *ch)
   3624 {
   3625 	SubstringWords words;
   3626 
   3627 	if (!IsDelimiter((*pp)[1], ch))
   3628 		return AMR_UNKNOWN;
   3629 	(*pp)++;
   3630 
   3631 	if (!ModChain_ShouldEval(ch))
   3632 		return AMR_OK;
   3633 
   3634 	words = Expr_Words(ch->expr);
   3635 
   3636 	if (words.len > 1) {
   3637 		size_t si, di;
   3638 
   3639 		di = 0;
   3640 		for (si = 1; si < words.len; si++) {
   3641 			if (!Substring_Eq(words.words[si], words.words[di])) {
   3642 				di++;
   3643 				if (di != si)
   3644 					words.words[di] = words.words[si];
   3645 			}
   3646 		}
   3647 		words.len = di + 1;
   3648 	}
   3649 
   3650 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3651 
   3652 	return AMR_OK;
   3653 }
   3654 
   3655 #ifdef SYSVVARSUB
   3656 /* :from=to */
   3657 static ApplyModifierResult
   3658 ApplyModifier_SysV(const char **pp, ModChain *ch)
   3659 {
   3660 	Expr *expr = ch->expr;
   3661 	VarParseResult res;
   3662 	LazyBuf lhsBuf, rhsBuf;
   3663 	FStr rhs;
   3664 	struct ModifyWord_SysVSubstArgs args;
   3665 	Substring lhs;
   3666 	const char *lhsSuffix;
   3667 
   3668 	const char *mod = *pp;
   3669 	bool eqFound = false;
   3670 
   3671 	/*
   3672 	 * First we make a pass through the string trying to verify it is a
   3673 	 * SysV-make-style translation. It must be: <lhs>=<rhs>
   3674 	 */
   3675 	int depth = 1;
   3676 	const char *p = mod;
   3677 	while (*p != '\0' && depth > 0) {
   3678 		if (*p == '=') {	/* XXX: should also test depth == 1 */
   3679 			eqFound = true;
   3680 			/* continue looking for ch->endc */
   3681 		} else if (*p == ch->endc)
   3682 			depth--;
   3683 		else if (*p == ch->startc)
   3684 			depth++;
   3685 		if (depth > 0)
   3686 			p++;
   3687 	}
   3688 	if (*p != ch->endc || !eqFound)
   3689 		return AMR_UNKNOWN;
   3690 
   3691 	res = ParseModifierPart(pp, '=', expr->emode, ch, &lhsBuf);
   3692 	if (res != VPR_OK)
   3693 		return AMR_CLEANUP;
   3694 
   3695 	/*
   3696 	 * The SysV modifier lasts until the end of the variable expression.
   3697 	 */
   3698 	res = ParseModifierPart(pp, ch->endc, expr->emode, ch, &rhsBuf);
   3699 	if (res != VPR_OK) {
   3700 		LazyBuf_Done(&lhsBuf);
   3701 		return AMR_CLEANUP;
   3702 	}
   3703 	rhs = LazyBuf_DoneGet(&rhsBuf);
   3704 
   3705 	(*pp)--;		/* Go back to the ch->endc. */
   3706 
   3707 	/* Do not turn an empty expression into non-empty. */
   3708 	if (lhsBuf.len == 0 && Expr_Str(expr)[0] == '\0')
   3709 		goto done;
   3710 
   3711 	lhs = LazyBuf_Get(&lhsBuf);
   3712 	lhsSuffix = Substring_SkipFirst(lhs, '%');
   3713 
   3714 	args.scope = expr->scope;
   3715 	args.lhsPrefix = Substring_Init(lhs.start,
   3716 	    lhsSuffix != lhs.start ? lhsSuffix - 1 : lhs.start);
   3717 	args.lhsPercent = lhsSuffix != lhs.start;
   3718 	args.lhsSuffix = Substring_Init(lhsSuffix, lhs.end);
   3719 	args.rhs = rhs.str;
   3720 
   3721 	ModifyWords(ch, ModifyWord_SysVSubst, &args, ch->oneBigWord);
   3722 
   3723 done:
   3724 	LazyBuf_Done(&lhsBuf);
   3725 	return AMR_OK;
   3726 }
   3727 #endif
   3728 
   3729 #ifdef SUNSHCMD
   3730 /* :sh */
   3731 static ApplyModifierResult
   3732 ApplyModifier_SunShell(const char **pp, ModChain *ch)
   3733 {
   3734 	Expr *expr = ch->expr;
   3735 	const char *p = *pp;
   3736 	if (!(p[1] == 'h' && IsDelimiter(p[2], ch)))
   3737 		return AMR_UNKNOWN;
   3738 	*pp = p + 2;
   3739 
   3740 	if (Expr_ShouldEval(expr)) {
   3741 		char *output, *error;
   3742 		output = Cmd_Exec(Expr_Str(expr), &error);
   3743 		if (error != NULL) {
   3744 			Error("%s", error);
   3745 			free(error);
   3746 		}
   3747 		Expr_SetValueOwn(expr, output);
   3748 	}
   3749 
   3750 	return AMR_OK;
   3751 }
   3752 #endif
   3753 
   3754 static void
   3755 LogBeforeApply(const ModChain *ch, const char *mod)
   3756 {
   3757 	const Expr *expr = ch->expr;
   3758 	bool is_single_char = mod[0] != '\0' && IsDelimiter(mod[1], ch);
   3759 
   3760 	/*
   3761 	 * At this point, only the first character of the modifier can
   3762 	 * be used since the end of the modifier is not yet known.
   3763 	 */
   3764 
   3765 	if (!Expr_ShouldEval(expr)) {
   3766 		debug_printf("Parsing modifier ${%s:%c%s}\n",
   3767 		    expr->name, mod[0], is_single_char ? "" : "...");
   3768 		return;
   3769 	}
   3770 
   3771 	if ((expr->emode == VARE_WANTRES || expr->emode == VARE_UNDEFERR) &&
   3772 	    expr->defined == DEF_REGULAR) {
   3773 		debug_printf(
   3774 		    "Evaluating modifier ${%s:%c%s} on value \"%s\"\n",
   3775 		    expr->name, mod[0], is_single_char ? "" : "...",
   3776 		    Expr_Str(expr));
   3777 		return;
   3778 	}
   3779 
   3780 	debug_printf(
   3781 	    "Evaluating modifier ${%s:%c%s} on value \"%s\" (%s, %s)\n",
   3782 	    expr->name, mod[0], is_single_char ? "" : "...", Expr_Str(expr),
   3783 	    VarEvalMode_Name[expr->emode], ExprDefined_Name[expr->defined]);
   3784 }
   3785 
   3786 static void
   3787 LogAfterApply(const ModChain *ch, const char *p, const char *mod)
   3788 {
   3789 	const Expr *expr = ch->expr;
   3790 	const char *value = Expr_Str(expr);
   3791 	const char *quot = value == var_Error ? "" : "\"";
   3792 
   3793 	if ((expr->emode == VARE_WANTRES || expr->emode == VARE_UNDEFERR) &&
   3794 	    expr->defined == DEF_REGULAR) {
   3795 
   3796 		debug_printf("Result of ${%s:%.*s} is %s%s%s\n",
   3797 		    expr->name, (int)(p - mod), mod,
   3798 		    quot, value == var_Error ? "error" : value, quot);
   3799 		return;
   3800 	}
   3801 
   3802 	debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s)\n",
   3803 	    expr->name, (int)(p - mod), mod,
   3804 	    quot, value == var_Error ? "error" : value, quot,
   3805 	    VarEvalMode_Name[expr->emode],
   3806 	    ExprDefined_Name[expr->defined]);
   3807 }
   3808 
   3809 static ApplyModifierResult
   3810 ApplyModifier(const char **pp, ModChain *ch)
   3811 {
   3812 	switch (**pp) {
   3813 	case '!':
   3814 		return ApplyModifier_ShellCommand(pp, ch);
   3815 	case ':':
   3816 		return ApplyModifier_Assign(pp, ch);
   3817 	case '?':
   3818 		return ApplyModifier_IfElse(pp, ch);
   3819 	case '@':
   3820 		return ApplyModifier_Loop(pp, ch);
   3821 	case '[':
   3822 		return ApplyModifier_Words(pp, ch);
   3823 	case '_':
   3824 		return ApplyModifier_Remember(pp, ch);
   3825 #ifndef NO_REGEX
   3826 	case 'C':
   3827 		return ApplyModifier_Regex(pp, ch);
   3828 #endif
   3829 	case 'D':
   3830 	case 'U':
   3831 		return ApplyModifier_Defined(pp, ch);
   3832 	case 'E':
   3833 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Suffix);
   3834 	case 'g':
   3835 	case 'l':
   3836 		return ApplyModifier_Time(pp, ch);
   3837 	case 'H':
   3838 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Head);
   3839 	case 'h':
   3840 		return ApplyModifier_Hash(pp, ch);
   3841 	case 'L':
   3842 		return ApplyModifier_Literal(pp, ch);
   3843 	case 'M':
   3844 	case 'N':
   3845 		return ApplyModifier_Match(pp, ch);
   3846 	case 'O':
   3847 		return ApplyModifier_Order(pp, ch);
   3848 	case 'P':
   3849 		return ApplyModifier_Path(pp, ch);
   3850 	case 'Q':
   3851 	case 'q':
   3852 		return ApplyModifier_Quote(pp, ch);
   3853 	case 'R':
   3854 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Root);
   3855 	case 'r':
   3856 		return ApplyModifier_Range(pp, ch);
   3857 	case 'S':
   3858 		return ApplyModifier_Subst(pp, ch);
   3859 #ifdef SUNSHCMD
   3860 	case 's':
   3861 		return ApplyModifier_SunShell(pp, ch);
   3862 #endif
   3863 	case 'T':
   3864 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Tail);
   3865 	case 't':
   3866 		return ApplyModifier_To(pp, ch);
   3867 	case 'u':
   3868 		return ApplyModifier_Unique(pp, ch);
   3869 	default:
   3870 		return AMR_UNKNOWN;
   3871 	}
   3872 }
   3873 
   3874 static void ApplyModifiers(Expr *, const char **, char, char);
   3875 
   3876 typedef enum ApplyModifiersIndirectResult {
   3877 	/* The indirect modifiers have been applied successfully. */
   3878 	AMIR_CONTINUE,
   3879 	/* Fall back to the SysV modifier. */
   3880 	AMIR_SYSV,
   3881 	/* Error out. */
   3882 	AMIR_OUT
   3883 } ApplyModifiersIndirectResult;
   3884 
   3885 /*
   3886  * While expanding a variable expression, expand and apply indirect modifiers,
   3887  * such as in ${VAR:${M_indirect}}.
   3888  *
   3889  * All indirect modifiers of a group must come from a single variable
   3890  * expression.  ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
   3891  *
   3892  * Multiple groups of indirect modifiers can be chained by separating them
   3893  * with colons.  ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
   3894  *
   3895  * If the variable expression is not followed by ch->endc or ':', fall
   3896  * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
   3897  */
   3898 static ApplyModifiersIndirectResult
   3899 ApplyModifiersIndirect(ModChain *ch, const char **pp)
   3900 {
   3901 	Expr *expr = ch->expr;
   3902 	const char *p = *pp;
   3903 	FStr mods;
   3904 
   3905 	(void)Var_Parse(&p, expr->scope, expr->emode, &mods);
   3906 	/* TODO: handle errors */
   3907 
   3908 	if (mods.str[0] != '\0' && *p != '\0' && !IsDelimiter(*p, ch)) {
   3909 		FStr_Done(&mods);
   3910 		return AMIR_SYSV;
   3911 	}
   3912 
   3913 	DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
   3914 	    mods.str, (int)(p - *pp), *pp);
   3915 
   3916 	if (mods.str[0] != '\0') {
   3917 		const char *modsp = mods.str;
   3918 		ApplyModifiers(expr, &modsp, '\0', '\0');
   3919 		if (Expr_Str(expr) == var_Error || *modsp != '\0') {
   3920 			FStr_Done(&mods);
   3921 			*pp = p;
   3922 			return AMIR_OUT;	/* error already reported */
   3923 		}
   3924 	}
   3925 	FStr_Done(&mods);
   3926 
   3927 	if (*p == ':')
   3928 		p++;
   3929 	else if (*p == '\0' && ch->endc != '\0') {
   3930 		Error("Unclosed variable expression after indirect "
   3931 		      "modifier, expecting '%c' for variable \"%s\"",
   3932 		    ch->endc, expr->name);
   3933 		*pp = p;
   3934 		return AMIR_OUT;
   3935 	}
   3936 
   3937 	*pp = p;
   3938 	return AMIR_CONTINUE;
   3939 }
   3940 
   3941 static ApplyModifierResult
   3942 ApplySingleModifier(const char **pp, ModChain *ch)
   3943 {
   3944 	ApplyModifierResult res;
   3945 	const char *mod = *pp;
   3946 	const char *p = *pp;
   3947 
   3948 	if (DEBUG(VAR))
   3949 		LogBeforeApply(ch, mod);
   3950 
   3951 	res = ApplyModifier(&p, ch);
   3952 
   3953 #ifdef SYSVVARSUB
   3954 	if (res == AMR_UNKNOWN) {
   3955 		assert(p == mod);
   3956 		res = ApplyModifier_SysV(&p, ch);
   3957 	}
   3958 #endif
   3959 
   3960 	if (res == AMR_UNKNOWN) {
   3961 		/*
   3962 		 * Guess the end of the current modifier.
   3963 		 * XXX: Skipping the rest of the modifier hides
   3964 		 * errors and leads to wrong results.
   3965 		 * Parsing should rather stop here.
   3966 		 */
   3967 		for (p++; !IsDelimiter(*p, ch) && *p != '\0'; p++)
   3968 			continue;
   3969 		Parse_Error(PARSE_FATAL, "Unknown modifier \"%.*s\"",
   3970 		    (int)(p - mod), mod);
   3971 		Expr_SetValueRefer(ch->expr, var_Error);
   3972 	}
   3973 	if (res == AMR_CLEANUP || res == AMR_BAD) {
   3974 		*pp = p;
   3975 		return res;
   3976 	}
   3977 
   3978 	if (DEBUG(VAR))
   3979 		LogAfterApply(ch, p, mod);
   3980 
   3981 	if (*p == '\0' && ch->endc != '\0') {
   3982 		Error(
   3983 		    "Unclosed variable expression, expecting '%c' for "
   3984 		    "modifier \"%.*s\" of variable \"%s\" with value \"%s\"",
   3985 		    ch->endc,
   3986 		    (int)(p - mod), mod,
   3987 		    ch->expr->name, Expr_Str(ch->expr));
   3988 	} else if (*p == ':') {
   3989 		p++;
   3990 	} else if (opts.strict && *p != '\0' && *p != ch->endc) {
   3991 		Parse_Error(PARSE_FATAL,
   3992 		    "Missing delimiter ':' after modifier \"%.*s\"",
   3993 		    (int)(p - mod), mod);
   3994 		/*
   3995 		 * TODO: propagate parse error to the enclosing
   3996 		 * expression
   3997 		 */
   3998 	}
   3999 	*pp = p;
   4000 	return AMR_OK;
   4001 }
   4002 
   4003 #if __STDC_VERSION__ >= 199901L
   4004 #define ModChain_Literal(expr, startc, endc, sep, oneBigWord) \
   4005 	(ModChain) { expr, startc, endc, sep, oneBigWord }
   4006 #else
   4007 MAKE_INLINE ModChain
   4008 ModChain_Literal(Expr *expr, char startc, char endc, char sep, bool oneBigWord)
   4009 {
   4010 	ModChain ch;
   4011 	ch.expr = expr;
   4012 	ch.startc = startc;
   4013 	ch.endc = endc;
   4014 	ch.sep = sep;
   4015 	ch.oneBigWord = oneBigWord;
   4016 	return ch;
   4017 }
   4018 #endif
   4019 
   4020 /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
   4021 static void
   4022 ApplyModifiers(
   4023     Expr *expr,
   4024     const char **pp,	/* the parsing position, updated upon return */
   4025     char startc,	/* '(' or '{'; or '\0' for indirect modifiers */
   4026     char endc		/* ')' or '}'; or '\0' for indirect modifiers */
   4027 )
   4028 {
   4029 	ModChain ch = ModChain_Literal(expr, startc, endc, ' ', false);
   4030 	const char *p;
   4031 	const char *mod;
   4032 
   4033 	assert(startc == '(' || startc == '{' || startc == '\0');
   4034 	assert(endc == ')' || endc == '}' || endc == '\0');
   4035 	assert(Expr_Str(expr) != NULL);
   4036 
   4037 	p = *pp;
   4038 
   4039 	if (*p == '\0' && endc != '\0') {
   4040 		Error(
   4041 		    "Unclosed variable expression (expecting '%c') for \"%s\"",
   4042 		    ch.endc, expr->name);
   4043 		goto cleanup;
   4044 	}
   4045 
   4046 	while (*p != '\0' && *p != endc) {
   4047 		ApplyModifierResult res;
   4048 
   4049 		if (*p == '$') {
   4050 			ApplyModifiersIndirectResult amir =
   4051 			    ApplyModifiersIndirect(&ch, &p);
   4052 			if (amir == AMIR_CONTINUE)
   4053 				continue;
   4054 			if (amir == AMIR_OUT)
   4055 				break;
   4056 			/*
   4057 			 * It's neither '${VAR}:' nor '${VAR}}'.  Try to parse
   4058 			 * it as a SysV modifier, as that is the only modifier
   4059 			 * that can start with '$'.
   4060 			 */
   4061 		}
   4062 
   4063 		mod = p;
   4064 
   4065 		res = ApplySingleModifier(&p, &ch);
   4066 		if (res == AMR_CLEANUP)
   4067 			goto cleanup;
   4068 		if (res == AMR_BAD)
   4069 			goto bad_modifier;
   4070 	}
   4071 
   4072 	*pp = p;
   4073 	assert(Expr_Str(expr) != NULL);	/* Use var_Error or varUndefined. */
   4074 	return;
   4075 
   4076 bad_modifier:
   4077 	/* XXX: The modifier end is only guessed. */
   4078 	Error("Bad modifier \":%.*s\" for variable \"%s\"",
   4079 	    (int)strcspn(mod, ":)}"), mod, expr->name);
   4080 
   4081 cleanup:
   4082 	/*
   4083 	 * TODO: Use p + strlen(p) instead, to stop parsing immediately.
   4084 	 *
   4085 	 * In the unit tests, this generates a few unterminated strings in the
   4086 	 * shell commands though.  Instead of producing these unfinished
   4087 	 * strings, commands with evaluation errors should not be run at all.
   4088 	 *
   4089 	 * To make that happen, Var_Subst must report the actual errors
   4090 	 * instead of returning VPR_OK unconditionally.
   4091 	 */
   4092 	*pp = p;
   4093 	Expr_SetValueRefer(expr, var_Error);
   4094 }
   4095 
   4096 /*
   4097  * Only 4 of the 7 local variables are treated specially as they are the only
   4098  * ones that will be set when dynamic sources are expanded.
   4099  */
   4100 static bool
   4101 VarnameIsDynamic(Substring varname)
   4102 {
   4103 	const char *name;
   4104 	size_t len;
   4105 
   4106 	name = varname.start;
   4107 	len = Substring_Length(varname);
   4108 	if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
   4109 		switch (name[0]) {
   4110 		case '@':
   4111 		case '%':
   4112 		case '*':
   4113 		case '!':
   4114 			return true;
   4115 		}
   4116 		return false;
   4117 	}
   4118 
   4119 	if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
   4120 		return Substring_Equals(varname, ".TARGET") ||
   4121 		       Substring_Equals(varname, ".ARCHIVE") ||
   4122 		       Substring_Equals(varname, ".PREFIX") ||
   4123 		       Substring_Equals(varname, ".MEMBER");
   4124 	}
   4125 
   4126 	return false;
   4127 }
   4128 
   4129 static const char *
   4130 UndefinedShortVarValue(char varname, const GNode *scope)
   4131 {
   4132 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
   4133 		/*
   4134 		 * If substituting a local variable in a non-local scope,
   4135 		 * assume it's for dynamic source stuff. We have to handle
   4136 		 * this specially and return the longhand for the variable
   4137 		 * with the dollar sign escaped so it makes it back to the
   4138 		 * caller. Only four of the local variables are treated
   4139 		 * specially as they are the only four that will be set
   4140 		 * when dynamic sources are expanded.
   4141 		 */
   4142 		switch (varname) {
   4143 		case '@':
   4144 			return "$(.TARGET)";
   4145 		case '%':
   4146 			return "$(.MEMBER)";
   4147 		case '*':
   4148 			return "$(.PREFIX)";
   4149 		case '!':
   4150 			return "$(.ARCHIVE)";
   4151 		}
   4152 	}
   4153 	return NULL;
   4154 }
   4155 
   4156 /*
   4157  * Parse a variable name, until the end character or a colon, whichever
   4158  * comes first.
   4159  */
   4160 static void
   4161 ParseVarname(const char **pp, char startc, char endc,
   4162 	     GNode *scope, VarEvalMode emode,
   4163 	     LazyBuf *buf)
   4164 {
   4165 	const char *p = *pp;
   4166 	int depth = 0;		/* Track depth so we can spot parse errors. */
   4167 
   4168 	LazyBuf_Init(buf, p);
   4169 
   4170 	while (*p != '\0') {
   4171 		if ((*p == endc || *p == ':') && depth == 0)
   4172 			break;
   4173 		if (*p == startc)
   4174 			depth++;
   4175 		if (*p == endc)
   4176 			depth--;
   4177 
   4178 		/* A variable inside a variable, expand. */
   4179 		if (*p == '$') {
   4180 			FStr nested_val;
   4181 			(void)Var_Parse(&p, scope, emode, &nested_val);
   4182 			/* TODO: handle errors */
   4183 			LazyBuf_AddStr(buf, nested_val.str);
   4184 			FStr_Done(&nested_val);
   4185 		} else {
   4186 			LazyBuf_Add(buf, *p);
   4187 			p++;
   4188 		}
   4189 	}
   4190 	*pp = p;
   4191 }
   4192 
   4193 static VarParseResult
   4194 ValidShortVarname(char varname, const char *start)
   4195 {
   4196 	if (varname != '$' && varname != ':' && varname != '}' &&
   4197 	    varname != ')' && varname != '\0')
   4198 		return VPR_OK;
   4199 
   4200 	if (!opts.strict)
   4201 		return VPR_ERR;	/* XXX: Missing error message */
   4202 
   4203 	if (varname == '$')
   4204 		Parse_Error(PARSE_FATAL,
   4205 		    "To escape a dollar, use \\$, not $$, at \"%s\"", start);
   4206 	else if (varname == '\0')
   4207 		Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
   4208 	else
   4209 		Parse_Error(PARSE_FATAL,
   4210 		    "Invalid variable name '%c', at \"%s\"", varname, start);
   4211 
   4212 	return VPR_ERR;
   4213 }
   4214 
   4215 /*
   4216  * Parse a single-character variable name such as in $V or $@.
   4217  * Return whether to continue parsing.
   4218  */
   4219 static bool
   4220 ParseVarnameShort(char varname, const char **pp, GNode *scope,
   4221 		  VarEvalMode emode,
   4222 		  VarParseResult *out_false_res, const char **out_false_val,
   4223 		  Var **out_true_var)
   4224 {
   4225 	char name[2];
   4226 	Var *v;
   4227 	VarParseResult vpr;
   4228 
   4229 	vpr = ValidShortVarname(varname, *pp);
   4230 	if (vpr != VPR_OK) {
   4231 		(*pp)++;
   4232 		*out_false_res = vpr;
   4233 		*out_false_val = var_Error;
   4234 		return false;
   4235 	}
   4236 
   4237 	name[0] = varname;
   4238 	name[1] = '\0';
   4239 	v = VarFind(name, scope, true);
   4240 	if (v == NULL) {
   4241 		const char *val;
   4242 		*pp += 2;
   4243 
   4244 		val = UndefinedShortVarValue(varname, scope);
   4245 		if (val == NULL)
   4246 			val = emode == VARE_UNDEFERR
   4247 			    ? var_Error : varUndefined;
   4248 
   4249 		if (opts.strict && val == var_Error) {
   4250 			Parse_Error(PARSE_FATAL,
   4251 			    "Variable \"%s\" is undefined", name);
   4252 			*out_false_res = VPR_ERR;
   4253 			*out_false_val = val;
   4254 			return false;
   4255 		}
   4256 
   4257 		/*
   4258 		 * XXX: This looks completely wrong.
   4259 		 *
   4260 		 * If undefined expressions are not allowed, this should
   4261 		 * rather be VPR_ERR instead of VPR_UNDEF, together with an
   4262 		 * error message.
   4263 		 *
   4264 		 * If undefined expressions are allowed, this should rather
   4265 		 * be VPR_UNDEF instead of VPR_OK.
   4266 		 */
   4267 		*out_false_res = emode == VARE_UNDEFERR
   4268 		    ? VPR_UNDEF : VPR_OK;
   4269 		*out_false_val = val;
   4270 		return false;
   4271 	}
   4272 
   4273 	*out_true_var = v;
   4274 	return true;
   4275 }
   4276 
   4277 /* Find variables like @F or <D. */
   4278 static Var *
   4279 FindLocalLegacyVar(Substring varname, GNode *scope,
   4280 		   const char **out_extraModifiers)
   4281 {
   4282 	Var *v;
   4283 
   4284 	/* Only resolve these variables if scope is a "real" target. */
   4285 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
   4286 		return NULL;
   4287 
   4288 	if (Substring_Length(varname) != 2)
   4289 		return NULL;
   4290 	if (varname.start[1] != 'F' && varname.start[1] != 'D')
   4291 		return NULL;
   4292 	if (strchr("@%?*!<>", varname.start[0]) == NULL)
   4293 		return NULL;
   4294 
   4295 	v = VarFindSubstring(Substring_Sub(varname, 0, 1), scope, false);
   4296 	if (v == NULL)
   4297 		return NULL;
   4298 
   4299 	*out_extraModifiers = varname.start[1] == 'D' ? "H:" : "T:";
   4300 	return v;
   4301 }
   4302 
   4303 static VarParseResult
   4304 EvalUndefined(bool dynamic, const char *start, const char *p,
   4305 	      Substring varname, VarEvalMode emode, FStr *out_val)
   4306 {
   4307 	if (dynamic) {
   4308 		*out_val = FStr_InitOwn(bmake_strsedup(start, p));
   4309 		return VPR_OK;
   4310 	}
   4311 
   4312 	if (emode == VARE_UNDEFERR && opts.strict) {
   4313 		Parse_Error(PARSE_FATAL,
   4314 		    "Variable \"%.*s\" is undefined",
   4315 		    (int)Substring_Length(varname), varname.start);
   4316 		*out_val = FStr_InitRefer(var_Error);
   4317 		return VPR_ERR;
   4318 	}
   4319 
   4320 	if (emode == VARE_UNDEFERR) {
   4321 		*out_val = FStr_InitRefer(var_Error);
   4322 		return VPR_UNDEF;	/* XXX: Should be VPR_ERR instead. */
   4323 	}
   4324 
   4325 	*out_val = FStr_InitRefer(varUndefined);
   4326 	return VPR_OK;
   4327 }
   4328 
   4329 /*
   4330  * Parse a long variable name enclosed in braces or parentheses such as $(VAR)
   4331  * or ${VAR}, up to the closing brace or parenthesis, or in the case of
   4332  * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
   4333  * Return whether to continue parsing.
   4334  */
   4335 static bool
   4336 ParseVarnameLong(
   4337 	const char **pp,
   4338 	char startc,
   4339 	GNode *scope,
   4340 	VarEvalMode emode,
   4341 
   4342 	const char **out_false_pp,
   4343 	VarParseResult *out_false_res,
   4344 	FStr *out_false_val,
   4345 
   4346 	char *out_true_endc,
   4347 	Var **out_true_v,
   4348 	bool *out_true_haveModifier,
   4349 	const char **out_true_extraModifiers,
   4350 	bool *out_true_dynamic,
   4351 	ExprDefined *out_true_exprDefined
   4352 )
   4353 {
   4354 	LazyBuf varname;
   4355 	Substring name;
   4356 	Var *v;
   4357 	bool haveModifier;
   4358 	bool dynamic = false;
   4359 
   4360 	const char *p = *pp;
   4361 	const char *const start = p;
   4362 	char endc = startc == '(' ? ')' : '}';
   4363 
   4364 	p += 2;			/* skip "${" or "$(" or "y(" */
   4365 	ParseVarname(&p, startc, endc, scope, emode, &varname);
   4366 	name = LazyBuf_Get(&varname);
   4367 
   4368 	if (*p == ':') {
   4369 		haveModifier = true;
   4370 	} else if (*p == endc) {
   4371 		haveModifier = false;
   4372 	} else {
   4373 		Parse_Error(PARSE_FATAL, "Unclosed variable \"%.*s\"",
   4374 		    (int)Substring_Length(name), name.start);
   4375 		LazyBuf_Done(&varname);
   4376 		*out_false_pp = p;
   4377 		*out_false_val = FStr_InitRefer(var_Error);
   4378 		*out_false_res = VPR_ERR;
   4379 		return false;
   4380 	}
   4381 
   4382 	v = VarFindSubstring(name, scope, true);
   4383 
   4384 	/*
   4385 	 * At this point, p points just after the variable name, either at
   4386 	 * ':' or at endc.
   4387 	 */
   4388 
   4389 	if (v == NULL && Substring_Equals(name, ".SUFFIXES")) {
   4390 		char *suffixes = Suff_NamesStr();
   4391 		v = VarNew(FStr_InitRefer(".SUFFIXES"), suffixes,
   4392 		    true, false, true);
   4393 		free(suffixes);
   4394 	} else if (v == NULL)
   4395 		v = FindLocalLegacyVar(name, scope, out_true_extraModifiers);
   4396 
   4397 	if (v == NULL) {
   4398 		/*
   4399 		 * Defer expansion of dynamic variables if they appear in
   4400 		 * non-local scope since they are not defined there.
   4401 		 */
   4402 		dynamic = VarnameIsDynamic(name) &&
   4403 			  (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
   4404 
   4405 		if (!haveModifier) {
   4406 			p++;	/* skip endc */
   4407 			*out_false_pp = p;
   4408 			*out_false_res = EvalUndefined(dynamic, start, p,
   4409 			    name, emode, out_false_val);
   4410 			LazyBuf_Done(&varname);
   4411 			return false;
   4412 		}
   4413 
   4414 		/*
   4415 		 * The variable expression is based on an undefined variable.
   4416 		 * Nevertheless it needs a Var, for modifiers that access the
   4417 		 * variable name, such as :L or :?.
   4418 		 *
   4419 		 * Most modifiers leave this expression in the "undefined"
   4420 		 * state (VES_UNDEF), only a few modifiers like :D, :U, :L,
   4421 		 * :P turn this undefined expression into a defined
   4422 		 * expression (VES_DEF).
   4423 		 *
   4424 		 * In the end, after applying all modifiers, if the expression
   4425 		 * is still undefined, Var_Parse will return an empty string
   4426 		 * instead of the actually computed value.
   4427 		 */
   4428 		v = VarNew(LazyBuf_DoneGet(&varname), "",
   4429 		    true, false, false);
   4430 		*out_true_exprDefined = DEF_UNDEF;
   4431 	} else
   4432 		LazyBuf_Done(&varname);
   4433 
   4434 	*pp = p;
   4435 	*out_true_endc = endc;
   4436 	*out_true_v = v;
   4437 	*out_true_haveModifier = haveModifier;
   4438 	*out_true_dynamic = dynamic;
   4439 	return true;
   4440 }
   4441 
   4442 #if __STDC_VERSION__ >= 199901L
   4443 #define Expr_Literal(name, value, emode, scope, defined) \
   4444 	{ name, value, emode, scope, defined }
   4445 #else
   4446 MAKE_INLINE Expr
   4447 Expr_Literal(const char *name, FStr value,
   4448 	     VarEvalMode emode, GNode *scope, ExprDefined defined)
   4449 {
   4450 	Expr expr;
   4451 
   4452 	expr.name = name;
   4453 	expr.value = value;
   4454 	expr.emode = emode;
   4455 	expr.scope = scope;
   4456 	expr.defined = defined;
   4457 	return expr;
   4458 }
   4459 #endif
   4460 
   4461 /*
   4462  * Expressions of the form ${:U...} with a trivial value are often generated
   4463  * by .for loops and are boring, therefore parse and evaluate them in a fast
   4464  * lane without debug logging.
   4465  */
   4466 static bool
   4467 Var_Parse_FastLane(const char **pp, VarEvalMode emode, FStr *out_value)
   4468 {
   4469 	const char *p;
   4470 
   4471 	p = *pp;
   4472 	if (!(p[0] == '$' && p[1] == '{' && p[2] == ':' && p[3] == 'U'))
   4473 		return false;
   4474 
   4475 	p += 4;
   4476 	while (*p != '$' && *p != '{' && *p != ':' && *p != '\\' &&
   4477 	       *p != '}' && *p != '\0')
   4478 		p++;
   4479 	if (*p != '}')
   4480 		return false;
   4481 
   4482 	if (emode == VARE_PARSE_ONLY)
   4483 		*out_value = FStr_InitRefer("");
   4484 	else
   4485 		*out_value = FStr_InitOwn(bmake_strsedup(*pp + 4, p));
   4486 	*pp = p + 1;
   4487 	return true;
   4488 }
   4489 
   4490 /*
   4491  * Given the start of a variable expression (such as $v, $(VAR),
   4492  * ${VAR:Mpattern}), extract the variable name and value, and the modifiers,
   4493  * if any.  While doing that, apply the modifiers to the value of the
   4494  * expression, forming its final value.  A few of the modifiers such as :!cmd!
   4495  * or ::= have side effects.
   4496  *
   4497  * Input:
   4498  *	*pp		The string to parse.
   4499  *			In CondParser_FuncCallEmpty, it may also point to the
   4500  *			"y" of "empty(VARNAME:Modifiers)", which is
   4501  *			syntactically the same.
   4502  *	scope		The scope for finding variables
   4503  *	emode		Controls the exact details of parsing and evaluation
   4504  *
   4505  * Output:
   4506  *	*pp		The position where to continue parsing.
   4507  *			TODO: After a parse error, the value of *pp is
   4508  *			unspecified.  It may not have been updated at all,
   4509  *			point to some random character in the string, to the
   4510  *			location of the parse error, or at the end of the
   4511  *			string.
   4512  *	*out_val	The value of the variable expression, never NULL.
   4513  *	*out_val	var_Error if there was a parse error.
   4514  *	*out_val	var_Error if the base variable of the expression was
   4515  *			undefined, emode is VARE_UNDEFERR, and none of
   4516  *			the modifiers turned the undefined expression into a
   4517  *			defined expression.
   4518  *			XXX: It is not guaranteed that an error message has
   4519  *			been printed.
   4520  *	*out_val	varUndefined if the base variable of the expression
   4521  *			was undefined, emode was not VARE_UNDEFERR,
   4522  *			and none of the modifiers turned the undefined
   4523  *			expression into a defined expression.
   4524  *			XXX: It is not guaranteed that an error message has
   4525  *			been printed.
   4526  */
   4527 VarParseResult
   4528 Var_Parse(const char **pp, GNode *scope, VarEvalMode emode, FStr *out_val)
   4529 {
   4530 	const char *p = *pp;
   4531 	const char *const start = p;
   4532 	/* true if have modifiers for the variable. */
   4533 	bool haveModifier;
   4534 	/* Starting character if variable in parens or braces. */
   4535 	char startc;
   4536 	/* Ending character if variable in parens or braces. */
   4537 	char endc;
   4538 	/*
   4539 	 * true if the variable is local and we're expanding it in a
   4540 	 * non-local scope. This is done to support dynamic sources.
   4541 	 * The result is just the expression, unaltered.
   4542 	 */
   4543 	bool dynamic;
   4544 	const char *extramodifiers;
   4545 	Var *v;
   4546 	Expr expr = Expr_Literal(NULL, FStr_InitRefer(NULL), emode,
   4547 	    scope, DEF_REGULAR);
   4548 
   4549 	if (Var_Parse_FastLane(pp, emode, out_val))
   4550 		return VPR_OK;
   4551 
   4552 	DEBUG2(VAR, "Var_Parse: %s (%s)\n", start, VarEvalMode_Name[emode]);
   4553 
   4554 	*out_val = FStr_InitRefer(NULL);
   4555 	extramodifiers = NULL;	/* extra modifiers to apply first */
   4556 	dynamic = false;
   4557 
   4558 	/*
   4559 	 * Appease GCC, which thinks that the variable might not be
   4560 	 * initialized.
   4561 	 */
   4562 	endc = '\0';
   4563 
   4564 	startc = p[1];
   4565 	if (startc != '(' && startc != '{') {
   4566 		VarParseResult res;
   4567 		if (!ParseVarnameShort(startc, pp, scope, emode, &res,
   4568 		    &out_val->str, &v))
   4569 			return res;
   4570 		haveModifier = false;
   4571 		p++;
   4572 	} else {
   4573 		VarParseResult res;
   4574 		if (!ParseVarnameLong(&p, startc, scope, emode,
   4575 		    pp, &res, out_val,
   4576 		    &endc, &v, &haveModifier, &extramodifiers,
   4577 		    &dynamic, &expr.defined))
   4578 			return res;
   4579 	}
   4580 
   4581 	expr.name = v->name.str;
   4582 	if (v->inUse)
   4583 		Fatal("Variable %s is recursive.", v->name.str);
   4584 
   4585 	/*
   4586 	 * XXX: This assignment creates an alias to the current value of the
   4587 	 * variable.  This means that as long as the value of the expression
   4588 	 * stays the same, the value of the variable must not change.
   4589 	 * Using the '::=' modifier, it could be possible to do exactly this.
   4590 	 * At the bottom of this function, the resulting value is compared to
   4591 	 * the then-current value of the variable.  This might also invoke
   4592 	 * undefined behavior.
   4593 	 */
   4594 	expr.value = FStr_InitRefer(v->val.data);
   4595 
   4596 	/*
   4597 	 * Before applying any modifiers, expand any nested expressions from
   4598 	 * the variable value.
   4599 	 */
   4600 	if (strchr(Expr_Str(&expr), '$') != NULL &&
   4601 	    VarEvalMode_ShouldEval(emode)) {
   4602 		char *expanded;
   4603 		VarEvalMode nested_emode = emode;
   4604 		if (opts.strict)
   4605 			nested_emode = VarEvalMode_UndefOk(nested_emode);
   4606 		v->inUse = true;
   4607 		(void)Var_Subst(Expr_Str(&expr), scope, nested_emode,
   4608 		    &expanded);
   4609 		v->inUse = false;
   4610 		/* TODO: handle errors */
   4611 		Expr_SetValueOwn(&expr, expanded);
   4612 	}
   4613 
   4614 	if (extramodifiers != NULL) {
   4615 		const char *em = extramodifiers;
   4616 		ApplyModifiers(&expr, &em, '\0', '\0');
   4617 	}
   4618 
   4619 	if (haveModifier) {
   4620 		p++;		/* Skip initial colon. */
   4621 		ApplyModifiers(&expr, &p, startc, endc);
   4622 	}
   4623 
   4624 	if (*p != '\0')		/* Skip past endc if possible. */
   4625 		p++;
   4626 
   4627 	*pp = p;
   4628 
   4629 	if (expr.defined == DEF_UNDEF) {
   4630 		if (dynamic)
   4631 			Expr_SetValueOwn(&expr, bmake_strsedup(start, p));
   4632 		else {
   4633 			/*
   4634 			 * The expression is still undefined, therefore
   4635 			 * discard the actual value and return an error marker
   4636 			 * instead.
   4637 			 */
   4638 			Expr_SetValueRefer(&expr,
   4639 			    emode == VARE_UNDEFERR
   4640 				? var_Error : varUndefined);
   4641 		}
   4642 	}
   4643 
   4644 	if (v->shortLived) {
   4645 		if (expr.value.str == v->val.data) {
   4646 			/* move ownership */
   4647 			expr.value.freeIt = v->val.data;
   4648 			v->val.data = NULL;
   4649 		}
   4650 		VarFreeShortLived(v);
   4651 	}
   4652 
   4653 	*out_val = expr.value;
   4654 	return VPR_OK;		/* XXX: Is not correct in all cases */
   4655 }
   4656 
   4657 static void
   4658 VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalMode emode)
   4659 {
   4660 	/* A dollar sign may be escaped with another dollar sign. */
   4661 	if (save_dollars && VarEvalMode_ShouldKeepDollar(emode))
   4662 		Buf_AddByte(res, '$');
   4663 	Buf_AddByte(res, '$');
   4664 	*pp += 2;
   4665 }
   4666 
   4667 static void
   4668 VarSubstExpr(const char **pp, Buffer *buf, GNode *scope,
   4669 	     VarEvalMode emode, bool *inout_errorReported)
   4670 {
   4671 	const char *p = *pp;
   4672 	const char *nested_p = p;
   4673 	FStr val;
   4674 
   4675 	(void)Var_Parse(&nested_p, scope, emode, &val);
   4676 	/* TODO: handle errors */
   4677 
   4678 	if (val.str == var_Error || val.str == varUndefined) {
   4679 		if (!VarEvalMode_ShouldKeepUndef(emode)) {
   4680 			p = nested_p;
   4681 		} else if (emode == VARE_UNDEFERR || val.str == var_Error) {
   4682 
   4683 			/*
   4684 			 * XXX: This condition is wrong.  If val == var_Error,
   4685 			 * this doesn't necessarily mean there was an undefined
   4686 			 * variable.  It could equally well be a parse error;
   4687 			 * see unit-tests/varmod-order.exp.
   4688 			 */
   4689 
   4690 			/*
   4691 			 * If variable is undefined, complain and skip the
   4692 			 * variable. The complaint will stop us from doing
   4693 			 * anything when the file is parsed.
   4694 			 */
   4695 			if (!*inout_errorReported) {
   4696 				Parse_Error(PARSE_FATAL,
   4697 				    "Undefined variable \"%.*s\"",
   4698 				    (int)(size_t)(nested_p - p), p);
   4699 			}
   4700 			p = nested_p;
   4701 			*inout_errorReported = true;
   4702 		} else {
   4703 			/*
   4704 			 * Copy the initial '$' of the undefined expression,
   4705 			 * thereby deferring expansion of the expression, but
   4706 			 * expand nested expressions if already possible. See
   4707 			 * unit-tests/varparse-undef-partial.mk.
   4708 			 */
   4709 			Buf_AddByte(buf, *p);
   4710 			p++;
   4711 		}
   4712 	} else {
   4713 		p = nested_p;
   4714 		Buf_AddStr(buf, val.str);
   4715 	}
   4716 
   4717 	FStr_Done(&val);
   4718 
   4719 	*pp = p;
   4720 }
   4721 
   4722 /*
   4723  * Skip as many characters as possible -- either to the end of the string
   4724  * or to the next dollar sign (variable expression).
   4725  */
   4726 static void
   4727 VarSubstPlain(const char **pp, Buffer *res)
   4728 {
   4729 	const char *p = *pp;
   4730 	const char *start = p;
   4731 
   4732 	for (p++; *p != '$' && *p != '\0'; p++)
   4733 		continue;
   4734 	Buf_AddBytesBetween(res, start, p);
   4735 	*pp = p;
   4736 }
   4737 
   4738 /*
   4739  * Expand all variable expressions like $V, ${VAR}, $(VAR:Modifiers) in the
   4740  * given string.
   4741  *
   4742  * Input:
   4743  *	str		The string in which the variable expressions are
   4744  *			expanded.
   4745  *	scope		The scope in which to start searching for
   4746  *			variables.  The other scopes are searched as well.
   4747  *	emode		The mode for parsing or evaluating subexpressions.
   4748  */
   4749 VarParseResult
   4750 Var_Subst(const char *str, GNode *scope, VarEvalMode emode, char **out_res)
   4751 {
   4752 	const char *p = str;
   4753 	Buffer res;
   4754 
   4755 	/*
   4756 	 * Set true if an error has already been reported, to prevent a
   4757 	 * plethora of messages when recursing
   4758 	 */
   4759 	/* XXX: Why is the 'static' necessary here? */
   4760 	static bool errorReported;
   4761 
   4762 	Buf_Init(&res);
   4763 	errorReported = false;
   4764 
   4765 	while (*p != '\0') {
   4766 		if (p[0] == '$' && p[1] == '$')
   4767 			VarSubstDollarDollar(&p, &res, emode);
   4768 		else if (p[0] == '$')
   4769 			VarSubstExpr(&p, &res, scope, emode, &errorReported);
   4770 		else
   4771 			VarSubstPlain(&p, &res);
   4772 	}
   4773 
   4774 	*out_res = Buf_DoneDataCompact(&res);
   4775 	return VPR_OK;
   4776 }
   4777 
   4778 /* Initialize the variables module. */
   4779 void
   4780 Var_Init(void)
   4781 {
   4782 	SCOPE_INTERNAL = GNode_New("Internal");
   4783 	SCOPE_GLOBAL = GNode_New("Global");
   4784 	SCOPE_CMDLINE = GNode_New("Command");
   4785 }
   4786 
   4787 /* Clean up the variables module. */
   4788 void
   4789 Var_End(void)
   4790 {
   4791 	Var_Stats();
   4792 }
   4793 
   4794 void
   4795 Var_Stats(void)
   4796 {
   4797 	HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables");
   4798 }
   4799 
   4800 static int
   4801 StrAsc(const void *sa, const void *sb)
   4802 {
   4803 	return strcmp(
   4804 	    *((const char *const *)sa), *((const char *const *)sb));
   4805 }
   4806 
   4807 
   4808 /* Print all variables in a scope, sorted by name. */
   4809 void
   4810 Var_Dump(GNode *scope)
   4811 {
   4812 	Vector /* of const char * */ vec;
   4813 	HashIter hi;
   4814 	size_t i;
   4815 	const char **varnames;
   4816 
   4817 	Vector_Init(&vec, sizeof(const char *));
   4818 
   4819 	HashIter_Init(&hi, &scope->vars);
   4820 	while (HashIter_Next(&hi) != NULL)
   4821 		*(const char **)Vector_Push(&vec) = hi.entry->key;
   4822 	varnames = vec.items;
   4823 
   4824 	qsort(varnames, vec.len, sizeof varnames[0], StrAsc);
   4825 
   4826 	for (i = 0; i < vec.len; i++) {
   4827 		const char *varname = varnames[i];
   4828 		Var *var = HashTable_FindValue(&scope->vars, varname);
   4829 		debug_printf("%-16s = %s\n", varname, var->val.data);
   4830 	}
   4831 
   4832 	Vector_Done(&vec);
   4833 }
   4834