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