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