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