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