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