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