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