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