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