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