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