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