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