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