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