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