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