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