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