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