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