Home | History | Annotate | Line # | Download | only in make
      1 /*	$NetBSD: var.c,v 1.1182 2026/07/13 19:23: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.1182 2026/07/13 19:23: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 	StringList patterns;
   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 	StringListNode *ln;
   2819 	StrMatchResult res;
   2820 	const char *pattern;
   2821 
   2822 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   2823 	for (ln = args->patterns.first; ln != NULL; ln = ln->next) {
   2824 		pattern = ln->datum;
   2825 		res = Str_Match(word.start, pattern);
   2826 		if (res.error != NULL && !args->error_reported) {
   2827 			args->error_reported = true;
   2828 			Parse_Error(PARSE_FATAL,
   2829 			    "%s in pattern \"%s\" of modifier \"%s\"",
   2830 			    res.error, pattern, args->neg ? ":N" : ":M");
   2831 		}
   2832 		if (res.matched != args->neg) {
   2833 			SepBuf_AddSubstring(buf, word);
   2834 			break;
   2835 		}
   2836 	}
   2837 }
   2838 
   2839 /* :Mpattern or :Npattern */
   2840 static ApplyModifierResult
   2841 ApplyModifier_Match(const char **pp, ModChain *ch)
   2842 {
   2843 	char mod = **pp;
   2844 	char *pattern;
   2845 
   2846 	pattern = ParseModifier_Match(pp, ch);
   2847 
   2848 	if (ModChain_ShouldEval(ch)) {
   2849 		struct ModifyWord_MatchArgs args;
   2850 		const char *brace;
   2851 
   2852 		Lst_Init(&args.patterns);
   2853 		if (mod == 'N')
   2854 			brace = NULL;	/* not supported */
   2855 		else
   2856 			for (brace = strchr(pattern, '{'); brace != NULL;
   2857 			     brace = strchr(++brace, '{')) {
   2858 				if (brace == pattern
   2859 				    || (brace[-1] != '\\' && brace[-1] != '$'))
   2860 					break;
   2861 			}
   2862 
   2863 		if (brace != NULL)
   2864 			ExpandCurly(pattern, brace, NULL, &args.patterns);
   2865 		else
   2866 			Lst_Append(&args.patterns, pattern);
   2867 		args.neg = mod == 'N';
   2868 		args.error_reported = false;
   2869 		ModifyWords(ch, ModifyWord_Match, &args, ch->oneBigWord);
   2870 		if (brace != NULL)
   2871 			Lst_DoneFree(&args.patterns);
   2872 		else
   2873 			Lst_Done(&args.patterns);
   2874 	}
   2875 
   2876 	free(pattern);
   2877 	return AMR_OK;
   2878 }
   2879 
   2880 struct ModifyWord_MtimeArgs {
   2881 	bool error;
   2882 	bool use_fallback;
   2883 	ApplyModifierResult rc;
   2884 	time_t fallback;
   2885 };
   2886 
   2887 static void
   2888 ModifyWord_Mtime(Substring word, SepBuf *buf, void *data)
   2889 {
   2890 	struct ModifyWord_MtimeArgs *args = data;
   2891 	struct stat st;
   2892 	char tbuf[21];
   2893 
   2894 	if (Substring_IsEmpty(word))
   2895 		return;
   2896 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   2897 	if (stat(word.start, &st) < 0) {
   2898 		if (args->error) {
   2899 			Parse_Error(PARSE_FATAL,
   2900 			    "Cannot determine mtime for \"%s\": %s",
   2901 			    word.start, strerror(errno));
   2902 			args->rc = AMR_CLEANUP;
   2903 			return;
   2904 		}
   2905 		if (args->use_fallback)
   2906 			st.st_mtime = args->fallback;
   2907 		else
   2908 			time(&st.st_mtime);
   2909 	}
   2910 	snprintf(tbuf, sizeof(tbuf), "%u", (unsigned)st.st_mtime);
   2911 	SepBuf_AddStr(buf, tbuf);
   2912 }
   2913 
   2914 /* :mtime */
   2915 static ApplyModifierResult
   2916 ApplyModifier_Mtime(const char **pp, ModChain *ch)
   2917 {
   2918 	const char *p, *mod = *pp;
   2919 	struct ModifyWord_MtimeArgs args;
   2920 
   2921 	if (!ModMatchEq(mod, "mtime", ch))
   2922 		return AMR_UNKNOWN;
   2923 	*pp += 5;
   2924 	p = *pp;
   2925 	args.error = false;
   2926 	args.use_fallback = p[0] == '=';
   2927 	args.rc = AMR_OK;
   2928 	if (args.use_fallback) {
   2929 		p++;
   2930 		if (TryParseTime(&p, &args.fallback)) {
   2931 		} else if (strncmp(p, "error", 5) == 0) {
   2932 			p += 5;
   2933 			args.error = true;
   2934 		} else
   2935 			goto invalid_argument;
   2936 		if (!IsDelimiter(*p, ch))
   2937 			goto invalid_argument;
   2938 		*pp = p;
   2939 	}
   2940 	ModifyWords(ch, ModifyWord_Mtime, &args, ch->oneBigWord);
   2941 	return args.rc;
   2942 
   2943 invalid_argument:
   2944 	Parse_Error(PARSE_FATAL,
   2945 	    "Invalid argument \"%.*s\" for modifier \":mtime\"",
   2946 	    (int)strcspn(*pp + 1, ":{}()"), *pp + 1);
   2947 	return AMR_CLEANUP;
   2948 }
   2949 
   2950 static void
   2951 ParsePatternFlags(const char **pp, PatternFlags *pflags, bool *oneBigWord)
   2952 {
   2953 	for (;; (*pp)++) {
   2954 		if (**pp == 'g')
   2955 			pflags->subGlobal = true;
   2956 		else if (**pp == '1')
   2957 			pflags->subOnce = true;
   2958 		else if (**pp == 'W')
   2959 			*oneBigWord = true;
   2960 		else
   2961 			break;
   2962 	}
   2963 }
   2964 
   2965 MAKE_INLINE PatternFlags
   2966 PatternFlags_None(void)
   2967 {
   2968 	PatternFlags pflags = { false, false, false, false };
   2969 	return pflags;
   2970 }
   2971 
   2972 /* :S,from,to, */
   2973 static ApplyModifierResult
   2974 ApplyModifier_Subst(const char **pp, ModChain *ch)
   2975 {
   2976 	struct ModifyWord_SubstArgs args;
   2977 	bool oneBigWord;
   2978 	LazyBuf lhsBuf, rhsBuf;
   2979 
   2980 	char delim = (*pp)[1];
   2981 	if (delim == '\0') {
   2982 		Parse_Error(PARSE_FATAL,
   2983 		    "Missing delimiter for modifier \":S\"");
   2984 		(*pp)++;
   2985 		return AMR_CLEANUP;
   2986 	}
   2987 
   2988 	*pp += 2;
   2989 
   2990 	args.pflags = PatternFlags_None();
   2991 	args.matched = false;
   2992 
   2993 	if (**pp == '^') {
   2994 		args.pflags.anchorStart = true;
   2995 		(*pp)++;
   2996 	}
   2997 
   2998 	if (!ParseModifierPart(pp, delim, delim, ch->expr->emode,
   2999 	    ch, &lhsBuf, &args.pflags, NULL))
   3000 		return AMR_CLEANUP;
   3001 	args.lhs = LazyBuf_Get(&lhsBuf);
   3002 
   3003 	if (!ParseModifierPart(pp, delim, delim, ch->expr->emode,
   3004 	    ch, &rhsBuf, NULL, &args)) {
   3005 		LazyBuf_Done(&lhsBuf);
   3006 		return AMR_CLEANUP;
   3007 	}
   3008 	args.rhs = LazyBuf_Get(&rhsBuf);
   3009 
   3010 	oneBigWord = ch->oneBigWord;
   3011 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   3012 
   3013 	ModifyWords(ch, ModifyWord_Subst, &args, oneBigWord);
   3014 
   3015 	LazyBuf_Done(&lhsBuf);
   3016 	LazyBuf_Done(&rhsBuf);
   3017 	return AMR_OK;
   3018 }
   3019 
   3020 /* :C,from,to, */
   3021 static ApplyModifierResult
   3022 ApplyModifier_Regex(const char **pp, ModChain *ch)
   3023 {
   3024 	struct ModifyWord_SubstRegexArgs args;
   3025 	bool oneBigWord;
   3026 	int error;
   3027 	LazyBuf reBuf, replaceBuf;
   3028 	FStr re;
   3029 
   3030 	char delim = (*pp)[1];
   3031 	if (delim == '\0') {
   3032 		Parse_Error(PARSE_FATAL,
   3033 		    "Missing delimiter for modifier \":C\"");
   3034 		(*pp)++;
   3035 		return AMR_CLEANUP;
   3036 	}
   3037 
   3038 	*pp += 2;
   3039 
   3040 	if (!ParseModifierPart(pp, delim, delim, ch->expr->emode,
   3041 	    ch, &reBuf, NULL, NULL))
   3042 		return AMR_CLEANUP;
   3043 	re = LazyBuf_DoneGet(&reBuf);
   3044 
   3045 	if (!ParseModifierPart(pp, delim, delim, ch->expr->emode,
   3046 	    ch, &replaceBuf, NULL, NULL)) {
   3047 		FStr_Done(&re);
   3048 		return AMR_CLEANUP;
   3049 	}
   3050 	args.replace = LazyBuf_Get(&replaceBuf);
   3051 
   3052 	args.pflags = PatternFlags_None();
   3053 	args.matched = false;
   3054 	oneBigWord = ch->oneBigWord;
   3055 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   3056 
   3057 	if (!ModChain_ShouldEval(ch))
   3058 		goto done;
   3059 
   3060 	if (re.str[0] == '\0') {
   3061 	    /* not all regcomp() fail on this */
   3062 	    Parse_Error(PARSE_FATAL, "Regex compilation error: empty");
   3063 	    goto re_err;
   3064 	}
   3065 
   3066 	error = regcomp(&args.re, re.str, REG_EXTENDED);
   3067 	if (error != 0) {
   3068 		RegexError(error, &args.re, "Regex compilation error");
   3069 	re_err:
   3070 		LazyBuf_Done(&replaceBuf);
   3071 		FStr_Done(&re);
   3072 		return AMR_CLEANUP;
   3073 	}
   3074 
   3075 	args.nsub = args.re.re_nsub + 1;
   3076 	if (args.nsub > 10)
   3077 		args.nsub = 10;
   3078 
   3079 	ModifyWords(ch, ModifyWord_SubstRegex, &args, oneBigWord);
   3080 
   3081 	regfree(&args.re);
   3082 done:
   3083 	LazyBuf_Done(&replaceBuf);
   3084 	FStr_Done(&re);
   3085 	return AMR_OK;
   3086 }
   3087 
   3088 /* :Q, :q */
   3089 static ApplyModifierResult
   3090 ApplyModifier_Quote(const char **pp, ModChain *ch)
   3091 {
   3092 	LazyBuf buf;
   3093 	bool quoteDollar;
   3094 
   3095 	quoteDollar = **pp == 'q';
   3096 	if (!IsDelimiter((*pp)[1], ch))
   3097 		return AMR_UNKNOWN;
   3098 	(*pp)++;
   3099 
   3100 	if (!ModChain_ShouldEval(ch))
   3101 		return AMR_OK;
   3102 
   3103 	QuoteShell(Expr_Str(ch->expr), quoteDollar, &buf);
   3104 	if (buf.data != NULL)
   3105 		Expr_SetValue(ch->expr, LazyBuf_DoneGet(&buf));
   3106 	else
   3107 		LazyBuf_Done(&buf);
   3108 
   3109 	return AMR_OK;
   3110 }
   3111 
   3112 static void
   3113 ModifyWord_Copy(Substring word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   3114 {
   3115 	SepBuf_AddSubstring(buf, word);
   3116 }
   3117 
   3118 /* :ts<separator> */
   3119 static ApplyModifierResult
   3120 ApplyModifier_ToSep(const char **pp, ModChain *ch)
   3121 {
   3122 	const char *sep = *pp + 2;
   3123 
   3124 	/*
   3125 	 * Even in parse-only mode, apply the side effects, since the side
   3126 	 * effects are neither observable nor is there a performance penalty.
   3127 	 * Checking for VARE_EVAL for every single piece of code in here
   3128 	 * would make the code in this function too hard to read.
   3129 	 */
   3130 
   3131 	/* ":ts<any><endc>" or ":ts<any>:" */
   3132 	if (sep[0] != ch->endc && IsDelimiter(sep[1], ch)) {
   3133 		*pp = sep + 1;
   3134 		ch->sep = sep[0];
   3135 		goto ok;
   3136 	}
   3137 
   3138 	/* ":ts<endc>" or ":ts:" */
   3139 	if (IsDelimiter(sep[0], ch)) {
   3140 		*pp = sep;
   3141 		ch->sep = '\0';	/* no separator */
   3142 		goto ok;
   3143 	}
   3144 
   3145 	if (sep[0] != '\\')
   3146 		return AMR_UNKNOWN;
   3147 
   3148 	/* ":ts\n" */
   3149 	if (sep[1] == 'n') {
   3150 		*pp = sep + 2;
   3151 		ch->sep = '\n';
   3152 		goto ok;
   3153 	}
   3154 
   3155 	/* ":ts\t" */
   3156 	if (sep[1] == 't') {
   3157 		*pp = sep + 2;
   3158 		ch->sep = '\t';
   3159 		goto ok;
   3160 	}
   3161 
   3162 	/* ":ts\x40" or ":ts\100" */
   3163 	{
   3164 		const char *p = sep + 1;
   3165 		int base = 8;	/* assume octal */
   3166 
   3167 		if (sep[1] == 'x') {
   3168 			base = 16;
   3169 			p++;
   3170 		} else if (!ch_isdigit(sep[1]))
   3171 			return AMR_UNKNOWN;	/* ":ts\..." */
   3172 
   3173 		if (!TryParseChar(&p, base, &ch->sep)) {
   3174 			Parse_Error(PARSE_FATAL,
   3175 			    "Invalid character number at \"%s\"", p);
   3176 			return AMR_CLEANUP;
   3177 		}
   3178 		if (!IsDelimiter(*p, ch))
   3179 			return AMR_UNKNOWN;
   3180 
   3181 		*pp = p;
   3182 	}
   3183 
   3184 ok:
   3185 	ModifyWords(ch, ModifyWord_Copy, NULL, ch->oneBigWord);
   3186 	return AMR_OK;
   3187 }
   3188 
   3189 static char *
   3190 str_totitle(const char *str)
   3191 {
   3192 	size_t i, n = strlen(str) + 1;
   3193 	char *res = bmake_malloc(n);
   3194 	for (i = 0; i < n; i++) {
   3195 		if (i == 0 || ch_isspace(res[i - 1]))
   3196 			res[i] = ch_toupper(str[i]);
   3197 		else
   3198 			res[i] = ch_tolower(str[i]);
   3199 	}
   3200 	return res;
   3201 }
   3202 
   3203 
   3204 static char *
   3205 str_toupper(const char *str)
   3206 {
   3207 	size_t i, n = strlen(str) + 1;
   3208 	char *res = bmake_malloc(n);
   3209 	for (i = 0; i < n; i++)
   3210 		res[i] = ch_toupper(str[i]);
   3211 	return res;
   3212 }
   3213 
   3214 static char *
   3215 str_tolower(const char *str)
   3216 {
   3217 	size_t i, n = strlen(str) + 1;
   3218 	char *res = bmake_malloc(n);
   3219 	for (i = 0; i < n; i++)
   3220 		res[i] = ch_tolower(str[i]);
   3221 	return res;
   3222 }
   3223 
   3224 /* :tA, :tu, :tl, :ts<separator>, etc. */
   3225 static ApplyModifierResult
   3226 ApplyModifier_To(const char **pp, ModChain *ch)
   3227 {
   3228 	Expr *expr = ch->expr;
   3229 	const char *mod = *pp;
   3230 	assert(mod[0] == 't');
   3231 
   3232 	if (IsDelimiter(mod[1], ch))
   3233 		return AMR_UNKNOWN;		/* ":t<endc>" or ":t:" */
   3234 
   3235 	if (mod[1] == 's')
   3236 		return ApplyModifier_ToSep(pp, ch);
   3237 
   3238 	if (!IsDelimiter(mod[2], ch))
   3239 		return AMR_UNKNOWN;
   3240 
   3241 	if (mod[1] == 'A') {				/* :tA */
   3242 		*pp = mod + 2;
   3243 		ModifyWords(ch, ModifyWord_Realpath, NULL, ch->oneBigWord);
   3244 		return AMR_OK;
   3245 	}
   3246 
   3247 	if (mod[1] == 't') {				/* :tt */
   3248 		*pp = mod + 2;
   3249 		if (Expr_ShouldEval(expr))
   3250 			Expr_SetValueOwn(expr, str_totitle(Expr_Str(expr)));
   3251 		return AMR_OK;
   3252 	}
   3253 
   3254 	if (mod[1] == 'u') {				/* :tu */
   3255 		*pp = mod + 2;
   3256 		if (Expr_ShouldEval(expr))
   3257 			Expr_SetValueOwn(expr, str_toupper(Expr_Str(expr)));
   3258 		return AMR_OK;
   3259 	}
   3260 
   3261 	if (mod[1] == 'l') {				/* :tl */
   3262 		*pp = mod + 2;
   3263 		if (Expr_ShouldEval(expr))
   3264 			Expr_SetValueOwn(expr, str_tolower(Expr_Str(expr)));
   3265 		return AMR_OK;
   3266 	}
   3267 
   3268 	if (mod[1] == 'W' || mod[1] == 'w') {		/* :tW, :tw */
   3269 		*pp = mod + 2;
   3270 		ch->oneBigWord = mod[1] == 'W';
   3271 		return AMR_OK;
   3272 	}
   3273 
   3274 	return AMR_UNKNOWN;		/* ":t<any>:" or ":t<any><endc>" */
   3275 }
   3276 
   3277 /* :[#], :[1], :[-1..1], etc. */
   3278 static ApplyModifierResult
   3279 ApplyModifier_Words(const char **pp, ModChain *ch)
   3280 {
   3281 	Expr *expr = ch->expr;
   3282 	int first, last;
   3283 	const char *p;
   3284 	LazyBuf argBuf;
   3285 	FStr arg;
   3286 
   3287 	(*pp)++;		/* skip the '[' */
   3288 	if (!ParseModifierPart(pp, ']', ']', expr->emode,
   3289 	    ch, &argBuf, NULL, NULL))
   3290 		return AMR_CLEANUP;
   3291 	arg = LazyBuf_DoneGet(&argBuf);
   3292 	p = arg.str;
   3293 
   3294 	if (!IsDelimiter(**pp, ch)) {
   3295 		Parse_Error(PARSE_FATAL,
   3296 		    "Extra text after \"[%s]\"", arg.str);
   3297 		FStr_Done(&arg);
   3298 		return AMR_CLEANUP;
   3299 	}
   3300 
   3301 	if (!ModChain_ShouldEval(ch))
   3302 		goto ok;
   3303 
   3304 	if (p[0] == '\0')
   3305 		goto bad_modifier;		/* Found ":[]". */
   3306 
   3307 	if (strcmp(p, "#") == 0) {		/* Found ":[#]" */
   3308 		if (ch->oneBigWord)
   3309 			Expr_SetValueRefer(expr, "1");
   3310 		else {
   3311 			Buffer buf;
   3312 
   3313 			SubstringWords words = Expr_Words(expr);
   3314 			size_t ac = words.len;
   3315 			SubstringWords_Free(words);
   3316 
   3317 			Buf_Init(&buf);
   3318 			Buf_AddInt(&buf, (int)ac);
   3319 			Expr_SetValueOwn(expr, Buf_DoneData(&buf));
   3320 		}
   3321 		goto ok;
   3322 	}
   3323 
   3324 	if (strcmp(p, "*") == 0) {		/* ":[*]" */
   3325 		ch->oneBigWord = true;
   3326 		goto ok;
   3327 	}
   3328 
   3329 	if (strcmp(p, "@") == 0) {		/* ":[@]" */
   3330 		ch->oneBigWord = false;
   3331 		goto ok;
   3332 	}
   3333 
   3334 	/* Expect ":[N]" or ":[start..end]" */
   3335 	if (!TryParseIntBase0(&p, &first))
   3336 		goto bad_modifier;
   3337 
   3338 	if (p[0] == '\0')			/* ":[N]" */
   3339 		last = first;
   3340 	else if (strncmp(p, "..", 2) == 0) {
   3341 		p += 2;
   3342 		if (!TryParseIntBase0(&p, &last) || *p != '\0')
   3343 			goto bad_modifier;
   3344 	} else
   3345 		goto bad_modifier;
   3346 
   3347 	if (first == 0 && last == 0) {		/* ":[0]" or ":[0..0]" */
   3348 		ch->oneBigWord = true;
   3349 		goto ok;
   3350 	}
   3351 
   3352 	if (first == 0 || last == 0)		/* ":[0..N]" or ":[N..0]" */
   3353 		goto bad_modifier;
   3354 
   3355 	Expr_SetValueOwn(expr,
   3356 	    VarSelectWords(Expr_Str(expr), first, last,
   3357 		ch->sep, ch->oneBigWord));
   3358 
   3359 ok:
   3360 	FStr_Done(&arg);
   3361 	return AMR_OK;
   3362 
   3363 bad_modifier:
   3364 	Parse_Error(PARSE_FATAL, "Invalid modifier \":[%s]\"", arg.str);
   3365 	FStr_Done(&arg);
   3366 	return AMR_CLEANUP;
   3367 }
   3368 
   3369 #if __STDC_VERSION__ >= 199901L
   3370 # define NUM_TYPE long long
   3371 # define PARSE_NUM_TYPE strtoll
   3372 #else
   3373 # define NUM_TYPE long
   3374 # define PARSE_NUM_TYPE strtol
   3375 #endif
   3376 
   3377 static NUM_TYPE
   3378 num_val(Substring s)
   3379 {
   3380 	NUM_TYPE val;
   3381 	char *ep;
   3382 
   3383 	val = PARSE_NUM_TYPE(s.start, &ep, 0);
   3384 	if (ep != s.start) {
   3385 		switch (*ep) {
   3386 		case 'K':
   3387 		case 'k':
   3388 			val <<= 10;
   3389 			break;
   3390 		case 'M':
   3391 		case 'm':
   3392 			val <<= 20;
   3393 			break;
   3394 		case 'G':
   3395 		case 'g':
   3396 			val <<= 30;
   3397 			break;
   3398 		}
   3399 	}
   3400 	return val;
   3401 }
   3402 
   3403 static int
   3404 SubNumAsc(const void *sa, const void *sb)
   3405 {
   3406 	NUM_TYPE a, b;
   3407 
   3408 	a = num_val(*(const Substring *)sa);
   3409 	b = num_val(*(const Substring *)sb);
   3410 	return a > b ? 1 : b > a ? -1 : 0;
   3411 }
   3412 
   3413 static int
   3414 SubNumDesc(const void *sa, const void *sb)
   3415 {
   3416 	return SubNumAsc(sb, sa);
   3417 }
   3418 
   3419 static int
   3420 Substring_Cmp(Substring a, Substring b)
   3421 {
   3422 	for (; a.start < a.end && b.start < b.end; a.start++, b.start++)
   3423 		if (a.start[0] != b.start[0])
   3424 			return (unsigned char)a.start[0]
   3425 			    - (unsigned char)b.start[0];
   3426 	return (int)((a.end - a.start) - (b.end - b.start));
   3427 }
   3428 
   3429 static int
   3430 SubStrAsc(const void *sa, const void *sb)
   3431 {
   3432 	return Substring_Cmp(*(const Substring *)sa, *(const Substring *)sb);
   3433 }
   3434 
   3435 static int
   3436 SubStrDesc(const void *sa, const void *sb)
   3437 {
   3438 	return SubStrAsc(sb, sa);
   3439 }
   3440 
   3441 static void
   3442 ShuffleSubstrings(Substring *strs, size_t n)
   3443 {
   3444 	size_t i;
   3445 
   3446 	for (i = n - 1; i > 0; i--) {
   3447 		size_t rndidx = (size_t)random() % (i + 1);
   3448 		Substring t = strs[i];
   3449 		strs[i] = strs[rndidx];
   3450 		strs[rndidx] = t;
   3451 	}
   3452 }
   3453 
   3454 /*
   3455  * :O		order ascending
   3456  * :Or		order descending
   3457  * :Ox		shuffle
   3458  * :On		numeric ascending
   3459  * :Onr, :Orn	numeric descending
   3460  */
   3461 static ApplyModifierResult
   3462 ApplyModifier_Order(const char **pp, ModChain *ch)
   3463 {
   3464 	const char *mod = *pp;
   3465 	SubstringWords words;
   3466 	int (*cmp)(const void *, const void *);
   3467 
   3468 	if (IsDelimiter(mod[1], ch)) {
   3469 		cmp = SubStrAsc;
   3470 		(*pp)++;
   3471 	} else if (IsDelimiter(mod[2], ch)) {
   3472 		if (mod[1] == 'n')
   3473 			cmp = SubNumAsc;
   3474 		else if (mod[1] == 'r')
   3475 			cmp = SubStrDesc;
   3476 		else if (mod[1] == 'x')
   3477 			cmp = NULL;
   3478 		else
   3479 			return AMR_UNKNOWN;
   3480 		*pp += 2;
   3481 	} else if (IsDelimiter(mod[3], ch)) {
   3482 		if ((mod[1] == 'n' && mod[2] == 'r') ||
   3483 		    (mod[1] == 'r' && mod[2] == 'n'))
   3484 			cmp = SubNumDesc;
   3485 		else
   3486 			return AMR_UNKNOWN;
   3487 		*pp += 3;
   3488 	} else
   3489 		return AMR_UNKNOWN;
   3490 
   3491 	if (!ModChain_ShouldEval(ch))
   3492 		return AMR_OK;
   3493 
   3494 	words = Expr_Words(ch->expr);
   3495 	if (cmp == NULL)
   3496 		ShuffleSubstrings(words.words, words.len);
   3497 	else {
   3498 		assert(words.words[0].end[0] == '\0');
   3499 		qsort(words.words, words.len, sizeof(words.words[0]), cmp);
   3500 	}
   3501 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3502 
   3503 	return AMR_OK;
   3504 }
   3505 
   3506 /* :? then : else */
   3507 static ApplyModifierResult
   3508 ApplyModifier_IfElse(const char **pp, ModChain *ch)
   3509 {
   3510 	Expr *expr = ch->expr;
   3511 	LazyBuf thenBuf;
   3512 	LazyBuf elseBuf;
   3513 
   3514 	VarEvalMode then_emode = VARE_PARSE;
   3515 	VarEvalMode else_emode = VARE_PARSE;
   3516 	int parseErrorsBefore = parseErrors;
   3517 
   3518 	CondResult cond_rc = CR_TRUE;	/* anything other than CR_ERROR */
   3519 	if (Expr_ShouldEval(expr)) {
   3520 		evalStack.elems[evalStack.len - 1].kind = VSK_COND;
   3521 		cond_rc = Cond_EvalCondition(expr->name);
   3522 		if (cond_rc == CR_TRUE)
   3523 			then_emode = expr->emode;
   3524 		else if (cond_rc == CR_FALSE)
   3525 			else_emode = expr->emode;
   3526 		else if (parseErrors == parseErrorsBefore)
   3527 			Parse_Error(PARSE_FATAL, "Bad condition");
   3528 	}
   3529 
   3530 	evalStack.elems[evalStack.len - 1].kind = VSK_COND_THEN;
   3531 	(*pp)++;		/* skip past the '?' */
   3532 	if (!ParseModifierPart(pp, ':', ':', then_emode,
   3533 	    ch, &thenBuf, NULL, NULL))
   3534 		return AMR_CLEANUP;
   3535 
   3536 	evalStack.elems[evalStack.len - 1].kind = VSK_COND_ELSE;
   3537 	if (!ParseModifierPart(pp, ch->endc, ch->endc, else_emode,
   3538 	    ch, &elseBuf, NULL, NULL)) {
   3539 		LazyBuf_Done(&thenBuf);
   3540 		return AMR_CLEANUP;
   3541 	}
   3542 
   3543 	(*pp)--;		/* Go back to the ch->endc. */
   3544 
   3545 	if (cond_rc == CR_ERROR) {
   3546 		LazyBuf_Done(&thenBuf);
   3547 		LazyBuf_Done(&elseBuf);
   3548 		return AMR_CLEANUP;
   3549 	}
   3550 
   3551 	if (!Expr_ShouldEval(expr)) {
   3552 		LazyBuf_Done(&thenBuf);
   3553 		LazyBuf_Done(&elseBuf);
   3554 	} else if (cond_rc == CR_TRUE) {
   3555 		Expr_SetValue(expr, LazyBuf_DoneGet(&thenBuf));
   3556 		LazyBuf_Done(&elseBuf);
   3557 	} else {
   3558 		LazyBuf_Done(&thenBuf);
   3559 		Expr_SetValue(expr, LazyBuf_DoneGet(&elseBuf));
   3560 	}
   3561 	Expr_Define(expr);
   3562 	return AMR_OK;
   3563 }
   3564 
   3565 /*
   3566  * The ::= modifiers are special in that they do not read the variable value
   3567  * but instead assign to that variable.  They always expand to an empty
   3568  * string.
   3569  *
   3570  * Their main purpose is in supporting .for loops that generate shell commands
   3571  * since an ordinary variable assignment at that point would terminate the
   3572  * dependency group for these targets.  For example:
   3573  *
   3574  * list-targets: .USE
   3575  * .for i in ${.TARGET} ${.TARGET:R}.gz
   3576  *	@${t::=$i}
   3577  *	@echo 'The target is ${t:T}.'
   3578  * .endfor
   3579  *
   3580  *	  ::=<str>	Assigns <str> as the new value of variable.
   3581  *	  ::?=<str>	Assigns <str> as value of variable if
   3582  *			it was not already set.
   3583  *	  ::+=<str>	Appends <str> to variable.
   3584  *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
   3585  *			variable.
   3586  */
   3587 static ApplyModifierResult
   3588 ApplyModifier_Assign(const char **pp, ModChain *ch)
   3589 {
   3590 	Expr *expr = ch->expr;
   3591 	GNode *scope;
   3592 	FStr val;
   3593 	LazyBuf buf;
   3594 
   3595 	const char *mod = *pp;
   3596 	const char *op = mod + 1;
   3597 
   3598 	if (op[0] == '=')
   3599 		goto found_op;
   3600 	if ((op[0] == '+' || op[0] == '?' || op[0] == '!') && op[1] == '=')
   3601 		goto found_op;
   3602 	return AMR_UNKNOWN;	/* "::<unrecognized>" */
   3603 
   3604 found_op:
   3605 	if (expr->name[0] == '\0') {
   3606 		const char *value = op[0] == '=' ? op + 1 : op + 2;
   3607 		*pp = mod + 1;
   3608 		/* Take a guess at where the modifier ends. */
   3609 		Parse_Error(PARSE_FATAL,
   3610 		    "Invalid attempt to assign \"%.*s\" to variable \"\" "
   3611 		    "via modifier \":%.*s\"",
   3612 		    (int)strcspn(value, ":)}"), value,
   3613 		    (int)(value - mod), mod);
   3614 		return AMR_CLEANUP;
   3615 	}
   3616 
   3617 	*pp = mod + (op[0] != '=' ? 3 : 2);
   3618 
   3619 	if (!ParseModifierPart(pp, ch->endc, ch->endc, expr->emode,
   3620 	    ch, &buf, NULL, NULL))
   3621 		return AMR_CLEANUP;
   3622 	val = LazyBuf_DoneGet(&buf);
   3623 
   3624 	(*pp)--;		/* Go back to the ch->endc. */
   3625 
   3626 	if (!Expr_ShouldEval(expr))
   3627 		goto done;
   3628 
   3629 	scope = expr->scope;	/* scope where v belongs */
   3630 	if (expr->defined == DEF_REGULAR && expr->scope != SCOPE_GLOBAL
   3631 	    && VarFind(expr->name, expr->scope, false) == NULL)
   3632 		scope = SCOPE_GLOBAL;
   3633 
   3634 	if (op[0] == '+')
   3635 		Var_Append(scope, expr->name, val.str);
   3636 	else if (op[0] == '!') {
   3637 		char *output, *error;
   3638 		output = Cmd_Exec(val.str, &error);
   3639 		if (error != NULL) {
   3640 			Parse_Error(PARSE_WARNING, "%s", error);
   3641 			free(error);
   3642 		} else
   3643 			Var_Set(scope, expr->name, output);
   3644 		free(output);
   3645 	} else if (op[0] == '?' && expr->defined == DEF_REGULAR) {
   3646 		/* Do nothing. */
   3647 	} else
   3648 		Var_Set(scope, expr->name, val.str);
   3649 
   3650 	Expr_SetValueRefer(expr, "");
   3651 
   3652 done:
   3653 	FStr_Done(&val);
   3654 	return AMR_OK;
   3655 }
   3656 
   3657 /*
   3658  * :_=...
   3659  * remember current value
   3660  */
   3661 static ApplyModifierResult
   3662 ApplyModifier_Remember(const char **pp, ModChain *ch)
   3663 {
   3664 	Expr *expr = ch->expr;
   3665 	const char *mod = *pp;
   3666 	FStr name;
   3667 
   3668 	if (!ModMatchEq(mod, "_", ch))
   3669 		return AMR_UNKNOWN;
   3670 
   3671 	name = FStr_InitRefer("_");
   3672 	if (mod[1] == '=') {
   3673 		/*
   3674 		 * XXX: This ad-hoc call to strcspn deviates from the usual
   3675 		 * behavior defined in ParseModifierPart.  This creates an
   3676 		 * unnecessary and undocumented inconsistency in make.
   3677 		 */
   3678 		const char *arg = mod + 2;
   3679 		size_t argLen = strcspn(arg, ":)}");
   3680 		*pp = arg + argLen;
   3681 		name = FStr_InitOwn(bmake_strldup(arg, argLen));
   3682 	} else
   3683 		*pp = mod + 1;
   3684 
   3685 	if (Expr_ShouldEval(expr))
   3686 		Var_Set(SCOPE_GLOBAL, name.str, Expr_Str(expr));
   3687 	FStr_Done(&name);
   3688 
   3689 	return AMR_OK;
   3690 }
   3691 
   3692 /*
   3693  * Apply the given function to each word of the variable value,
   3694  * for a single-letter modifier such as :H, :T.
   3695  */
   3696 static ApplyModifierResult
   3697 ApplyModifier_WordFunc(const char **pp, ModChain *ch,
   3698 		       ModifyWordProc modifyWord)
   3699 {
   3700 	if (!IsDelimiter((*pp)[1], ch))
   3701 		return AMR_UNKNOWN;
   3702 	(*pp)++;
   3703 
   3704 	ModifyWords(ch, modifyWord, NULL, ch->oneBigWord);
   3705 
   3706 	return AMR_OK;
   3707 }
   3708 
   3709 /* Remove adjacent duplicate words. */
   3710 static ApplyModifierResult
   3711 ApplyModifier_Unique(const char **pp, ModChain *ch)
   3712 {
   3713 	SubstringWords words;
   3714 
   3715 	if (!IsDelimiter((*pp)[1], ch))
   3716 		return AMR_UNKNOWN;
   3717 	(*pp)++;
   3718 
   3719 	if (!ModChain_ShouldEval(ch))
   3720 		return AMR_OK;
   3721 
   3722 	words = Expr_Words(ch->expr);
   3723 
   3724 	if (words.len > 1) {
   3725 		size_t di, si;
   3726 		for (di = 0, si = 1; si < words.len; si++)
   3727 			if (!Substring_Eq(words.words[di], words.words[si]))
   3728 				words.words[++di] = words.words[si];
   3729 		words.len = di + 1;
   3730 	}
   3731 
   3732 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3733 
   3734 	return AMR_OK;
   3735 }
   3736 
   3737 /* Test whether the modifier has the form '<lhs>=<rhs>'. */
   3738 static bool
   3739 IsSysVModifier(const char *p, char startc, char endc)
   3740 {
   3741 	bool eqFound = false;
   3742 
   3743 	int depth = 1;
   3744 	while (*p != '\0') {
   3745 		if (*p == '=')	/* XXX: should also test depth == 1 */
   3746 			eqFound = true;
   3747 		else if (*p == endc) {
   3748 			if (--depth == 0)
   3749 				break;
   3750 		} else if (*p == startc)
   3751 			depth++;
   3752 		p++;
   3753 	}
   3754 	return eqFound;
   3755 }
   3756 
   3757 /* :from=to */
   3758 static ApplyModifierResult
   3759 ApplyModifier_SysV(const char **pp, ModChain *ch)
   3760 {
   3761 	Expr *expr = ch->expr;
   3762 	LazyBuf lhsBuf, rhsBuf;
   3763 	FStr rhs;
   3764 	struct ModifyWord_SysVSubstArgs args;
   3765 	Substring lhs;
   3766 	const char *lhsSuffix;
   3767 
   3768 	const char *mod = *pp;
   3769 
   3770 	if (!IsSysVModifier(mod, ch->startc, ch->endc))
   3771 		return AMR_UNKNOWN;
   3772 
   3773 	if (!ParseModifierPart(pp, '=', '=', expr->emode,
   3774 	    ch, &lhsBuf, NULL, NULL))
   3775 		return AMR_CLEANUP;
   3776 
   3777 	if (!ParseModifierPart(pp, ch->endc, ch->endc, expr->emode,
   3778 	    ch, &rhsBuf, NULL, NULL)) {
   3779 		LazyBuf_Done(&lhsBuf);
   3780 		return AMR_CLEANUP;
   3781 	}
   3782 	rhs = LazyBuf_DoneGet(&rhsBuf);
   3783 
   3784 	(*pp)--;		/* Go back to the ch->endc. */
   3785 
   3786 	/* Do not turn an empty expression into non-empty. */
   3787 	if (lhsBuf.len == 0 && Expr_Str(expr)[0] == '\0')
   3788 		goto done;
   3789 
   3790 	lhs = LazyBuf_Get(&lhsBuf);
   3791 	lhsSuffix = Substring_SkipFirst(lhs, '%');
   3792 
   3793 	args.scope = expr->scope;
   3794 	args.lhsPrefix = Substring_Init(lhs.start,
   3795 	    lhsSuffix != lhs.start ? lhsSuffix - 1 : lhs.start);
   3796 	args.lhsPercent = lhsSuffix != lhs.start;
   3797 	args.lhsSuffix = Substring_Init(lhsSuffix, lhs.end);
   3798 	args.rhs = rhs.str;
   3799 
   3800 	ModifyWords(ch, ModifyWord_SysVSubst, &args, ch->oneBigWord);
   3801 
   3802 done:
   3803 	LazyBuf_Done(&lhsBuf);
   3804 	FStr_Done(&rhs);
   3805 	return AMR_OK;
   3806 }
   3807 
   3808 /* :sh */
   3809 static ApplyModifierResult
   3810 ApplyModifier_SunShell(const char **pp, ModChain *ch)
   3811 {
   3812 	Expr *expr = ch->expr;
   3813 	const char *p = *pp;
   3814 	if (!(p[1] == 'h' && IsDelimiter(p[2], ch)))
   3815 		return AMR_UNKNOWN;
   3816 	*pp = p + 2;
   3817 
   3818 	if (Expr_ShouldEval(expr)) {
   3819 		char *output, *error;
   3820 		output = Cmd_Exec(Expr_Str(expr), &error);
   3821 		if (error != NULL) {
   3822 			Parse_Error(PARSE_WARNING, "%s", error);
   3823 			free(error);
   3824 		}
   3825 		Expr_SetValueOwn(expr, output);
   3826 	}
   3827 
   3828 	return AMR_OK;
   3829 }
   3830 
   3831 /* :sh1 */
   3832 static ApplyModifierResult
   3833 ApplyModifier_SunShell1(const char **pp, ModChain *ch)
   3834 {
   3835 	Expr *expr = ch->expr;
   3836 	const char *p = *pp;
   3837 
   3838 	if (!(p[1] == 'h' && p[2] == '1' && IsDelimiter(p[3], ch)))
   3839 		return AMR_UNKNOWN;
   3840 	*pp = p + 3;
   3841 
   3842 	if (Expr_ShouldEval(expr)) {
   3843 		char *cache_varname;
   3844 		Var *v;
   3845 
   3846 		cache_varname = str_concat2(".MAKE.SH1.", expr->name);
   3847 		v = VarFind(cache_varname, SCOPE_GLOBAL, false);
   3848 		if (v == NULL) {
   3849 			char *output, *error;
   3850 
   3851 			output = Cmd_Exec(Expr_Str(expr), &error);
   3852 			if (error != NULL) {
   3853 				Parse_Error(PARSE_WARNING, "%s", error);
   3854 				free(error);
   3855 			}
   3856 			Var_SetWithFlags(SCOPE_GLOBAL, cache_varname, output,
   3857 			    VAR_SET_NO_EXPORT);
   3858 			Expr_SetValueOwn(expr, output);
   3859 		} else {
   3860 			Expr_SetValueRefer(expr, v->val.data);
   3861 		}
   3862 		free(cache_varname);
   3863 	}
   3864 
   3865 	return AMR_OK;
   3866 }
   3867 
   3868 
   3869 /*
   3870  * In cases where the evaluation mode and the definedness are the "standard"
   3871  * ones, don't log them, to keep the logs readable.
   3872  */
   3873 static bool
   3874 ShouldLogInSimpleFormat(const Expr *expr)
   3875 {
   3876 	return (expr->emode == VARE_EVAL
   3877 		|| expr->emode == VARE_EVAL_DEFINED
   3878 		|| expr->emode == VARE_EVAL_DEFINED_LOUD)
   3879 	    && expr->defined == DEF_REGULAR;
   3880 }
   3881 
   3882 static void
   3883 LogBeforeApply(const ModChain *ch, const char *mod)
   3884 {
   3885 	const Expr *expr = ch->expr;
   3886 	bool is_single_char = mod[0] != '\0' && IsDelimiter(mod[1], ch);
   3887 
   3888 	/*
   3889 	 * At this point, only the first character of the modifier can
   3890 	 * be used since the end of the modifier is not yet known.
   3891 	 */
   3892 
   3893 	if (!Expr_ShouldEval(expr)) {
   3894 		debug_printf("Parsing modifier ${%s:%c%s}\n",
   3895 		    expr->name, mod[0], is_single_char ? "" : "...");
   3896 		return;
   3897 	}
   3898 
   3899 	if (ShouldLogInSimpleFormat(expr)) {
   3900 		debug_printf(
   3901 		    "Evaluating modifier ${%s:%c%s} on value \"%s\"\n",
   3902 		    expr->name, mod[0], is_single_char ? "" : "...",
   3903 		    Expr_Str(expr));
   3904 		return;
   3905 	}
   3906 
   3907 	debug_printf(
   3908 	    "Evaluating modifier ${%s:%c%s} on value \"%s\" (%s, %s)\n",
   3909 	    expr->name, mod[0], is_single_char ? "" : "...", Expr_Str(expr),
   3910 	    VarEvalMode_Name[expr->emode], ExprDefined_Name[expr->defined]);
   3911 }
   3912 
   3913 static void
   3914 LogAfterApply(const ModChain *ch, const char *p, const char *mod)
   3915 {
   3916 	const Expr *expr = ch->expr;
   3917 	const char *value = Expr_Str(expr);
   3918 
   3919 	if (ShouldLogInSimpleFormat(expr)) {
   3920 		debug_printf("Result of ${%s:%.*s} is \"%s\"\n",
   3921 		    expr->name, (int)(p - mod), mod, value);
   3922 		return;
   3923 	}
   3924 
   3925 	debug_printf("Result of ${%s:%.*s} is \"%s\" (%s, %s)\n",
   3926 	    expr->name, (int)(p - mod), mod, value,
   3927 	    VarEvalMode_Name[expr->emode],
   3928 	    ExprDefined_Name[expr->defined]);
   3929 }
   3930 
   3931 static ApplyModifierResult
   3932 ApplyModifier(const char **pp, ModChain *ch)
   3933 {
   3934 	switch (**pp) {
   3935 	case '!':
   3936 		return ApplyModifier_ShellCommand(pp, ch);
   3937 	case ':':
   3938 		return ApplyModifier_Assign(pp, ch);
   3939 	case '?':
   3940 		return ApplyModifier_IfElse(pp, ch);
   3941 	case '@':
   3942 		return ApplyModifier_Loop(pp, ch);
   3943 	case '[':
   3944 		return ApplyModifier_Words(pp, ch);
   3945 	case '_':
   3946 		return ApplyModifier_Remember(pp, ch);
   3947 	case 'C':
   3948 		return ApplyModifier_Regex(pp, ch);
   3949 	case 'D':
   3950 	case 'U':
   3951 		return ApplyModifier_Defined(pp, ch);
   3952 	case 'E':
   3953 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Suffix);
   3954 	case 'g':
   3955 	case 'l':
   3956 		return ApplyModifier_Time(pp, ch);
   3957 	case 'H':
   3958 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Head);
   3959 	case 'h':
   3960 		return ApplyModifier_Hash(pp, ch);
   3961 	case 'L':
   3962 		return ApplyModifier_Literal(pp, ch);
   3963 	case 'M':
   3964 	case 'N':
   3965 		return ApplyModifier_Match(pp, ch);
   3966 	case 'm':
   3967 		return ApplyModifier_Mtime(pp, ch);
   3968 	case 'O':
   3969 		return ApplyModifier_Order(pp, ch);
   3970 	case 'P':
   3971 		return ApplyModifier_Path(pp, ch);
   3972 	case 'Q':
   3973 	case 'q':
   3974 		return ApplyModifier_Quote(pp, ch);
   3975 	case 'R':
   3976 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Root);
   3977 	case 'r':
   3978 		return ApplyModifier_Range(pp, ch);
   3979 	case 'S':
   3980 		return ApplyModifier_Subst(pp, ch);
   3981 	case 's':
   3982 		if ((*pp)[1] == 'h' && (*pp)[2] == '1')
   3983 			return ApplyModifier_SunShell1(pp, ch);
   3984 		return ApplyModifier_SunShell(pp, ch);
   3985 	case 'T':
   3986 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Tail);
   3987 	case 't':
   3988 		return ApplyModifier_To(pp, ch);
   3989 	case 'u':
   3990 		return ApplyModifier_Unique(pp, ch);
   3991 	default:
   3992 		return AMR_UNKNOWN;
   3993 	}
   3994 }
   3995 
   3996 static void ApplyModifiers(Expr *, const char **, char, char);
   3997 
   3998 typedef enum ApplyModifiersIndirectResult {
   3999 	/* The indirect modifiers have been applied successfully. */
   4000 	AMIR_CONTINUE,
   4001 	/* Fall back to the SysV modifier. */
   4002 	AMIR_SYSV,
   4003 	/* Error out. */
   4004 	AMIR_OUT
   4005 } ApplyModifiersIndirectResult;
   4006 
   4007 /*
   4008  * While expanding an expression, expand and apply indirect modifiers,
   4009  * such as in ${VAR:${M_indirect}}.
   4010  *
   4011  * All indirect modifiers of a group must come from a single
   4012  * expression.  ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
   4013  *
   4014  * Multiple groups of indirect modifiers can be chained by separating them
   4015  * with colons.  ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
   4016  *
   4017  * If the expression is not followed by ch->endc or ':', fall
   4018  * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
   4019  */
   4020 static ApplyModifiersIndirectResult
   4021 ApplyModifiersIndirect(ModChain *ch, const char **pp)
   4022 {
   4023 	Expr *expr = ch->expr;
   4024 	const char *p = *pp;
   4025 	FStr mods = Var_Parse(&p, expr->scope, expr->emode);
   4026 	/* TODO: handle errors */
   4027 
   4028 	if (mods.str[0] != '\0' && !IsDelimiter(*p, ch)) {
   4029 		FStr_Done(&mods);
   4030 		return AMIR_SYSV;
   4031 	}
   4032 
   4033 	DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
   4034 	    mods.str, (int)(p - *pp), *pp);
   4035 
   4036 	if (ModChain_ShouldEval(ch) && mods.str[0] != '\0') {
   4037 		const char *modsp = mods.str;
   4038 		EvalStack_Push(VSK_INDIRECT_MODIFIERS, mods.str, NULL);
   4039 		ApplyModifiers(expr, &modsp, '\0', '\0');
   4040 		EvalStack_Pop();
   4041 		if (Expr_Str(expr) == var_Error || *modsp != '\0') {
   4042 			FStr_Done(&mods);
   4043 			*pp = p;
   4044 			return AMIR_OUT;	/* error already reported */
   4045 		}
   4046 	}
   4047 	FStr_Done(&mods);
   4048 
   4049 	if (*p == ':')
   4050 		p++;
   4051 	else if (*p == '\0' && ch->endc != '\0') {
   4052 		Parse_Error(PARSE_FATAL,
   4053 		    "Unclosed expression after indirect modifier, "
   4054 		    "expecting \"%c\"",
   4055 		    ch->endc);
   4056 		*pp = p;
   4057 		return AMIR_OUT;
   4058 	}
   4059 
   4060 	*pp = p;
   4061 	return AMIR_CONTINUE;
   4062 }
   4063 
   4064 static ApplyModifierResult
   4065 ApplySingleModifier(const char **pp, ModChain *ch)
   4066 {
   4067 	ApplyModifierResult res;
   4068 	const char *mod = *pp;
   4069 	const char *p = *pp;
   4070 
   4071 	if (DEBUG(VAR))
   4072 		LogBeforeApply(ch, mod);
   4073 
   4074 	if (posix_state == PS_SET)
   4075 		res = ApplyModifier_SysV(&p, ch);
   4076 	else
   4077 		res = AMR_UNKNOWN;
   4078 	if (res == AMR_UNKNOWN)
   4079 		res = ApplyModifier(&p, ch);
   4080 
   4081 	if (res == AMR_UNKNOWN && posix_state != PS_SET) {
   4082 		assert(p == mod);
   4083 		res = ApplyModifier_SysV(&p, ch);
   4084 	}
   4085 
   4086 	if (res == AMR_UNKNOWN) {
   4087 		/*
   4088 		 * Guess the end of the current modifier.
   4089 		 * XXX: Skipping the rest of the modifier hides
   4090 		 * errors and leads to wrong results.
   4091 		 * Parsing should rather stop here.
   4092 		 */
   4093 		for (p++; !IsDelimiter(*p, ch); p++)
   4094 			continue;
   4095 		Parse_Error(PARSE_FATAL, "Unknown modifier \":%.*s\"",
   4096 		    (int)(p - mod), mod);
   4097 		Expr_SetValueRefer(ch->expr, var_Error);
   4098 		res = AMR_CLEANUP;
   4099 	}
   4100 	if (res != AMR_OK) {
   4101 		*pp = p;
   4102 		return res;
   4103 	}
   4104 
   4105 	if (DEBUG(VAR))
   4106 		LogAfterApply(ch, p, mod);
   4107 
   4108 	if (*p == '\0' && ch->endc != '\0') {
   4109 		Parse_Error(PARSE_FATAL,
   4110 		    "Unclosed expression, expecting \"%c\" for "
   4111 		    "modifier \"%.*s\"",
   4112 		    ch->endc, (int)(p - mod), mod);
   4113 	} else if (*p == ':') {
   4114 		p++;
   4115 	} else if (opts.strict && *p != '\0' && *p != ch->endc) {
   4116 		Parse_Error(PARSE_FATAL,
   4117 		    "Missing delimiter \":\" after modifier \"%.*s\"",
   4118 		    (int)(p - mod), mod);
   4119 		/*
   4120 		 * TODO: propagate parse error to the enclosing
   4121 		 * expression
   4122 		 */
   4123 	}
   4124 	*pp = p;
   4125 	return AMR_OK;
   4126 }
   4127 
   4128 #if __STDC_VERSION__ >= 199901L
   4129 #define ModChain_Init(expr, startc, endc, sep, oneBigWord) \
   4130 	(ModChain) { expr, startc, endc, sep, oneBigWord }
   4131 #else
   4132 MAKE_INLINE ModChain
   4133 ModChain_Init(Expr *expr, char startc, char endc, char sep, bool oneBigWord)
   4134 {
   4135 	ModChain ch;
   4136 	ch.expr = expr;
   4137 	ch.startc = startc;
   4138 	ch.endc = endc;
   4139 	ch.sep = sep;
   4140 	ch.oneBigWord = oneBigWord;
   4141 	return ch;
   4142 }
   4143 #endif
   4144 
   4145 /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
   4146 static void
   4147 ApplyModifiers(
   4148     Expr *expr,
   4149     const char **pp,	/* the parsing position, updated upon return */
   4150     char startc,	/* '(' or '{'; or '\0' for indirect modifiers */
   4151     char endc		/* ')' or '}'; or '\0' for indirect modifiers */
   4152 )
   4153 {
   4154 	ModChain ch = ModChain_Init(expr, startc, endc, ' ', false);
   4155 	const char *p;
   4156 
   4157 	assert(startc == '(' || startc == '{' || startc == '\0');
   4158 	assert(endc == ')' || endc == '}' || endc == '\0');
   4159 	assert(Expr_Str(expr) != NULL);
   4160 
   4161 	p = *pp;
   4162 
   4163 	if (*p == '\0' && endc != '\0') {
   4164 		Parse_Error(PARSE_FATAL,
   4165 		    "Unclosed expression, expecting \"%c\"", ch.endc);
   4166 		goto cleanup;
   4167 	}
   4168 
   4169 	while (*p != '\0' && *p != endc) {
   4170 		ApplyModifierResult res;
   4171 
   4172 		if (*p == '$') {
   4173 			/*
   4174 			 * TODO: Only evaluate the expression once, no matter
   4175 			 * whether it's an indirect modifier or the initial
   4176 			 * part of a SysV modifier.
   4177 			 */
   4178 			ApplyModifiersIndirectResult amir =
   4179 			    ApplyModifiersIndirect(&ch, &p);
   4180 			if (amir == AMIR_CONTINUE)
   4181 				continue;
   4182 			if (amir == AMIR_OUT)
   4183 				break;
   4184 		}
   4185 
   4186 		res = ApplySingleModifier(&p, &ch);
   4187 		if (res == AMR_CLEANUP)
   4188 			goto cleanup;
   4189 	}
   4190 
   4191 	*pp = p;
   4192 	assert(Expr_Str(expr) != NULL);	/* Use var_Error or varUndefined. */
   4193 	return;
   4194 
   4195 cleanup:
   4196 	/*
   4197 	 * TODO: Use p + strlen(p) instead, to stop parsing immediately.
   4198 	 *
   4199 	 * In the unit tests, this generates a few shell commands with
   4200 	 * unbalanced quotes.  Instead of producing these incomplete strings,
   4201 	 * commands with evaluation errors should not be run at all.
   4202 	 *
   4203 	 * To make that happen, Var_Subst must report the actual errors
   4204 	 * instead of returning the resulting string unconditionally.
   4205 	 */
   4206 	*pp = p;
   4207 	Expr_SetValueRefer(expr, var_Error);
   4208 }
   4209 
   4210 /*
   4211  * Only 4 of the 7 built-in local variables are treated specially as they are
   4212  * the only ones that will be set when dynamic sources are expanded.
   4213  */
   4214 static bool
   4215 VarnameIsDynamic(Substring varname)
   4216 {
   4217 	const char *name;
   4218 	size_t len;
   4219 
   4220 	name = varname.start;
   4221 	len = Substring_Length(varname);
   4222 	if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
   4223 		switch (name[0]) {
   4224 		case '@':
   4225 		case '%':
   4226 		case '*':
   4227 		case '!':
   4228 			return true;
   4229 		}
   4230 		return false;
   4231 	}
   4232 
   4233 	if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
   4234 		return Substring_Equals(varname, ".TARGET") ||
   4235 		       Substring_Equals(varname, ".ARCHIVE") ||
   4236 		       Substring_Equals(varname, ".PREFIX") ||
   4237 		       Substring_Equals(varname, ".MEMBER");
   4238 	}
   4239 
   4240 	return false;
   4241 }
   4242 
   4243 static const char *
   4244 UndefinedShortVarValue(char varname, const GNode *scope)
   4245 {
   4246 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
   4247 		/*
   4248 		 * If substituting a local variable in a non-local scope,
   4249 		 * assume it's for dynamic source stuff. We have to handle
   4250 		 * this specially and return the longhand for the variable
   4251 		 * with the dollar sign escaped so it makes it back to the
   4252 		 * caller. Only four of the local variables are treated
   4253 		 * specially as they are the only four that will be set
   4254 		 * when dynamic sources are expanded.
   4255 		 */
   4256 		switch (varname) {
   4257 		case '@':
   4258 			return "$(.TARGET)";
   4259 		case '%':
   4260 			return "$(.MEMBER)";
   4261 		case '*':
   4262 			return "$(.PREFIX)";
   4263 		case '!':
   4264 			return "$(.ARCHIVE)";
   4265 		}
   4266 	}
   4267 	return NULL;
   4268 }
   4269 
   4270 /*
   4271  * Parse a variable name, until the end character or a colon, whichever
   4272  * comes first.
   4273  */
   4274 static void
   4275 ParseVarname(const char **pp, char startc, char endc,
   4276 	     GNode *scope, VarEvalMode emode,
   4277 	     LazyBuf *buf)
   4278 {
   4279 	const char *p = *pp;
   4280 	int depth = 0;
   4281 
   4282 	LazyBuf_Init(buf, p);
   4283 
   4284 	while (*p != '\0') {
   4285 		if ((*p == endc || *p == ':') && depth == 0)
   4286 			break;
   4287 		if (*p == startc)
   4288 			depth++;
   4289 		if (*p == endc)
   4290 			depth--;
   4291 
   4292 		if (*p == '$') {
   4293 			FStr nested_val = Var_Parse(&p, scope, emode);
   4294 			/* TODO: handle errors */
   4295 			LazyBuf_AddStr(buf, nested_val.str);
   4296 			FStr_Done(&nested_val);
   4297 		} else {
   4298 			LazyBuf_Add(buf, *p);
   4299 			p++;
   4300 		}
   4301 	}
   4302 	*pp = p;
   4303 }
   4304 
   4305 static bool
   4306 IsShortVarnameValid(char varname, const char *start)
   4307 {
   4308 	if (varname != '$' && varname != ':' && varname != '}' &&
   4309 	    varname != ')' && varname != '\0')
   4310 		return true;
   4311 
   4312 	if (!opts.strict)
   4313 		return false;	/* XXX: Missing error message */
   4314 
   4315 	if (varname == '$' && save_dollars)
   4316 		Parse_Error(PARSE_FATAL,
   4317 		    "To escape a dollar, use \\$, not $$, at \"%s\"", start);
   4318 	else if (varname == '\0')
   4319 		Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
   4320 	else if (save_dollars)
   4321 		Parse_Error(PARSE_FATAL,
   4322 		    "Invalid variable name \"%c\", at \"%s\"", varname, start);
   4323 
   4324 	return false;
   4325 }
   4326 
   4327 /*
   4328  * Parse a single-character variable name such as in $V or $@.
   4329  * Return whether to continue parsing.
   4330  */
   4331 static bool
   4332 ParseVarnameShort(char varname, const char **pp, GNode *scope,
   4333 		  VarEvalMode emode,
   4334 		  const char **out_false_val,
   4335 		  Var **out_true_var)
   4336 {
   4337 	char name[2];
   4338 	Var *v;
   4339 	const char *val;
   4340 
   4341 	if (!IsShortVarnameValid(varname, *pp)) {
   4342 		(*pp)++;	/* only skip the '$' */
   4343 		*out_false_val = var_Error;
   4344 		return false;
   4345 	}
   4346 
   4347 	name[0] = varname;
   4348 	name[1] = '\0';
   4349 	v = VarFind(name, scope, true);
   4350 	if (v != NULL) {
   4351 		/* No need to advance *pp, the calling code handles this. */
   4352 		*out_true_var = v;
   4353 		return true;
   4354 	}
   4355 
   4356 	*pp += 2;
   4357 
   4358 	val = UndefinedShortVarValue(varname, scope);
   4359 	if (val == NULL)
   4360 		val = emode == VARE_EVAL_DEFINED
   4361 		    || emode == VARE_EVAL_DEFINED_LOUD
   4362 		    ? var_Error : varUndefined;
   4363 
   4364 	if ((opts.strict || emode == VARE_EVAL_DEFINED_LOUD)
   4365 	    && val == var_Error) {
   4366 		Parse_Error(PARSE_FATAL,
   4367 		    "Variable \"%s\" is undefined", name);
   4368 	}
   4369 
   4370 	*out_false_val = val;
   4371 	return false;
   4372 }
   4373 
   4374 /* Find variables like @F or <D. */
   4375 static Var *
   4376 FindLocalLegacyVar(Substring varname, GNode *scope,
   4377 		   const char **out_extraModifiers)
   4378 {
   4379 	Var *v;
   4380 
   4381 	/* Only resolve these variables if scope is a "real" target. */
   4382 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
   4383 		return NULL;
   4384 
   4385 	if (Substring_Length(varname) != 2)
   4386 		return NULL;
   4387 	if (varname.start[1] != 'F' && varname.start[1] != 'D')
   4388 		return NULL;
   4389 	if (strchr("@%?*!<>^", varname.start[0]) == NULL)
   4390 		return NULL;
   4391 
   4392 	v = VarFindSubstring(Substring_Init(varname.start, varname.start + 1),
   4393 	    scope, false);
   4394 	if (v == NULL)
   4395 		return NULL;
   4396 
   4397 	*out_extraModifiers = varname.start[1] == 'D' ? "H:" : "T:";
   4398 	return v;
   4399 }
   4400 
   4401 static FStr
   4402 EvalUndefined(bool dynamic, const char *start, const char *p,
   4403 	      Substring varname, VarEvalMode emode, int parseErrorsBefore)
   4404 {
   4405 	if (dynamic)
   4406 		return FStr_InitOwn(bmake_strsedup(start, p));
   4407 
   4408 	if (emode == VARE_EVAL_DEFINED_LOUD
   4409 	    || (emode == VARE_EVAL_DEFINED && opts.strict)) {
   4410 		if (parseErrors == parseErrorsBefore) {
   4411 			Parse_Error(PARSE_FATAL,
   4412 			    "Variable \"%.*s\" is undefined",
   4413 			    (int) Substring_Length(varname), varname.start);
   4414 		}
   4415 		return FStr_InitRefer(var_Error);
   4416 	}
   4417 
   4418 	return FStr_InitRefer(
   4419 	    emode == VARE_EVAL_DEFINED_LOUD || emode == VARE_EVAL_DEFINED
   4420 		? var_Error : varUndefined);
   4421 }
   4422 
   4423 static void
   4424 CheckVarname(Substring name)
   4425 {
   4426 	const char *p;
   4427 
   4428 	for (p = name.start; p < name.end; p++) {
   4429 		if (ch_isspace(*p))
   4430 			break;
   4431 	}
   4432 	if (p < name.end) {
   4433 		Parse_Error(PARSE_WARNING,
   4434 		    ch_isprint(*p)
   4435 		    ? "Invalid character \"%c\" in variable name \"%.*s\""
   4436 		    : "Invalid character \"\\x%02x\" in variable name \"%.*s\"",
   4437 		    (int)*p,
   4438 		    (int)Substring_Length(name), name.start);
   4439 	}
   4440 }
   4441 
   4442 /*
   4443  * Parse a long variable name enclosed in braces or parentheses such as $(VAR)
   4444  * or ${VAR}, up to the closing brace or parenthesis, or in the case of
   4445  * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
   4446  * Return whether to continue parsing.
   4447  */
   4448 static bool
   4449 ParseVarnameLong(
   4450 	const char **pp,
   4451 	char startc,
   4452 	GNode *scope,
   4453 	VarEvalMode emode,
   4454 	VarEvalMode nested_emode,
   4455 	int parseErrorsBefore,
   4456 
   4457 	const char **out_false_pp,
   4458 	FStr *out_false_val,
   4459 
   4460 	char *out_true_endc,
   4461 	Var **out_true_v,
   4462 	bool *out_true_haveModifier,
   4463 	const char **out_true_extraModifiers,
   4464 	bool *out_true_dynamic,
   4465 	ExprDefined *out_true_exprDefined
   4466 )
   4467 {
   4468 	LazyBuf varname;
   4469 	Substring name;
   4470 	Var *v;
   4471 	bool haveModifier;
   4472 	bool dynamic = false;
   4473 
   4474 	const char *p = *pp;
   4475 	const char *start = p;
   4476 	char endc = startc == '(' ? ')' : '}';
   4477 
   4478 	p += 2;			/* skip "${" or "$(" or "y(" */
   4479 	ParseVarname(&p, startc, endc, scope, nested_emode, &varname);
   4480 	name = LazyBuf_Get(&varname);
   4481 
   4482 	if (*p == ':')
   4483 		haveModifier = true;
   4484 	else if (*p == endc)
   4485 		haveModifier = false;
   4486 	else {
   4487 		Parse_Error(PARSE_FATAL, "Unclosed variable \"%.*s\"",
   4488 		    (int)Substring_Length(name), name.start);
   4489 		LazyBuf_Done(&varname);
   4490 		*out_false_pp = p;
   4491 		*out_false_val = FStr_InitRefer(var_Error);
   4492 		return false;
   4493 	}
   4494 
   4495 	v = VarFindSubstring(name, scope, true);
   4496 
   4497 	/*
   4498 	 * At this point, p points just after the variable name, either at
   4499 	 * ':' or at endc.
   4500 	 */
   4501 
   4502 	if (v == NULL && Substring_Equals(name, ".SUFFIXES")) {
   4503 		char *suffixes = Suff_NamesStr();
   4504 		v = VarNew(FStr_InitRefer(".SUFFIXES"), suffixes,
   4505 		    true, false, true);
   4506 		free(suffixes);
   4507 	} else if (v == NULL)
   4508 		v = FindLocalLegacyVar(name, scope, out_true_extraModifiers);
   4509 
   4510 	if (v == NULL) {
   4511 		/*
   4512 		 * Defer expansion of dynamic variables if they appear in
   4513 		 * non-local scope since they are not defined there.
   4514 		 */
   4515 		dynamic = VarnameIsDynamic(name) &&
   4516 			  (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
   4517 
   4518 		if (!haveModifier) {
   4519 			CheckVarname(name);
   4520 			p++;	/* skip endc */
   4521 			*out_false_pp = p;
   4522 			*out_false_val = EvalUndefined(dynamic, start, p,
   4523 			    name, emode, parseErrorsBefore);
   4524 			LazyBuf_Done(&varname);
   4525 			return false;
   4526 		}
   4527 
   4528 		/*
   4529 		 * The expression is based on an undefined variable.
   4530 		 * Nevertheless it needs a Var, for modifiers that access the
   4531 		 * variable name, such as :L or :?.
   4532 		 *
   4533 		 * Most modifiers leave this expression in the "undefined"
   4534 		 * state (DEF_UNDEF), only a few modifiers like :D, :U, :L,
   4535 		 * :P turn this undefined expression into a defined
   4536 		 * expression (DEF_DEFINED).
   4537 		 *
   4538 		 * In the end, after applying all modifiers, if the expression
   4539 		 * is still undefined, Var_Parse will return an empty string
   4540 		 * instead of the actually computed value.
   4541 		 */
   4542 		v = VarNew(LazyBuf_DoneGet(&varname), "",
   4543 		    true, false, false);
   4544 		*out_true_exprDefined = DEF_UNDEF;
   4545 	} else
   4546 		LazyBuf_Done(&varname);
   4547 
   4548 	*pp = p;
   4549 	*out_true_endc = endc;
   4550 	*out_true_v = v;
   4551 	*out_true_haveModifier = haveModifier;
   4552 	*out_true_dynamic = dynamic;
   4553 	return true;
   4554 }
   4555 
   4556 #if __STDC_VERSION__ >= 199901L
   4557 #define Expr_Init(name, value, emode, scope, defined) \
   4558 	(Expr) { name, value, emode, scope, defined }
   4559 #else
   4560 MAKE_INLINE Expr
   4561 Expr_Init(const char *name, FStr value,
   4562 	  VarEvalMode emode, GNode *scope, ExprDefined defined)
   4563 {
   4564 	Expr expr;
   4565 
   4566 	expr.name = name;
   4567 	expr.value = value;
   4568 	expr.emode = emode;
   4569 	expr.scope = scope;
   4570 	expr.defined = defined;
   4571 	return expr;
   4572 }
   4573 #endif
   4574 
   4575 /*
   4576  * Expressions of the form ${:U...} with a trivial value are often generated
   4577  * by .for loops and are boring, so evaluate them without debug logging.
   4578  */
   4579 static bool
   4580 Var_Parse_U(const char **pp, VarEvalMode emode, FStr *out_value)
   4581 {
   4582 	const char *p;
   4583 
   4584 	p = *pp;
   4585 	if (!(p[0] == '$' && p[1] == '{' && p[2] == ':' && p[3] == 'U'))
   4586 		return false;
   4587 
   4588 	p += 4;
   4589 	while (*p != '$' && *p != '{' && *p != ':' && *p != '\\' &&
   4590 	       *p != '}' && *p != '\0')
   4591 		p++;
   4592 	if (*p != '}')
   4593 		return false;
   4594 
   4595 	*out_value = emode == VARE_PARSE
   4596 	    ? FStr_InitRefer("")
   4597 	    : FStr_InitOwn(bmake_strsedup(*pp + 4, p));
   4598 	*pp = p + 1;
   4599 	return true;
   4600 }
   4601 
   4602 /*
   4603  * Given the start of an expression (such as $v, $(VAR), ${VAR:Mpattern}),
   4604  * extract the variable name and the modifiers, if any.  While parsing, apply
   4605  * the modifiers to the value of the expression.
   4606  *
   4607  * Input:
   4608  *	*pp		The string to parse.
   4609  *			When called from CondParser_FuncCallEmpty, it can
   4610  *			also point to the "y" of "empty(VARNAME:Modifiers)".
   4611  *	scope		The scope for finding variables.
   4612  *	emode		Controls the exact details of parsing and evaluation.
   4613  *
   4614  * Output:
   4615  *	*pp		The position where to continue parsing.
   4616  *			TODO: After a parse error, the value of *pp is
   4617  *			unspecified.  It may not have been updated at all,
   4618  *			point to some random character in the string, to the
   4619  *			location of the parse error, or at the end of the
   4620  *			string.
   4621  *	return		The value of the expression, never NULL.
   4622  *	return		var_Error if there was a parse error.
   4623  *	return		var_Error if the base variable of the expression was
   4624  *			undefined, emode is VARE_EVAL_DEFINED, and none of
   4625  *			the modifiers turned the undefined expression into a
   4626  *			defined expression.
   4627  *			XXX: It is not guaranteed that an error message has
   4628  *			been printed.
   4629  *	return		varUndefined if the base variable of the expression
   4630  *			was undefined, emode was not VARE_EVAL_DEFINED,
   4631  *			and none of the modifiers turned the undefined
   4632  *			expression into a defined expression.
   4633  */
   4634 FStr
   4635 Var_Parse(const char **pp, GNode *scope, VarEvalMode emode)
   4636 {
   4637 	const char *start, *p;
   4638 	bool haveModifier;	/* true for ${VAR:...}, false for ${VAR} */
   4639 	char startc;		/* the actual '{' or '(' or '\0' */
   4640 	char endc;		/* the expected '}' or ')' or '\0' */
   4641 	/*
   4642 	 * true if the expression is based on one of the 7 predefined
   4643 	 * variables that are local to a target, and the expression is
   4644 	 * expanded in a non-local scope.  The result is the text of the
   4645 	 * expression, unaltered.  This is needed to support dynamic sources.
   4646 	 */
   4647 	bool dynamic;
   4648 	const char *extramodifiers;
   4649 	Var *v;
   4650 	Expr expr = Expr_Init(NULL, FStr_InitRefer(NULL),
   4651 	    emode == VARE_EVAL_DEFINED || emode == VARE_EVAL_DEFINED_LOUD
   4652 		? VARE_EVAL : emode,
   4653 	    scope, DEF_REGULAR);
   4654 	FStr val;
   4655 	int parseErrorsBefore = parseErrors;
   4656 
   4657 	if (Var_Parse_U(pp, emode, &val))
   4658 		return val;
   4659 
   4660 	p = *pp;
   4661 	start = p;
   4662 	DEBUG2(VAR, "Var_Parse: %s (%s)\n", start, VarEvalMode_Name[emode]);
   4663 
   4664 	val = FStr_InitRefer(NULL);
   4665 	extramodifiers = NULL;	/* extra modifiers to apply first */
   4666 	dynamic = false;
   4667 
   4668 	endc = '\0';		/* Appease GCC. */
   4669 
   4670 	startc = p[1];
   4671 	if (startc != '(' && startc != '{') {
   4672 		if (!ParseVarnameShort(startc, pp, scope, emode, &val.str, &v))
   4673 			return val;
   4674 		haveModifier = false;
   4675 		p++;
   4676 	} else {
   4677 		if (!ParseVarnameLong(&p, startc, scope, emode, expr.emode,
   4678 		    parseErrorsBefore,
   4679 		    pp, &val,
   4680 		    &endc, &v, &haveModifier, &extramodifiers,
   4681 		    &dynamic, &expr.defined))
   4682 			return val;
   4683 	}
   4684 
   4685 	expr.name = v->name.str;
   4686 	if (v->inUse && VarEvalMode_ShouldEval(emode)) {
   4687 		Parse_Error(PARSE_FATAL, "Variable %s is recursive.",
   4688 		    v->name.str);
   4689 		FStr_Done(&val);
   4690 		if (*p != '\0')
   4691 			p++;
   4692 		*pp = p;
   4693 		return FStr_InitRefer(var_Error);
   4694 	}
   4695 
   4696 	/*
   4697 	 * FIXME: This assignment creates an alias to the current value of the
   4698 	 * variable.  This means that as long as the value of the expression
   4699 	 * stays the same, the value of the variable must not change, and the
   4700 	 * variable must not be deleted.  Using the ':@' modifier, it is
   4701 	 * possible (since var.c 1.212 from 2017-02-01) to delete the variable
   4702 	 * while its value is still being used:
   4703 	 *
   4704 	 *	VAR=	value
   4705 	 *	_:=	${VAR:${:U:@VAR@@}:S,^,prefix,}
   4706 	 *
   4707 	 * The same effect might be achievable using the '::=' or the ':_'
   4708 	 * modifiers.
   4709 	 *
   4710 	 * At the bottom of this function, the resulting value is compared to
   4711 	 * the then-current value of the variable.  This might also invoke
   4712 	 * undefined behavior.
   4713 	 */
   4714 	expr.value = FStr_InitRefer(v->val.data);
   4715 
   4716 	if (!VarEvalMode_ShouldEval(emode))
   4717 		EvalStack_Push(VSK_EXPR_PARSE, start, NULL);
   4718 	else if (expr.name[0] != '\0')
   4719 		EvalStack_Push(VSK_VARNAME, expr.name, &expr.value);
   4720 	else
   4721 		EvalStack_Push(VSK_EXPR, start, &expr.value);
   4722 
   4723 	/*
   4724 	 * Before applying any modifiers, expand any nested expressions from
   4725 	 * the variable value.
   4726 	 */
   4727 	if (VarEvalMode_ShouldEval(emode) &&
   4728 	    strchr(Expr_Str(&expr), '$') != NULL) {
   4729 		char *expanded;
   4730 		v->inUse = true;
   4731 		expanded = Var_Subst(Expr_Str(&expr), scope, expr.emode);
   4732 		v->inUse = false;
   4733 		/* TODO: handle errors */
   4734 		Expr_SetValueOwn(&expr, expanded);
   4735 	}
   4736 
   4737 	if (extramodifiers != NULL) {
   4738 		const char *em = extramodifiers;
   4739 		ApplyModifiers(&expr, &em, '\0', '\0');
   4740 	}
   4741 
   4742 	if (haveModifier) {
   4743 		p++;		/* Skip initial colon. */
   4744 		ApplyModifiers(&expr, &p, startc, endc);
   4745 	}
   4746 
   4747 	if (*p != '\0')		/* Skip past endc if possible. */
   4748 		p++;
   4749 
   4750 	*pp = p;
   4751 
   4752 	if (expr.defined == DEF_UNDEF) {
   4753 		Substring varname = Substring_InitStr(expr.name);
   4754 		FStr value = EvalUndefined(dynamic, start, p, varname, emode,
   4755 		    parseErrorsBefore);
   4756 		Expr_SetValue(&expr, value);
   4757 	}
   4758 
   4759 	EvalStack_Pop();
   4760 
   4761 	if (v->shortLived) {
   4762 		if (expr.value.str == v->val.data) {
   4763 			/* move ownership */
   4764 			expr.value.freeIt = v->val.data;
   4765 			v->val.data = NULL;
   4766 		}
   4767 		VarFreeShortLived(v);
   4768 	}
   4769 
   4770 	return expr.value;
   4771 }
   4772 
   4773 static void
   4774 VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalMode emode)
   4775 {
   4776 	/* A dollar sign may be escaped with another dollar sign. */
   4777 	if (save_dollars && VarEvalMode_ShouldKeepDollar(emode))
   4778 		Buf_AddByte(res, '$');
   4779 	Buf_AddByte(res, '$');
   4780 	*pp += 2;
   4781 }
   4782 
   4783 static void
   4784 VarSubstExpr(const char **pp, Buffer *buf, GNode *scope, VarEvalMode emode)
   4785 {
   4786 	const char *p = *pp;
   4787 	const char *nested_p = p;
   4788 	FStr val = Var_Parse(&nested_p, scope, emode);
   4789 	/* TODO: handle errors */
   4790 
   4791 	if (val.str == var_Error || val.str == varUndefined) {
   4792 		if (!VarEvalMode_ShouldKeepUndef(emode)
   4793 		    || val.str == var_Error) {
   4794 			p = nested_p;
   4795 		} else {
   4796 			/*
   4797 			 * Copy the initial '$' of the undefined expression,
   4798 			 * thereby deferring expansion of the expression, but
   4799 			 * expand nested expressions if already possible. See
   4800 			 * unit-tests/varparse-undef-partial.mk.
   4801 			 */
   4802 			Buf_AddByte(buf, *p);
   4803 			p++;
   4804 		}
   4805 	} else {
   4806 		p = nested_p;
   4807 		Buf_AddStr(buf, val.str);
   4808 	}
   4809 
   4810 	FStr_Done(&val);
   4811 
   4812 	*pp = p;
   4813 }
   4814 
   4815 /*
   4816  * Skip as many characters as possible -- either to the end of the string,
   4817  * or to the next dollar sign, which may start an expression.
   4818  */
   4819 static void
   4820 VarSubstPlain(const char **pp, Buffer *res)
   4821 {
   4822 	const char *p = *pp;
   4823 	const char *start = p;
   4824 
   4825 	for (p++; *p != '$' && *p != '\0'; p++)
   4826 		continue;
   4827 	Buf_AddRange(res, start, p);
   4828 	*pp = p;
   4829 }
   4830 
   4831 /*
   4832  * Expand all expressions like $V, ${VAR}, $(VAR:Modifiers) in the
   4833  * given string.
   4834  *
   4835  * Input:
   4836  *	str		The string in which the expressions are expanded.
   4837  *	scope		The scope in which to start searching for variables.
   4838  *			The other scopes are searched as well.
   4839  *	emode		The mode for parsing or evaluating subexpressions.
   4840  */
   4841 char *
   4842 Var_Subst(const char *str, GNode *scope, VarEvalMode emode)
   4843 {
   4844 	const char *p = str;
   4845 	Buffer res;
   4846 
   4847 	Buf_Init(&res);
   4848 
   4849 	while (*p != '\0') {
   4850 		if (p[0] == '$' && p[1] == '$')
   4851 			VarSubstDollarDollar(&p, &res, emode);
   4852 		else if (p[0] == '$')
   4853 			VarSubstExpr(&p, &res, scope, emode);
   4854 		else
   4855 			VarSubstPlain(&p, &res);
   4856 	}
   4857 
   4858 	return Buf_DoneData(&res);
   4859 }
   4860 
   4861 char *
   4862 Var_SubstInTarget(const char *str, GNode *scope)
   4863 {
   4864 	char *res;
   4865 	EvalStack_Push(VSK_TARGET, scope->name, NULL);
   4866 	EvalStack_Push(VSK_COMMAND, str, NULL);
   4867 	res = Var_Subst(str, scope, VARE_EVAL);
   4868 	EvalStack_Pop();
   4869 	EvalStack_Pop();
   4870 	return res;
   4871 }
   4872 
   4873 void
   4874 Var_ExportStackTrace(const char *target, const char *cmd)
   4875 {
   4876 	char *stackTrace;
   4877 
   4878 	if (GetParentStackTrace() == NULL)
   4879 		return;
   4880 
   4881 	if (target != NULL)
   4882 		EvalStack_Push(VSK_TARGET, target, NULL);
   4883 	if (cmd != NULL)
   4884 		EvalStack_Push(VSK_COMMAND, cmd, NULL);
   4885 
   4886 	stackTrace = GetStackTrace(true);
   4887 	(void)setenv("MAKE_STACK_TRACE", stackTrace, 1);
   4888 	free(stackTrace);
   4889 
   4890 	if (cmd != NULL)
   4891 		EvalStack_Pop();
   4892 	if (target != NULL)
   4893 		EvalStack_Pop();
   4894 }
   4895 
   4896 void
   4897 Var_Expand(FStr *str, GNode *scope, VarEvalMode emode)
   4898 {
   4899 	char *expanded;
   4900 
   4901 	if (strchr(str->str, '$') == NULL)
   4902 		return;
   4903 	expanded = Var_Subst(str->str, scope, emode);
   4904 	/* TODO: handle errors */
   4905 	FStr_Done(str);
   4906 	*str = FStr_InitOwn(expanded);
   4907 }
   4908 
   4909 void
   4910 Var_Stats(void)
   4911 {
   4912 	HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables");
   4913 }
   4914 
   4915 static int
   4916 StrAsc(const void *sa, const void *sb)
   4917 {
   4918 	return strcmp(*(const char *const *)sa, *(const char *const *)sb);
   4919 }
   4920 
   4921 
   4922 /* Print all variables in a scope, sorted by name. */
   4923 void
   4924 Var_Dump(GNode *scope)
   4925 {
   4926 	Vector /* of const char * */ vec;
   4927 	HashIter hi;
   4928 	size_t i;
   4929 	const char **varnames;
   4930 
   4931 	Vector_Init(&vec, sizeof(const char *));
   4932 
   4933 	HashIter_Init(&hi, &scope->vars);
   4934 	while (HashIter_Next(&hi))
   4935 		*(const char **)Vector_Push(&vec) = hi.entry->key;
   4936 	varnames = vec.items;
   4937 
   4938 	qsort(varnames, vec.len, sizeof varnames[0], StrAsc);
   4939 
   4940 	for (i = 0; i < vec.len; i++) {
   4941 		const char *varname = varnames[i];
   4942 		const Var *var = HashTable_FindValue(&scope->vars, varname);
   4943 		debug_printf("%-16s = %s%s\n", varname,
   4944 		    var->val.data, ValueDescription(var->val.data));
   4945 	}
   4946 
   4947 	Vector_Done(&vec);
   4948 }
   4949