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