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