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