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