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