Home | History | Annotate | Line # | Download | only in make
var.c revision 1.995
      1 /*	$NetBSD: var.c,v 1.995 2022/01/07 12:44:57 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.995 2022/01/07 12:44:57 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, time_t t, bool gmt)
   1946 {
   1947 	char buf[BUFSIZ];
   1948 
   1949 	if (t == 0)
   1950 		time(&t);
   1951 	if (*fmt == '\0')
   1952 		fmt = "%c";
   1953 	strftime(buf, sizeof buf, fmt, gmt ? gmtime(&t) : localtime(&t));
   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 and :localtime */
   2598 static ApplyModifierResult
   2599 ApplyModifier_Time(const char **pp, ModChain *ch)
   2600 {
   2601 	Expr *expr;
   2602 	time_t t;
   2603 	const char *args;
   2604 	const char *mod = *pp;
   2605 	bool gmt = mod[0] == 'g';
   2606 
   2607 	if (!ModMatchEq(mod, gmt ? "gmtime" : "localtime", ch))
   2608 		return AMR_UNKNOWN;
   2609 	args = mod + (gmt ? 6 : 9);
   2610 
   2611 	if (args[0] == '=') {
   2612 		const char *p = args + 1;
   2613 		if (!TryParseTime(&p, &t)) {
   2614 			Parse_Error(PARSE_FATAL,
   2615 			    "Invalid time value at \"%s\"", p);
   2616 			return AMR_CLEANUP;
   2617 		}
   2618 		*pp = p;
   2619 	} else {
   2620 		t = 0;
   2621 		*pp = args;
   2622 	}
   2623 
   2624 	expr = ch->expr;
   2625 	if (Expr_ShouldEval(expr))
   2626 		Expr_SetValueOwn(expr, VarStrftime(Expr_Str(expr), t, gmt));
   2627 
   2628 	return AMR_OK;
   2629 }
   2630 
   2631 /* :hash */
   2632 static ApplyModifierResult
   2633 ApplyModifier_Hash(const char **pp, ModChain *ch)
   2634 {
   2635 	if (!ModMatch(*pp, "hash", ch))
   2636 		return AMR_UNKNOWN;
   2637 	*pp += 4;
   2638 
   2639 	if (ModChain_ShouldEval(ch))
   2640 		Expr_SetValueOwn(ch->expr, VarHash(Expr_Str(ch->expr)));
   2641 
   2642 	return AMR_OK;
   2643 }
   2644 
   2645 /* :P */
   2646 static ApplyModifierResult
   2647 ApplyModifier_Path(const char **pp, ModChain *ch)
   2648 {
   2649 	Expr *expr = ch->expr;
   2650 	GNode *gn;
   2651 	char *path;
   2652 
   2653 	(*pp)++;
   2654 
   2655 	if (!Expr_ShouldEval(expr))
   2656 		return AMR_OK;
   2657 
   2658 	Expr_Define(expr);
   2659 
   2660 	gn = Targ_FindNode(expr->name);
   2661 	if (gn == NULL || gn->type & OP_NOPATH) {
   2662 		path = NULL;
   2663 	} else if (gn->path != NULL) {
   2664 		path = bmake_strdup(gn->path);
   2665 	} else {
   2666 		SearchPath *searchPath = Suff_FindPath(gn);
   2667 		path = Dir_FindFile(expr->name, searchPath);
   2668 	}
   2669 	if (path == NULL)
   2670 		path = bmake_strdup(expr->name);
   2671 	Expr_SetValueOwn(expr, path);
   2672 
   2673 	return AMR_OK;
   2674 }
   2675 
   2676 /* :!cmd! */
   2677 static ApplyModifierResult
   2678 ApplyModifier_ShellCommand(const char **pp, ModChain *ch)
   2679 {
   2680 	Expr *expr = ch->expr;
   2681 	const char *errfmt;
   2682 	VarParseResult res;
   2683 	LazyBuf cmdBuf;
   2684 	FStr cmd;
   2685 
   2686 	(*pp)++;
   2687 	res = ParseModifierPart(pp, '!', expr->emode, ch, &cmdBuf);
   2688 	if (res != VPR_OK)
   2689 		return AMR_CLEANUP;
   2690 	cmd = LazyBuf_DoneGet(&cmdBuf);
   2691 
   2692 
   2693 	errfmt = NULL;
   2694 	if (Expr_ShouldEval(expr))
   2695 		Expr_SetValueOwn(expr, Cmd_Exec(cmd.str, &errfmt));
   2696 	else
   2697 		Expr_SetValueRefer(expr, "");
   2698 	if (errfmt != NULL)
   2699 		Error(errfmt, cmd.str);	/* XXX: why still return AMR_OK? */
   2700 	FStr_Done(&cmd);
   2701 	Expr_Define(expr);
   2702 
   2703 	return AMR_OK;
   2704 }
   2705 
   2706 /*
   2707  * The :range modifier generates an integer sequence as long as the words.
   2708  * The :range=7 modifier generates an integer sequence from 1 to 7.
   2709  */
   2710 static ApplyModifierResult
   2711 ApplyModifier_Range(const char **pp, ModChain *ch)
   2712 {
   2713 	size_t n;
   2714 	Buffer buf;
   2715 	size_t i;
   2716 
   2717 	const char *mod = *pp;
   2718 	if (!ModMatchEq(mod, "range", ch))
   2719 		return AMR_UNKNOWN;
   2720 
   2721 	if (mod[5] == '=') {
   2722 		const char *p = mod + 6;
   2723 		if (!TryParseSize(&p, &n)) {
   2724 			Parse_Error(PARSE_FATAL,
   2725 			    "Invalid number \"%s\" for ':range' modifier",
   2726 			    mod + 6);
   2727 			return AMR_CLEANUP;
   2728 		}
   2729 		*pp = p;
   2730 	} else {
   2731 		n = 0;
   2732 		*pp = mod + 5;
   2733 	}
   2734 
   2735 	if (!ModChain_ShouldEval(ch))
   2736 		return AMR_OK;
   2737 
   2738 	if (n == 0) {
   2739 		SubstringWords words = Expr_Words(ch->expr);
   2740 		n = words.len;
   2741 		SubstringWords_Free(words);
   2742 	}
   2743 
   2744 	Buf_Init(&buf);
   2745 
   2746 	for (i = 0; i < n; i++) {
   2747 		if (i != 0) {
   2748 			/*
   2749 			 * XXX: Use ch->sep instead of ' ', for consistency.
   2750 			 */
   2751 			Buf_AddByte(&buf, ' ');
   2752 		}
   2753 		Buf_AddInt(&buf, 1 + (int)i);
   2754 	}
   2755 
   2756 	Expr_SetValueOwn(ch->expr, Buf_DoneData(&buf));
   2757 	return AMR_OK;
   2758 }
   2759 
   2760 /* Parse a ':M' or ':N' modifier. */
   2761 static void
   2762 ParseModifier_Match(const char **pp, const ModChain *ch,
   2763 		    char **out_pattern)
   2764 {
   2765 	const char *mod = *pp;
   2766 	Expr *expr = ch->expr;
   2767 	bool copy = false;	/* pattern should be, or has been, copied */
   2768 	bool needSubst = false;
   2769 	const char *endpat;
   2770 	char *pattern;
   2771 
   2772 	/*
   2773 	 * In the loop below, ignore ':' unless we are at (or back to) the
   2774 	 * original brace level.
   2775 	 * XXX: This will likely not work right if $() and ${} are intermixed.
   2776 	 */
   2777 	/*
   2778 	 * XXX: This code is similar to the one in Var_Parse.
   2779 	 * See if the code can be merged.
   2780 	 * See also ApplyModifier_Defined.
   2781 	 */
   2782 	int nest = 0;
   2783 	const char *p;
   2784 	for (p = mod + 1; *p != '\0' && !(*p == ':' && nest == 0); p++) {
   2785 		if (*p == '\\' &&
   2786 		    (IsDelimiter(p[1], ch) || p[1] == ch->startc)) {
   2787 			if (!needSubst)
   2788 				copy = true;
   2789 			p++;
   2790 			continue;
   2791 		}
   2792 		if (*p == '$')
   2793 			needSubst = true;
   2794 		if (*p == '(' || *p == '{')
   2795 			nest++;
   2796 		if (*p == ')' || *p == '}') {
   2797 			nest--;
   2798 			if (nest < 0)
   2799 				break;
   2800 		}
   2801 	}
   2802 	*pp = p;
   2803 	endpat = p;
   2804 
   2805 	if (copy) {
   2806 		char *dst;
   2807 		const char *src;
   2808 
   2809 		/* Compress the \:'s out of the pattern. */
   2810 		pattern = bmake_malloc((size_t)(endpat - (mod + 1)) + 1);
   2811 		dst = pattern;
   2812 		src = mod + 1;
   2813 		for (; src < endpat; src++, dst++) {
   2814 			if (src[0] == '\\' && src + 1 < endpat &&
   2815 			    /* XXX: ch->startc is missing here; see above */
   2816 			    IsDelimiter(src[1], ch))
   2817 				src++;
   2818 			*dst = *src;
   2819 		}
   2820 		*dst = '\0';
   2821 	} else {
   2822 		pattern = bmake_strsedup(mod + 1, endpat);
   2823 	}
   2824 
   2825 	if (needSubst) {
   2826 		char *old_pattern = pattern;
   2827 		(void)Var_Subst(pattern, expr->scope, expr->emode, &pattern);
   2828 		/* TODO: handle errors */
   2829 		free(old_pattern);
   2830 	}
   2831 
   2832 	DEBUG2(VAR, "Pattern for ':%c' is \"%s\"\n", mod[0], pattern);
   2833 
   2834 	*out_pattern = pattern;
   2835 }
   2836 
   2837 /* :Mpattern or :Npattern */
   2838 static ApplyModifierResult
   2839 ApplyModifier_Match(const char **pp, ModChain *ch)
   2840 {
   2841 	const char mod = **pp;
   2842 	char *pattern;
   2843 
   2844 	ParseModifier_Match(pp, ch, &pattern);
   2845 
   2846 	if (ModChain_ShouldEval(ch)) {
   2847 		ModifyWordProc modifyWord =
   2848 		    mod == 'M' ? ModifyWord_Match : ModifyWord_NoMatch;
   2849 		ModifyWords(ch, modifyWord, pattern, ch->oneBigWord);
   2850 	}
   2851 
   2852 	free(pattern);
   2853 	return AMR_OK;
   2854 }
   2855 
   2856 static void
   2857 ParsePatternFlags(const char **pp, PatternFlags *pflags, bool *oneBigWord)
   2858 {
   2859 	for (;; (*pp)++) {
   2860 		if (**pp == 'g')
   2861 			pflags->subGlobal = true;
   2862 		else if (**pp == '1')
   2863 			pflags->subOnce = true;
   2864 		else if (**pp == 'W')
   2865 			*oneBigWord = true;
   2866 		else
   2867 			break;
   2868 	}
   2869 }
   2870 
   2871 MAKE_INLINE PatternFlags
   2872 PatternFlags_None(void)
   2873 {
   2874 	PatternFlags pflags = { false, false, false, false };
   2875 	return pflags;
   2876 }
   2877 
   2878 /* :S,from,to, */
   2879 static ApplyModifierResult
   2880 ApplyModifier_Subst(const char **pp, ModChain *ch)
   2881 {
   2882 	struct ModifyWord_SubstArgs args;
   2883 	bool oneBigWord;
   2884 	VarParseResult res;
   2885 	LazyBuf lhsBuf, rhsBuf;
   2886 
   2887 	char delim = (*pp)[1];
   2888 	if (delim == '\0') {
   2889 		Error("Missing delimiter for modifier ':S'");
   2890 		(*pp)++;
   2891 		return AMR_CLEANUP;
   2892 	}
   2893 
   2894 	*pp += 2;
   2895 
   2896 	args.pflags = PatternFlags_None();
   2897 	args.matched = false;
   2898 
   2899 	if (**pp == '^') {
   2900 		args.pflags.anchorStart = true;
   2901 		(*pp)++;
   2902 	}
   2903 
   2904 	res = ParseModifierPartSubst(pp, delim, ch->expr->emode, ch, &lhsBuf,
   2905 	    &args.pflags, NULL);
   2906 	if (res != VPR_OK)
   2907 		return AMR_CLEANUP;
   2908 	args.lhs = LazyBuf_Get(&lhsBuf);
   2909 
   2910 	res = ParseModifierPartSubst(pp, delim, ch->expr->emode, ch, &rhsBuf,
   2911 	    NULL, &args);
   2912 	if (res != VPR_OK) {
   2913 		LazyBuf_Done(&lhsBuf);
   2914 		return AMR_CLEANUP;
   2915 	}
   2916 	args.rhs = LazyBuf_Get(&rhsBuf);
   2917 
   2918 	oneBigWord = ch->oneBigWord;
   2919 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   2920 
   2921 	ModifyWords(ch, ModifyWord_Subst, &args, oneBigWord);
   2922 
   2923 	LazyBuf_Done(&lhsBuf);
   2924 	LazyBuf_Done(&rhsBuf);
   2925 	return AMR_OK;
   2926 }
   2927 
   2928 #ifndef NO_REGEX
   2929 
   2930 /* :C,from,to, */
   2931 static ApplyModifierResult
   2932 ApplyModifier_Regex(const char **pp, ModChain *ch)
   2933 {
   2934 	struct ModifyWord_SubstRegexArgs args;
   2935 	bool oneBigWord;
   2936 	int error;
   2937 	VarParseResult res;
   2938 	LazyBuf reBuf, replaceBuf;
   2939 	FStr re;
   2940 
   2941 	char delim = (*pp)[1];
   2942 	if (delim == '\0') {
   2943 		Error("Missing delimiter for :C modifier");
   2944 		(*pp)++;
   2945 		return AMR_CLEANUP;
   2946 	}
   2947 
   2948 	*pp += 2;
   2949 
   2950 	res = ParseModifierPart(pp, delim, ch->expr->emode, ch, &reBuf);
   2951 	if (res != VPR_OK)
   2952 		return AMR_CLEANUP;
   2953 	re = LazyBuf_DoneGet(&reBuf);
   2954 
   2955 	res = ParseModifierPart(pp, delim, ch->expr->emode, ch, &replaceBuf);
   2956 	if (res != VPR_OK) {
   2957 		FStr_Done(&re);
   2958 		return AMR_CLEANUP;
   2959 	}
   2960 	args.replace = LazyBuf_Get(&replaceBuf);
   2961 
   2962 	args.pflags = PatternFlags_None();
   2963 	args.matched = false;
   2964 	oneBigWord = ch->oneBigWord;
   2965 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   2966 
   2967 	if (!ModChain_ShouldEval(ch)) {
   2968 		LazyBuf_Done(&replaceBuf);
   2969 		FStr_Done(&re);
   2970 		return AMR_OK;
   2971 	}
   2972 
   2973 	error = regcomp(&args.re, re.str, REG_EXTENDED);
   2974 	if (error != 0) {
   2975 		VarREError(error, &args.re, "Regex compilation error");
   2976 		LazyBuf_Done(&replaceBuf);
   2977 		FStr_Done(&re);
   2978 		return AMR_CLEANUP;
   2979 	}
   2980 
   2981 	args.nsub = args.re.re_nsub + 1;
   2982 	if (args.nsub > 10)
   2983 		args.nsub = 10;
   2984 
   2985 	ModifyWords(ch, ModifyWord_SubstRegex, &args, oneBigWord);
   2986 
   2987 	regfree(&args.re);
   2988 	LazyBuf_Done(&replaceBuf);
   2989 	FStr_Done(&re);
   2990 	return AMR_OK;
   2991 }
   2992 
   2993 #endif
   2994 
   2995 /* :Q, :q */
   2996 static ApplyModifierResult
   2997 ApplyModifier_Quote(const char **pp, ModChain *ch)
   2998 {
   2999 	LazyBuf buf;
   3000 	bool quoteDollar;
   3001 
   3002 	quoteDollar = **pp == 'q';
   3003 	if (!IsDelimiter((*pp)[1], ch))
   3004 		return AMR_UNKNOWN;
   3005 	(*pp)++;
   3006 
   3007 	if (!ModChain_ShouldEval(ch))
   3008 		return AMR_OK;
   3009 
   3010 	VarQuote(Expr_Str(ch->expr), quoteDollar, &buf);
   3011 	if (buf.data != NULL)
   3012 		Expr_SetValue(ch->expr, LazyBuf_DoneGet(&buf));
   3013 	else
   3014 		LazyBuf_Done(&buf);
   3015 
   3016 	return AMR_OK;
   3017 }
   3018 
   3019 /*ARGSUSED*/
   3020 static void
   3021 ModifyWord_Copy(Substring word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   3022 {
   3023 	SepBuf_AddSubstring(buf, word);
   3024 }
   3025 
   3026 /* :ts<separator> */
   3027 static ApplyModifierResult
   3028 ApplyModifier_ToSep(const char **pp, ModChain *ch)
   3029 {
   3030 	const char *sep = *pp + 2;
   3031 
   3032 	/*
   3033 	 * Even in parse-only mode, proceed as normal since there is
   3034 	 * neither any observable side effect nor a performance penalty.
   3035 	 * Checking for wantRes for every single piece of code in here
   3036 	 * would make the code in this function too hard to read.
   3037 	 */
   3038 
   3039 	/* ":ts<any><endc>" or ":ts<any>:" */
   3040 	if (sep[0] != ch->endc && IsDelimiter(sep[1], ch)) {
   3041 		*pp = sep + 1;
   3042 		ch->sep = sep[0];
   3043 		goto ok;
   3044 	}
   3045 
   3046 	/* ":ts<endc>" or ":ts:" */
   3047 	if (IsDelimiter(sep[0], ch)) {
   3048 		*pp = sep;
   3049 		ch->sep = '\0';	/* no separator */
   3050 		goto ok;
   3051 	}
   3052 
   3053 	/* ":ts<unrecognised><unrecognised>". */
   3054 	if (sep[0] != '\\') {
   3055 		(*pp)++;	/* just for backwards compatibility */
   3056 		return AMR_BAD;
   3057 	}
   3058 
   3059 	/* ":ts\n" */
   3060 	if (sep[1] == 'n') {
   3061 		*pp = sep + 2;
   3062 		ch->sep = '\n';
   3063 		goto ok;
   3064 	}
   3065 
   3066 	/* ":ts\t" */
   3067 	if (sep[1] == 't') {
   3068 		*pp = sep + 2;
   3069 		ch->sep = '\t';
   3070 		goto ok;
   3071 	}
   3072 
   3073 	/* ":ts\x40" or ":ts\100" */
   3074 	{
   3075 		const char *p = sep + 1;
   3076 		int base = 8;	/* assume octal */
   3077 
   3078 		if (sep[1] == 'x') {
   3079 			base = 16;
   3080 			p++;
   3081 		} else if (!ch_isdigit(sep[1])) {
   3082 			(*pp)++;	/* just for backwards compatibility */
   3083 			return AMR_BAD;	/* ":ts<backslash><unrecognised>". */
   3084 		}
   3085 
   3086 		if (!TryParseChar(&p, base, &ch->sep)) {
   3087 			Parse_Error(PARSE_FATAL,
   3088 			    "Invalid character number at \"%s\"", p);
   3089 			return AMR_CLEANUP;
   3090 		}
   3091 		if (!IsDelimiter(*p, ch)) {
   3092 			(*pp)++;	/* just for backwards compatibility */
   3093 			return AMR_BAD;
   3094 		}
   3095 
   3096 		*pp = p;
   3097 	}
   3098 
   3099 ok:
   3100 	ModifyWords(ch, ModifyWord_Copy, NULL, ch->oneBigWord);
   3101 	return AMR_OK;
   3102 }
   3103 
   3104 static char *
   3105 str_toupper(const char *str)
   3106 {
   3107 	char *res;
   3108 	size_t i, len;
   3109 
   3110 	len = strlen(str);
   3111 	res = bmake_malloc(len + 1);
   3112 	for (i = 0; i < len + 1; i++)
   3113 		res[i] = ch_toupper(str[i]);
   3114 
   3115 	return res;
   3116 }
   3117 
   3118 static char *
   3119 str_tolower(const char *str)
   3120 {
   3121 	char *res;
   3122 	size_t i, len;
   3123 
   3124 	len = strlen(str);
   3125 	res = bmake_malloc(len + 1);
   3126 	for (i = 0; i < len + 1; i++)
   3127 		res[i] = ch_tolower(str[i]);
   3128 
   3129 	return res;
   3130 }
   3131 
   3132 /* :tA, :tu, :tl, :ts<separator>, etc. */
   3133 static ApplyModifierResult
   3134 ApplyModifier_To(const char **pp, ModChain *ch)
   3135 {
   3136 	Expr *expr = ch->expr;
   3137 	const char *mod = *pp;
   3138 	assert(mod[0] == 't');
   3139 
   3140 	if (IsDelimiter(mod[1], ch) || mod[1] == '\0') {
   3141 		*pp = mod + 1;
   3142 		return AMR_BAD;	/* Found ":t<endc>" or ":t:". */
   3143 	}
   3144 
   3145 	if (mod[1] == 's')
   3146 		return ApplyModifier_ToSep(pp, ch);
   3147 
   3148 	if (!IsDelimiter(mod[2], ch)) {			/* :t<unrecognized> */
   3149 		*pp = mod + 1;
   3150 		return AMR_BAD;
   3151 	}
   3152 
   3153 	if (mod[1] == 'A') {				/* :tA */
   3154 		*pp = mod + 2;
   3155 		ModifyWords(ch, ModifyWord_Realpath, NULL, ch->oneBigWord);
   3156 		return AMR_OK;
   3157 	}
   3158 
   3159 	if (mod[1] == 'u') {				/* :tu */
   3160 		*pp = mod + 2;
   3161 		if (Expr_ShouldEval(expr))
   3162 			Expr_SetValueOwn(expr, str_toupper(Expr_Str(expr)));
   3163 		return AMR_OK;
   3164 	}
   3165 
   3166 	if (mod[1] == 'l') {				/* :tl */
   3167 		*pp = mod + 2;
   3168 		if (Expr_ShouldEval(expr))
   3169 			Expr_SetValueOwn(expr, str_tolower(Expr_Str(expr)));
   3170 		return AMR_OK;
   3171 	}
   3172 
   3173 	if (mod[1] == 'W' || mod[1] == 'w') {		/* :tW, :tw */
   3174 		*pp = mod + 2;
   3175 		ch->oneBigWord = mod[1] == 'W';
   3176 		return AMR_OK;
   3177 	}
   3178 
   3179 	/* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
   3180 	*pp = mod + 1;		/* XXX: unnecessary but observable */
   3181 	return AMR_BAD;
   3182 }
   3183 
   3184 /* :[#], :[1], :[-1..1], etc. */
   3185 static ApplyModifierResult
   3186 ApplyModifier_Words(const char **pp, ModChain *ch)
   3187 {
   3188 	Expr *expr = ch->expr;
   3189 	const char *estr;
   3190 	int first, last;
   3191 	VarParseResult res;
   3192 	const char *p;
   3193 	LazyBuf estrBuf;
   3194 	FStr festr;
   3195 
   3196 	(*pp)++;		/* skip the '[' */
   3197 	res = ParseModifierPart(pp, ']', expr->emode, ch, &estrBuf);
   3198 	if (res != VPR_OK)
   3199 		return AMR_CLEANUP;
   3200 	festr = LazyBuf_DoneGet(&estrBuf);
   3201 	estr = festr.str;
   3202 
   3203 	if (!IsDelimiter(**pp, ch))
   3204 		goto bad_modifier;		/* Found junk after ']' */
   3205 
   3206 	if (!ModChain_ShouldEval(ch))
   3207 		goto ok;
   3208 
   3209 	if (estr[0] == '\0')
   3210 		goto bad_modifier;			/* Found ":[]". */
   3211 
   3212 	if (estr[0] == '#' && estr[1] == '\0') {	/* Found ":[#]" */
   3213 		if (ch->oneBigWord) {
   3214 			Expr_SetValueRefer(expr, "1");
   3215 		} else {
   3216 			Buffer buf;
   3217 
   3218 			SubstringWords words = Expr_Words(expr);
   3219 			size_t ac = words.len;
   3220 			SubstringWords_Free(words);
   3221 
   3222 			/* 3 digits + '\0' is usually enough */
   3223 			Buf_InitSize(&buf, 4);
   3224 			Buf_AddInt(&buf, (int)ac);
   3225 			Expr_SetValueOwn(expr, Buf_DoneData(&buf));
   3226 		}
   3227 		goto ok;
   3228 	}
   3229 
   3230 	if (estr[0] == '*' && estr[1] == '\0') {	/* Found ":[*]" */
   3231 		ch->oneBigWord = true;
   3232 		goto ok;
   3233 	}
   3234 
   3235 	if (estr[0] == '@' && estr[1] == '\0') {	/* Found ":[@]" */
   3236 		ch->oneBigWord = false;
   3237 		goto ok;
   3238 	}
   3239 
   3240 	/*
   3241 	 * We expect estr to contain a single integer for :[N], or two
   3242 	 * integers separated by ".." for :[start..end].
   3243 	 */
   3244 	p = estr;
   3245 	if (!TryParseIntBase0(&p, &first))
   3246 		goto bad_modifier;	/* Found junk instead of a number */
   3247 
   3248 	if (p[0] == '\0') {		/* Found only one integer in :[N] */
   3249 		last = first;
   3250 	} else if (p[0] == '.' && p[1] == '.' && p[2] != '\0') {
   3251 		/* Expecting another integer after ".." */
   3252 		p += 2;
   3253 		if (!TryParseIntBase0(&p, &last) || *p != '\0')
   3254 			goto bad_modifier; /* Found junk after ".." */
   3255 	} else
   3256 		goto bad_modifier;	/* Found junk instead of ".." */
   3257 
   3258 	/*
   3259 	 * Now first and last are properly filled in, but we still have to
   3260 	 * check for 0 as a special case.
   3261 	 */
   3262 	if (first == 0 && last == 0) {
   3263 		/* ":[0]" or perhaps ":[0..0]" */
   3264 		ch->oneBigWord = true;
   3265 		goto ok;
   3266 	}
   3267 
   3268 	/* ":[0..N]" or ":[N..0]" */
   3269 	if (first == 0 || last == 0)
   3270 		goto bad_modifier;
   3271 
   3272 	/* Normal case: select the words described by first and last. */
   3273 	Expr_SetValueOwn(expr,
   3274 	    VarSelectWords(Expr_Str(expr), first, last,
   3275 	        ch->sep, ch->oneBigWord));
   3276 
   3277 ok:
   3278 	FStr_Done(&festr);
   3279 	return AMR_OK;
   3280 
   3281 bad_modifier:
   3282 	FStr_Done(&festr);
   3283 	return AMR_BAD;
   3284 }
   3285 
   3286 #ifndef NUM_TYPE
   3287 # define NUM_TYPE long long
   3288 #endif
   3289 
   3290 static NUM_TYPE
   3291 num_val(Substring s)
   3292 {
   3293 	NUM_TYPE val;
   3294 	char *ep;
   3295 
   3296 	val = strtoll(s.start, &ep, 0);
   3297 	if (ep != s.start) {
   3298 		switch (*ep) {
   3299 		case 'K':
   3300 		case 'k':
   3301 			val <<= 10;
   3302 			break;
   3303 		case 'M':
   3304 		case 'm':
   3305 			val <<= 20;
   3306 			break;
   3307 		case 'G':
   3308 		case 'g':
   3309 			val <<= 30;
   3310 			break;
   3311 		}
   3312 	}
   3313 	return val;
   3314 }
   3315 
   3316 static int
   3317 SubNumAsc(const void *sa, const void *sb)
   3318 {
   3319 	NUM_TYPE a, b;
   3320 
   3321 	a = num_val(*((const Substring *)sa));
   3322 	b = num_val(*((const Substring *)sb));
   3323 	return (a > b) ? 1 : (b > a) ? -1 : 0;
   3324 }
   3325 
   3326 static int
   3327 SubNumDesc(const void *sa, const void *sb)
   3328 {
   3329 	return SubNumAsc(sb, sa);
   3330 }
   3331 
   3332 static int
   3333 SubStrAsc(const void *sa, const void *sb)
   3334 {
   3335 	return strcmp(
   3336 	    ((const Substring *)sa)->start, ((const Substring *)sb)->start);
   3337 }
   3338 
   3339 static int
   3340 SubStrDesc(const void *sa, const void *sb)
   3341 {
   3342 	return SubStrAsc(sb, sa);
   3343 }
   3344 
   3345 static void
   3346 ShuffleSubstrings(Substring *strs, size_t n)
   3347 {
   3348 	size_t i;
   3349 
   3350 	for (i = n - 1; i > 0; i--) {
   3351 		size_t rndidx = (size_t)random() % (i + 1);
   3352 		Substring t = strs[i];
   3353 		strs[i] = strs[rndidx];
   3354 		strs[rndidx] = t;
   3355 	}
   3356 }
   3357 
   3358 /*
   3359  * :O		order ascending
   3360  * :Or		order descending
   3361  * :Ox		shuffle
   3362  * :On		numeric ascending
   3363  * :Onr, :Orn	numeric descending
   3364  */
   3365 static ApplyModifierResult
   3366 ApplyModifier_Order(const char **pp, ModChain *ch)
   3367 {
   3368 	const char *mod = *pp;
   3369 	SubstringWords words;
   3370 	int (*cmp)(const void *, const void *);
   3371 
   3372 	if (IsDelimiter(mod[1], ch) || mod[1] == '\0') {
   3373 		cmp = SubStrAsc;
   3374 		(*pp)++;
   3375 	} else if (IsDelimiter(mod[2], ch) || mod[2] == '\0') {
   3376 		if (mod[1] == 'n')
   3377 			cmp = SubNumAsc;
   3378 		else if (mod[1] == 'r')
   3379 			cmp = SubStrDesc;
   3380 		else if (mod[1] == 'x')
   3381 			cmp = NULL;
   3382 		else
   3383 			goto bad;
   3384 		*pp += 2;
   3385 	} else if (IsDelimiter(mod[3], ch) || mod[3] == '\0') {
   3386 		if ((mod[1] == 'n' && mod[2] == 'r') ||
   3387 		    (mod[1] == 'r' && mod[2] == 'n'))
   3388 			cmp = SubNumDesc;
   3389 		else
   3390 			goto bad;
   3391 		*pp += 3;
   3392 	} else {
   3393 		goto bad;
   3394 	}
   3395 
   3396 	if (!ModChain_ShouldEval(ch))
   3397 		return AMR_OK;
   3398 
   3399 	words = Expr_Words(ch->expr);
   3400 	if (cmp == NULL)
   3401 		ShuffleSubstrings(words.words, words.len);
   3402 	else {
   3403 		assert(words.words[0].end[0] == '\0');
   3404 		qsort(words.words, words.len, sizeof(words.words[0]), cmp);
   3405 	}
   3406 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3407 
   3408 	return AMR_OK;
   3409 
   3410 bad:
   3411 	(*pp)++;
   3412 	return AMR_BAD;
   3413 }
   3414 
   3415 /* :? then : else */
   3416 static ApplyModifierResult
   3417 ApplyModifier_IfElse(const char **pp, ModChain *ch)
   3418 {
   3419 	Expr *expr = ch->expr;
   3420 	VarParseResult res;
   3421 	LazyBuf thenBuf;
   3422 	LazyBuf elseBuf;
   3423 
   3424 	VarEvalMode then_emode = VARE_PARSE_ONLY;
   3425 	VarEvalMode else_emode = VARE_PARSE_ONLY;
   3426 
   3427 	CondResult cond_rc = CR_TRUE;	/* just not CR_ERROR */
   3428 	if (Expr_ShouldEval(expr)) {
   3429 		cond_rc = Cond_EvalCondition(expr->name);
   3430 		if (cond_rc == CR_TRUE)
   3431 			then_emode = expr->emode;
   3432 		if (cond_rc == CR_FALSE)
   3433 			else_emode = expr->emode;
   3434 	}
   3435 
   3436 	(*pp)++;		/* skip past the '?' */
   3437 	res = ParseModifierPart(pp, ':', then_emode, ch, &thenBuf);
   3438 	if (res != VPR_OK)
   3439 		return AMR_CLEANUP;
   3440 
   3441 	res = ParseModifierPart(pp, ch->endc, else_emode, ch, &elseBuf);
   3442 	if (res != VPR_OK) {
   3443 		LazyBuf_Done(&thenBuf);
   3444 		return AMR_CLEANUP;
   3445 	}
   3446 
   3447 	(*pp)--;		/* Go back to the ch->endc. */
   3448 
   3449 	if (cond_rc == CR_ERROR) {
   3450 		Substring thenExpr = LazyBuf_Get(&thenBuf);
   3451 		Substring elseExpr = LazyBuf_Get(&elseBuf);
   3452 		Error("Bad conditional expression '%s' in '%s?%.*s:%.*s'",
   3453 		    expr->name, expr->name,
   3454 		    (int)Substring_Length(thenExpr), thenExpr.start,
   3455 		    (int)Substring_Length(elseExpr), elseExpr.start);
   3456 		LazyBuf_Done(&thenBuf);
   3457 		LazyBuf_Done(&elseBuf);
   3458 		return AMR_CLEANUP;
   3459 	}
   3460 
   3461 	if (!Expr_ShouldEval(expr)) {
   3462 		LazyBuf_Done(&thenBuf);
   3463 		LazyBuf_Done(&elseBuf);
   3464 	} else if (cond_rc == CR_TRUE) {
   3465 		Expr_SetValue(expr, LazyBuf_DoneGet(&thenBuf));
   3466 		LazyBuf_Done(&elseBuf);
   3467 	} else {
   3468 		LazyBuf_Done(&thenBuf);
   3469 		Expr_SetValue(expr, LazyBuf_DoneGet(&elseBuf));
   3470 	}
   3471 	Expr_Define(expr);
   3472 	return AMR_OK;
   3473 }
   3474 
   3475 /*
   3476  * The ::= modifiers are special in that they do not read the variable value
   3477  * but instead assign to that variable.  They always expand to an empty
   3478  * string.
   3479  *
   3480  * Their main purpose is in supporting .for loops that generate shell commands
   3481  * since an ordinary variable assignment at that point would terminate the
   3482  * dependency group for these targets.  For example:
   3483  *
   3484  * list-targets: .USE
   3485  * .for i in ${.TARGET} ${.TARGET:R}.gz
   3486  *	@${t::=$i}
   3487  *	@echo 'The target is ${t:T}.'
   3488  * .endfor
   3489  *
   3490  *	  ::=<str>	Assigns <str> as the new value of variable.
   3491  *	  ::?=<str>	Assigns <str> as value of variable if
   3492  *			it was not already set.
   3493  *	  ::+=<str>	Appends <str> to variable.
   3494  *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
   3495  *			variable.
   3496  */
   3497 static ApplyModifierResult
   3498 ApplyModifier_Assign(const char **pp, ModChain *ch)
   3499 {
   3500 	Expr *expr = ch->expr;
   3501 	GNode *scope;
   3502 	FStr val;
   3503 	VarParseResult res;
   3504 	LazyBuf buf;
   3505 
   3506 	const char *mod = *pp;
   3507 	const char *op = mod + 1;
   3508 
   3509 	if (op[0] == '=')
   3510 		goto found_op;
   3511 	if ((op[0] == '+' || op[0] == '?' || op[0] == '!') && op[1] == '=')
   3512 		goto found_op;
   3513 	return AMR_UNKNOWN;	/* "::<unrecognised>" */
   3514 
   3515 found_op:
   3516 	if (expr->name[0] == '\0') {
   3517 		*pp = mod + 1;
   3518 		return AMR_BAD;
   3519 	}
   3520 
   3521 	*pp = mod + (op[0] == '+' || op[0] == '?' || op[0] == '!' ? 3 : 2);
   3522 
   3523 	res = ParseModifierPart(pp, ch->endc, expr->emode, ch, &buf);
   3524 	if (res != VPR_OK)
   3525 		return AMR_CLEANUP;
   3526 	val = LazyBuf_DoneGet(&buf);
   3527 
   3528 	(*pp)--;		/* Go back to the ch->endc. */
   3529 
   3530 	if (!Expr_ShouldEval(expr))
   3531 		goto done;
   3532 
   3533 	scope = expr->scope;	/* scope where v belongs */
   3534 	if (expr->defined == DEF_REGULAR && expr->scope != SCOPE_GLOBAL) {
   3535 		Var *gv = VarFind(expr->name, expr->scope, false);
   3536 		if (gv == NULL)
   3537 			scope = SCOPE_GLOBAL;
   3538 		else
   3539 			VarFreeShortLived(gv);
   3540 	}
   3541 
   3542 	switch (op[0]) {
   3543 	case '+':
   3544 		Var_Append(scope, expr->name, val.str);
   3545 		break;
   3546 	case '!': {
   3547 		const char *errfmt;
   3548 		char *cmd_output = Cmd_Exec(val.str, &errfmt);
   3549 		if (errfmt != NULL)
   3550 			Error(errfmt, val.str);
   3551 		else
   3552 			Var_Set(scope, expr->name, cmd_output);
   3553 		free(cmd_output);
   3554 		break;
   3555 	}
   3556 	case '?':
   3557 		if (expr->defined == DEF_REGULAR)
   3558 			break;
   3559 		/* FALLTHROUGH */
   3560 	default:
   3561 		Var_Set(scope, expr->name, val.str);
   3562 		break;
   3563 	}
   3564 	Expr_SetValueRefer(expr, "");
   3565 
   3566 done:
   3567 	FStr_Done(&val);
   3568 	return AMR_OK;
   3569 }
   3570 
   3571 /*
   3572  * :_=...
   3573  * remember current value
   3574  */
   3575 static ApplyModifierResult
   3576 ApplyModifier_Remember(const char **pp, ModChain *ch)
   3577 {
   3578 	Expr *expr = ch->expr;
   3579 	const char *mod = *pp;
   3580 	FStr name;
   3581 
   3582 	if (!ModMatchEq(mod, "_", ch))
   3583 		return AMR_UNKNOWN;
   3584 
   3585 	name = FStr_InitRefer("_");
   3586 	if (mod[1] == '=') {
   3587 		/*
   3588 		 * XXX: This ad-hoc call to strcspn deviates from the usual
   3589 		 * behavior defined in ParseModifierPart.  This creates an
   3590 		 * unnecessary, undocumented inconsistency in make.
   3591 		 */
   3592 		const char *arg = mod + 2;
   3593 		size_t argLen = strcspn(arg, ":)}");
   3594 		*pp = arg + argLen;
   3595 		name = FStr_InitOwn(bmake_strldup(arg, argLen));
   3596 	} else
   3597 		*pp = mod + 1;
   3598 
   3599 	if (Expr_ShouldEval(expr))
   3600 		Var_Set(expr->scope, name.str, Expr_Str(expr));
   3601 	FStr_Done(&name);
   3602 
   3603 	return AMR_OK;
   3604 }
   3605 
   3606 /*
   3607  * Apply the given function to each word of the variable value,
   3608  * for a single-letter modifier such as :H, :T.
   3609  */
   3610 static ApplyModifierResult
   3611 ApplyModifier_WordFunc(const char **pp, ModChain *ch,
   3612 		       ModifyWordProc modifyWord)
   3613 {
   3614 	if (!IsDelimiter((*pp)[1], ch))
   3615 		return AMR_UNKNOWN;
   3616 	(*pp)++;
   3617 
   3618 	if (ModChain_ShouldEval(ch))
   3619 		ModifyWords(ch, modifyWord, NULL, ch->oneBigWord);
   3620 
   3621 	return AMR_OK;
   3622 }
   3623 
   3624 /* Remove adjacent duplicate words. */
   3625 static ApplyModifierResult
   3626 ApplyModifier_Unique(const char **pp, ModChain *ch)
   3627 {
   3628 	SubstringWords words;
   3629 
   3630 	if (!IsDelimiter((*pp)[1], ch))
   3631 		return AMR_UNKNOWN;
   3632 	(*pp)++;
   3633 
   3634 	if (!ModChain_ShouldEval(ch))
   3635 		return AMR_OK;
   3636 
   3637 	words = Expr_Words(ch->expr);
   3638 
   3639 	if (words.len > 1) {
   3640 		size_t si, di;
   3641 
   3642 		di = 0;
   3643 		for (si = 1; si < words.len; si++) {
   3644 			if (!Substring_Eq(words.words[si], words.words[di])) {
   3645 				di++;
   3646 				if (di != si)
   3647 					words.words[di] = words.words[si];
   3648 			}
   3649 		}
   3650 		words.len = di + 1;
   3651 	}
   3652 
   3653 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3654 
   3655 	return AMR_OK;
   3656 }
   3657 
   3658 #ifdef SYSVVARSUB
   3659 /* :from=to */
   3660 static ApplyModifierResult
   3661 ApplyModifier_SysV(const char **pp, ModChain *ch)
   3662 {
   3663 	Expr *expr = ch->expr;
   3664 	VarParseResult res;
   3665 	LazyBuf lhsBuf, rhsBuf;
   3666 	FStr rhs;
   3667 	struct ModifyWord_SysVSubstArgs args;
   3668 	Substring lhs;
   3669 	const char *lhsSuffix;
   3670 
   3671 	const char *mod = *pp;
   3672 	bool eqFound = false;
   3673 
   3674 	/*
   3675 	 * First we make a pass through the string trying to verify it is a
   3676 	 * SysV-make-style translation. It must be: <lhs>=<rhs>
   3677 	 */
   3678 	int depth = 1;
   3679 	const char *p = mod;
   3680 	while (*p != '\0' && depth > 0) {
   3681 		if (*p == '=') {	/* XXX: should also test depth == 1 */
   3682 			eqFound = true;
   3683 			/* continue looking for ch->endc */
   3684 		} else if (*p == ch->endc)
   3685 			depth--;
   3686 		else if (*p == ch->startc)
   3687 			depth++;
   3688 		if (depth > 0)
   3689 			p++;
   3690 	}
   3691 	if (*p != ch->endc || !eqFound)
   3692 		return AMR_UNKNOWN;
   3693 
   3694 	res = ParseModifierPart(pp, '=', expr->emode, ch, &lhsBuf);
   3695 	if (res != VPR_OK)
   3696 		return AMR_CLEANUP;
   3697 
   3698 	/*
   3699 	 * The SysV modifier lasts until the end of the variable expression.
   3700 	 */
   3701 	res = ParseModifierPart(pp, ch->endc, expr->emode, ch, &rhsBuf);
   3702 	if (res != VPR_OK) {
   3703 		LazyBuf_Done(&lhsBuf);
   3704 		return AMR_CLEANUP;
   3705 	}
   3706 	rhs = LazyBuf_DoneGet(&rhsBuf);
   3707 
   3708 	(*pp)--;		/* Go back to the ch->endc. */
   3709 
   3710 	/* Do not turn an empty expression into non-empty. */
   3711 	if (lhsBuf.len == 0 && Expr_Str(expr)[0] == '\0')
   3712 		goto done;
   3713 
   3714 	lhs = LazyBuf_Get(&lhsBuf);
   3715 	lhsSuffix = Substring_SkipFirst(lhs, '%');
   3716 
   3717 	args.scope = expr->scope;
   3718 	args.lhsPrefix = Substring_Init(lhs.start,
   3719 	    lhsSuffix != lhs.start ? lhsSuffix - 1 : lhs.start);
   3720 	args.lhsPercent = lhsSuffix != lhs.start;
   3721 	args.lhsSuffix = Substring_Init(lhsSuffix, lhs.end);
   3722 	args.rhs = rhs.str;
   3723 
   3724 	ModifyWords(ch, ModifyWord_SysVSubst, &args, ch->oneBigWord);
   3725 
   3726 done:
   3727 	LazyBuf_Done(&lhsBuf);
   3728 	return AMR_OK;
   3729 }
   3730 #endif
   3731 
   3732 #ifdef SUNSHCMD
   3733 /* :sh */
   3734 static ApplyModifierResult
   3735 ApplyModifier_SunShell(const char **pp, ModChain *ch)
   3736 {
   3737 	Expr *expr = ch->expr;
   3738 	const char *p = *pp;
   3739 	if (!(p[1] == 'h' && IsDelimiter(p[2], ch)))
   3740 		return AMR_UNKNOWN;
   3741 	*pp = p + 2;
   3742 
   3743 	if (Expr_ShouldEval(expr)) {
   3744 		const char *errfmt;
   3745 		char *output = Cmd_Exec(Expr_Str(expr), &errfmt);
   3746 		if (errfmt != NULL)
   3747 			Error(errfmt, Expr_Str(expr));
   3748 		Expr_SetValueOwn(expr, output);
   3749 	}
   3750 
   3751 	return AMR_OK;
   3752 }
   3753 #endif
   3754 
   3755 static void
   3756 LogBeforeApply(const ModChain *ch, const char *mod)
   3757 {
   3758 	const Expr *expr = ch->expr;
   3759 	bool is_single_char = mod[0] != '\0' && IsDelimiter(mod[1], ch);
   3760 
   3761 	/*
   3762 	 * At this point, only the first character of the modifier can
   3763 	 * be used since the end of the modifier is not yet known.
   3764 	 */
   3765 
   3766 	if (!Expr_ShouldEval(expr)) {
   3767 		debug_printf("Parsing modifier ${%s:%c%s}\n",
   3768 		    expr->name, mod[0], is_single_char ? "" : "...");
   3769 		return;
   3770 	}
   3771 
   3772 	if ((expr->emode == VARE_WANTRES || expr->emode == VARE_UNDEFERR) &&
   3773 	    expr->defined == DEF_REGULAR) {
   3774 		debug_printf(
   3775 		    "Evaluating modifier ${%s:%c%s} on value \"%s\"\n",
   3776 		    expr->name, mod[0], is_single_char ? "" : "...",
   3777 		    Expr_Str(expr));
   3778 		return;
   3779 	}
   3780 
   3781 	debug_printf(
   3782 	    "Evaluating modifier ${%s:%c%s} on value \"%s\" (%s, %s)\n",
   3783 	    expr->name, mod[0], is_single_char ? "" : "...", Expr_Str(expr),
   3784 	    VarEvalMode_Name[expr->emode], ExprDefined_Name[expr->defined]);
   3785 }
   3786 
   3787 static void
   3788 LogAfterApply(const ModChain *ch, const char *p, const char *mod)
   3789 {
   3790 	const Expr *expr = ch->expr;
   3791 	const char *value = Expr_Str(expr);
   3792 	const char *quot = value == var_Error ? "" : "\"";
   3793 
   3794 	if ((expr->emode == VARE_WANTRES || expr->emode == VARE_UNDEFERR) &&
   3795 	    expr->defined == DEF_REGULAR) {
   3796 
   3797 		debug_printf("Result of ${%s:%.*s} is %s%s%s\n",
   3798 		    expr->name, (int)(p - mod), mod,
   3799 		    quot, value == var_Error ? "error" : value, quot);
   3800 		return;
   3801 	}
   3802 
   3803 	debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s)\n",
   3804 	    expr->name, (int)(p - mod), mod,
   3805 	    quot, value == var_Error ? "error" : value, quot,
   3806 	    VarEvalMode_Name[expr->emode],
   3807 	    ExprDefined_Name[expr->defined]);
   3808 }
   3809 
   3810 static ApplyModifierResult
   3811 ApplyModifier(const char **pp, ModChain *ch)
   3812 {
   3813 	switch (**pp) {
   3814 	case '!':
   3815 		return ApplyModifier_ShellCommand(pp, ch);
   3816 	case ':':
   3817 		return ApplyModifier_Assign(pp, ch);
   3818 	case '?':
   3819 		return ApplyModifier_IfElse(pp, ch);
   3820 	case '@':
   3821 		return ApplyModifier_Loop(pp, ch);
   3822 	case '[':
   3823 		return ApplyModifier_Words(pp, ch);
   3824 	case '_':
   3825 		return ApplyModifier_Remember(pp, ch);
   3826 #ifndef NO_REGEX
   3827 	case 'C':
   3828 		return ApplyModifier_Regex(pp, ch);
   3829 #endif
   3830 	case 'D':
   3831 	case 'U':
   3832 		return ApplyModifier_Defined(pp, ch);
   3833 	case 'E':
   3834 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Suffix);
   3835 	case 'g':
   3836 	case 'l':
   3837 		return ApplyModifier_Time(pp, ch);
   3838 	case 'H':
   3839 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Head);
   3840 	case 'h':
   3841 		return ApplyModifier_Hash(pp, ch);
   3842 	case 'L':
   3843 		return ApplyModifier_Literal(pp, ch);
   3844 	case 'M':
   3845 	case 'N':
   3846 		return ApplyModifier_Match(pp, ch);
   3847 	case 'O':
   3848 		return ApplyModifier_Order(pp, ch);
   3849 	case 'P':
   3850 		return ApplyModifier_Path(pp, ch);
   3851 	case 'Q':
   3852 	case 'q':
   3853 		return ApplyModifier_Quote(pp, ch);
   3854 	case 'R':
   3855 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Root);
   3856 	case 'r':
   3857 		return ApplyModifier_Range(pp, ch);
   3858 	case 'S':
   3859 		return ApplyModifier_Subst(pp, ch);
   3860 #ifdef SUNSHCMD
   3861 	case 's':
   3862 		return ApplyModifier_SunShell(pp, ch);
   3863 #endif
   3864 	case 'T':
   3865 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Tail);
   3866 	case 't':
   3867 		return ApplyModifier_To(pp, ch);
   3868 	case 'u':
   3869 		return ApplyModifier_Unique(pp, ch);
   3870 	default:
   3871 		return AMR_UNKNOWN;
   3872 	}
   3873 }
   3874 
   3875 static void ApplyModifiers(Expr *, const char **, char, char);
   3876 
   3877 typedef enum ApplyModifiersIndirectResult {
   3878 	/* The indirect modifiers have been applied successfully. */
   3879 	AMIR_CONTINUE,
   3880 	/* Fall back to the SysV modifier. */
   3881 	AMIR_SYSV,
   3882 	/* Error out. */
   3883 	AMIR_OUT
   3884 } ApplyModifiersIndirectResult;
   3885 
   3886 /*
   3887  * While expanding a variable expression, expand and apply indirect modifiers,
   3888  * such as in ${VAR:${M_indirect}}.
   3889  *
   3890  * All indirect modifiers of a group must come from a single variable
   3891  * expression.  ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
   3892  *
   3893  * Multiple groups of indirect modifiers can be chained by separating them
   3894  * with colons.  ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
   3895  *
   3896  * If the variable expression is not followed by ch->endc or ':', fall
   3897  * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
   3898  */
   3899 static ApplyModifiersIndirectResult
   3900 ApplyModifiersIndirect(ModChain *ch, const char **pp)
   3901 {
   3902 	Expr *expr = ch->expr;
   3903 	const char *p = *pp;
   3904 	FStr mods;
   3905 
   3906 	(void)Var_Parse(&p, expr->scope, expr->emode, &mods);
   3907 	/* TODO: handle errors */
   3908 
   3909 	if (mods.str[0] != '\0' && *p != '\0' && !IsDelimiter(*p, ch)) {
   3910 		FStr_Done(&mods);
   3911 		return AMIR_SYSV;
   3912 	}
   3913 
   3914 	DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
   3915 	    mods.str, (int)(p - *pp), *pp);
   3916 
   3917 	if (mods.str[0] != '\0') {
   3918 		const char *modsp = mods.str;
   3919 		ApplyModifiers(expr, &modsp, '\0', '\0');
   3920 		if (Expr_Str(expr) == var_Error || *modsp != '\0') {
   3921 			FStr_Done(&mods);
   3922 			*pp = p;
   3923 			return AMIR_OUT;	/* error already reported */
   3924 		}
   3925 	}
   3926 	FStr_Done(&mods);
   3927 
   3928 	if (*p == ':')
   3929 		p++;
   3930 	else if (*p == '\0' && ch->endc != '\0') {
   3931 		Error("Unclosed variable expression after indirect "
   3932 		      "modifier, expecting '%c' for variable \"%s\"",
   3933 		    ch->endc, expr->name);
   3934 		*pp = p;
   3935 		return AMIR_OUT;
   3936 	}
   3937 
   3938 	*pp = p;
   3939 	return AMIR_CONTINUE;
   3940 }
   3941 
   3942 static ApplyModifierResult
   3943 ApplySingleModifier(const char **pp, ModChain *ch)
   3944 {
   3945 	ApplyModifierResult res;
   3946 	const char *mod = *pp;
   3947 	const char *p = *pp;
   3948 
   3949 	if (DEBUG(VAR))
   3950 		LogBeforeApply(ch, mod);
   3951 
   3952 	res = ApplyModifier(&p, ch);
   3953 
   3954 #ifdef SYSVVARSUB
   3955 	if (res == AMR_UNKNOWN) {
   3956 		assert(p == mod);
   3957 		res = ApplyModifier_SysV(&p, ch);
   3958 	}
   3959 #endif
   3960 
   3961 	if (res == AMR_UNKNOWN) {
   3962 		/*
   3963 		 * Guess the end of the current modifier.
   3964 		 * XXX: Skipping the rest of the modifier hides
   3965 		 * errors and leads to wrong results.
   3966 		 * Parsing should rather stop here.
   3967 		 */
   3968 		for (p++; !IsDelimiter(*p, ch) && *p != '\0'; p++)
   3969 			continue;
   3970 		Parse_Error(PARSE_FATAL, "Unknown modifier \"%.*s\"",
   3971 		    (int)(p - mod), mod);
   3972 		Expr_SetValueRefer(ch->expr, var_Error);
   3973 	}
   3974 	if (res == AMR_CLEANUP || res == AMR_BAD) {
   3975 		*pp = p;
   3976 		return res;
   3977 	}
   3978 
   3979 	if (DEBUG(VAR))
   3980 		LogAfterApply(ch, p, mod);
   3981 
   3982 	if (*p == '\0' && ch->endc != '\0') {
   3983 		Error(
   3984 		    "Unclosed variable expression, expecting '%c' for "
   3985 		    "modifier \"%.*s\" of variable \"%s\" with value \"%s\"",
   3986 		    ch->endc,
   3987 		    (int)(p - mod), mod,
   3988 		    ch->expr->name, Expr_Str(ch->expr));
   3989 	} else if (*p == ':') {
   3990 		p++;
   3991 	} else if (opts.strict && *p != '\0' && *p != ch->endc) {
   3992 		Parse_Error(PARSE_FATAL,
   3993 		    "Missing delimiter ':' after modifier \"%.*s\"",
   3994 		    (int)(p - mod), mod);
   3995 		/*
   3996 		 * TODO: propagate parse error to the enclosing
   3997 		 * expression
   3998 		 */
   3999 	}
   4000 	*pp = p;
   4001 	return AMR_OK;
   4002 }
   4003 
   4004 #if __STDC_VERSION__ >= 199901L
   4005 #define ModChain_Literal(expr, startc, endc, sep, oneBigWord) \
   4006 	(ModChain) { expr, startc, endc, sep, oneBigWord }
   4007 #else
   4008 MAKE_INLINE ModChain
   4009 ModChain_Literal(Expr *expr, char startc, char endc, char sep, bool oneBigWord)
   4010 {
   4011 	ModChain ch;
   4012 	ch.expr = expr;
   4013 	ch.startc = startc;
   4014 	ch.endc = endc;
   4015 	ch.sep = sep;
   4016 	ch.oneBigWord = oneBigWord;
   4017 	return ch;
   4018 }
   4019 #endif
   4020 
   4021 /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
   4022 static void
   4023 ApplyModifiers(
   4024     Expr *expr,
   4025     const char **pp,	/* the parsing position, updated upon return */
   4026     char startc,	/* '(' or '{'; or '\0' for indirect modifiers */
   4027     char endc		/* ')' or '}'; or '\0' for indirect modifiers */
   4028 )
   4029 {
   4030 	ModChain ch = ModChain_Literal(expr, startc, endc, ' ', false);
   4031 	const char *p;
   4032 	const char *mod;
   4033 
   4034 	assert(startc == '(' || startc == '{' || startc == '\0');
   4035 	assert(endc == ')' || endc == '}' || endc == '\0');
   4036 	assert(Expr_Str(expr) != NULL);
   4037 
   4038 	p = *pp;
   4039 
   4040 	if (*p == '\0' && endc != '\0') {
   4041 		Error(
   4042 		    "Unclosed variable expression (expecting '%c') for \"%s\"",
   4043 		    ch.endc, expr->name);
   4044 		goto cleanup;
   4045 	}
   4046 
   4047 	while (*p != '\0' && *p != endc) {
   4048 		ApplyModifierResult res;
   4049 
   4050 		if (*p == '$') {
   4051 			ApplyModifiersIndirectResult amir =
   4052 			    ApplyModifiersIndirect(&ch, &p);
   4053 			if (amir == AMIR_CONTINUE)
   4054 				continue;
   4055 			if (amir == AMIR_OUT)
   4056 				break;
   4057 			/*
   4058 			 * It's neither '${VAR}:' nor '${VAR}}'.  Try to parse
   4059 			 * it as a SysV modifier, as that is the only modifier
   4060 			 * that can start with '$'.
   4061 			 */
   4062 		}
   4063 
   4064 		mod = p;
   4065 
   4066 		res = ApplySingleModifier(&p, &ch);
   4067 		if (res == AMR_CLEANUP)
   4068 			goto cleanup;
   4069 		if (res == AMR_BAD)
   4070 			goto bad_modifier;
   4071 	}
   4072 
   4073 	*pp = p;
   4074 	assert(Expr_Str(expr) != NULL);	/* Use var_Error or varUndefined. */
   4075 	return;
   4076 
   4077 bad_modifier:
   4078 	/* XXX: The modifier end is only guessed. */
   4079 	Error("Bad modifier \":%.*s\" for variable \"%s\"",
   4080 	    (int)strcspn(mod, ":)}"), mod, expr->name);
   4081 
   4082 cleanup:
   4083 	/*
   4084 	 * TODO: Use p + strlen(p) instead, to stop parsing immediately.
   4085 	 *
   4086 	 * In the unit tests, this generates a few unterminated strings in the
   4087 	 * shell commands though.  Instead of producing these unfinished
   4088 	 * strings, commands with evaluation errors should not be run at all.
   4089 	 *
   4090 	 * To make that happen, Var_Subst must report the actual errors
   4091 	 * instead of returning VPR_OK unconditionally.
   4092 	 */
   4093 	*pp = p;
   4094 	Expr_SetValueRefer(expr, var_Error);
   4095 }
   4096 
   4097 /*
   4098  * Only 4 of the 7 local variables are treated specially as they are the only
   4099  * ones that will be set when dynamic sources are expanded.
   4100  */
   4101 static bool
   4102 VarnameIsDynamic(Substring varname)
   4103 {
   4104 	const char *name;
   4105 	size_t len;
   4106 
   4107 	name = varname.start;
   4108 	len = Substring_Length(varname);
   4109 	if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
   4110 		switch (name[0]) {
   4111 		case '@':
   4112 		case '%':
   4113 		case '*':
   4114 		case '!':
   4115 			return true;
   4116 		}
   4117 		return false;
   4118 	}
   4119 
   4120 	if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
   4121 		return Substring_Equals(varname, ".TARGET") ||
   4122 		       Substring_Equals(varname, ".ARCHIVE") ||
   4123 		       Substring_Equals(varname, ".PREFIX") ||
   4124 		       Substring_Equals(varname, ".MEMBER");
   4125 	}
   4126 
   4127 	return false;
   4128 }
   4129 
   4130 static const char *
   4131 UndefinedShortVarValue(char varname, const GNode *scope)
   4132 {
   4133 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
   4134 		/*
   4135 		 * If substituting a local variable in a non-local scope,
   4136 		 * assume it's for dynamic source stuff. We have to handle
   4137 		 * this specially and return the longhand for the variable
   4138 		 * with the dollar sign escaped so it makes it back to the
   4139 		 * caller. Only four of the local variables are treated
   4140 		 * specially as they are the only four that will be set
   4141 		 * when dynamic sources are expanded.
   4142 		 */
   4143 		switch (varname) {
   4144 		case '@':
   4145 			return "$(.TARGET)";
   4146 		case '%':
   4147 			return "$(.MEMBER)";
   4148 		case '*':
   4149 			return "$(.PREFIX)";
   4150 		case '!':
   4151 			return "$(.ARCHIVE)";
   4152 		}
   4153 	}
   4154 	return NULL;
   4155 }
   4156 
   4157 /*
   4158  * Parse a variable name, until the end character or a colon, whichever
   4159  * comes first.
   4160  */
   4161 static void
   4162 ParseVarname(const char **pp, char startc, char endc,
   4163 	     GNode *scope, VarEvalMode emode,
   4164 	     LazyBuf *buf)
   4165 {
   4166 	const char *p = *pp;
   4167 	int depth = 0;		/* Track depth so we can spot parse errors. */
   4168 
   4169 	LazyBuf_Init(buf, p);
   4170 
   4171 	while (*p != '\0') {
   4172 		if ((*p == endc || *p == ':') && depth == 0)
   4173 			break;
   4174 		if (*p == startc)
   4175 			depth++;
   4176 		if (*p == endc)
   4177 			depth--;
   4178 
   4179 		/* A variable inside a variable, expand. */
   4180 		if (*p == '$') {
   4181 			FStr nested_val;
   4182 			(void)Var_Parse(&p, scope, emode, &nested_val);
   4183 			/* TODO: handle errors */
   4184 			LazyBuf_AddStr(buf, nested_val.str);
   4185 			FStr_Done(&nested_val);
   4186 		} else {
   4187 			LazyBuf_Add(buf, *p);
   4188 			p++;
   4189 		}
   4190 	}
   4191 	*pp = p;
   4192 }
   4193 
   4194 static VarParseResult
   4195 ValidShortVarname(char varname, const char *start)
   4196 {
   4197 	if (varname != '$' && varname != ':' && varname != '}' &&
   4198 	    varname != ')' && varname != '\0')
   4199 		return VPR_OK;
   4200 
   4201 	if (!opts.strict)
   4202 		return VPR_ERR;	/* XXX: Missing error message */
   4203 
   4204 	if (varname == '$')
   4205 		Parse_Error(PARSE_FATAL,
   4206 		    "To escape a dollar, use \\$, not $$, at \"%s\"", start);
   4207 	else if (varname == '\0')
   4208 		Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
   4209 	else
   4210 		Parse_Error(PARSE_FATAL,
   4211 		    "Invalid variable name '%c', at \"%s\"", varname, start);
   4212 
   4213 	return VPR_ERR;
   4214 }
   4215 
   4216 /*
   4217  * Parse a single-character variable name such as in $V or $@.
   4218  * Return whether to continue parsing.
   4219  */
   4220 static bool
   4221 ParseVarnameShort(char varname, const char **pp, GNode *scope,
   4222 		  VarEvalMode emode,
   4223 		  VarParseResult *out_false_res, const char **out_false_val,
   4224 		  Var **out_true_var)
   4225 {
   4226 	char name[2];
   4227 	Var *v;
   4228 	VarParseResult vpr;
   4229 
   4230 	vpr = ValidShortVarname(varname, *pp);
   4231 	if (vpr != VPR_OK) {
   4232 		(*pp)++;
   4233 		*out_false_res = vpr;
   4234 		*out_false_val = var_Error;
   4235 		return false;
   4236 	}
   4237 
   4238 	name[0] = varname;
   4239 	name[1] = '\0';
   4240 	v = VarFind(name, scope, true);
   4241 	if (v == NULL) {
   4242 		const char *val;
   4243 		*pp += 2;
   4244 
   4245 		val = UndefinedShortVarValue(varname, scope);
   4246 		if (val == NULL)
   4247 			val = emode == VARE_UNDEFERR
   4248 			    ? var_Error : varUndefined;
   4249 
   4250 		if (opts.strict && val == var_Error) {
   4251 			Parse_Error(PARSE_FATAL,
   4252 			    "Variable \"%s\" is undefined", name);
   4253 			*out_false_res = VPR_ERR;
   4254 			*out_false_val = val;
   4255 			return false;
   4256 		}
   4257 
   4258 		/*
   4259 		 * XXX: This looks completely wrong.
   4260 		 *
   4261 		 * If undefined expressions are not allowed, this should
   4262 		 * rather be VPR_ERR instead of VPR_UNDEF, together with an
   4263 		 * error message.
   4264 		 *
   4265 		 * If undefined expressions are allowed, this should rather
   4266 		 * be VPR_UNDEF instead of VPR_OK.
   4267 		 */
   4268 		*out_false_res = emode == VARE_UNDEFERR
   4269 		    ? VPR_UNDEF : VPR_OK;
   4270 		*out_false_val = val;
   4271 		return false;
   4272 	}
   4273 
   4274 	*out_true_var = v;
   4275 	return true;
   4276 }
   4277 
   4278 /* Find variables like @F or <D. */
   4279 static Var *
   4280 FindLocalLegacyVar(Substring varname, GNode *scope,
   4281 		   const char **out_extraModifiers)
   4282 {
   4283 	Var *v;
   4284 
   4285 	/* Only resolve these variables if scope is a "real" target. */
   4286 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
   4287 		return NULL;
   4288 
   4289 	if (Substring_Length(varname) != 2)
   4290 		return NULL;
   4291 	if (varname.start[1] != 'F' && varname.start[1] != 'D')
   4292 		return NULL;
   4293 	if (strchr("@%?*!<>", varname.start[0]) == NULL)
   4294 		return NULL;
   4295 
   4296 	v = VarFindSubstring(Substring_Sub(varname, 0, 1), scope, false);
   4297 	if (v == NULL)
   4298 		return NULL;
   4299 
   4300 	*out_extraModifiers = varname.start[1] == 'D' ? "H:" : "T:";
   4301 	return v;
   4302 }
   4303 
   4304 static VarParseResult
   4305 EvalUndefined(bool dynamic, const char *start, const char *p,
   4306 	      Substring varname, VarEvalMode emode, FStr *out_val)
   4307 {
   4308 	if (dynamic) {
   4309 		*out_val = FStr_InitOwn(bmake_strsedup(start, p));
   4310 		return VPR_OK;
   4311 	}
   4312 
   4313 	if (emode == VARE_UNDEFERR && opts.strict) {
   4314 		Parse_Error(PARSE_FATAL,
   4315 		    "Variable \"%.*s\" is undefined",
   4316 		    (int)Substring_Length(varname), varname.start);
   4317 		*out_val = FStr_InitRefer(var_Error);
   4318 		return VPR_ERR;
   4319 	}
   4320 
   4321 	if (emode == VARE_UNDEFERR) {
   4322 		*out_val = FStr_InitRefer(var_Error);
   4323 		return VPR_UNDEF;	/* XXX: Should be VPR_ERR instead. */
   4324 	}
   4325 
   4326 	*out_val = FStr_InitRefer(varUndefined);
   4327 	return VPR_OK;
   4328 }
   4329 
   4330 /*
   4331  * Parse a long variable name enclosed in braces or parentheses such as $(VAR)
   4332  * or ${VAR}, up to the closing brace or parenthesis, or in the case of
   4333  * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
   4334  * Return whether to continue parsing.
   4335  */
   4336 static bool
   4337 ParseVarnameLong(
   4338 	const char **pp,
   4339 	char startc,
   4340 	GNode *scope,
   4341 	VarEvalMode emode,
   4342 
   4343 	const char **out_false_pp,
   4344 	VarParseResult *out_false_res,
   4345 	FStr *out_false_val,
   4346 
   4347 	char *out_true_endc,
   4348 	Var **out_true_v,
   4349 	bool *out_true_haveModifier,
   4350 	const char **out_true_extraModifiers,
   4351 	bool *out_true_dynamic,
   4352 	ExprDefined *out_true_exprDefined
   4353 )
   4354 {
   4355 	LazyBuf varname;
   4356 	Substring name;
   4357 	Var *v;
   4358 	bool haveModifier;
   4359 	bool dynamic = false;
   4360 
   4361 	const char *p = *pp;
   4362 	const char *const start = p;
   4363 	char endc = startc == '(' ? ')' : '}';
   4364 
   4365 	p += 2;			/* skip "${" or "$(" or "y(" */
   4366 	ParseVarname(&p, startc, endc, scope, emode, &varname);
   4367 	name = LazyBuf_Get(&varname);
   4368 
   4369 	if (*p == ':') {
   4370 		haveModifier = true;
   4371 	} else if (*p == endc) {
   4372 		haveModifier = false;
   4373 	} else {
   4374 		Parse_Error(PARSE_FATAL, "Unclosed variable \"%.*s\"",
   4375 		    (int)Substring_Length(name), name.start);
   4376 		LazyBuf_Done(&varname);
   4377 		*out_false_pp = p;
   4378 		*out_false_val = FStr_InitRefer(var_Error);
   4379 		*out_false_res = VPR_ERR;
   4380 		return false;
   4381 	}
   4382 
   4383 	v = VarFindSubstring(name, scope, true);
   4384 
   4385 	/*
   4386 	 * At this point, p points just after the variable name, either at
   4387 	 * ':' or at endc.
   4388 	 */
   4389 
   4390 	if (v == NULL && Substring_Equals(name, ".SUFFIXES")) {
   4391 		char *suffixes = Suff_NamesStr();
   4392 		v = VarNew(FStr_InitRefer(".SUFFIXES"), suffixes,
   4393 		    true, false, true);
   4394 		free(suffixes);
   4395 	} else if (v == NULL)
   4396 		v = FindLocalLegacyVar(name, scope, out_true_extraModifiers);
   4397 
   4398 	if (v == NULL) {
   4399 		/*
   4400 		 * Defer expansion of dynamic variables if they appear in
   4401 		 * non-local scope since they are not defined there.
   4402 		 */
   4403 		dynamic = VarnameIsDynamic(name) &&
   4404 			  (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
   4405 
   4406 		if (!haveModifier) {
   4407 			p++;	/* skip endc */
   4408 			*out_false_pp = p;
   4409 			*out_false_res = EvalUndefined(dynamic, start, p,
   4410 			    name, emode, out_false_val);
   4411 			LazyBuf_Done(&varname);
   4412 			return false;
   4413 		}
   4414 
   4415 		/*
   4416 		 * The variable expression is based on an undefined variable.
   4417 		 * Nevertheless it needs a Var, for modifiers that access the
   4418 		 * variable name, such as :L or :?.
   4419 		 *
   4420 		 * Most modifiers leave this expression in the "undefined"
   4421 		 * state (VES_UNDEF), only a few modifiers like :D, :U, :L,
   4422 		 * :P turn this undefined expression into a defined
   4423 		 * expression (VES_DEF).
   4424 		 *
   4425 		 * In the end, after applying all modifiers, if the expression
   4426 		 * is still undefined, Var_Parse will return an empty string
   4427 		 * instead of the actually computed value.
   4428 		 */
   4429 		v = VarNew(LazyBuf_DoneGet(&varname), "",
   4430 		    true, false, false);
   4431 		*out_true_exprDefined = DEF_UNDEF;
   4432 	} else
   4433 		LazyBuf_Done(&varname);
   4434 
   4435 	*pp = p;
   4436 	*out_true_endc = endc;
   4437 	*out_true_v = v;
   4438 	*out_true_haveModifier = haveModifier;
   4439 	*out_true_dynamic = dynamic;
   4440 	return true;
   4441 }
   4442 
   4443 #if __STDC_VERSION__ >= 199901L
   4444 #define Expr_Literal(name, value, emode, scope, defined) \
   4445 	{ name, value, emode, scope, defined }
   4446 #else
   4447 MAKE_INLINE Expr
   4448 Expr_Literal(const char *name, FStr value,
   4449 	     VarEvalMode emode, GNode *scope, ExprDefined defined)
   4450 {
   4451 	Expr expr;
   4452 
   4453 	expr.name = name;
   4454 	expr.value = value;
   4455 	expr.emode = emode;
   4456 	expr.scope = scope;
   4457 	expr.defined = defined;
   4458 	return expr;
   4459 }
   4460 #endif
   4461 
   4462 /*
   4463  * Expressions of the form ${:U...} with a trivial value are often generated
   4464  * by .for loops and are boring, therefore parse and evaluate them in a fast
   4465  * lane without debug logging.
   4466  */
   4467 static bool
   4468 Var_Parse_FastLane(const char **pp, VarEvalMode emode, FStr *out_value)
   4469 {
   4470 	const char *p;
   4471 
   4472 	p = *pp;
   4473 	if (!(p[0] == '$' && p[1] == '{' && p[2] == ':' && p[3] == 'U'))
   4474 		return false;
   4475 
   4476 	p += 4;
   4477 	while (*p != '$' && *p != '{' && *p != ':' && *p != '\\' &&
   4478 	       *p != '}' && *p != '\0')
   4479 		p++;
   4480 	if (*p != '}')
   4481 		return false;
   4482 
   4483 	if (emode == VARE_PARSE_ONLY)
   4484 		*out_value = FStr_InitRefer("");
   4485 	else
   4486 		*out_value = FStr_InitOwn(bmake_strsedup(*pp + 4, p));
   4487 	*pp = p + 1;
   4488 	return true;
   4489 }
   4490 
   4491 /*
   4492  * Given the start of a variable expression (such as $v, $(VAR),
   4493  * ${VAR:Mpattern}), extract the variable name and value, and the modifiers,
   4494  * if any.  While doing that, apply the modifiers to the value of the
   4495  * expression, forming its final value.  A few of the modifiers such as :!cmd!
   4496  * or ::= have side effects.
   4497  *
   4498  * Input:
   4499  *	*pp		The string to parse.
   4500  *			In CondParser_FuncCallEmpty, it may also point to the
   4501  *			"y" of "empty(VARNAME:Modifiers)", which is
   4502  *			syntactically the same.
   4503  *	scope		The scope for finding variables
   4504  *	emode		Controls the exact details of parsing and evaluation
   4505  *
   4506  * Output:
   4507  *	*pp		The position where to continue parsing.
   4508  *			TODO: After a parse error, the value of *pp is
   4509  *			unspecified.  It may not have been updated at all,
   4510  *			point to some random character in the string, to the
   4511  *			location of the parse error, or at the end of the
   4512  *			string.
   4513  *	*out_val	The value of the variable expression, never NULL.
   4514  *	*out_val	var_Error if there was a parse error.
   4515  *	*out_val	var_Error if the base variable of the expression was
   4516  *			undefined, emode is VARE_UNDEFERR, and none of
   4517  *			the modifiers turned the undefined expression into a
   4518  *			defined expression.
   4519  *			XXX: It is not guaranteed that an error message has
   4520  *			been printed.
   4521  *	*out_val	varUndefined if the base variable of the expression
   4522  *			was undefined, emode was not VARE_UNDEFERR,
   4523  *			and none of the modifiers turned the undefined
   4524  *			expression into a defined expression.
   4525  *			XXX: It is not guaranteed that an error message has
   4526  *			been printed.
   4527  */
   4528 VarParseResult
   4529 Var_Parse(const char **pp, GNode *scope, VarEvalMode emode, FStr *out_val)
   4530 {
   4531 	const char *p = *pp;
   4532 	const char *const start = p;
   4533 	/* true if have modifiers for the variable. */
   4534 	bool haveModifier;
   4535 	/* Starting character if variable in parens or braces. */
   4536 	char startc;
   4537 	/* Ending character if variable in parens or braces. */
   4538 	char endc;
   4539 	/*
   4540 	 * true if the variable is local and we're expanding it in a
   4541 	 * non-local scope. This is done to support dynamic sources.
   4542 	 * The result is just the expression, unaltered.
   4543 	 */
   4544 	bool dynamic;
   4545 	const char *extramodifiers;
   4546 	Var *v;
   4547 	Expr expr = Expr_Literal(NULL, FStr_InitRefer(NULL), emode,
   4548 	    scope, DEF_REGULAR);
   4549 
   4550 	if (Var_Parse_FastLane(pp, emode, out_val))
   4551 		return VPR_OK;
   4552 
   4553 	DEBUG2(VAR, "Var_Parse: %s (%s)\n", start, VarEvalMode_Name[emode]);
   4554 
   4555 	*out_val = FStr_InitRefer(NULL);
   4556 	extramodifiers = NULL;	/* extra modifiers to apply first */
   4557 	dynamic = false;
   4558 
   4559 	/*
   4560 	 * Appease GCC, which thinks that the variable might not be
   4561 	 * initialized.
   4562 	 */
   4563 	endc = '\0';
   4564 
   4565 	startc = p[1];
   4566 	if (startc != '(' && startc != '{') {
   4567 		VarParseResult res;
   4568 		if (!ParseVarnameShort(startc, pp, scope, emode, &res,
   4569 		    &out_val->str, &v))
   4570 			return res;
   4571 		haveModifier = false;
   4572 		p++;
   4573 	} else {
   4574 		VarParseResult res;
   4575 		if (!ParseVarnameLong(&p, startc, scope, emode,
   4576 		    pp, &res, out_val,
   4577 		    &endc, &v, &haveModifier, &extramodifiers,
   4578 		    &dynamic, &expr.defined))
   4579 			return res;
   4580 	}
   4581 
   4582 	expr.name = v->name.str;
   4583 	if (v->inUse)
   4584 		Fatal("Variable %s is recursive.", v->name.str);
   4585 
   4586 	/*
   4587 	 * XXX: This assignment creates an alias to the current value of the
   4588 	 * variable.  This means that as long as the value of the expression
   4589 	 * stays the same, the value of the variable must not change.
   4590 	 * Using the '::=' modifier, it could be possible to do exactly this.
   4591 	 * At the bottom of this function, the resulting value is compared to
   4592 	 * the then-current value of the variable.  This might also invoke
   4593 	 * undefined behavior.
   4594 	 */
   4595 	expr.value = FStr_InitRefer(v->val.data);
   4596 
   4597 	/*
   4598 	 * Before applying any modifiers, expand any nested expressions from
   4599 	 * the variable value.
   4600 	 */
   4601 	if (strchr(Expr_Str(&expr), '$') != NULL &&
   4602 	    VarEvalMode_ShouldEval(emode)) {
   4603 		char *expanded;
   4604 		VarEvalMode nested_emode = emode;
   4605 		if (opts.strict)
   4606 			nested_emode = VarEvalMode_UndefOk(nested_emode);
   4607 		v->inUse = true;
   4608 		(void)Var_Subst(Expr_Str(&expr), scope, nested_emode,
   4609 		    &expanded);
   4610 		v->inUse = false;
   4611 		/* TODO: handle errors */
   4612 		Expr_SetValueOwn(&expr, expanded);
   4613 	}
   4614 
   4615 	if (extramodifiers != NULL) {
   4616 		const char *em = extramodifiers;
   4617 		ApplyModifiers(&expr, &em, '\0', '\0');
   4618 	}
   4619 
   4620 	if (haveModifier) {
   4621 		p++;		/* Skip initial colon. */
   4622 		ApplyModifiers(&expr, &p, startc, endc);
   4623 	}
   4624 
   4625 	if (*p != '\0')		/* Skip past endc if possible. */
   4626 		p++;
   4627 
   4628 	*pp = p;
   4629 
   4630 	if (expr.defined == DEF_UNDEF) {
   4631 		if (dynamic)
   4632 			Expr_SetValueOwn(&expr, bmake_strsedup(start, p));
   4633 		else {
   4634 			/*
   4635 			 * The expression is still undefined, therefore
   4636 			 * discard the actual value and return an error marker
   4637 			 * instead.
   4638 			 */
   4639 			Expr_SetValueRefer(&expr,
   4640 			    emode == VARE_UNDEFERR
   4641 				? var_Error : varUndefined);
   4642 		}
   4643 	}
   4644 
   4645 	if (v->shortLived) {
   4646 		if (expr.value.str == v->val.data) {
   4647 			/* move ownership */
   4648 			expr.value.freeIt = v->val.data;
   4649 			v->val.data = NULL;
   4650 		}
   4651 		VarFreeShortLived(v);
   4652 	}
   4653 
   4654 	*out_val = expr.value;
   4655 	return VPR_OK;		/* XXX: Is not correct in all cases */
   4656 }
   4657 
   4658 static void
   4659 VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalMode emode)
   4660 {
   4661 	/* A dollar sign may be escaped with another dollar sign. */
   4662 	if (save_dollars && VarEvalMode_ShouldKeepDollar(emode))
   4663 		Buf_AddByte(res, '$');
   4664 	Buf_AddByte(res, '$');
   4665 	*pp += 2;
   4666 }
   4667 
   4668 static void
   4669 VarSubstExpr(const char **pp, Buffer *buf, GNode *scope,
   4670 	     VarEvalMode emode, bool *inout_errorReported)
   4671 {
   4672 	const char *p = *pp;
   4673 	const char *nested_p = p;
   4674 	FStr val;
   4675 
   4676 	(void)Var_Parse(&nested_p, scope, emode, &val);
   4677 	/* TODO: handle errors */
   4678 
   4679 	if (val.str == var_Error || val.str == varUndefined) {
   4680 		if (!VarEvalMode_ShouldKeepUndef(emode)) {
   4681 			p = nested_p;
   4682 		} else if (emode == VARE_UNDEFERR || val.str == var_Error) {
   4683 
   4684 			/*
   4685 			 * XXX: This condition is wrong.  If val == var_Error,
   4686 			 * this doesn't necessarily mean there was an undefined
   4687 			 * variable.  It could equally well be a parse error;
   4688 			 * see unit-tests/varmod-order.exp.
   4689 			 */
   4690 
   4691 			/*
   4692 			 * If variable is undefined, complain and skip the
   4693 			 * variable. The complaint will stop us from doing
   4694 			 * anything when the file is parsed.
   4695 			 */
   4696 			if (!*inout_errorReported) {
   4697 				Parse_Error(PARSE_FATAL,
   4698 				    "Undefined variable \"%.*s\"",
   4699 				    (int)(size_t)(nested_p - p), p);
   4700 			}
   4701 			p = nested_p;
   4702 			*inout_errorReported = true;
   4703 		} else {
   4704 			/*
   4705 			 * Copy the initial '$' of the undefined expression,
   4706 			 * thereby deferring expansion of the expression, but
   4707 			 * expand nested expressions if already possible. See
   4708 			 * unit-tests/varparse-undef-partial.mk.
   4709 			 */
   4710 			Buf_AddByte(buf, *p);
   4711 			p++;
   4712 		}
   4713 	} else {
   4714 		p = nested_p;
   4715 		Buf_AddStr(buf, val.str);
   4716 	}
   4717 
   4718 	FStr_Done(&val);
   4719 
   4720 	*pp = p;
   4721 }
   4722 
   4723 /*
   4724  * Skip as many characters as possible -- either to the end of the string
   4725  * or to the next dollar sign (variable expression).
   4726  */
   4727 static void
   4728 VarSubstPlain(const char **pp, Buffer *res)
   4729 {
   4730 	const char *p = *pp;
   4731 	const char *start = p;
   4732 
   4733 	for (p++; *p != '$' && *p != '\0'; p++)
   4734 		continue;
   4735 	Buf_AddBytesBetween(res, start, p);
   4736 	*pp = p;
   4737 }
   4738 
   4739 /*
   4740  * Expand all variable expressions like $V, ${VAR}, $(VAR:Modifiers) in the
   4741  * given string.
   4742  *
   4743  * Input:
   4744  *	str		The string in which the variable expressions are
   4745  *			expanded.
   4746  *	scope		The scope in which to start searching for
   4747  *			variables.  The other scopes are searched as well.
   4748  *	emode		The mode for parsing or evaluating subexpressions.
   4749  */
   4750 VarParseResult
   4751 Var_Subst(const char *str, GNode *scope, VarEvalMode emode, char **out_res)
   4752 {
   4753 	const char *p = str;
   4754 	Buffer res;
   4755 
   4756 	/*
   4757 	 * Set true if an error has already been reported, to prevent a
   4758 	 * plethora of messages when recursing
   4759 	 */
   4760 	/* XXX: Why is the 'static' necessary here? */
   4761 	static bool errorReported;
   4762 
   4763 	Buf_Init(&res);
   4764 	errorReported = false;
   4765 
   4766 	while (*p != '\0') {
   4767 		if (p[0] == '$' && p[1] == '$')
   4768 			VarSubstDollarDollar(&p, &res, emode);
   4769 		else if (p[0] == '$')
   4770 			VarSubstExpr(&p, &res, scope, emode, &errorReported);
   4771 		else
   4772 			VarSubstPlain(&p, &res);
   4773 	}
   4774 
   4775 	*out_res = Buf_DoneDataCompact(&res);
   4776 	return VPR_OK;
   4777 }
   4778 
   4779 /* Initialize the variables module. */
   4780 void
   4781 Var_Init(void)
   4782 {
   4783 	SCOPE_INTERNAL = GNode_New("Internal");
   4784 	SCOPE_GLOBAL = GNode_New("Global");
   4785 	SCOPE_CMDLINE = GNode_New("Command");
   4786 }
   4787 
   4788 /* Clean up the variables module. */
   4789 void
   4790 Var_End(void)
   4791 {
   4792 	Var_Stats();
   4793 }
   4794 
   4795 void
   4796 Var_Stats(void)
   4797 {
   4798 	HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables");
   4799 }
   4800 
   4801 static int
   4802 StrAsc(const void *sa, const void *sb)
   4803 {
   4804 	return strcmp(
   4805 	    *((const char *const *)sa), *((const char *const *)sb));
   4806 }
   4807 
   4808 
   4809 /* Print all variables in a scope, sorted by name. */
   4810 void
   4811 Var_Dump(GNode *scope)
   4812 {
   4813 	Vector /* of const char * */ vec;
   4814 	HashIter hi;
   4815 	size_t i;
   4816 	const char **varnames;
   4817 
   4818 	Vector_Init(&vec, sizeof(const char *));
   4819 
   4820 	HashIter_Init(&hi, &scope->vars);
   4821 	while (HashIter_Next(&hi) != NULL)
   4822 		*(const char **)Vector_Push(&vec) = hi.entry->key;
   4823 	varnames = vec.items;
   4824 
   4825 	qsort(varnames, vec.len, sizeof varnames[0], StrAsc);
   4826 
   4827 	for (i = 0; i < vec.len; i++) {
   4828 		const char *varname = varnames[i];
   4829 		Var *var = HashTable_FindValue(&scope->vars, varname);
   4830 		debug_printf("%-16s = %s\n", varname, var->val.data);
   4831 	}
   4832 
   4833 	Vector_Done(&vec);
   4834 }
   4835