Home | History | Annotate | Line # | Download | only in make
var.c revision 1.1128
      1 /*	$NetBSD: var.c,v 1.1128 2024/07/04 17:47:53 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Adam de Boor.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Copyright (c) 1989 by Berkeley Softworks
     37  * All rights reserved.
     38  *
     39  * This code is derived from software contributed to Berkeley by
     40  * Adam de Boor.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *	This product includes software developed by the University of
     53  *	California, Berkeley and its contributors.
     54  * 4. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  */
     70 
     71 /*
     72  * Handling of variables and the expressions formed from them.
     73  *
     74  * Variables are set using lines of the form VAR=value.  Both the variable
     75  * name and the value can contain references to other variables, by using
     76  * expressions like ${VAR}, ${VAR:Modifiers}, ${${VARNAME}} or ${VAR:${MODS}}.
     77  *
     78  * Interface:
     79  *	Var_Init	Initialize this module.
     80  *
     81  *	Var_End		Clean up the module.
     82  *
     83  *	Var_Set
     84  *	Var_SetExpand	Set the value of the variable, creating it if
     85  *			necessary.
     86  *
     87  *	Var_Append
     88  *	Var_AppendExpand
     89  *			Append more characters to the variable, creating it if
     90  *			necessary. A space is placed between the old value and
     91  *			the new one.
     92  *
     93  *	Var_Exists
     94  *	Var_ExistsExpand
     95  *			See if a variable exists.
     96  *
     97  *	Var_Value	Return the unexpanded value of a variable, or NULL if
     98  *			the variable is undefined.
     99  *
    100  *	Var_Subst	Substitute all expressions in a string.
    101  *
    102  *	Var_Parse	Parse an expression such as ${VAR:Mpattern}.
    103  *
    104  *	Var_Delete	Delete a variable.
    105  *
    106  *	Var_ReexportVars
    107  *			Export some or even all variables to the environment
    108  *			of this process and its child processes.
    109  *
    110  *	Var_Export	Export the variable to the environment of this process
    111  *			and its child processes.
    112  *
    113  *	Var_UnExport	Don't export the variable anymore.
    114  *
    115  * Debugging:
    116  *	Var_Stats	Print out hashing statistics if in -dh mode.
    117  *
    118  *	Var_Dump	Print out all variables defined in the given scope.
    119  */
    120 
    121 #include <sys/stat.h>
    122 #include <sys/types.h>
    123 #include <regex.h>
    124 #include <errno.h>
    125 #include <inttypes.h>
    126 #include <limits.h>
    127 #include <time.h>
    128 
    129 #include "make.h"
    130 #include "dir.h"
    131 #include "job.h"
    132 #include "metachar.h"
    133 
    134 /*	"@(#)var.c	8.3 (Berkeley) 3/19/94" */
    135 MAKE_RCSID("$NetBSD: var.c,v 1.1128 2024/07/04 17:47:53 rillig Exp $");
    136 
    137 /*
    138  * Variables are defined using one of the VAR=value assignments.  Their
    139  * value can be queried by expressions such as $V, ${VAR}, or with modifiers
    140  * such as ${VAR:S,from,to,g:Q}.
    141  *
    142  * There are 3 kinds of variables: scope variables, environment variables,
    143  * undefined variables.
    144  *
    145  * Scope variables are stored in GNode.vars.  The only way to undefine
    146  * a scope variable is using the .undef directive.  In particular, it must
    147  * not be possible to undefine a variable during the evaluation of an
    148  * expression, or Var.name might point nowhere.  (There is another,
    149  * unintended way to undefine a scope variable, see varmod-loop-delete.mk.)
    150  *
    151  * Environment variables are short-lived.  They are returned by VarFind, and
    152  * after using them, they must be freed using VarFreeShortLived.
    153  *
    154  * Undefined variables occur during evaluation of expressions such
    155  * as ${UNDEF:Ufallback} in Var_Parse and ApplyModifiers.
    156  */
    157 typedef struct Var {
    158 	/*
    159 	 * The name of the variable, once set, doesn't change anymore.
    160 	 * For scope variables, it aliases the corresponding HashEntry name.
    161 	 * For environment and undefined variables, it is allocated.
    162 	 */
    163 	FStr name;
    164 
    165 	/* The unexpanded value of the variable. */
    166 	Buffer val;
    167 
    168 	/* The variable came from the command line. */
    169 	bool fromCmd:1;
    170 
    171 	/*
    172 	 * The variable is short-lived.
    173 	 * These variables are not registered in any GNode, therefore they
    174 	 * must be freed after use.
    175 	 */
    176 	bool shortLived:1;
    177 
    178 	/*
    179 	 * The variable comes from the environment.
    180 	 * Appending to its value depends on the scope, see var-op-append.mk.
    181 	 */
    182 	bool fromEnvironment:1;
    183 
    184 	/*
    185 	 * The variable value cannot be changed anymore, and the variable
    186 	 * cannot be deleted.  Any attempts to do so are silently ignored,
    187 	 * they are logged with -dv though.
    188 	 * Use .[NO]READONLY: to adjust.
    189 	 *
    190 	 * See VAR_SET_READONLY.
    191 	 */
    192 	bool readOnly:1;
    193 
    194 	/*
    195 	 * The variable is read-only and immune to the .NOREADONLY special
    196 	 * target.  Any attempt to modify it results in an error.
    197 	 */
    198 	bool readOnlyLoud:1;
    199 
    200 	/*
    201 	 * The variable is currently being accessed by Var_Parse or Var_Subst.
    202 	 * This temporary marker is used to avoid endless recursion.
    203 	 */
    204 	bool inUse:1;
    205 
    206 	/*
    207 	 * The variable is exported to the environment, to be used by child
    208 	 * processes.
    209 	 */
    210 	bool exported:1;
    211 
    212 	/*
    213 	 * At the point where this variable was exported, it contained an
    214 	 * unresolved reference to another variable.  Before any child
    215 	 * process is started, it needs to be actually exported, resolving
    216 	 * the referenced variable just in time.
    217 	 */
    218 	bool reexport:1;
    219 } Var;
    220 
    221 /*
    222  * Exporting variables is expensive and may leak memory, so skip it if we
    223  * can.
    224  */
    225 typedef enum VarExportedMode {
    226 	VAR_EXPORTED_NONE,
    227 	VAR_EXPORTED_SOME,
    228 	VAR_EXPORTED_ALL
    229 } VarExportedMode;
    230 
    231 typedef enum UnexportWhat {
    232 	/* Unexport the variables given by name. */
    233 	UNEXPORT_NAMED,
    234 	/*
    235 	 * Unexport all globals previously exported, but keep the environment
    236 	 * inherited from the parent.
    237 	 */
    238 	UNEXPORT_ALL,
    239 	/*
    240 	 * Unexport all globals previously exported and clear the environment
    241 	 * inherited from the parent.
    242 	 */
    243 	UNEXPORT_ENV
    244 } UnexportWhat;
    245 
    246 /* Flags for pattern matching in the :S and :C modifiers */
    247 typedef struct PatternFlags {
    248 	bool subGlobal:1;	/* 'g': replace as often as possible */
    249 	bool subOnce:1;		/* '1': replace only once */
    250 	bool anchorStart:1;	/* '^': match only at start of word */
    251 	bool anchorEnd:1;	/* '$': match only at end of word */
    252 } PatternFlags;
    253 
    254 /* SepBuf builds a string from words interleaved with separators. */
    255 typedef struct SepBuf {
    256 	Buffer buf;
    257 	bool needSep;
    258 	/* Usually ' ', but see the ':ts' modifier. */
    259 	char sep;
    260 } SepBuf;
    261 
    262 typedef enum {
    263 	VSK_TARGET,
    264 	VSK_VARNAME,
    265 	VSK_COND,
    266 	VSK_COND_THEN,
    267 	VSK_COND_ELSE,
    268 	VSK_EXPR
    269 } EvalStackElementKind;
    270 
    271 typedef struct {
    272 	EvalStackElementKind kind;
    273 	const char *str;
    274 	const FStr *value;
    275 } EvalStackElement;
    276 
    277 typedef struct {
    278 	EvalStackElement *elems;
    279 	size_t len;
    280 	size_t cap;
    281 	Buffer details;
    282 } EvalStack;
    283 
    284 /* Whether we have replaced the original environ (which we cannot free). */
    285 char **savedEnv = NULL;
    286 
    287 /*
    288  * Special return value for Var_Parse, indicating a parse error.  It may be
    289  * caused by an undefined variable, a syntax error in a modifier or
    290  * something entirely different.
    291  */
    292 char var_Error[] = "";
    293 
    294 /*
    295  * Special return value for Var_Parse, indicating an undefined variable in
    296  * a case where VARE_EVAL_DEFINED is not set.  This undefined variable is
    297  * typically a dynamic variable such as ${.TARGET}, whose expansion needs to
    298  * be deferred until it is defined in an actual target.
    299  *
    300  * See VARE_EVAL_KEEP_UNDEFINED.
    301  */
    302 static char varUndefined[] = "";
    303 
    304 /*
    305  * Traditionally this make consumed $$ during := like any other expansion.
    306  * Other make's do not, and this make follows straight since 2016-01-09.
    307  *
    308  * This knob allows controlling the behavior:
    309  *	false to consume $$ during := assignment.
    310  *	true to preserve $$ during := assignment.
    311  */
    312 #define MAKE_SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
    313 static bool save_dollars = true;
    314 
    315 /*
    316  * A scope collects variable names and their values.
    317  *
    318  * The main scope is SCOPE_GLOBAL, which contains the variables that are set
    319  * in the makefiles.  SCOPE_INTERNAL acts as a fallback for SCOPE_GLOBAL and
    320  * contains some internal make variables.  These internal variables can thus
    321  * be overridden, they can also be restored by undefining the overriding
    322  * variable.
    323  *
    324  * SCOPE_CMDLINE contains variables from the command line arguments.  These
    325  * override variables from SCOPE_GLOBAL.
    326  *
    327  * There is no scope for environment variables, these are generated on-the-fly
    328  * whenever they are referenced.
    329  *
    330  * Each target has its own scope, containing the 7 target-local variables
    331  * .TARGET, .ALLSRC, etc.  Variables set on dependency lines also go in
    332  * this scope.
    333  */
    334 
    335 GNode *SCOPE_CMDLINE;
    336 GNode *SCOPE_GLOBAL;
    337 GNode *SCOPE_INTERNAL;
    338 
    339 static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE;
    340 
    341 static const char VarEvalMode_Name[][32] = {
    342 	"parse",
    343 	"parse-balanced",
    344 	"eval",
    345 	"eval-defined",
    346 	"eval-keep-undefined",
    347 	"eval-keep-dollar-and-undefined",
    348 };
    349 
    350 static EvalStack evalStack;
    351 
    352 
    353 static void
    354 EvalStack_Push(EvalStackElementKind kind, const char *str, const FStr *value)
    355 {
    356 	if (evalStack.len >= evalStack.cap) {
    357 		evalStack.cap = 16 + 2 * evalStack.cap;
    358 		evalStack.elems = bmake_realloc(evalStack.elems,
    359 		    evalStack.cap * sizeof(*evalStack.elems));
    360 	}
    361 	evalStack.elems[evalStack.len].kind = kind;
    362 	evalStack.elems[evalStack.len].str = str;
    363 	evalStack.elems[evalStack.len].value = value;
    364 	evalStack.len++;
    365 }
    366 
    367 static void
    368 EvalStack_Pop(void)
    369 {
    370 	assert(evalStack.len > 0);
    371 	evalStack.len--;
    372 }
    373 
    374 const char *
    375 EvalStack_Details(void)
    376 {
    377 	size_t i;
    378 	Buffer *buf = &evalStack.details;
    379 
    380 
    381 	buf->len = 0;
    382 	for (i = 0; i < evalStack.len; i++) {
    383 		static const char descr[][42] = {
    384 			"in target",
    385 			"while evaluating variable",
    386 			"while evaluating condition",
    387 			"while evaluating then-branch of condition",
    388 			"while evaluating else-branch of condition",
    389 			"while evaluating",
    390 		};
    391 		EvalStackElement *elem = evalStack.elems + i;
    392 		Buf_AddStr(buf, descr[elem->kind]);
    393 		Buf_AddStr(buf, " \"");
    394 		Buf_AddStr(buf, elem->str);
    395 		if (elem->kind == VSK_VARNAME) {
    396 			Buf_AddStr(buf, "\" with value \"");
    397 			Buf_AddStr(buf, elem->value->str);
    398 		}
    399 		Buf_AddStr(buf, "\": ");
    400 	}
    401 	return buf->len > 0 ? buf->data : "";
    402 }
    403 
    404 static Var *
    405 VarNew(FStr name, const char *value,
    406        bool shortLived, bool fromEnvironment, bool readOnly)
    407 {
    408 	size_t value_len = strlen(value);
    409 	Var *var = bmake_malloc(sizeof *var);
    410 	var->name = name;
    411 	Buf_InitSize(&var->val, value_len + 1);
    412 	Buf_AddBytes(&var->val, value, value_len);
    413 	var->fromCmd = false;
    414 	var->shortLived = shortLived;
    415 	var->fromEnvironment = fromEnvironment;
    416 	var->readOnly = readOnly;
    417 	var->readOnlyLoud = false;
    418 	var->inUse = false;
    419 	var->exported = false;
    420 	var->reexport = false;
    421 	return var;
    422 }
    423 
    424 static Substring
    425 CanonicalVarname(Substring name)
    426 {
    427 
    428 	if (!(Substring_Length(name) > 0 && name.start[0] == '.'))
    429 		return name;
    430 
    431 	if (Substring_Equals(name, ".ALLSRC"))
    432 		return Substring_InitStr(ALLSRC);
    433 	if (Substring_Equals(name, ".ARCHIVE"))
    434 		return Substring_InitStr(ARCHIVE);
    435 	if (Substring_Equals(name, ".IMPSRC"))
    436 		return Substring_InitStr(IMPSRC);
    437 	if (Substring_Equals(name, ".MEMBER"))
    438 		return Substring_InitStr(MEMBER);
    439 	if (Substring_Equals(name, ".OODATE"))
    440 		return Substring_InitStr(OODATE);
    441 	if (Substring_Equals(name, ".PREFIX"))
    442 		return Substring_InitStr(PREFIX);
    443 	if (Substring_Equals(name, ".TARGET"))
    444 		return Substring_InitStr(TARGET);
    445 
    446 	/* GNU make has an additional alias $^ == ${.ALLSRC}. */
    447 
    448 	if (Substring_Equals(name, ".SHELL") && shellPath == NULL)
    449 		Shell_Init();
    450 
    451 	return name;
    452 }
    453 
    454 static Var *
    455 GNode_FindVar(GNode *scope, Substring varname, unsigned int hash)
    456 {
    457 	return HashTable_FindValueBySubstringHash(&scope->vars, varname, hash);
    458 }
    459 
    460 /*
    461  * Find the variable in the scope, and maybe in other scopes as well.
    462  *
    463  * Input:
    464  *	name		name to find, is not expanded any further
    465  *	scope		scope in which to look first
    466  *	elsewhere	true to look in other scopes as well
    467  *
    468  * Results:
    469  *	The found variable, or NULL if the variable does not exist.
    470  *	If the variable is short-lived (such as environment variables), it
    471  *	must be freed using VarFreeShortLived after use.
    472  */
    473 static Var *
    474 VarFindSubstring(Substring name, GNode *scope, bool elsewhere)
    475 {
    476 	Var *var;
    477 	unsigned int nameHash;
    478 
    479 	/* Replace '.TARGET' with '@', likewise for other local variables. */
    480 	name = CanonicalVarname(name);
    481 	nameHash = Hash_Substring(name);
    482 
    483 	var = GNode_FindVar(scope, name, nameHash);
    484 	if (!elsewhere)
    485 		return var;
    486 
    487 	if (var == NULL && scope != SCOPE_CMDLINE)
    488 		var = GNode_FindVar(SCOPE_CMDLINE, name, nameHash);
    489 
    490 	if (!opts.checkEnvFirst && var == NULL && scope != SCOPE_GLOBAL) {
    491 		var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
    492 		if (var == NULL && scope != SCOPE_INTERNAL) {
    493 			/* SCOPE_INTERNAL is subordinate to SCOPE_GLOBAL */
    494 			var = GNode_FindVar(SCOPE_INTERNAL, name, nameHash);
    495 		}
    496 	}
    497 
    498 	if (var == NULL) {
    499 		FStr envName = Substring_Str(name);
    500 		const char *envValue = getenv(envName.str);
    501 		if (envValue != NULL)
    502 			return VarNew(envName, envValue, true, true, false);
    503 		FStr_Done(&envName);
    504 
    505 		if (opts.checkEnvFirst && scope != SCOPE_GLOBAL) {
    506 			var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
    507 			if (var == NULL && scope != SCOPE_INTERNAL)
    508 				var = GNode_FindVar(SCOPE_INTERNAL, name,
    509 				    nameHash);
    510 			return var;
    511 		}
    512 
    513 		return NULL;
    514 	}
    515 
    516 	return var;
    517 }
    518 
    519 static Var *
    520 VarFind(const char *name, GNode *scope, bool elsewhere)
    521 {
    522 	return VarFindSubstring(Substring_InitStr(name), scope, elsewhere);
    523 }
    524 
    525 /* If the variable is short-lived, free it, including its value. */
    526 static void
    527 VarFreeShortLived(Var *v)
    528 {
    529 	if (!v->shortLived)
    530 		return;
    531 
    532 	FStr_Done(&v->name);
    533 	Buf_Done(&v->val);
    534 	free(v);
    535 }
    536 
    537 static const char *
    538 ValueDescription(const char *value)
    539 {
    540 	if (value[0] == '\0')
    541 		return "# (empty)";
    542 	if (ch_isspace(value[strlen(value) - 1]))
    543 		return "# (ends with space)";
    544 	return "";
    545 }
    546 
    547 /* Add a new variable of the given name and value to the given scope. */
    548 static Var *
    549 VarAdd(const char *name, const char *value, GNode *scope, VarSetFlags flags)
    550 {
    551 	HashEntry *he = HashTable_CreateEntry(&scope->vars, name, NULL);
    552 	Var *v = VarNew(FStr_InitRefer(/* aliased to */ he->key), value,
    553 	    false, false, (flags & VAR_SET_READONLY) != 0);
    554 	HashEntry_Set(he, v);
    555 	DEBUG4(VAR, "%s: %s = %s%s\n",
    556 	    scope->name, name, value, ValueDescription(value));
    557 	return v;
    558 }
    559 
    560 /*
    561  * Remove a variable from a scope, freeing all related memory as well.
    562  * The variable name is kept as-is, it is not expanded.
    563  */
    564 void
    565 Var_Delete(GNode *scope, const char *varname)
    566 {
    567 	HashEntry *he = HashTable_FindEntry(&scope->vars, varname);
    568 	Var *v;
    569 
    570 	if (he == NULL) {
    571 		DEBUG2(VAR, "%s: ignoring delete '%s' as it is not found\n",
    572 		    scope->name, varname);
    573 		return;
    574 	}
    575 
    576 	v = he->value;
    577 	if (v->readOnlyLoud) {
    578 		Parse_Error(PARSE_FATAL,
    579 		    "Cannot delete \"%s\" as it is read-only",
    580 		    v->name.str);
    581 		return;
    582 	}
    583 	if (v->readOnly) {
    584 		DEBUG2(VAR, "%s: ignoring delete '%s' as it is read-only\n",
    585 		    scope->name, varname);
    586 		return;
    587 	}
    588 	if (v->inUse) {
    589 		Parse_Error(PARSE_FATAL,
    590 		    "Cannot delete variable \"%s\" while it is used",
    591 		    v->name.str);
    592 		return;
    593 	}
    594 
    595 	DEBUG2(VAR, "%s: delete %s\n", scope->name, varname);
    596 	if (v->exported)
    597 		unsetenv(v->name.str);
    598 	if (strcmp(v->name.str, ".MAKE.EXPORTED") == 0)
    599 		var_exportedVars = VAR_EXPORTED_NONE;
    600 
    601 	assert(v->name.freeIt == NULL);
    602 	HashTable_DeleteEntry(&scope->vars, he);
    603 	Buf_Done(&v->val);
    604 	free(v);
    605 }
    606 
    607 #ifdef CLEANUP
    608 void
    609 Var_DeleteAll(GNode *scope)
    610 {
    611 	HashIter hi;
    612 	HashIter_Init(&hi, &scope->vars);
    613 	while (HashIter_Next(&hi)) {
    614 		Var *v = hi.entry->value;
    615 		Buf_Done(&v->val);
    616 		free(v);
    617 	}
    618 }
    619 #endif
    620 
    621 /*
    622  * Undefine one or more variables from the global scope.
    623  * The argument is expanded exactly once and then split into words.
    624  */
    625 void
    626 Var_Undef(const char *arg)
    627 {
    628 	char *expanded;
    629 	Words varnames;
    630 	size_t i;
    631 
    632 	if (arg[0] == '\0') {
    633 		Parse_Error(PARSE_FATAL,
    634 		    "The .undef directive requires an argument");
    635 		return;
    636 	}
    637 
    638 	expanded = Var_Subst(arg, SCOPE_GLOBAL, VARE_EVAL);
    639 	if (expanded == var_Error) {
    640 		/* TODO: Make this part of the code reachable. */
    641 		Parse_Error(PARSE_FATAL,
    642 		    "Error in variable names to be undefined");
    643 		return;
    644 	}
    645 
    646 	varnames = Str_Words(expanded, false);
    647 	if (varnames.len == 1 && varnames.words[0][0] == '\0')
    648 		varnames.len = 0;
    649 
    650 	for (i = 0; i < varnames.len; i++) {
    651 		const char *varname = varnames.words[i];
    652 		Global_Delete(varname);
    653 	}
    654 
    655 	Words_Free(varnames);
    656 	free(expanded);
    657 }
    658 
    659 static bool
    660 MayExport(const char *name)
    661 {
    662 	if (name[0] == '.')
    663 		return false;	/* skip internals */
    664 	if (name[0] == '-')
    665 		return false;	/* skip misnamed variables */
    666 	if (name[1] == '\0') {
    667 		/*
    668 		 * A single char.
    669 		 * If it is one of the variables that should only appear in
    670 		 * local scope, skip it, else we can get Var_Subst
    671 		 * into a loop.
    672 		 */
    673 		switch (name[0]) {
    674 		case '@':
    675 		case '%':
    676 		case '*':
    677 		case '!':
    678 			return false;
    679 		}
    680 	}
    681 	return true;
    682 }
    683 
    684 static bool
    685 ExportVarEnv(Var *v, GNode *scope)
    686 {
    687 	const char *name = v->name.str;
    688 	char *val = v->val.data;
    689 	char *expr;
    690 
    691 	if (v->exported && !v->reexport)
    692 		return false;	/* nothing to do */
    693 
    694 	if (strchr(val, '$') == NULL) {
    695 		if (!v->exported)
    696 			setenv(name, val, 1);
    697 		return true;
    698 	}
    699 
    700 	if (v->inUse)
    701 		return false;	/* see EMPTY_SHELL in directive-export.mk */
    702 
    703 	/* XXX: name is injected without escaping it */
    704 	expr = str_concat3("${", name, "}");
    705 	val = Var_Subst(expr, scope, VARE_EVAL);
    706 	if (scope != SCOPE_GLOBAL) {
    707 		/* we will need to re-export the global version */
    708 		v = VarFind(name, SCOPE_GLOBAL, false);
    709 		if (v != NULL)
    710 			v->exported = false;
    711 	}
    712 	/* TODO: handle errors */
    713 	setenv(name, val, 1);
    714 	free(val);
    715 	free(expr);
    716 	return true;
    717 }
    718 
    719 static bool
    720 ExportVarPlain(Var *v)
    721 {
    722 	if (strchr(v->val.data, '$') == NULL) {
    723 		setenv(v->name.str, v->val.data, 1);
    724 		v->exported = true;
    725 		v->reexport = false;
    726 		return true;
    727 	}
    728 
    729 	/*
    730 	 * Flag the variable as something we need to re-export.
    731 	 * No point actually exporting it now though,
    732 	 * the child process can do it at the last minute.
    733 	 * Avoid calling setenv more often than necessary since it can leak.
    734 	 */
    735 	v->exported = true;
    736 	v->reexport = true;
    737 	return true;
    738 }
    739 
    740 static bool
    741 ExportVarLiteral(Var *v)
    742 {
    743 	if (v->exported && !v->reexport)
    744 		return false;
    745 
    746 	if (!v->exported)
    747 		setenv(v->name.str, v->val.data, 1);
    748 
    749 	return true;
    750 }
    751 
    752 /*
    753  * Mark a single variable to be exported later for subprocesses.
    754  *
    755  * Internal variables are not exported.
    756  */
    757 static bool
    758 ExportVar(const char *name, GNode *scope, VarExportMode mode)
    759 {
    760 	Var *v;
    761 
    762 	if (!MayExport(name))
    763 		return false;
    764 
    765 	v = VarFind(name, scope, false);
    766 	if (v == NULL && scope != SCOPE_GLOBAL)
    767 		v = VarFind(name, SCOPE_GLOBAL, false);
    768 	if (v == NULL)
    769 		return false;
    770 
    771 	if (mode == VEM_ENV)
    772 		return ExportVarEnv(v, scope);
    773 	else if (mode == VEM_PLAIN)
    774 		return ExportVarPlain(v);
    775 	else
    776 		return ExportVarLiteral(v);
    777 }
    778 
    779 /*
    780  * Actually export the variables that have been marked as needing to be
    781  * re-exported.
    782  */
    783 void
    784 Var_ReexportVars(GNode *scope)
    785 {
    786 	char *xvarnames;
    787 
    788 	/*
    789 	 * Several make implementations support this sort of mechanism for
    790 	 * tracking recursion - but each uses a different name.
    791 	 * We allow the makefiles to update MAKELEVEL and ensure
    792 	 * children see a correctly incremented value.
    793 	 */
    794 	char level_buf[21];
    795 	snprintf(level_buf, sizeof level_buf, "%d", makelevel + 1);
    796 	setenv(MAKE_LEVEL_ENV, level_buf, 1);
    797 
    798 	if (var_exportedVars == VAR_EXPORTED_NONE)
    799 		return;
    800 
    801 	if (var_exportedVars == VAR_EXPORTED_ALL) {
    802 		HashIter hi;
    803 
    804 		/* Ouch! Exporting all variables at once is crazy. */
    805 		HashIter_Init(&hi, &SCOPE_GLOBAL->vars);
    806 		while (HashIter_Next(&hi)) {
    807 			Var *var = hi.entry->value;
    808 			ExportVar(var->name.str, scope, VEM_ENV);
    809 		}
    810 		return;
    811 	}
    812 
    813 	xvarnames = Var_Subst("${.MAKE.EXPORTED:O:u}", SCOPE_GLOBAL,
    814 	    VARE_EVAL);
    815 	/* TODO: handle errors */
    816 	if (xvarnames[0] != '\0') {
    817 		Words varnames = Str_Words(xvarnames, false);
    818 		size_t i;
    819 
    820 		for (i = 0; i < varnames.len; i++)
    821 			ExportVar(varnames.words[i], scope, VEM_ENV);
    822 		Words_Free(varnames);
    823 	}
    824 	free(xvarnames);
    825 }
    826 
    827 static void
    828 ExportVars(const char *varnames, bool isExport, VarExportMode mode)
    829 /* TODO: try to combine the parameters 'isExport' and 'mode'. */
    830 {
    831 	Words words = Str_Words(varnames, false);
    832 	size_t i;
    833 
    834 	if (words.len == 1 && words.words[0][0] == '\0')
    835 		words.len = 0;
    836 
    837 	for (i = 0; i < words.len; i++) {
    838 		const char *varname = words.words[i];
    839 		if (!ExportVar(varname, SCOPE_GLOBAL, mode))
    840 			continue;
    841 
    842 		if (var_exportedVars == VAR_EXPORTED_NONE)
    843 			var_exportedVars = VAR_EXPORTED_SOME;
    844 
    845 		if (isExport && mode == VEM_PLAIN)
    846 			Global_Append(".MAKE.EXPORTED", varname);
    847 	}
    848 	Words_Free(words);
    849 }
    850 
    851 static void
    852 ExportVarsExpand(const char *uvarnames, bool isExport, VarExportMode mode)
    853 {
    854 	char *xvarnames = Var_Subst(uvarnames, SCOPE_GLOBAL, VARE_EVAL);
    855 	/* TODO: handle errors */
    856 	ExportVars(xvarnames, isExport, mode);
    857 	free(xvarnames);
    858 }
    859 
    860 /* Export the named variables, or all variables. */
    861 void
    862 Var_Export(VarExportMode mode, const char *varnames)
    863 {
    864 	if (mode == VEM_ALL) {
    865 		var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
    866 		return;
    867 	} else if (mode == VEM_PLAIN && varnames[0] == '\0') {
    868 		Parse_Error(PARSE_WARNING, ".export requires an argument.");
    869 		return;
    870 	}
    871 
    872 	ExportVarsExpand(varnames, true, mode);
    873 }
    874 
    875 void
    876 Var_ExportVars(const char *varnames)
    877 {
    878 	ExportVarsExpand(varnames, false, VEM_PLAIN);
    879 }
    880 
    881 
    882 static void
    883 ClearEnv(void)
    884 {
    885 	const char *level;
    886 	char **newenv;
    887 
    888 	level = getenv(MAKE_LEVEL_ENV);	/* we should preserve this */
    889 	if (environ == savedEnv) {
    890 		/* we have been here before! */
    891 		newenv = bmake_realloc(environ, 2 * sizeof(char *));
    892 	} else {
    893 		if (savedEnv != NULL) {
    894 			free(savedEnv);
    895 			savedEnv = NULL;
    896 		}
    897 		newenv = bmake_malloc(2 * sizeof(char *));
    898 	}
    899 
    900 	/* Note: we cannot safely free() the original environ. */
    901 	environ = savedEnv = newenv;
    902 	newenv[0] = NULL;
    903 	newenv[1] = NULL;
    904 	if (level != NULL && *level != '\0')
    905 		setenv(MAKE_LEVEL_ENV, level, 1);
    906 }
    907 
    908 static void
    909 GetVarnamesToUnexport(bool isEnv, const char *arg,
    910 		      FStr *out_varnames, UnexportWhat *out_what)
    911 {
    912 	UnexportWhat what;
    913 	FStr varnames = FStr_InitRefer("");
    914 
    915 	if (isEnv) {
    916 		if (arg[0] != '\0') {
    917 			Parse_Error(PARSE_FATAL,
    918 			    "The directive .unexport-env does not take "
    919 			    "arguments");
    920 			/* continue anyway */
    921 		}
    922 		what = UNEXPORT_ENV;
    923 
    924 	} else {
    925 		what = arg[0] != '\0' ? UNEXPORT_NAMED : UNEXPORT_ALL;
    926 		if (what == UNEXPORT_NAMED)
    927 			varnames = FStr_InitRefer(arg);
    928 	}
    929 
    930 	if (what != UNEXPORT_NAMED) {
    931 		char *expanded = Var_Subst("${.MAKE.EXPORTED:O:u}",
    932 		    SCOPE_GLOBAL, VARE_EVAL);
    933 		/* TODO: handle errors */
    934 		varnames = FStr_InitOwn(expanded);
    935 	}
    936 
    937 	*out_varnames = varnames;
    938 	*out_what = what;
    939 }
    940 
    941 static void
    942 UnexportVar(Substring varname, UnexportWhat what)
    943 {
    944 	Var *v = VarFindSubstring(varname, SCOPE_GLOBAL, false);
    945 	if (v == NULL) {
    946 		DEBUG2(VAR, "Not unexporting \"%.*s\" (not found)\n",
    947 		    (int)Substring_Length(varname), varname.start);
    948 		return;
    949 	}
    950 
    951 	DEBUG2(VAR, "Unexporting \"%.*s\"\n",
    952 	    (int)Substring_Length(varname), varname.start);
    953 	if (what != UNEXPORT_ENV && v->exported && !v->reexport)
    954 		unsetenv(v->name.str);
    955 	v->exported = false;
    956 	v->reexport = false;
    957 
    958 	if (what == UNEXPORT_NAMED) {
    959 		/* Remove the variable names from .MAKE.EXPORTED. */
    960 		/* XXX: v->name is injected without escaping it */
    961 		char *expr = str_concat3(
    962 		    "${.MAKE.EXPORTED:N", v->name.str, "}");
    963 		char *filtered = Var_Subst(expr, SCOPE_GLOBAL, VARE_EVAL);
    964 		/* TODO: handle errors */
    965 		Global_Set(".MAKE.EXPORTED", filtered);
    966 		free(filtered);
    967 		free(expr);
    968 	}
    969 }
    970 
    971 static void
    972 UnexportVars(FStr *varnames, UnexportWhat what)
    973 {
    974 	size_t i;
    975 	SubstringWords words;
    976 
    977 	if (what == UNEXPORT_ENV)
    978 		ClearEnv();
    979 
    980 	words = Substring_Words(varnames->str, false);
    981 	for (i = 0; i < words.len; i++)
    982 		UnexportVar(words.words[i], what);
    983 	SubstringWords_Free(words);
    984 
    985 	if (what != UNEXPORT_NAMED)
    986 		Global_Delete(".MAKE.EXPORTED");
    987 }
    988 
    989 /* Handle the .unexport and .unexport-env directives. */
    990 void
    991 Var_UnExport(bool isEnv, const char *arg)
    992 {
    993 	UnexportWhat what;
    994 	FStr varnames;
    995 
    996 	GetVarnamesToUnexport(isEnv, arg, &varnames, &what);
    997 	UnexportVars(&varnames, what);
    998 	FStr_Done(&varnames);
    999 }
   1000 
   1001 /* Set the variable to the value; the name is not expanded. */
   1002 void
   1003 Var_SetWithFlags(GNode *scope, const char *name, const char *val,
   1004 		 VarSetFlags flags)
   1005 {
   1006 	Var *v;
   1007 
   1008 	assert(val != NULL);
   1009 	if (name[0] == '\0') {
   1010 		DEBUG3(VAR,
   1011 		    "%s: ignoring '%s = %s' as the variable name is empty\n",
   1012 		    scope->name, name, val);
   1013 		return;
   1014 	}
   1015 
   1016 	if (scope == SCOPE_GLOBAL
   1017 	    && VarFind(name, SCOPE_CMDLINE, false) != NULL) {
   1018 		/*
   1019 		 * The global variable would not be visible anywhere.
   1020 		 * Therefore, there is no point in setting it at all.
   1021 		 */
   1022 		DEBUG3(VAR,
   1023 		    "%s: ignoring '%s = %s' "
   1024 		    "due to a command line variable of the same name\n",
   1025 		    scope->name, name, val);
   1026 		return;
   1027 	}
   1028 
   1029 	/*
   1030 	 * Only look for a variable in the given scope since anything set
   1031 	 * here will override anything in a lower scope, so there's not much
   1032 	 * point in searching them all.
   1033 	 */
   1034 	v = VarFind(name, scope, false);
   1035 	if (v == NULL) {
   1036 		if (scope == SCOPE_CMDLINE && !(flags & VAR_SET_NO_EXPORT)) {
   1037 			/*
   1038 			 * This variable would normally prevent the same name
   1039 			 * being added to SCOPE_GLOBAL, so delete it from
   1040 			 * there if needed. Otherwise -V name may show the
   1041 			 * wrong value.
   1042 			 *
   1043 			 * See ExistsInCmdline.
   1044 			 */
   1045 			Var_Delete(SCOPE_GLOBAL, name);
   1046 		}
   1047 		if (strcmp(name, ".SUFFIXES") == 0) {
   1048 			/* special: treat as read-only */
   1049 			DEBUG3(VAR,
   1050 			    "%s: ignoring '%s = %s' as it is read-only\n",
   1051 			    scope->name, name, val);
   1052 			return;
   1053 		}
   1054 		v = VarAdd(name, val, scope, flags);
   1055 	} else {
   1056 		if (v->readOnlyLoud) {
   1057 			Parse_Error(PARSE_FATAL,
   1058 			    "Cannot overwrite \"%s\" as it is read-only",
   1059 			    name);
   1060 			return;
   1061 		}
   1062 		if (v->readOnly && !(flags & VAR_SET_READONLY)) {
   1063 			DEBUG3(VAR,
   1064 			    "%s: ignoring '%s = %s' as it is read-only\n",
   1065 			    scope->name, name, val);
   1066 			return;
   1067 		}
   1068 		Buf_Clear(&v->val);
   1069 		Buf_AddStr(&v->val, val);
   1070 
   1071 		DEBUG4(VAR, "%s: %s = %s%s\n",
   1072 		    scope->name, name, val, ValueDescription(val));
   1073 		if (v->exported)
   1074 			ExportVar(name, scope, VEM_PLAIN);
   1075 	}
   1076 
   1077 	if (scope == SCOPE_CMDLINE) {
   1078 		v->fromCmd = true;
   1079 
   1080 		/*
   1081 		 * Any variables given on the command line are automatically
   1082 		 * exported to the environment (as per POSIX standard), except
   1083 		 * for internals.
   1084 		 */
   1085 		if (!(flags & VAR_SET_NO_EXPORT)) {
   1086 
   1087 			/*
   1088 			 * If requested, don't export these in the
   1089 			 * environment individually.  We still put
   1090 			 * them in .MAKEOVERRIDES so that the
   1091 			 * command-line settings continue to override
   1092 			 * Makefile settings.
   1093 			 */
   1094 			if (!opts.varNoExportEnv && name[0] != '.')
   1095 				setenv(name, val, 1);
   1096 
   1097 			if (!(flags & VAR_SET_INTERNAL))
   1098 				Global_Append(".MAKEOVERRIDES", name);
   1099 		}
   1100 	}
   1101 
   1102 	if (name[0] == '.' && strcmp(name, MAKE_SAVE_DOLLARS) == 0)
   1103 		save_dollars = ParseBoolean(val, save_dollars);
   1104 
   1105 	if (v != NULL)
   1106 		VarFreeShortLived(v);
   1107 }
   1108 
   1109 void
   1110 Var_Set(GNode *scope, const char *name, const char *val)
   1111 {
   1112 	Var_SetWithFlags(scope, name, val, VAR_SET_NONE);
   1113 }
   1114 
   1115 /*
   1116  * In the scope, expand the variable name once, then create the variable or
   1117  * replace its value.
   1118  */
   1119 void
   1120 Var_SetExpand(GNode *scope, const char *name, const char *val)
   1121 {
   1122 	FStr varname = FStr_InitRefer(name);
   1123 
   1124 	assert(val != NULL);
   1125 
   1126 	Var_Expand(&varname, scope, VARE_EVAL);
   1127 
   1128 	if (varname.str[0] == '\0') {
   1129 		DEBUG4(VAR,
   1130 		    "%s: ignoring '%s = %s' "
   1131 		    "as the variable name '%s' expands to empty\n",
   1132 		    scope->name, varname.str, val, name);
   1133 	} else
   1134 		Var_SetWithFlags(scope, varname.str, val, VAR_SET_NONE);
   1135 
   1136 	FStr_Done(&varname);
   1137 }
   1138 
   1139 void
   1140 Global_Set(const char *name, const char *value)
   1141 {
   1142 	Var_Set(SCOPE_GLOBAL, name, value);
   1143 }
   1144 
   1145 void
   1146 Global_Delete(const char *name)
   1147 {
   1148 	Var_Delete(SCOPE_GLOBAL, name);
   1149 }
   1150 
   1151 void
   1152 Global_Set_ReadOnly(const char *name, const char *value)
   1153 {
   1154 	Var_SetWithFlags(SCOPE_GLOBAL, name, value, VAR_SET_NONE);
   1155 	VarFind(name, SCOPE_GLOBAL, false)->readOnlyLoud = true;
   1156 }
   1157 
   1158 /*
   1159  * Append the value to the named variable.
   1160  *
   1161  * If the variable doesn't exist, it is created.  Otherwise a single space
   1162  * and the given value are appended.
   1163  */
   1164 void
   1165 Var_Append(GNode *scope, const char *name, const char *val)
   1166 {
   1167 	Var *v;
   1168 
   1169 	v = VarFind(name, scope, scope == SCOPE_GLOBAL);
   1170 
   1171 	if (v == NULL) {
   1172 		Var_SetWithFlags(scope, name, val, VAR_SET_NONE);
   1173 	} else if (v->readOnlyLoud) {
   1174 		Parse_Error(PARSE_FATAL,
   1175 		    "Cannot append to \"%s\" as it is read-only", name);
   1176 		return;
   1177 	} else if (v->readOnly) {
   1178 		DEBUG3(VAR, "%s: ignoring '%s += %s' as it is read-only\n",
   1179 		    scope->name, name, val);
   1180 	} else if (scope == SCOPE_CMDLINE || !v->fromCmd) {
   1181 		Buf_AddByte(&v->val, ' ');
   1182 		Buf_AddStr(&v->val, val);
   1183 
   1184 		DEBUG3(VAR, "%s: %s = %s\n", scope->name, name, v->val.data);
   1185 
   1186 		if (v->fromEnvironment) {
   1187 			/* See VarAdd. */
   1188 			HashEntry *he =
   1189 			    HashTable_CreateEntry(&scope->vars, name, NULL);
   1190 			HashEntry_Set(he, v);
   1191 			FStr_Done(&v->name);
   1192 			v->name = FStr_InitRefer(/* aliased to */ he->key);
   1193 			v->shortLived = false;
   1194 			v->fromEnvironment = false;
   1195 		}
   1196 	}
   1197 }
   1198 
   1199 /*
   1200  * In the scope, expand the variable name once.  If the variable exists in the
   1201  * scope, add a space and the value, otherwise set the variable to the value.
   1202  *
   1203  * Appending to an environment variable only works in the global scope, that
   1204  * is, for variable assignments in makefiles, but not inside conditions or the
   1205  * commands of a target.
   1206  */
   1207 void
   1208 Var_AppendExpand(GNode *scope, const char *name, const char *val)
   1209 {
   1210 	FStr xname = FStr_InitRefer(name);
   1211 
   1212 	assert(val != NULL);
   1213 
   1214 	Var_Expand(&xname, scope, VARE_EVAL);
   1215 	if (xname.str != name && xname.str[0] == '\0')
   1216 		DEBUG4(VAR,
   1217 		    "%s: ignoring '%s += %s' "
   1218 		    "as the variable name '%s' expands to empty\n",
   1219 		    scope->name, xname.str, val, name);
   1220 	else
   1221 		Var_Append(scope, xname.str, val);
   1222 
   1223 	FStr_Done(&xname);
   1224 }
   1225 
   1226 void
   1227 Global_Append(const char *name, const char *value)
   1228 {
   1229 	Var_Append(SCOPE_GLOBAL, name, value);
   1230 }
   1231 
   1232 bool
   1233 Var_Exists(GNode *scope, const char *name)
   1234 {
   1235 	Var *v = VarFind(name, scope, true);
   1236 	if (v == NULL)
   1237 		return false;
   1238 
   1239 	VarFreeShortLived(v);
   1240 	return true;
   1241 }
   1242 
   1243 /*
   1244  * See if the given variable exists, in the given scope or in other
   1245  * fallback scopes.
   1246  *
   1247  * Input:
   1248  *	scope		scope in which to start search
   1249  *	name		name of the variable to find, is expanded once
   1250  */
   1251 bool
   1252 Var_ExistsExpand(GNode *scope, const char *name)
   1253 {
   1254 	FStr varname = FStr_InitRefer(name);
   1255 	bool exists;
   1256 
   1257 	Var_Expand(&varname, scope, VARE_EVAL);
   1258 	exists = Var_Exists(scope, varname.str);
   1259 	FStr_Done(&varname);
   1260 	return exists;
   1261 }
   1262 
   1263 /*
   1264  * Return the unexpanded value of the given variable in the given scope,
   1265  * falling back to the command, global and environment scopes, in this order,
   1266  * but see the -e option.
   1267  *
   1268  * Input:
   1269  *	name		the name to find, is not expanded any further
   1270  *
   1271  * Results:
   1272  *	The value if the variable exists, NULL if it doesn't.
   1273  *	The value is valid until the next modification to any variable.
   1274  */
   1275 FStr
   1276 Var_Value(GNode *scope, const char *name)
   1277 {
   1278 	Var *v = VarFind(name, scope, true);
   1279 	char *value;
   1280 
   1281 	if (v == NULL)
   1282 		return FStr_InitRefer(NULL);
   1283 
   1284 	if (!v->shortLived)
   1285 		return FStr_InitRefer(v->val.data);
   1286 
   1287 	value = v->val.data;
   1288 	v->val.data = NULL;
   1289 	VarFreeShortLived(v);
   1290 
   1291 	return FStr_InitOwn(value);
   1292 }
   1293 
   1294 /* Set or clear the read-only attribute of the variable if it exists. */
   1295 void
   1296 Var_ReadOnly(const char *name, bool bf)
   1297 {
   1298 	Var *v;
   1299 
   1300 	v = VarFind(name, SCOPE_GLOBAL, false);
   1301 	if (v == NULL) {
   1302 		DEBUG1(VAR, "Var_ReadOnly: %s not found\n", name);
   1303 		return;
   1304 	}
   1305 	v->readOnly = bf;
   1306 	DEBUG2(VAR, "Var_ReadOnly: %s %s\n", name, bf ? "true" : "false");
   1307 }
   1308 
   1309 /*
   1310  * Return the unexpanded variable value from this node, without trying to look
   1311  * up the variable in any other scope.
   1312  */
   1313 const char *
   1314 GNode_ValueDirect(GNode *gn, const char *name)
   1315 {
   1316 	Var *v = VarFind(name, gn, false);
   1317 	return v != NULL ? v->val.data : NULL;
   1318 }
   1319 
   1320 static VarEvalMode
   1321 VarEvalMode_WithoutKeepDollar(VarEvalMode emode)
   1322 {
   1323 	return emode == VARE_EVAL_KEEP_DOLLAR_AND_UNDEFINED
   1324 	    ? VARE_EVAL_KEEP_UNDEFINED : emode;
   1325 }
   1326 
   1327 static VarEvalMode
   1328 VarEvalMode_UndefOk(VarEvalMode emode)
   1329 {
   1330 	return emode == VARE_EVAL_DEFINED ? VARE_EVAL : emode;
   1331 }
   1332 
   1333 static bool
   1334 VarEvalMode_ShouldEval(VarEvalMode emode)
   1335 {
   1336 	return emode != VARE_PARSE;
   1337 }
   1338 
   1339 static bool
   1340 VarEvalMode_ShouldKeepUndef(VarEvalMode emode)
   1341 {
   1342 	return emode == VARE_EVAL_KEEP_UNDEFINED ||
   1343 	       emode == VARE_EVAL_KEEP_DOLLAR_AND_UNDEFINED;
   1344 }
   1345 
   1346 static bool
   1347 VarEvalMode_ShouldKeepDollar(VarEvalMode emode)
   1348 {
   1349 	return emode == VARE_EVAL_KEEP_DOLLAR_AND_UNDEFINED;
   1350 }
   1351 
   1352 
   1353 static void
   1354 SepBuf_Init(SepBuf *buf, char sep)
   1355 {
   1356 	Buf_InitSize(&buf->buf, 32);
   1357 	buf->needSep = false;
   1358 	buf->sep = sep;
   1359 }
   1360 
   1361 static void
   1362 SepBuf_Sep(SepBuf *buf)
   1363 {
   1364 	buf->needSep = true;
   1365 }
   1366 
   1367 static void
   1368 SepBuf_AddBytes(SepBuf *buf, const char *mem, size_t mem_size)
   1369 {
   1370 	if (mem_size == 0)
   1371 		return;
   1372 	if (buf->needSep && buf->sep != '\0') {
   1373 		Buf_AddByte(&buf->buf, buf->sep);
   1374 		buf->needSep = false;
   1375 	}
   1376 	Buf_AddBytes(&buf->buf, mem, mem_size);
   1377 }
   1378 
   1379 static void
   1380 SepBuf_AddRange(SepBuf *buf, const char *start, const char *end)
   1381 {
   1382 	SepBuf_AddBytes(buf, start, (size_t)(end - start));
   1383 }
   1384 
   1385 static void
   1386 SepBuf_AddStr(SepBuf *buf, const char *str)
   1387 {
   1388 	SepBuf_AddBytes(buf, str, strlen(str));
   1389 }
   1390 
   1391 static void
   1392 SepBuf_AddSubstring(SepBuf *buf, Substring sub)
   1393 {
   1394 	SepBuf_AddRange(buf, sub.start, sub.end);
   1395 }
   1396 
   1397 static char *
   1398 SepBuf_DoneData(SepBuf *buf)
   1399 {
   1400 	return Buf_DoneData(&buf->buf);
   1401 }
   1402 
   1403 
   1404 /*
   1405  * This callback for ModifyWords gets a single word from an expression
   1406  * and typically adds a modification of this word to the buffer. It may also
   1407  * do nothing or add several words.
   1408  *
   1409  * For example, when evaluating the modifier ':M*b' in ${:Ua b c:M*b}, the
   1410  * callback is called 3 times, once for "a", "b" and "c".
   1411  *
   1412  * Some ModifyWord functions assume that they are always passed a
   1413  * null-terminated substring, which is currently guaranteed but may change in
   1414  * the future.
   1415  */
   1416 typedef void (*ModifyWordProc)(Substring word, SepBuf *buf, void *data);
   1417 
   1418 
   1419 /*ARGSUSED*/
   1420 static void
   1421 ModifyWord_Head(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1422 {
   1423 	SepBuf_AddSubstring(buf, Substring_Dirname(word));
   1424 }
   1425 
   1426 /*ARGSUSED*/
   1427 static void
   1428 ModifyWord_Tail(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1429 {
   1430 	SepBuf_AddSubstring(buf, Substring_Basename(word));
   1431 }
   1432 
   1433 /*ARGSUSED*/
   1434 static void
   1435 ModifyWord_Suffix(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1436 {
   1437 	const char *lastDot = Substring_FindLast(word, '.');
   1438 	if (lastDot != NULL)
   1439 		SepBuf_AddRange(buf, lastDot + 1, word.end);
   1440 }
   1441 
   1442 /*ARGSUSED*/
   1443 static void
   1444 ModifyWord_Root(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1445 {
   1446 	const char *lastDot, *end;
   1447 
   1448 	lastDot = Substring_FindLast(word, '.');
   1449 	end = lastDot != NULL ? lastDot : word.end;
   1450 	SepBuf_AddRange(buf, word.start, end);
   1451 }
   1452 
   1453 struct ModifyWord_SysVSubstArgs {
   1454 	GNode *scope;
   1455 	Substring lhsPrefix;
   1456 	bool lhsPercent;
   1457 	Substring lhsSuffix;
   1458 	const char *rhs;
   1459 };
   1460 
   1461 static void
   1462 ModifyWord_SysVSubst(Substring word, SepBuf *buf, void *data)
   1463 {
   1464 	const struct ModifyWord_SysVSubstArgs *args = data;
   1465 	FStr rhs;
   1466 	const char *percent;
   1467 
   1468 	if (Substring_IsEmpty(word))
   1469 		return;
   1470 
   1471 	if (!Substring_HasPrefix(word, args->lhsPrefix) ||
   1472 	    !Substring_HasSuffix(word, args->lhsSuffix)) {
   1473 		SepBuf_AddSubstring(buf, word);
   1474 		return;
   1475 	}
   1476 
   1477 	rhs = FStr_InitRefer(args->rhs);
   1478 	Var_Expand(&rhs, args->scope, VARE_EVAL);
   1479 
   1480 	percent = args->lhsPercent ? strchr(rhs.str, '%') : NULL;
   1481 
   1482 	if (percent != NULL)
   1483 		SepBuf_AddRange(buf, rhs.str, percent);
   1484 	if (percent != NULL || !args->lhsPercent)
   1485 		SepBuf_AddRange(buf,
   1486 		    word.start + Substring_Length(args->lhsPrefix),
   1487 		    word.end - Substring_Length(args->lhsSuffix));
   1488 	SepBuf_AddStr(buf, percent != NULL ? percent + 1 : rhs.str);
   1489 
   1490 	FStr_Done(&rhs);
   1491 }
   1492 
   1493 static const char *
   1494 Substring_Find(Substring haystack, Substring needle)
   1495 {
   1496 	size_t len, needleLen, i;
   1497 
   1498 	len = Substring_Length(haystack);
   1499 	needleLen = Substring_Length(needle);
   1500 	for (i = 0; i + needleLen <= len; i++)
   1501 		if (memcmp(haystack.start + i, needle.start, needleLen) == 0)
   1502 			return haystack.start + i;
   1503 	return NULL;
   1504 }
   1505 
   1506 struct ModifyWord_SubstArgs {
   1507 	Substring lhs;
   1508 	Substring rhs;
   1509 	PatternFlags pflags;
   1510 	bool matched;
   1511 };
   1512 
   1513 static void
   1514 ModifyWord_Subst(Substring word, SepBuf *buf, void *data)
   1515 {
   1516 	struct ModifyWord_SubstArgs *args = data;
   1517 	size_t wordLen, lhsLen;
   1518 	const char *match;
   1519 
   1520 	wordLen = Substring_Length(word);
   1521 	if (args->pflags.subOnce && args->matched)
   1522 		goto nosub;
   1523 
   1524 	lhsLen = Substring_Length(args->lhs);
   1525 	if (args->pflags.anchorStart) {
   1526 		if (wordLen < lhsLen ||
   1527 		    memcmp(word.start, args->lhs.start, lhsLen) != 0)
   1528 			goto nosub;
   1529 
   1530 		if (args->pflags.anchorEnd && wordLen != lhsLen)
   1531 			goto nosub;
   1532 
   1533 		/* :S,^prefix,replacement, or :S,^whole$,replacement, */
   1534 		SepBuf_AddSubstring(buf, args->rhs);
   1535 		SepBuf_AddRange(buf, word.start + lhsLen, word.end);
   1536 		args->matched = true;
   1537 		return;
   1538 	}
   1539 
   1540 	if (args->pflags.anchorEnd) {
   1541 		if (wordLen < lhsLen)
   1542 			goto nosub;
   1543 		if (memcmp(word.end - lhsLen, args->lhs.start, lhsLen) != 0)
   1544 			goto nosub;
   1545 
   1546 		/* :S,suffix$,replacement, */
   1547 		SepBuf_AddRange(buf, word.start, word.end - lhsLen);
   1548 		SepBuf_AddSubstring(buf, args->rhs);
   1549 		args->matched = true;
   1550 		return;
   1551 	}
   1552 
   1553 	if (Substring_IsEmpty(args->lhs))
   1554 		goto nosub;
   1555 
   1556 	/* unanchored case, may match more than once */
   1557 	while ((match = Substring_Find(word, args->lhs)) != NULL) {
   1558 		SepBuf_AddRange(buf, word.start, match);
   1559 		SepBuf_AddSubstring(buf, args->rhs);
   1560 		args->matched = true;
   1561 		word.start = match + lhsLen;
   1562 		if (Substring_IsEmpty(word) || !args->pflags.subGlobal)
   1563 			break;
   1564 	}
   1565 nosub:
   1566 	SepBuf_AddSubstring(buf, word);
   1567 }
   1568 
   1569 /* Print the error caused by a regcomp or regexec call. */
   1570 static void
   1571 RegexError(int reerr, const regex_t *pat, const char *str)
   1572 {
   1573 	size_t errlen = regerror(reerr, pat, NULL, 0);
   1574 	char *errbuf = bmake_malloc(errlen);
   1575 	regerror(reerr, pat, errbuf, errlen);
   1576 	Parse_Error(PARSE_FATAL, "%s: %s", str, errbuf);
   1577 	free(errbuf);
   1578 }
   1579 
   1580 /* In the modifier ':C', replace a backreference from \0 to \9. */
   1581 static void
   1582 RegexReplaceBackref(char ref, SepBuf *buf, const char *wp,
   1583 		    const regmatch_t *m, size_t nsub)
   1584 {
   1585 	unsigned int n = (unsigned)ref - '0';
   1586 
   1587 	if (n >= nsub)
   1588 		Parse_Error(PARSE_FATAL, "No subexpression \\%u", n);
   1589 	else if (m[n].rm_so == -1) {
   1590 		if (opts.strict)
   1591 			Error("No match for subexpression \\%u", n);
   1592 	} else {
   1593 		SepBuf_AddRange(buf,
   1594 		    wp + (size_t)m[n].rm_so,
   1595 		    wp + (size_t)m[n].rm_eo);
   1596 	}
   1597 }
   1598 
   1599 /*
   1600  * The regular expression matches the word; now add the replacement to the
   1601  * buffer, taking back-references from 'wp'.
   1602  */
   1603 static void
   1604 RegexReplace(Substring replace, SepBuf *buf, const char *wp,
   1605 	     const regmatch_t *m, size_t nsub)
   1606 {
   1607 	const char *rp;
   1608 
   1609 	for (rp = replace.start; rp != replace.end; rp++) {
   1610 		if (*rp == '\\' && rp + 1 != replace.end &&
   1611 		    (rp[1] == '&' || rp[1] == '\\'))
   1612 			SepBuf_AddBytes(buf, ++rp, 1);
   1613 		else if (*rp == '\\' && rp + 1 != replace.end &&
   1614 			 ch_isdigit(rp[1]))
   1615 			RegexReplaceBackref(*++rp, buf, wp, m, nsub);
   1616 		else if (*rp == '&') {
   1617 			SepBuf_AddRange(buf,
   1618 			    wp + (size_t)m[0].rm_so,
   1619 			    wp + (size_t)m[0].rm_eo);
   1620 		} else
   1621 			SepBuf_AddBytes(buf, rp, 1);
   1622 	}
   1623 }
   1624 
   1625 struct ModifyWord_SubstRegexArgs {
   1626 	regex_t re;
   1627 	size_t nsub;
   1628 	Substring replace;
   1629 	PatternFlags pflags;
   1630 	bool matched;
   1631 };
   1632 
   1633 static void
   1634 ModifyWord_SubstRegex(Substring word, SepBuf *buf, void *data)
   1635 {
   1636 	struct ModifyWord_SubstRegexArgs *args = data;
   1637 	int xrv;
   1638 	const char *wp;
   1639 	int flags = 0;
   1640 	regmatch_t m[10];
   1641 
   1642 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   1643 	wp = word.start;
   1644 	if (args->pflags.subOnce && args->matched)
   1645 		goto no_match;
   1646 
   1647 again:
   1648 	xrv = regexec(&args->re, wp, args->nsub, m, flags);
   1649 	if (xrv == 0)
   1650 		goto ok;
   1651 	if (xrv != REG_NOMATCH)
   1652 		RegexError(xrv, &args->re, "Unexpected regex error");
   1653 no_match:
   1654 	SepBuf_AddRange(buf, wp, word.end);
   1655 	return;
   1656 
   1657 ok:
   1658 	args->matched = true;
   1659 	SepBuf_AddBytes(buf, wp, (size_t)m[0].rm_so);
   1660 
   1661 	RegexReplace(args->replace, buf, wp, m, args->nsub);
   1662 
   1663 	wp += (size_t)m[0].rm_eo;
   1664 	if (args->pflags.subGlobal) {
   1665 		flags |= REG_NOTBOL;
   1666 		if (m[0].rm_so == 0 && m[0].rm_eo == 0 && *wp != '\0') {
   1667 			SepBuf_AddBytes(buf, wp, 1);
   1668 			wp++;
   1669 		}
   1670 		if (*wp != '\0')
   1671 			goto again;
   1672 	}
   1673 	if (*wp != '\0')
   1674 		SepBuf_AddStr(buf, wp);
   1675 }
   1676 
   1677 
   1678 struct ModifyWord_LoopArgs {
   1679 	GNode *scope;
   1680 	const char *var;	/* name of the temporary variable */
   1681 	const char *body;	/* string to expand */
   1682 	VarEvalMode emode;
   1683 };
   1684 
   1685 static void
   1686 ModifyWord_Loop(Substring word, SepBuf *buf, void *data)
   1687 {
   1688 	const struct ModifyWord_LoopArgs *args;
   1689 	char *s;
   1690 
   1691 	if (Substring_IsEmpty(word))
   1692 		return;
   1693 
   1694 	args = data;
   1695 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   1696 	Var_SetWithFlags(args->scope, args->var, word.start,
   1697 	    VAR_SET_NO_EXPORT);
   1698 	s = Var_Subst(args->body, args->scope, args->emode);
   1699 	/* TODO: handle errors */
   1700 
   1701 	DEBUG2(VAR, "ModifyWord_Loop: expand \"%s\" to \"%s\"\n",
   1702 	    args->body, s);
   1703 
   1704 	if (s[0] == '\n' || Buf_EndsWith(&buf->buf, '\n'))
   1705 		buf->needSep = false;
   1706 	SepBuf_AddStr(buf, s);
   1707 	free(s);
   1708 }
   1709 
   1710 
   1711 /*
   1712  * The :[first..last] modifier selects words from the expression.
   1713  * It can also reverse the words.
   1714  */
   1715 static char *
   1716 VarSelectWords(const char *str, int first, int last,
   1717 	       char sep, bool oneBigWord)
   1718 {
   1719 	SubstringWords words;
   1720 	int len, start, end, step;
   1721 	int i;
   1722 
   1723 	SepBuf buf;
   1724 	SepBuf_Init(&buf, sep);
   1725 
   1726 	if (oneBigWord) {
   1727 		/* fake what Substring_Words() would do */
   1728 		words.len = 1;
   1729 		words.words = bmake_malloc(sizeof(words.words[0]));
   1730 		words.freeIt = NULL;
   1731 		words.words[0] = Substring_InitStr(str); /* no need to copy */
   1732 	} else {
   1733 		words = Substring_Words(str, false);
   1734 	}
   1735 
   1736 	/* Convert -1 to len, -2 to (len - 1), etc. */
   1737 	len = (int)words.len;
   1738 	if (first < 0)
   1739 		first += len + 1;
   1740 	if (last < 0)
   1741 		last += len + 1;
   1742 
   1743 	if (first > last) {
   1744 		start = (first > len ? len : first) - 1;
   1745 		end = last < 1 ? 0 : last - 1;
   1746 		step = -1;
   1747 	} else {
   1748 		start = first < 1 ? 0 : first - 1;
   1749 		end = last > len ? len : last;
   1750 		step = 1;
   1751 	}
   1752 
   1753 	for (i = start; (step < 0) == (i >= end); i += step) {
   1754 		SepBuf_AddSubstring(&buf, words.words[i]);
   1755 		SepBuf_Sep(&buf);
   1756 	}
   1757 
   1758 	SubstringWords_Free(words);
   1759 
   1760 	return SepBuf_DoneData(&buf);
   1761 }
   1762 
   1763 
   1764 /*ARGSUSED*/
   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  * using Error.  This function has no side effects, it really just prints the
   1970  * error message, continuing as if nothing had happened.  TODO: This should be
   1971  * fixed by adding proper error handling to Var_Subst, Var_Parse,
   1972  * ApplyModifiers and ModifyWords.
   1973  *
   1974  * Some modifiers such as :D and :U turn undefined expressions into defined
   1975  * expressions using Expr_Define.
   1976  */
   1977 
   1978 typedef enum ExprDefined {
   1979 	/* The expression is based on a regular, defined variable. */
   1980 	DEF_REGULAR,
   1981 	/* The expression is based on an undefined variable. */
   1982 	DEF_UNDEF,
   1983 	/*
   1984 	 * The expression started as an undefined expression, but one
   1985 	 * of the modifiers (such as ':D' or ':U') has turned the expression
   1986 	 * from undefined to defined.
   1987 	 */
   1988 	DEF_DEFINED
   1989 } ExprDefined;
   1990 
   1991 static const char ExprDefined_Name[][10] = {
   1992 	"regular",
   1993 	"undefined",
   1994 	"defined"
   1995 };
   1996 
   1997 #if __STDC_VERSION__ >= 199901L
   1998 #define const_member		const
   1999 #else
   2000 #define const_member		/* no const possible */
   2001 #endif
   2002 
   2003 /* An expression based on a variable, such as $@ or ${VAR:Mpattern:Q}. */
   2004 typedef struct Expr {
   2005 	const char *name;
   2006 	FStr value;
   2007 	VarEvalMode const_member emode;
   2008 	GNode *const_member scope;
   2009 	ExprDefined defined;
   2010 } Expr;
   2011 
   2012 /*
   2013  * The status of applying a chain of modifiers to an expression.
   2014  *
   2015  * The modifiers of an expression are broken into chains of modifiers,
   2016  * starting a new nested chain whenever an indirect modifier starts.  There
   2017  * are at most 2 nesting levels: the outer one for the direct modifiers, and
   2018  * the inner one for the indirect modifiers.
   2019  *
   2020  * For example, the expression ${VAR:M*:${IND1}:${IND2}:O:u} has 3 chains of
   2021  * modifiers:
   2022  *
   2023  *	Chain 1 starts with the single modifier ':M*'.
   2024  *	  Chain 2 starts with all modifiers from ${IND1}.
   2025  *	  Chain 2 ends at the ':' between ${IND1} and ${IND2}.
   2026  *	  Chain 3 starts with all modifiers from ${IND2}.
   2027  *	  Chain 3 ends at the ':' after ${IND2}.
   2028  *	Chain 1 continues with the 2 modifiers ':O' and ':u'.
   2029  *	Chain 1 ends at the final '}' of the expression.
   2030  *
   2031  * After such a chain ends, its properties no longer have any effect.
   2032  *
   2033  * See varmod-indirect.mk.
   2034  */
   2035 typedef struct ModChain {
   2036 	Expr *expr;
   2037 	/* '\0' or '{' or '(' */
   2038 	char const_member startc;
   2039 	/* '\0' or '}' or ')' */
   2040 	char const_member endc;
   2041 	/* Separator when joining words (see the :ts modifier). */
   2042 	char sep;
   2043 	/*
   2044 	 * Whether some modifiers that otherwise split the variable value
   2045 	 * into words, like :S and :C, treat the variable value as a single
   2046 	 * big word, possibly containing spaces.
   2047 	 */
   2048 	bool oneBigWord;
   2049 } ModChain;
   2050 
   2051 static void
   2052 Expr_Define(Expr *expr)
   2053 {
   2054 	if (expr->defined == DEF_UNDEF)
   2055 		expr->defined = DEF_DEFINED;
   2056 }
   2057 
   2058 static const char *
   2059 Expr_Str(const Expr *expr)
   2060 {
   2061 	return expr->value.str;
   2062 }
   2063 
   2064 static SubstringWords
   2065 Expr_Words(const Expr *expr)
   2066 {
   2067 	return Substring_Words(Expr_Str(expr), false);
   2068 }
   2069 
   2070 static void
   2071 Expr_SetValue(Expr *expr, FStr value)
   2072 {
   2073 	FStr_Done(&expr->value);
   2074 	expr->value = value;
   2075 }
   2076 
   2077 static void
   2078 Expr_SetValueOwn(Expr *expr, char *value)
   2079 {
   2080 	Expr_SetValue(expr, FStr_InitOwn(value));
   2081 }
   2082 
   2083 static void
   2084 Expr_SetValueRefer(Expr *expr, const char *value)
   2085 {
   2086 	Expr_SetValue(expr, FStr_InitRefer(value));
   2087 }
   2088 
   2089 static bool
   2090 Expr_ShouldEval(const Expr *expr)
   2091 {
   2092 	return VarEvalMode_ShouldEval(expr->emode);
   2093 }
   2094 
   2095 static bool
   2096 ModChain_ShouldEval(const ModChain *ch)
   2097 {
   2098 	return Expr_ShouldEval(ch->expr);
   2099 }
   2100 
   2101 
   2102 typedef enum ApplyModifierResult {
   2103 	/* Continue parsing */
   2104 	AMR_OK,
   2105 	/* Not a match, try the ':from=to' modifier as well. */
   2106 	AMR_UNKNOWN,
   2107 	/* Error out with "Bad modifier" message. */
   2108 	AMR_BAD,
   2109 	/* Error out without the standard error message. */
   2110 	AMR_CLEANUP
   2111 } ApplyModifierResult;
   2112 
   2113 /*
   2114  * Allow backslashes to escape the delimiter, $, and \, but don't touch other
   2115  * backslashes.
   2116  */
   2117 static bool
   2118 IsEscapedModifierPart(const char *p, char delim,
   2119 		      struct ModifyWord_SubstArgs *subst)
   2120 {
   2121 	if (p[0] != '\\' || p[1] == '\0')
   2122 		return false;
   2123 	if (p[1] == delim || p[1] == '\\' || p[1] == '$')
   2124 		return true;
   2125 	return p[1] == '&' && subst != NULL;
   2126 }
   2127 
   2128 /*
   2129  * In a part of a modifier, parse a subexpression and evaluate it.
   2130  */
   2131 static void
   2132 ParseModifierPartExpr(const char **pp, LazyBuf *part, const ModChain *ch,
   2133 		      VarEvalMode emode)
   2134 {
   2135 	const char *p = *pp;
   2136 	FStr nested_val = Var_Parse(&p, ch->expr->scope,
   2137 	    VarEvalMode_WithoutKeepDollar(emode));
   2138 	/* TODO: handle errors */
   2139 	if (VarEvalMode_ShouldEval(emode))
   2140 		LazyBuf_AddStr(part, nested_val.str);
   2141 	else
   2142 		LazyBuf_AddSubstring(part, Substring_Init(*pp, p));
   2143 	FStr_Done(&nested_val);
   2144 	*pp = p;
   2145 }
   2146 
   2147 /*
   2148  * In a part of a modifier, parse some text that looks like a subexpression.
   2149  * If the text starts with '$(', any '(' and ')' must be balanced.
   2150  * If the text starts with '${', any '{' and '}' must be balanced.
   2151  * If the text starts with '$', that '$' is copied verbatim, it is not parsed
   2152  * as a short-name expression.
   2153  */
   2154 static void
   2155 ParseModifierPartBalanced(const char **pp, LazyBuf *part)
   2156 {
   2157 	const char *p = *pp;
   2158 
   2159 	if (p[1] == '(' || p[1] == '{') {
   2160 		char startc = p[1];
   2161 		int endc = startc == '(' ? ')' : '}';
   2162 		int depth = 1;
   2163 
   2164 		for (p += 2; *p != '\0' && depth > 0; p++) {
   2165 			if (p[-1] != '\\') {
   2166 				if (*p == startc)
   2167 					depth++;
   2168 				if (*p == endc)
   2169 					depth--;
   2170 			}
   2171 		}
   2172 		LazyBuf_AddSubstring(part, Substring_Init(*pp, p));
   2173 		*pp = p;
   2174 	} else {
   2175 		LazyBuf_Add(part, *p);
   2176 		*pp = p + 1;
   2177 	}
   2178 }
   2179 
   2180 /*
   2181  * Parse a part of a modifier such as the "from" and "to" in :S/from/to/ or
   2182  * the "var" or "replacement ${var}" in :@var@replacement ${var}@, up to and
   2183  * including the next unescaped delimiter.  The delimiter, as well as the
   2184  * backslash or the dollar, can be escaped with a backslash.
   2185  *
   2186  * Return true if parsing succeeded, together with the parsed (and possibly
   2187  * expanded) part.  In that case, pp points right after the delimiter.  The
   2188  * delimiter is not included in the part though.
   2189  */
   2190 static bool
   2191 ParseModifierPart(
   2192     /* The parsing position, updated upon return */
   2193     const char **pp,
   2194     char end1,
   2195     char end2,
   2196     /* Mode for evaluating nested expressions. */
   2197     VarEvalMode emode,
   2198     ModChain *ch,
   2199     LazyBuf *part,
   2200     /*
   2201      * For the first part of the ':S' modifier, set anchorEnd if the last
   2202      * character of the pattern is a $.
   2203      */
   2204     PatternFlags *out_pflags,
   2205     /*
   2206      * For the second part of the ':S' modifier, allow ampersands to be
   2207      * escaped and replace unescaped ampersands with subst->lhs.
   2208      */
   2209     struct ModifyWord_SubstArgs *subst
   2210 )
   2211 {
   2212 	const char *p = *pp;
   2213 
   2214 	LazyBuf_Init(part, p);
   2215 	while (*p != '\0' && *p != end1 && *p != end2) {
   2216 		if (IsEscapedModifierPart(p, end2, subst)) {
   2217 			LazyBuf_Add(part, p[1]);
   2218 			p += 2;
   2219 		} else if (*p != '$') {	/* Unescaped, simple text */
   2220 			if (subst != NULL && *p == '&')
   2221 				LazyBuf_AddSubstring(part, subst->lhs);
   2222 			else
   2223 				LazyBuf_Add(part, *p);
   2224 			p++;
   2225 		} else if (p[1] == end2) {	/* Unescaped '$' at end */
   2226 			if (out_pflags != NULL)
   2227 				out_pflags->anchorEnd = true;
   2228 			else
   2229 				LazyBuf_Add(part, *p);
   2230 			p++;
   2231 		} else if (emode == VARE_PARSE_BALANCED)
   2232 			ParseModifierPartBalanced(&p, part);
   2233 		else
   2234 			ParseModifierPartExpr(&p, part, ch, emode);
   2235 	}
   2236 
   2237 	*pp = p;
   2238 	if (*p != end1 && *p != end2) {
   2239 		Parse_Error(PARSE_FATAL,
   2240 		    "Unfinished modifier ('%c' missing)", end2);
   2241 		LazyBuf_Done(part);
   2242 		return false;
   2243 	}
   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_WARNING,
   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 /*ARGSUSED*/
   3066 static void
   3067 ModifyWord_Copy(Substring word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   3068 {
   3069 	SepBuf_AddSubstring(buf, word);
   3070 }
   3071 
   3072 /* :ts<separator> */
   3073 static ApplyModifierResult
   3074 ApplyModifier_ToSep(const char **pp, ModChain *ch)
   3075 {
   3076 	const char *sep = *pp + 2;
   3077 
   3078 	/*
   3079 	 * Even in parse-only mode, apply the side effects, since the side
   3080 	 * effects are neither observable nor is there a performance penalty.
   3081 	 * Checking for VARE_EVAL for every single piece of code in here
   3082 	 * would make the code in this function too hard to read.
   3083 	 */
   3084 
   3085 	/* ":ts<any><endc>" or ":ts<any>:" */
   3086 	if (sep[0] != ch->endc && IsDelimiter(sep[1], ch)) {
   3087 		*pp = sep + 1;
   3088 		ch->sep = sep[0];
   3089 		goto ok;
   3090 	}
   3091 
   3092 	/* ":ts<endc>" or ":ts:" */
   3093 	if (IsDelimiter(sep[0], ch)) {
   3094 		*pp = sep;
   3095 		ch->sep = '\0';	/* no separator */
   3096 		goto ok;
   3097 	}
   3098 
   3099 	/* ":ts<unrecognized><unrecognized>". */
   3100 	if (sep[0] != '\\') {
   3101 		(*pp)++;	/* just for backwards compatibility */
   3102 		return AMR_BAD;
   3103 	}
   3104 
   3105 	/* ":ts\n" */
   3106 	if (sep[1] == 'n') {
   3107 		*pp = sep + 2;
   3108 		ch->sep = '\n';
   3109 		goto ok;
   3110 	}
   3111 
   3112 	/* ":ts\t" */
   3113 	if (sep[1] == 't') {
   3114 		*pp = sep + 2;
   3115 		ch->sep = '\t';
   3116 		goto ok;
   3117 	}
   3118 
   3119 	/* ":ts\x40" or ":ts\100" */
   3120 	{
   3121 		const char *p = sep + 1;
   3122 		int base = 8;	/* assume octal */
   3123 
   3124 		if (sep[1] == 'x') {
   3125 			base = 16;
   3126 			p++;
   3127 		} else if (!ch_isdigit(sep[1])) {
   3128 			(*pp)++;	/* just for backwards compatibility */
   3129 			return AMR_BAD;	/* ":ts<backslash><unrecognized>". */
   3130 		}
   3131 
   3132 		if (!TryParseChar(&p, base, &ch->sep)) {
   3133 			Parse_Error(PARSE_FATAL,
   3134 			    "Invalid character number at \"%s\"", p);
   3135 			return AMR_CLEANUP;
   3136 		}
   3137 		if (!IsDelimiter(*p, ch)) {
   3138 			(*pp)++;	/* just for backwards compatibility */
   3139 			return AMR_BAD;
   3140 		}
   3141 
   3142 		*pp = p;
   3143 	}
   3144 
   3145 ok:
   3146 	ModifyWords(ch, ModifyWord_Copy, NULL, ch->oneBigWord);
   3147 	return AMR_OK;
   3148 }
   3149 
   3150 static char *
   3151 str_totitle(const char *str)
   3152 {
   3153 	size_t i, n = strlen(str) + 1;
   3154 	char *res = bmake_malloc(n);
   3155 	for (i = 0; i < n; i++) {
   3156 		if (i == 0 || ch_isspace(res[i - 1]))
   3157 			res[i] = ch_toupper(str[i]);
   3158 		else
   3159 			res[i] = ch_tolower(str[i]);
   3160 	}
   3161 	return res;
   3162 }
   3163 
   3164 
   3165 static char *
   3166 str_toupper(const char *str)
   3167 {
   3168 	size_t i, n = strlen(str) + 1;
   3169 	char *res = bmake_malloc(n);
   3170 	for (i = 0; i < n; i++)
   3171 		res[i] = ch_toupper(str[i]);
   3172 	return res;
   3173 }
   3174 
   3175 static char *
   3176 str_tolower(const char *str)
   3177 {
   3178 	size_t i, n = strlen(str) + 1;
   3179 	char *res = bmake_malloc(n);
   3180 	for (i = 0; i < n; i++)
   3181 		res[i] = ch_tolower(str[i]);
   3182 	return res;
   3183 }
   3184 
   3185 /* :tA, :tu, :tl, :ts<separator>, etc. */
   3186 static ApplyModifierResult
   3187 ApplyModifier_To(const char **pp, ModChain *ch)
   3188 {
   3189 	Expr *expr = ch->expr;
   3190 	const char *mod = *pp;
   3191 	assert(mod[0] == 't');
   3192 
   3193 	if (IsDelimiter(mod[1], ch)) {
   3194 		*pp = mod + 1;
   3195 		return AMR_BAD;	/* Found ":t<endc>" or ":t:". */
   3196 	}
   3197 
   3198 	if (mod[1] == 's')
   3199 		return ApplyModifier_ToSep(pp, ch);
   3200 
   3201 	if (!IsDelimiter(mod[2], ch)) {			/* :t<any><any> */
   3202 		*pp = mod + 1;
   3203 		return AMR_BAD;
   3204 	}
   3205 
   3206 	if (mod[1] == 'A') {				/* :tA */
   3207 		*pp = mod + 2;
   3208 		ModifyWords(ch, ModifyWord_Realpath, NULL, ch->oneBigWord);
   3209 		return AMR_OK;
   3210 	}
   3211 
   3212 	if (mod[1] == 't') {				/* :tt */
   3213 		*pp = mod + 2;
   3214 		if (Expr_ShouldEval(expr))
   3215 			Expr_SetValueOwn(expr, str_totitle(Expr_Str(expr)));
   3216 		return AMR_OK;
   3217 	}
   3218 
   3219 	if (mod[1] == 'u') {				/* :tu */
   3220 		*pp = mod + 2;
   3221 		if (Expr_ShouldEval(expr))
   3222 			Expr_SetValueOwn(expr, str_toupper(Expr_Str(expr)));
   3223 		return AMR_OK;
   3224 	}
   3225 
   3226 	if (mod[1] == 'l') {				/* :tl */
   3227 		*pp = mod + 2;
   3228 		if (Expr_ShouldEval(expr))
   3229 			Expr_SetValueOwn(expr, str_tolower(Expr_Str(expr)));
   3230 		return AMR_OK;
   3231 	}
   3232 
   3233 	if (mod[1] == 'W' || mod[1] == 'w') {		/* :tW, :tw */
   3234 		*pp = mod + 2;
   3235 		ch->oneBigWord = mod[1] == 'W';
   3236 		return AMR_OK;
   3237 	}
   3238 
   3239 	/* Found ":t<unrecognized>:" or ":t<unrecognized><endc>". */
   3240 	*pp = mod + 1;		/* XXX: unnecessary but observable */
   3241 	return AMR_BAD;
   3242 }
   3243 
   3244 /* :[#], :[1], :[-1..1], etc. */
   3245 static ApplyModifierResult
   3246 ApplyModifier_Words(const char **pp, ModChain *ch)
   3247 {
   3248 	Expr *expr = ch->expr;
   3249 	int first, last;
   3250 	const char *p;
   3251 	LazyBuf argBuf;
   3252 	FStr arg;
   3253 
   3254 	(*pp)++;		/* skip the '[' */
   3255 	if (!ParseModifierPart(pp, ']', ']', expr->emode,
   3256 	    ch, &argBuf, NULL, NULL))
   3257 		return AMR_CLEANUP;
   3258 	arg = LazyBuf_DoneGet(&argBuf);
   3259 	p = arg.str;
   3260 
   3261 	if (!IsDelimiter(**pp, ch))
   3262 		goto bad_modifier;		/* Found junk after ']' */
   3263 
   3264 	if (!ModChain_ShouldEval(ch))
   3265 		goto ok;
   3266 
   3267 	if (p[0] == '\0')
   3268 		goto bad_modifier;		/* Found ":[]". */
   3269 
   3270 	if (strcmp(p, "#") == 0) {		/* Found ":[#]" */
   3271 		if (ch->oneBigWord)
   3272 			Expr_SetValueRefer(expr, "1");
   3273 		else {
   3274 			Buffer buf;
   3275 
   3276 			SubstringWords words = Expr_Words(expr);
   3277 			size_t ac = words.len;
   3278 			SubstringWords_Free(words);
   3279 
   3280 			Buf_Init(&buf);
   3281 			Buf_AddInt(&buf, (int)ac);
   3282 			Expr_SetValueOwn(expr, Buf_DoneData(&buf));
   3283 		}
   3284 		goto ok;
   3285 	}
   3286 
   3287 	if (strcmp(p, "*") == 0) {		/* ":[*]" */
   3288 		ch->oneBigWord = true;
   3289 		goto ok;
   3290 	}
   3291 
   3292 	if (strcmp(p, "@") == 0) {		/* ":[@]" */
   3293 		ch->oneBigWord = false;
   3294 		goto ok;
   3295 	}
   3296 
   3297 	/* Expect ":[N]" or ":[start..end]" */
   3298 	if (!TryParseIntBase0(&p, &first))
   3299 		goto bad_modifier;
   3300 
   3301 	if (p[0] == '\0')			/* ":[N]" */
   3302 		last = first;
   3303 	else if (strncmp(p, "..", 2) == 0) {
   3304 		p += 2;
   3305 		if (!TryParseIntBase0(&p, &last) || *p != '\0')
   3306 			goto bad_modifier;
   3307 	} else
   3308 		goto bad_modifier;
   3309 
   3310 	if (first == 0 && last == 0) {		/* ":[0]" or ":[0..0]" */
   3311 		ch->oneBigWord = true;
   3312 		goto ok;
   3313 	}
   3314 
   3315 	if (first == 0 || last == 0)		/* ":[0..N]" or ":[N..0]" */
   3316 		goto bad_modifier;
   3317 
   3318 	Expr_SetValueOwn(expr,
   3319 	    VarSelectWords(Expr_Str(expr), first, last,
   3320 		ch->sep, ch->oneBigWord));
   3321 
   3322 ok:
   3323 	FStr_Done(&arg);
   3324 	return AMR_OK;
   3325 
   3326 bad_modifier:
   3327 	FStr_Done(&arg);
   3328 	return AMR_BAD;
   3329 }
   3330 
   3331 #if __STDC_VERSION__ >= 199901L
   3332 # define NUM_TYPE long long
   3333 # define PARSE_NUM_TYPE strtoll
   3334 #else
   3335 # define NUM_TYPE long
   3336 # define PARSE_NUM_TYPE strtol
   3337 #endif
   3338 
   3339 static NUM_TYPE
   3340 num_val(Substring s)
   3341 {
   3342 	NUM_TYPE val;
   3343 	char *ep;
   3344 
   3345 	val = PARSE_NUM_TYPE(s.start, &ep, 0);
   3346 	if (ep != s.start) {
   3347 		switch (*ep) {
   3348 		case 'K':
   3349 		case 'k':
   3350 			val <<= 10;
   3351 			break;
   3352 		case 'M':
   3353 		case 'm':
   3354 			val <<= 20;
   3355 			break;
   3356 		case 'G':
   3357 		case 'g':
   3358 			val <<= 30;
   3359 			break;
   3360 		}
   3361 	}
   3362 	return val;
   3363 }
   3364 
   3365 static int
   3366 SubNumAsc(const void *sa, const void *sb)
   3367 {
   3368 	NUM_TYPE a, b;
   3369 
   3370 	a = num_val(*((const Substring *)sa));
   3371 	b = num_val(*((const Substring *)sb));
   3372 	return a > b ? 1 : b > a ? -1 : 0;
   3373 }
   3374 
   3375 static int
   3376 SubNumDesc(const void *sa, const void *sb)
   3377 {
   3378 	return SubNumAsc(sb, sa);
   3379 }
   3380 
   3381 static int
   3382 Substring_Cmp(Substring a, Substring b)
   3383 {
   3384 	for (; a.start < a.end && b.start < b.end; a.start++, b.start++)
   3385 		if (a.start[0] != b.start[0])
   3386 			return (unsigned char)a.start[0]
   3387 			    - (unsigned char)b.start[0];
   3388 	return (int)((a.end - a.start) - (b.end - b.start));
   3389 }
   3390 
   3391 static int
   3392 SubStrAsc(const void *sa, const void *sb)
   3393 {
   3394 	return Substring_Cmp(*(const Substring *)sa, *(const Substring *)sb);
   3395 }
   3396 
   3397 static int
   3398 SubStrDesc(const void *sa, const void *sb)
   3399 {
   3400 	return SubStrAsc(sb, sa);
   3401 }
   3402 
   3403 static void
   3404 ShuffleSubstrings(Substring *strs, size_t n)
   3405 {
   3406 	size_t i;
   3407 
   3408 	for (i = n - 1; i > 0; i--) {
   3409 		size_t rndidx = (size_t)random() % (i + 1);
   3410 		Substring t = strs[i];
   3411 		strs[i] = strs[rndidx];
   3412 		strs[rndidx] = t;
   3413 	}
   3414 }
   3415 
   3416 /*
   3417  * :O		order ascending
   3418  * :Or		order descending
   3419  * :Ox		shuffle
   3420  * :On		numeric ascending
   3421  * :Onr, :Orn	numeric descending
   3422  */
   3423 static ApplyModifierResult
   3424 ApplyModifier_Order(const char **pp, ModChain *ch)
   3425 {
   3426 	const char *mod = *pp;
   3427 	SubstringWords words;
   3428 	int (*cmp)(const void *, const void *);
   3429 
   3430 	if (IsDelimiter(mod[1], ch)) {
   3431 		cmp = SubStrAsc;
   3432 		(*pp)++;
   3433 	} else if (IsDelimiter(mod[2], ch)) {
   3434 		if (mod[1] == 'n')
   3435 			cmp = SubNumAsc;
   3436 		else if (mod[1] == 'r')
   3437 			cmp = SubStrDesc;
   3438 		else if (mod[1] == 'x')
   3439 			cmp = NULL;
   3440 		else
   3441 			goto bad;
   3442 		*pp += 2;
   3443 	} else if (IsDelimiter(mod[3], ch)) {
   3444 		if ((mod[1] == 'n' && mod[2] == 'r') ||
   3445 		    (mod[1] == 'r' && mod[2] == 'n'))
   3446 			cmp = SubNumDesc;
   3447 		else
   3448 			goto bad;
   3449 		*pp += 3;
   3450 	} else
   3451 		goto bad;
   3452 
   3453 	if (!ModChain_ShouldEval(ch))
   3454 		return AMR_OK;
   3455 
   3456 	words = Expr_Words(ch->expr);
   3457 	if (cmp == NULL)
   3458 		ShuffleSubstrings(words.words, words.len);
   3459 	else {
   3460 		assert(words.words[0].end[0] == '\0');
   3461 		qsort(words.words, words.len, sizeof(words.words[0]), cmp);
   3462 	}
   3463 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3464 
   3465 	return AMR_OK;
   3466 
   3467 bad:
   3468 	(*pp)++;
   3469 	return AMR_BAD;
   3470 }
   3471 
   3472 /* :? then : else */
   3473 static ApplyModifierResult
   3474 ApplyModifier_IfElse(const char **pp, ModChain *ch)
   3475 {
   3476 	Expr *expr = ch->expr;
   3477 	LazyBuf thenBuf;
   3478 	LazyBuf elseBuf;
   3479 
   3480 	VarEvalMode then_emode = VARE_PARSE;
   3481 	VarEvalMode else_emode = VARE_PARSE;
   3482 
   3483 	CondResult cond_rc = CR_TRUE;	/* just not 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 	}
   3492 
   3493 	evalStack.elems[evalStack.len - 1].kind = VSK_COND_THEN;
   3494 	(*pp)++;		/* skip past the '?' */
   3495 	if (!ParseModifierPart(pp, ':', ':', then_emode,
   3496 	    ch, &thenBuf, NULL, NULL))
   3497 		return AMR_CLEANUP;
   3498 
   3499 	evalStack.elems[evalStack.len - 1].kind = VSK_COND_ELSE;
   3500 	if (!ParseModifierPart(pp, ch->endc, ch->endc, else_emode,
   3501 	    ch, &elseBuf, NULL, NULL)) {
   3502 		LazyBuf_Done(&thenBuf);
   3503 		return AMR_CLEANUP;
   3504 	}
   3505 
   3506 	(*pp)--;		/* Go back to the ch->endc. */
   3507 
   3508 	if (cond_rc == CR_ERROR) {
   3509 		evalStack.elems[evalStack.len - 1].kind = VSK_COND;
   3510 		Parse_Error(PARSE_FATAL, "Bad condition");
   3511 		LazyBuf_Done(&thenBuf);
   3512 		LazyBuf_Done(&elseBuf);
   3513 		return AMR_CLEANUP;
   3514 	}
   3515 
   3516 	if (!Expr_ShouldEval(expr)) {
   3517 		LazyBuf_Done(&thenBuf);
   3518 		LazyBuf_Done(&elseBuf);
   3519 	} else if (cond_rc == CR_TRUE) {
   3520 		Expr_SetValue(expr, LazyBuf_DoneGet(&thenBuf));
   3521 		LazyBuf_Done(&elseBuf);
   3522 	} else {
   3523 		LazyBuf_Done(&thenBuf);
   3524 		Expr_SetValue(expr, LazyBuf_DoneGet(&elseBuf));
   3525 	}
   3526 	Expr_Define(expr);
   3527 	return AMR_OK;
   3528 }
   3529 
   3530 /*
   3531  * The ::= modifiers are special in that they do not read the variable value
   3532  * but instead assign to that variable.  They always expand to an empty
   3533  * string.
   3534  *
   3535  * Their main purpose is in supporting .for loops that generate shell commands
   3536  * since an ordinary variable assignment at that point would terminate the
   3537  * dependency group for these targets.  For example:
   3538  *
   3539  * list-targets: .USE
   3540  * .for i in ${.TARGET} ${.TARGET:R}.gz
   3541  *	@${t::=$i}
   3542  *	@echo 'The target is ${t:T}.'
   3543  * .endfor
   3544  *
   3545  *	  ::=<str>	Assigns <str> as the new value of variable.
   3546  *	  ::?=<str>	Assigns <str> as value of variable if
   3547  *			it was not already set.
   3548  *	  ::+=<str>	Appends <str> to variable.
   3549  *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
   3550  *			variable.
   3551  */
   3552 static ApplyModifierResult
   3553 ApplyModifier_Assign(const char **pp, ModChain *ch)
   3554 {
   3555 	Expr *expr = ch->expr;
   3556 	GNode *scope;
   3557 	FStr val;
   3558 	LazyBuf buf;
   3559 
   3560 	const char *mod = *pp;
   3561 	const char *op = mod + 1;
   3562 
   3563 	if (op[0] == '=')
   3564 		goto found_op;
   3565 	if ((op[0] == '+' || op[0] == '?' || op[0] == '!') && op[1] == '=')
   3566 		goto found_op;
   3567 	return AMR_UNKNOWN;	/* "::<unrecognized>" */
   3568 
   3569 found_op:
   3570 	if (expr->name[0] == '\0') {
   3571 		*pp = mod + 1;
   3572 		return AMR_BAD;
   3573 	}
   3574 
   3575 	*pp = mod + (op[0] != '=' ? 3 : 2);
   3576 
   3577 	if (!ParseModifierPart(pp, ch->endc, ch->endc, expr->emode,
   3578 	    ch, &buf, NULL, NULL))
   3579 		return AMR_CLEANUP;
   3580 	val = LazyBuf_DoneGet(&buf);
   3581 
   3582 	(*pp)--;		/* Go back to the ch->endc. */
   3583 
   3584 	if (!Expr_ShouldEval(expr))
   3585 		goto done;
   3586 
   3587 	scope = expr->scope;	/* scope where v belongs */
   3588 	if (expr->defined == DEF_REGULAR && expr->scope != SCOPE_GLOBAL
   3589 	    && VarFind(expr->name, expr->scope, false) == NULL)
   3590 		scope = SCOPE_GLOBAL;
   3591 
   3592 	if (op[0] == '+')
   3593 		Var_Append(scope, expr->name, val.str);
   3594 	else if (op[0] == '!') {
   3595 		char *output, *error;
   3596 		output = Cmd_Exec(val.str, &error);
   3597 		if (error != NULL) {
   3598 			Parse_Error(PARSE_WARNING, "%s", error);
   3599 			free(error);
   3600 		} else
   3601 			Var_Set(scope, expr->name, output);
   3602 		free(output);
   3603 	} else if (op[0] == '?' && expr->defined == DEF_REGULAR) {
   3604 		/* Do nothing. */
   3605 	} else
   3606 		Var_Set(scope, expr->name, val.str);
   3607 
   3608 	Expr_SetValueRefer(expr, "");
   3609 
   3610 done:
   3611 	FStr_Done(&val);
   3612 	return AMR_OK;
   3613 }
   3614 
   3615 /*
   3616  * :_=...
   3617  * remember current value
   3618  */
   3619 static ApplyModifierResult
   3620 ApplyModifier_Remember(const char **pp, ModChain *ch)
   3621 {
   3622 	Expr *expr = ch->expr;
   3623 	const char *mod = *pp;
   3624 	FStr name;
   3625 
   3626 	if (!ModMatchEq(mod, "_", ch))
   3627 		return AMR_UNKNOWN;
   3628 
   3629 	name = FStr_InitRefer("_");
   3630 	if (mod[1] == '=') {
   3631 		/*
   3632 		 * XXX: This ad-hoc call to strcspn deviates from the usual
   3633 		 * behavior defined in ParseModifierPart.  This creates an
   3634 		 * unnecessary and undocumented inconsistency in make.
   3635 		 */
   3636 		const char *arg = mod + 2;
   3637 		size_t argLen = strcspn(arg, ":)}");
   3638 		*pp = arg + argLen;
   3639 		name = FStr_InitOwn(bmake_strldup(arg, argLen));
   3640 	} else
   3641 		*pp = mod + 1;
   3642 
   3643 	if (Expr_ShouldEval(expr))
   3644 		Var_Set(SCOPE_GLOBAL, name.str, Expr_Str(expr));
   3645 	FStr_Done(&name);
   3646 
   3647 	return AMR_OK;
   3648 }
   3649 
   3650 /*
   3651  * Apply the given function to each word of the variable value,
   3652  * for a single-letter modifier such as :H, :T.
   3653  */
   3654 static ApplyModifierResult
   3655 ApplyModifier_WordFunc(const char **pp, ModChain *ch,
   3656 		       ModifyWordProc modifyWord)
   3657 {
   3658 	if (!IsDelimiter((*pp)[1], ch))
   3659 		return AMR_UNKNOWN;
   3660 	(*pp)++;
   3661 
   3662 	ModifyWords(ch, modifyWord, NULL, ch->oneBigWord);
   3663 
   3664 	return AMR_OK;
   3665 }
   3666 
   3667 /* Remove adjacent duplicate words. */
   3668 static ApplyModifierResult
   3669 ApplyModifier_Unique(const char **pp, ModChain *ch)
   3670 {
   3671 	SubstringWords words;
   3672 
   3673 	if (!IsDelimiter((*pp)[1], ch))
   3674 		return AMR_UNKNOWN;
   3675 	(*pp)++;
   3676 
   3677 	if (!ModChain_ShouldEval(ch))
   3678 		return AMR_OK;
   3679 
   3680 	words = Expr_Words(ch->expr);
   3681 
   3682 	if (words.len > 1) {
   3683 		size_t di, si;
   3684 
   3685 		di = 0;
   3686 		for (si = 1; si < words.len; si++) {
   3687 			if (!Substring_Eq(words.words[si], words.words[di])) {
   3688 				di++;
   3689 				if (di != si)
   3690 					words.words[di] = words.words[si];
   3691 			}
   3692 		}
   3693 		words.len = di + 1;
   3694 	}
   3695 
   3696 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3697 
   3698 	return AMR_OK;
   3699 }
   3700 
   3701 /* Test whether the modifier has the form '<lhs>=<rhs>'. */
   3702 static bool
   3703 IsSysVModifier(const char *p, char startc, char endc)
   3704 {
   3705 	bool eqFound = false;
   3706 
   3707 	int depth = 1;
   3708 	while (*p != '\0' && depth > 0) {
   3709 		if (*p == '=')	/* XXX: should also test depth == 1 */
   3710 			eqFound = true;
   3711 		else if (*p == endc)
   3712 			depth--;
   3713 		else if (*p == startc)
   3714 			depth++;
   3715 		if (depth > 0)
   3716 			p++;
   3717 	}
   3718 	return *p == endc && eqFound;
   3719 }
   3720 
   3721 /* :from=to */
   3722 static ApplyModifierResult
   3723 ApplyModifier_SysV(const char **pp, ModChain *ch)
   3724 {
   3725 	Expr *expr = ch->expr;
   3726 	LazyBuf lhsBuf, rhsBuf;
   3727 	FStr rhs;
   3728 	struct ModifyWord_SysVSubstArgs args;
   3729 	Substring lhs;
   3730 	const char *lhsSuffix;
   3731 
   3732 	const char *mod = *pp;
   3733 
   3734 	if (!IsSysVModifier(mod, ch->startc, ch->endc))
   3735 		return AMR_UNKNOWN;
   3736 
   3737 	if (!ParseModifierPart(pp, '=', '=', expr->emode,
   3738 	    ch, &lhsBuf, NULL, NULL))
   3739 		return AMR_CLEANUP;
   3740 
   3741 	if (!ParseModifierPart(pp, ch->endc, ch->endc, expr->emode,
   3742 	    ch, &rhsBuf, NULL, NULL)) {
   3743 		LazyBuf_Done(&lhsBuf);
   3744 		return AMR_CLEANUP;
   3745 	}
   3746 	rhs = LazyBuf_DoneGet(&rhsBuf);
   3747 
   3748 	(*pp)--;		/* Go back to the ch->endc. */
   3749 
   3750 	/* Do not turn an empty expression into non-empty. */
   3751 	if (lhsBuf.len == 0 && Expr_Str(expr)[0] == '\0')
   3752 		goto done;
   3753 
   3754 	lhs = LazyBuf_Get(&lhsBuf);
   3755 	lhsSuffix = Substring_SkipFirst(lhs, '%');
   3756 
   3757 	args.scope = expr->scope;
   3758 	args.lhsPrefix = Substring_Init(lhs.start,
   3759 	    lhsSuffix != lhs.start ? lhsSuffix - 1 : lhs.start);
   3760 	args.lhsPercent = lhsSuffix != lhs.start;
   3761 	args.lhsSuffix = Substring_Init(lhsSuffix, lhs.end);
   3762 	args.rhs = rhs.str;
   3763 
   3764 	ModifyWords(ch, ModifyWord_SysVSubst, &args, ch->oneBigWord);
   3765 
   3766 done:
   3767 	LazyBuf_Done(&lhsBuf);
   3768 	FStr_Done(&rhs);
   3769 	return AMR_OK;
   3770 }
   3771 
   3772 /* :sh */
   3773 static ApplyModifierResult
   3774 ApplyModifier_SunShell(const char **pp, ModChain *ch)
   3775 {
   3776 	Expr *expr = ch->expr;
   3777 	const char *p = *pp;
   3778 	if (!(p[1] == 'h' && IsDelimiter(p[2], ch)))
   3779 		return AMR_UNKNOWN;
   3780 	*pp = p + 2;
   3781 
   3782 	if (Expr_ShouldEval(expr)) {
   3783 		char *output, *error;
   3784 		output = Cmd_Exec(Expr_Str(expr), &error);
   3785 		if (error != NULL) {
   3786 			Parse_Error(PARSE_WARNING, "%s", error);
   3787 			free(error);
   3788 		}
   3789 		Expr_SetValueOwn(expr, output);
   3790 	}
   3791 
   3792 	return AMR_OK;
   3793 }
   3794 
   3795 /*
   3796  * In cases where the evaluation mode and the definedness are the "standard"
   3797  * ones, don't log them, to keep the logs readable.
   3798  */
   3799 static bool
   3800 ShouldLogInSimpleFormat(const Expr *expr)
   3801 {
   3802 	return (expr->emode == VARE_EVAL || expr->emode == VARE_EVAL_DEFINED)
   3803 	    && expr->defined == DEF_REGULAR;
   3804 }
   3805 
   3806 static void
   3807 LogBeforeApply(const ModChain *ch, const char *mod)
   3808 {
   3809 	const Expr *expr = ch->expr;
   3810 	bool is_single_char = mod[0] != '\0' && IsDelimiter(mod[1], ch);
   3811 
   3812 	/*
   3813 	 * At this point, only the first character of the modifier can
   3814 	 * be used since the end of the modifier is not yet known.
   3815 	 */
   3816 
   3817 	if (!Expr_ShouldEval(expr)) {
   3818 		debug_printf("Parsing modifier ${%s:%c%s}\n",
   3819 		    expr->name, mod[0], is_single_char ? "" : "...");
   3820 		return;
   3821 	}
   3822 
   3823 	if (ShouldLogInSimpleFormat(expr)) {
   3824 		debug_printf(
   3825 		    "Evaluating modifier ${%s:%c%s} on value \"%s\"\n",
   3826 		    expr->name, mod[0], is_single_char ? "" : "...",
   3827 		    Expr_Str(expr));
   3828 		return;
   3829 	}
   3830 
   3831 	debug_printf(
   3832 	    "Evaluating modifier ${%s:%c%s} on value \"%s\" (%s, %s)\n",
   3833 	    expr->name, mod[0], is_single_char ? "" : "...", Expr_Str(expr),
   3834 	    VarEvalMode_Name[expr->emode], ExprDefined_Name[expr->defined]);
   3835 }
   3836 
   3837 static void
   3838 LogAfterApply(const ModChain *ch, const char *p, const char *mod)
   3839 {
   3840 	const Expr *expr = ch->expr;
   3841 	const char *value = Expr_Str(expr);
   3842 	const char *quot = value == var_Error ? "" : "\"";
   3843 
   3844 	if (ShouldLogInSimpleFormat(expr)) {
   3845 		debug_printf("Result of ${%s:%.*s} is %s%s%s\n",
   3846 		    expr->name, (int)(p - mod), mod,
   3847 		    quot, value == var_Error ? "error" : value, quot);
   3848 		return;
   3849 	}
   3850 
   3851 	debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s)\n",
   3852 	    expr->name, (int)(p - mod), mod,
   3853 	    quot, value == var_Error ? "error" : value, quot,
   3854 	    VarEvalMode_Name[expr->emode],
   3855 	    ExprDefined_Name[expr->defined]);
   3856 }
   3857 
   3858 static ApplyModifierResult
   3859 ApplyModifier(const char **pp, ModChain *ch)
   3860 {
   3861 	switch (**pp) {
   3862 	case '!':
   3863 		return ApplyModifier_ShellCommand(pp, ch);
   3864 	case ':':
   3865 		return ApplyModifier_Assign(pp, ch);
   3866 	case '?':
   3867 		return ApplyModifier_IfElse(pp, ch);
   3868 	case '@':
   3869 		return ApplyModifier_Loop(pp, ch);
   3870 	case '[':
   3871 		return ApplyModifier_Words(pp, ch);
   3872 	case '_':
   3873 		return ApplyModifier_Remember(pp, ch);
   3874 	case 'C':
   3875 		return ApplyModifier_Regex(pp, ch);
   3876 	case 'D':
   3877 	case 'U':
   3878 		return ApplyModifier_Defined(pp, ch);
   3879 	case 'E':
   3880 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Suffix);
   3881 	case 'g':
   3882 	case 'l':
   3883 		return ApplyModifier_Time(pp, ch);
   3884 	case 'H':
   3885 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Head);
   3886 	case 'h':
   3887 		return ApplyModifier_Hash(pp, ch);
   3888 	case 'L':
   3889 		return ApplyModifier_Literal(pp, ch);
   3890 	case 'M':
   3891 	case 'N':
   3892 		return ApplyModifier_Match(pp, ch);
   3893 	case 'm':
   3894 		return ApplyModifier_Mtime(pp, ch);
   3895 	case 'O':
   3896 		return ApplyModifier_Order(pp, ch);
   3897 	case 'P':
   3898 		return ApplyModifier_Path(pp, ch);
   3899 	case 'Q':
   3900 	case 'q':
   3901 		return ApplyModifier_Quote(pp, ch);
   3902 	case 'R':
   3903 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Root);
   3904 	case 'r':
   3905 		return ApplyModifier_Range(pp, ch);
   3906 	case 'S':
   3907 		return ApplyModifier_Subst(pp, ch);
   3908 	case 's':
   3909 		return ApplyModifier_SunShell(pp, ch);
   3910 	case 'T':
   3911 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Tail);
   3912 	case 't':
   3913 		return ApplyModifier_To(pp, ch);
   3914 	case 'u':
   3915 		return ApplyModifier_Unique(pp, ch);
   3916 	default:
   3917 		return AMR_UNKNOWN;
   3918 	}
   3919 }
   3920 
   3921 static void ApplyModifiers(Expr *, const char **, char, char);
   3922 
   3923 typedef enum ApplyModifiersIndirectResult {
   3924 	/* The indirect modifiers have been applied successfully. */
   3925 	AMIR_CONTINUE,
   3926 	/* Fall back to the SysV modifier. */
   3927 	AMIR_SYSV,
   3928 	/* Error out. */
   3929 	AMIR_OUT
   3930 } ApplyModifiersIndirectResult;
   3931 
   3932 /*
   3933  * While expanding an expression, expand and apply indirect modifiers,
   3934  * such as in ${VAR:${M_indirect}}.
   3935  *
   3936  * All indirect modifiers of a group must come from a single
   3937  * expression.  ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
   3938  *
   3939  * Multiple groups of indirect modifiers can be chained by separating them
   3940  * with colons.  ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
   3941  *
   3942  * If the expression is not followed by ch->endc or ':', fall
   3943  * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
   3944  */
   3945 static ApplyModifiersIndirectResult
   3946 ApplyModifiersIndirect(ModChain *ch, const char **pp)
   3947 {
   3948 	Expr *expr = ch->expr;
   3949 	const char *p = *pp;
   3950 	FStr mods = Var_Parse(&p, expr->scope, expr->emode);
   3951 	/* TODO: handle errors */
   3952 
   3953 	if (mods.str[0] != '\0' && !IsDelimiter(*p, ch)) {
   3954 		FStr_Done(&mods);
   3955 		return AMIR_SYSV;
   3956 	}
   3957 
   3958 	DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
   3959 	    mods.str, (int)(p - *pp), *pp);
   3960 
   3961 	if (ModChain_ShouldEval(ch) && mods.str[0] != '\0') {
   3962 		const char *modsp = mods.str;
   3963 		ApplyModifiers(expr, &modsp, '\0', '\0');
   3964 		if (Expr_Str(expr) == var_Error || *modsp != '\0') {
   3965 			FStr_Done(&mods);
   3966 			*pp = p;
   3967 			return AMIR_OUT;	/* error already reported */
   3968 		}
   3969 	}
   3970 	FStr_Done(&mods);
   3971 
   3972 	if (*p == ':')
   3973 		p++;
   3974 	else if (*p == '\0' && ch->endc != '\0') {
   3975 		Error("Unclosed expression after indirect modifier, "
   3976 		      "expecting '%c' for variable \"%s\"",
   3977 		    ch->endc, expr->name);
   3978 		*pp = p;
   3979 		return AMIR_OUT;
   3980 	}
   3981 
   3982 	*pp = p;
   3983 	return AMIR_CONTINUE;
   3984 }
   3985 
   3986 static ApplyModifierResult
   3987 ApplySingleModifier(const char **pp, ModChain *ch)
   3988 {
   3989 	ApplyModifierResult res;
   3990 	const char *mod = *pp;
   3991 	const char *p = *pp;
   3992 
   3993 	if (DEBUG(VAR))
   3994 		LogBeforeApply(ch, mod);
   3995 
   3996 	res = ApplyModifier(&p, ch);
   3997 
   3998 	if (res == AMR_UNKNOWN) {
   3999 		assert(p == mod);
   4000 		res = ApplyModifier_SysV(&p, ch);
   4001 	}
   4002 
   4003 	if (res == AMR_UNKNOWN) {
   4004 		/*
   4005 		 * Guess the end of the current modifier.
   4006 		 * XXX: Skipping the rest of the modifier hides
   4007 		 * errors and leads to wrong results.
   4008 		 * Parsing should rather stop here.
   4009 		 */
   4010 		for (p++; !IsDelimiter(*p, ch); p++)
   4011 			continue;
   4012 		Parse_Error(PARSE_FATAL, "Unknown modifier \"%.*s\"",
   4013 		    (int)(p - mod), mod);
   4014 		Expr_SetValueRefer(ch->expr, var_Error);
   4015 	}
   4016 	if (res == AMR_CLEANUP || res == AMR_BAD) {
   4017 		*pp = p;
   4018 		return res;
   4019 	}
   4020 
   4021 	if (DEBUG(VAR))
   4022 		LogAfterApply(ch, p, mod);
   4023 
   4024 	if (*p == '\0' && ch->endc != '\0') {
   4025 		Error(
   4026 		    "Unclosed expression, expecting '%c' for "
   4027 		    "modifier \"%.*s\" of variable \"%s\" with value \"%s\"",
   4028 		    ch->endc,
   4029 		    (int)(p - mod), mod,
   4030 		    ch->expr->name, Expr_Str(ch->expr));
   4031 	} else if (*p == ':') {
   4032 		p++;
   4033 	} else if (opts.strict && *p != '\0' && *p != ch->endc) {
   4034 		Parse_Error(PARSE_FATAL,
   4035 		    "Missing delimiter ':' after modifier \"%.*s\"",
   4036 		    (int)(p - mod), mod);
   4037 		/*
   4038 		 * TODO: propagate parse error to the enclosing
   4039 		 * expression
   4040 		 */
   4041 	}
   4042 	*pp = p;
   4043 	return AMR_OK;
   4044 }
   4045 
   4046 #if __STDC_VERSION__ >= 199901L
   4047 #define ModChain_Init(expr, startc, endc, sep, oneBigWord) \
   4048 	(ModChain) { expr, startc, endc, sep, oneBigWord }
   4049 #else
   4050 MAKE_INLINE ModChain
   4051 ModChain_Init(Expr *expr, char startc, char endc, char sep, bool oneBigWord)
   4052 {
   4053 	ModChain ch;
   4054 	ch.expr = expr;
   4055 	ch.startc = startc;
   4056 	ch.endc = endc;
   4057 	ch.sep = sep;
   4058 	ch.oneBigWord = oneBigWord;
   4059 	return ch;
   4060 }
   4061 #endif
   4062 
   4063 /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
   4064 static void
   4065 ApplyModifiers(
   4066     Expr *expr,
   4067     const char **pp,	/* the parsing position, updated upon return */
   4068     char startc,	/* '(' or '{'; or '\0' for indirect modifiers */
   4069     char endc		/* ')' or '}'; or '\0' for indirect modifiers */
   4070 )
   4071 {
   4072 	ModChain ch = ModChain_Init(expr, startc, endc, ' ', false);
   4073 	const char *p;
   4074 	const char *mod;
   4075 
   4076 	assert(startc == '(' || startc == '{' || startc == '\0');
   4077 	assert(endc == ')' || endc == '}' || endc == '\0');
   4078 	assert(Expr_Str(expr) != NULL);
   4079 
   4080 	p = *pp;
   4081 
   4082 	if (*p == '\0' && endc != '\0') {
   4083 		Error(
   4084 		    "Unclosed expression, expecting '%c' for \"%s\"",
   4085 		    ch.endc, expr->name);
   4086 		goto cleanup;
   4087 	}
   4088 
   4089 	while (*p != '\0' && *p != endc) {
   4090 		ApplyModifierResult res;
   4091 
   4092 		if (*p == '$') {
   4093 			/*
   4094 			 * TODO: Only evaluate the expression once, no matter
   4095 			 * whether it's an indirect modifier or the initial
   4096 			 * part of a SysV modifier.
   4097 			 */
   4098 			ApplyModifiersIndirectResult amir =
   4099 			    ApplyModifiersIndirect(&ch, &p);
   4100 			if (amir == AMIR_CONTINUE)
   4101 				continue;
   4102 			if (amir == AMIR_OUT)
   4103 				break;
   4104 		}
   4105 
   4106 		mod = p;
   4107 
   4108 		res = ApplySingleModifier(&p, &ch);
   4109 		if (res == AMR_CLEANUP)
   4110 			goto cleanup;
   4111 		if (res == AMR_BAD)
   4112 			goto bad_modifier;
   4113 	}
   4114 
   4115 	*pp = p;
   4116 	assert(Expr_Str(expr) != NULL);	/* Use var_Error or varUndefined. */
   4117 	return;
   4118 
   4119 bad_modifier:
   4120 	/* Take a guess at where the modifier ends. */
   4121 	Error("Bad modifier \":%.*s\" for variable \"%s\"",
   4122 	    (int)strcspn(mod, ":)}"), mod, expr->name);
   4123 
   4124 cleanup:
   4125 	/*
   4126 	 * TODO: Use p + strlen(p) instead, to stop parsing immediately.
   4127 	 *
   4128 	 * In the unit tests, this generates a few shell commands with
   4129 	 * unbalanced quotes.  Instead of producing these incomplete strings,
   4130 	 * commands with evaluation errors should not be run at all.
   4131 	 *
   4132 	 * To make that happen, Var_Subst must report the actual errors
   4133 	 * instead of returning the resulting string unconditionally.
   4134 	 */
   4135 	*pp = p;
   4136 	Expr_SetValueRefer(expr, var_Error);
   4137 }
   4138 
   4139 /*
   4140  * Only 4 of the 7 built-in local variables are treated specially as they are
   4141  * the only ones that will be set when dynamic sources are expanded.
   4142  */
   4143 static bool
   4144 VarnameIsDynamic(Substring varname)
   4145 {
   4146 	const char *name;
   4147 	size_t len;
   4148 
   4149 	name = varname.start;
   4150 	len = Substring_Length(varname);
   4151 	if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
   4152 		switch (name[0]) {
   4153 		case '@':
   4154 		case '%':
   4155 		case '*':
   4156 		case '!':
   4157 			return true;
   4158 		}
   4159 		return false;
   4160 	}
   4161 
   4162 	if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
   4163 		return Substring_Equals(varname, ".TARGET") ||
   4164 		       Substring_Equals(varname, ".ARCHIVE") ||
   4165 		       Substring_Equals(varname, ".PREFIX") ||
   4166 		       Substring_Equals(varname, ".MEMBER");
   4167 	}
   4168 
   4169 	return false;
   4170 }
   4171 
   4172 static const char *
   4173 UndefinedShortVarValue(char varname, const GNode *scope)
   4174 {
   4175 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
   4176 		/*
   4177 		 * If substituting a local variable in a non-local scope,
   4178 		 * assume it's for dynamic source stuff. We have to handle
   4179 		 * this specially and return the longhand for the variable
   4180 		 * with the dollar sign escaped so it makes it back to the
   4181 		 * caller. Only four of the local variables are treated
   4182 		 * specially as they are the only four that will be set
   4183 		 * when dynamic sources are expanded.
   4184 		 */
   4185 		switch (varname) {
   4186 		case '@':
   4187 			return "$(.TARGET)";
   4188 		case '%':
   4189 			return "$(.MEMBER)";
   4190 		case '*':
   4191 			return "$(.PREFIX)";
   4192 		case '!':
   4193 			return "$(.ARCHIVE)";
   4194 		}
   4195 	}
   4196 	return NULL;
   4197 }
   4198 
   4199 /*
   4200  * Parse a variable name, until the end character or a colon, whichever
   4201  * comes first.
   4202  */
   4203 static void
   4204 ParseVarname(const char **pp, char startc, char endc,
   4205 	     GNode *scope, VarEvalMode emode,
   4206 	     LazyBuf *buf)
   4207 {
   4208 	const char *p = *pp;
   4209 	int depth = 0;
   4210 
   4211 	LazyBuf_Init(buf, p);
   4212 
   4213 	while (*p != '\0') {
   4214 		if ((*p == endc || *p == ':') && depth == 0)
   4215 			break;
   4216 		if (*p == startc)
   4217 			depth++;
   4218 		if (*p == endc)
   4219 			depth--;
   4220 
   4221 		if (*p == '$') {
   4222 			FStr nested_val = Var_Parse(&p, scope, emode);
   4223 			/* TODO: handle errors */
   4224 			LazyBuf_AddStr(buf, nested_val.str);
   4225 			FStr_Done(&nested_val);
   4226 		} else {
   4227 			LazyBuf_Add(buf, *p);
   4228 			p++;
   4229 		}
   4230 	}
   4231 	*pp = p;
   4232 }
   4233 
   4234 static bool
   4235 IsShortVarnameValid(char varname, const char *start)
   4236 {
   4237 	if (varname != '$' && varname != ':' && varname != '}' &&
   4238 	    varname != ')' && varname != '\0')
   4239 		return true;
   4240 
   4241 	if (!opts.strict)
   4242 		return false;	/* XXX: Missing error message */
   4243 
   4244 	if (varname == '$' && save_dollars)
   4245 		Parse_Error(PARSE_FATAL,
   4246 		    "To escape a dollar, use \\$, not $$, at \"%s\"", start);
   4247 	else if (varname == '\0')
   4248 		Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
   4249 	else if (save_dollars)
   4250 		Parse_Error(PARSE_FATAL,
   4251 		    "Invalid variable name '%c', at \"%s\"", varname, start);
   4252 
   4253 	return false;
   4254 }
   4255 
   4256 /*
   4257  * Parse a single-character variable name such as in $V or $@.
   4258  * Return whether to continue parsing.
   4259  */
   4260 static bool
   4261 ParseVarnameShort(char varname, const char **pp, GNode *scope,
   4262 		  VarEvalMode emode,
   4263 		  const char **out_false_val,
   4264 		  Var **out_true_var)
   4265 {
   4266 	char name[2];
   4267 	Var *v;
   4268 	const char *val;
   4269 
   4270 	if (!IsShortVarnameValid(varname, *pp)) {
   4271 		(*pp)++;	/* only skip the '$' */
   4272 		*out_false_val = var_Error;
   4273 		return false;
   4274 	}
   4275 
   4276 	name[0] = varname;
   4277 	name[1] = '\0';
   4278 	v = VarFind(name, scope, true);
   4279 	if (v != NULL) {
   4280 		/* No need to advance *pp, the calling code handles this. */
   4281 		*out_true_var = v;
   4282 		return true;
   4283 	}
   4284 
   4285 	*pp += 2;
   4286 
   4287 	val = UndefinedShortVarValue(varname, scope);
   4288 	if (val == NULL)
   4289 		val = emode == VARE_EVAL_DEFINED ? var_Error : varUndefined;
   4290 
   4291 	if (opts.strict && val == var_Error) {
   4292 		Parse_Error(PARSE_FATAL,
   4293 		    "Variable \"%s\" is undefined", name);
   4294 	}
   4295 
   4296 	*out_false_val = val;
   4297 	return false;
   4298 }
   4299 
   4300 /* Find variables like @F or <D. */
   4301 static Var *
   4302 FindLocalLegacyVar(Substring varname, GNode *scope,
   4303 		   const char **out_extraModifiers)
   4304 {
   4305 	Var *v;
   4306 
   4307 	/* Only resolve these variables if scope is a "real" target. */
   4308 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
   4309 		return NULL;
   4310 
   4311 	if (Substring_Length(varname) != 2)
   4312 		return NULL;
   4313 	if (varname.start[1] != 'F' && varname.start[1] != 'D')
   4314 		return NULL;
   4315 	if (strchr("@%?*!<>", varname.start[0]) == NULL)
   4316 		return NULL;
   4317 
   4318 	v = VarFindSubstring(Substring_Init(varname.start, varname.start + 1),
   4319 	    scope, false);
   4320 	if (v == NULL)
   4321 		return NULL;
   4322 
   4323 	*out_extraModifiers = varname.start[1] == 'D' ? "H:" : "T:";
   4324 	return v;
   4325 }
   4326 
   4327 static FStr
   4328 EvalUndefined(bool dynamic, const char *start, const char *p,
   4329 	      Substring varname, VarEvalMode emode)
   4330 {
   4331 	if (dynamic)
   4332 		return FStr_InitOwn(bmake_strsedup(start, p));
   4333 
   4334 	if (emode == VARE_EVAL_DEFINED && opts.strict) {
   4335 		Parse_Error(PARSE_FATAL,
   4336 		    "Variable \"%.*s\" is undefined",
   4337 		    (int)Substring_Length(varname), varname.start);
   4338 		return FStr_InitRefer(var_Error);
   4339 	}
   4340 
   4341 	return FStr_InitRefer(
   4342 	    emode == VARE_EVAL_DEFINED ? var_Error : varUndefined);
   4343 }
   4344 
   4345 /*
   4346  * Parse a long variable name enclosed in braces or parentheses such as $(VAR)
   4347  * or ${VAR}, up to the closing brace or parenthesis, or in the case of
   4348  * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
   4349  * Return whether to continue parsing.
   4350  */
   4351 static bool
   4352 ParseVarnameLong(
   4353 	const char **pp,
   4354 	char startc,
   4355 	GNode *scope,
   4356 	VarEvalMode emode,
   4357 
   4358 	const char **out_false_pp,
   4359 	FStr *out_false_val,
   4360 
   4361 	char *out_true_endc,
   4362 	Var **out_true_v,
   4363 	bool *out_true_haveModifier,
   4364 	const char **out_true_extraModifiers,
   4365 	bool *out_true_dynamic,
   4366 	ExprDefined *out_true_exprDefined
   4367 )
   4368 {
   4369 	LazyBuf varname;
   4370 	Substring name;
   4371 	Var *v;
   4372 	bool haveModifier;
   4373 	bool dynamic = false;
   4374 
   4375 	const char *p = *pp;
   4376 	const char *start = p;
   4377 	char endc = startc == '(' ? ')' : '}';
   4378 
   4379 	p += 2;			/* skip "${" or "$(" or "y(" */
   4380 	ParseVarname(&p, startc, endc, scope, emode, &varname);
   4381 	name = LazyBuf_Get(&varname);
   4382 
   4383 	if (*p == ':')
   4384 		haveModifier = true;
   4385 	else if (*p == endc)
   4386 		haveModifier = false;
   4387 	else {
   4388 		Parse_Error(PARSE_FATAL, "Unclosed variable \"%.*s\"",
   4389 		    (int)Substring_Length(name), name.start);
   4390 		LazyBuf_Done(&varname);
   4391 		*out_false_pp = p;
   4392 		*out_false_val = FStr_InitRefer(var_Error);
   4393 		return false;
   4394 	}
   4395 
   4396 	v = VarFindSubstring(name, scope, true);
   4397 
   4398 	/*
   4399 	 * At this point, p points just after the variable name, either at
   4400 	 * ':' or at endc.
   4401 	 */
   4402 
   4403 	if (v == NULL && Substring_Equals(name, ".SUFFIXES")) {
   4404 		char *suffixes = Suff_NamesStr();
   4405 		v = VarNew(FStr_InitRefer(".SUFFIXES"), suffixes,
   4406 		    true, false, true);
   4407 		free(suffixes);
   4408 	} else if (v == NULL)
   4409 		v = FindLocalLegacyVar(name, scope, out_true_extraModifiers);
   4410 
   4411 	if (v == NULL) {
   4412 		/*
   4413 		 * Defer expansion of dynamic variables if they appear in
   4414 		 * non-local scope since they are not defined there.
   4415 		 */
   4416 		dynamic = VarnameIsDynamic(name) &&
   4417 			  (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
   4418 
   4419 		if (!haveModifier) {
   4420 			p++;	/* skip endc */
   4421 			*out_false_pp = p;
   4422 			*out_false_val = EvalUndefined(dynamic, start, p,
   4423 			    name, emode);
   4424 			LazyBuf_Done(&varname);
   4425 			return false;
   4426 		}
   4427 
   4428 		/*
   4429 		 * The expression is based on an undefined variable.
   4430 		 * Nevertheless it needs a Var, for modifiers that access the
   4431 		 * variable name, such as :L or :?.
   4432 		 *
   4433 		 * Most modifiers leave this expression in the "undefined"
   4434 		 * state (DEF_UNDEF), only a few modifiers like :D, :U, :L,
   4435 		 * :P turn this undefined expression into a defined
   4436 		 * expression (DEF_DEFINED).
   4437 		 *
   4438 		 * In the end, after applying all modifiers, if the expression
   4439 		 * is still undefined, Var_Parse will return an empty string
   4440 		 * instead of the actually computed value.
   4441 		 */
   4442 		v = VarNew(LazyBuf_DoneGet(&varname), "",
   4443 		    true, false, false);
   4444 		*out_true_exprDefined = DEF_UNDEF;
   4445 	} else
   4446 		LazyBuf_Done(&varname);
   4447 
   4448 	*pp = p;
   4449 	*out_true_endc = endc;
   4450 	*out_true_v = v;
   4451 	*out_true_haveModifier = haveModifier;
   4452 	*out_true_dynamic = dynamic;
   4453 	return true;
   4454 }
   4455 
   4456 #if __STDC_VERSION__ >= 199901L
   4457 #define Expr_Init(name, value, emode, scope, defined) \
   4458 	(Expr) { name, value, emode, scope, defined }
   4459 #else
   4460 MAKE_INLINE Expr
   4461 Expr_Init(const char *name, FStr value,
   4462 	  VarEvalMode emode, GNode *scope, ExprDefined defined)
   4463 {
   4464 	Expr expr;
   4465 
   4466 	expr.name = name;
   4467 	expr.value = value;
   4468 	expr.emode = emode;
   4469 	expr.scope = scope;
   4470 	expr.defined = defined;
   4471 	return expr;
   4472 }
   4473 #endif
   4474 
   4475 /*
   4476  * Expressions of the form ${:U...} with a trivial value are often generated
   4477  * by .for loops and are boring, so evaluate them without debug logging.
   4478  */
   4479 static bool
   4480 Var_Parse_U(const char **pp, VarEvalMode emode, FStr *out_value)
   4481 {
   4482 	const char *p;
   4483 
   4484 	p = *pp;
   4485 	if (!(p[0] == '$' && p[1] == '{' && p[2] == ':' && p[3] == 'U'))
   4486 		return false;
   4487 
   4488 	p += 4;
   4489 	while (*p != '$' && *p != '{' && *p != ':' && *p != '\\' &&
   4490 	       *p != '}' && *p != '\0')
   4491 		p++;
   4492 	if (*p != '}')
   4493 		return false;
   4494 
   4495 	*out_value = emode == VARE_PARSE
   4496 	    ? FStr_InitRefer("")
   4497 	    : FStr_InitOwn(bmake_strsedup(*pp + 4, p));
   4498 	*pp = p + 1;
   4499 	return true;
   4500 }
   4501 
   4502 /*
   4503  * Given the start of an expression (such as $v, $(VAR), ${VAR:Mpattern}),
   4504  * extract the variable name and the modifiers, if any.  While parsing, apply
   4505  * the modifiers to the value of the expression.
   4506  *
   4507  * Input:
   4508  *	*pp		The string to parse.
   4509  *			When called from CondParser_FuncCallEmpty, it can
   4510  *			also point to the "y" of "empty(VARNAME:Modifiers)".
   4511  *	scope		The scope for finding variables.
   4512  *	emode		Controls the exact details of parsing and evaluation.
   4513  *
   4514  * Output:
   4515  *	*pp		The position where to continue parsing.
   4516  *			TODO: After a parse error, the value of *pp is
   4517  *			unspecified.  It may not have been updated at all,
   4518  *			point to some random character in the string, to the
   4519  *			location of the parse error, or at the end of the
   4520  *			string.
   4521  *	return		The value of the expression, never NULL.
   4522  *	return		var_Error if there was a parse error.
   4523  *	return		var_Error if the base variable of the expression was
   4524  *			undefined, emode is VARE_EVAL_DEFINED, and none of
   4525  *			the modifiers turned the undefined expression into a
   4526  *			defined expression.
   4527  *			XXX: It is not guaranteed that an error message has
   4528  *			been printed.
   4529  *	return		varUndefined if the base variable of the expression
   4530  *			was undefined, emode was not VARE_EVAL_DEFINED,
   4531  *			and none of the modifiers turned the undefined
   4532  *			expression into a defined expression.
   4533  *			XXX: It is not guaranteed that an error message has
   4534  *			been printed.
   4535  */
   4536 FStr
   4537 Var_Parse(const char **pp, GNode *scope, VarEvalMode emode)
   4538 {
   4539 	const char *start, *p;
   4540 	bool haveModifier;	/* true for ${VAR:...}, false for ${VAR} */
   4541 	char startc;		/* the actual '{' or '(' or '\0' */
   4542 	char endc;		/* the expected '}' or ')' or '\0' */
   4543 	/*
   4544 	 * true if the expression is based on one of the 7 predefined
   4545 	 * variables that are local to a target, and the expression is
   4546 	 * expanded in a non-local scope.  The result is the text of the
   4547 	 * expression, unaltered.  This is needed to support dynamic sources.
   4548 	 */
   4549 	bool dynamic;
   4550 	const char *extramodifiers;
   4551 	Var *v;
   4552 	Expr expr = Expr_Init(NULL, FStr_InitRefer(NULL), emode,
   4553 	    scope, DEF_REGULAR);
   4554 	FStr val;
   4555 
   4556 	if (Var_Parse_U(pp, emode, &val))
   4557 		return val;
   4558 
   4559 	p = *pp;
   4560 	start = p;
   4561 	DEBUG2(VAR, "Var_Parse: %s (%s)\n", start, VarEvalMode_Name[emode]);
   4562 
   4563 	val = FStr_InitRefer(NULL);
   4564 	extramodifiers = NULL;	/* extra modifiers to apply first */
   4565 	dynamic = false;
   4566 
   4567 	endc = '\0';		/* Appease GCC. */
   4568 
   4569 	startc = p[1];
   4570 	if (startc != '(' && startc != '{') {
   4571 		if (!ParseVarnameShort(startc, pp, scope, emode, &val.str, &v))
   4572 			return val;
   4573 		haveModifier = false;
   4574 		p++;
   4575 	} else {
   4576 		if (!ParseVarnameLong(&p, startc, scope, emode,
   4577 		    pp, &val,
   4578 		    &endc, &v, &haveModifier, &extramodifiers,
   4579 		    &dynamic, &expr.defined))
   4580 			return val;
   4581 	}
   4582 
   4583 	expr.name = v->name.str;
   4584 	if (v->inUse && VarEvalMode_ShouldEval(emode)) {
   4585 		if (scope->fname != NULL) {
   4586 			fprintf(stderr, "In a command near ");
   4587 			PrintLocation(stderr, false, scope);
   4588 		}
   4589 		Fatal("Variable %s is recursive.", v->name.str);
   4590 	}
   4591 
   4592 	/*
   4593 	 * FIXME: This assignment creates an alias to the current value of the
   4594 	 * variable.  This means that as long as the value of the expression
   4595 	 * stays the same, the value of the variable must not change, and the
   4596 	 * variable must not be deleted.  Using the ':@' modifier, it is
   4597 	 * possible (since var.c 1.212 from 2017-02-01) to delete the variable
   4598 	 * while its value is still being used:
   4599 	 *
   4600 	 *	VAR=	value
   4601 	 *	_:=	${VAR:${:U:@VAR@@}:S,^,prefix,}
   4602 	 *
   4603 	 * The same effect might be achievable using the '::=' or the ':_'
   4604 	 * modifiers.
   4605 	 *
   4606 	 * At the bottom of this function, the resulting value is compared to
   4607 	 * the then-current value of the variable.  This might also invoke
   4608 	 * undefined behavior.
   4609 	 */
   4610 	expr.value = FStr_InitRefer(v->val.data);
   4611 
   4612 	if (expr.name[0] != '\0')
   4613 		EvalStack_Push(VSK_VARNAME, expr.name, &expr.value);
   4614 	else
   4615 		EvalStack_Push(VSK_EXPR, start, NULL);
   4616 
   4617 	/*
   4618 	 * Before applying any modifiers, expand any nested expressions from
   4619 	 * the variable value.
   4620 	 */
   4621 	if (VarEvalMode_ShouldEval(emode) &&
   4622 	    strchr(Expr_Str(&expr), '$') != NULL) {
   4623 		char *expanded;
   4624 		VarEvalMode nested_emode = emode;
   4625 		if (opts.strict)
   4626 			nested_emode = VarEvalMode_UndefOk(nested_emode);
   4627 		v->inUse = true;
   4628 		expanded = Var_Subst(Expr_Str(&expr), scope, nested_emode);
   4629 		v->inUse = false;
   4630 		/* TODO: handle errors */
   4631 		Expr_SetValueOwn(&expr, expanded);
   4632 	}
   4633 
   4634 	if (extramodifiers != NULL) {
   4635 		const char *em = extramodifiers;
   4636 		ApplyModifiers(&expr, &em, '\0', '\0');
   4637 	}
   4638 
   4639 	if (haveModifier) {
   4640 		p++;		/* Skip initial colon. */
   4641 		ApplyModifiers(&expr, &p, startc, endc);
   4642 	}
   4643 
   4644 	if (*p != '\0')		/* Skip past endc if possible. */
   4645 		p++;
   4646 
   4647 	*pp = p;
   4648 
   4649 	if (expr.defined == DEF_UNDEF) {
   4650 		if (dynamic)
   4651 			Expr_SetValueOwn(&expr, bmake_strsedup(start, p));
   4652 		else {
   4653 			/*
   4654 			 * The expression is still undefined, therefore
   4655 			 * discard the actual value and return an error marker
   4656 			 * instead.
   4657 			 */
   4658 			Expr_SetValueRefer(&expr,
   4659 			    emode == VARE_EVAL_DEFINED
   4660 				? var_Error : varUndefined);
   4661 		}
   4662 	}
   4663 
   4664 	if (v->shortLived) {
   4665 		if (expr.value.str == v->val.data) {
   4666 			/* move ownership */
   4667 			expr.value.freeIt = v->val.data;
   4668 			v->val.data = NULL;
   4669 		}
   4670 		VarFreeShortLived(v);
   4671 	}
   4672 
   4673 	EvalStack_Pop();
   4674 	return expr.value;
   4675 }
   4676 
   4677 static void
   4678 VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalMode emode)
   4679 {
   4680 	/* A dollar sign may be escaped with another dollar sign. */
   4681 	if (save_dollars && VarEvalMode_ShouldKeepDollar(emode))
   4682 		Buf_AddByte(res, '$');
   4683 	Buf_AddByte(res, '$');
   4684 	*pp += 2;
   4685 }
   4686 
   4687 static void
   4688 VarSubstExpr(const char **pp, Buffer *buf, GNode *scope,
   4689 	     VarEvalMode emode, bool *inout_errorReported)
   4690 {
   4691 	const char *p = *pp;
   4692 	const char *nested_p = p;
   4693 	FStr val = Var_Parse(&nested_p, scope, emode);
   4694 	/* TODO: handle errors */
   4695 
   4696 	if (val.str == var_Error || val.str == varUndefined) {
   4697 		if (!VarEvalMode_ShouldKeepUndef(emode)) {
   4698 			p = nested_p;
   4699 		} else if (val.str == var_Error) {
   4700 
   4701 			/*
   4702 			 * FIXME: The condition 'val.str == var_Error' doesn't
   4703 			 * mean there was an undefined variable.  It could
   4704 			 * equally well be a parse error; see
   4705 			 * unit-tests/varmod-order.mk.
   4706 			 */
   4707 
   4708 			/*
   4709 			 * If variable is undefined, complain and skip the
   4710 			 * variable. The complaint will stop us from doing
   4711 			 * anything when the file is parsed.
   4712 			 */
   4713 			if (!*inout_errorReported) {
   4714 				Parse_Error(PARSE_FATAL,
   4715 				    "Undefined variable \"%.*s\"",
   4716 				    (int)(nested_p - p), p);
   4717 				*inout_errorReported = true;
   4718 			}
   4719 			p = nested_p;
   4720 		} else {
   4721 			/*
   4722 			 * Copy the initial '$' of the undefined expression,
   4723 			 * thereby deferring expansion of the expression, but
   4724 			 * expand nested expressions if already possible. See
   4725 			 * unit-tests/varparse-undef-partial.mk.
   4726 			 */
   4727 			Buf_AddByte(buf, *p);
   4728 			p++;
   4729 		}
   4730 	} else {
   4731 		p = nested_p;
   4732 		Buf_AddStr(buf, val.str);
   4733 	}
   4734 
   4735 	FStr_Done(&val);
   4736 
   4737 	*pp = p;
   4738 }
   4739 
   4740 /*
   4741  * Skip as many characters as possible -- either to the end of the string,
   4742  * or to the next dollar sign, which may start an expression.
   4743  */
   4744 static void
   4745 VarSubstPlain(const char **pp, Buffer *res)
   4746 {
   4747 	const char *p = *pp;
   4748 	const char *start = p;
   4749 
   4750 	for (p++; *p != '$' && *p != '\0'; p++)
   4751 		continue;
   4752 	Buf_AddRange(res, start, p);
   4753 	*pp = p;
   4754 }
   4755 
   4756 /*
   4757  * Expand all expressions like $V, ${VAR}, $(VAR:Modifiers) in the
   4758  * given string.
   4759  *
   4760  * Input:
   4761  *	str		The string in which the expressions are expanded.
   4762  *	scope		The scope in which to start searching for variables.
   4763  *			The other scopes are searched as well.
   4764  *	emode		The mode for parsing or evaluating subexpressions.
   4765  */
   4766 char *
   4767 Var_Subst(const char *str, GNode *scope, VarEvalMode emode)
   4768 {
   4769 	const char *p = str;
   4770 	Buffer res;
   4771 
   4772 	/*
   4773 	 * Set true if an error has already been reported, to prevent a
   4774 	 * plethora of messages when recursing
   4775 	 */
   4776 	static bool errorReported;
   4777 
   4778 	Buf_Init(&res);
   4779 	errorReported = false;
   4780 
   4781 	while (*p != '\0') {
   4782 		if (p[0] == '$' && p[1] == '$')
   4783 			VarSubstDollarDollar(&p, &res, emode);
   4784 		else if (p[0] == '$')
   4785 			VarSubstExpr(&p, &res, scope, emode, &errorReported);
   4786 		else
   4787 			VarSubstPlain(&p, &res);
   4788 	}
   4789 
   4790 	return Buf_DoneData(&res);
   4791 }
   4792 
   4793 char *
   4794 Var_SubstInTarget(const char *str, GNode *scope)
   4795 {
   4796 	char *res;
   4797 	EvalStack_Push(VSK_TARGET, scope->name, NULL);
   4798 	res = Var_Subst(str, scope, VARE_EVAL);
   4799 	EvalStack_Pop();
   4800 	return res;
   4801 }
   4802 
   4803 void
   4804 Var_Expand(FStr *str, GNode *scope, VarEvalMode emode)
   4805 {
   4806 	char *expanded;
   4807 
   4808 	if (strchr(str->str, '$') == NULL)
   4809 		return;
   4810 	expanded = Var_Subst(str->str, scope, emode);
   4811 	/* TODO: handle errors */
   4812 	FStr_Done(str);
   4813 	*str = FStr_InitOwn(expanded);
   4814 }
   4815 
   4816 /* Initialize the variables module. */
   4817 void
   4818 Var_Init(void)
   4819 {
   4820 	SCOPE_INTERNAL = GNode_New("Internal");
   4821 	SCOPE_GLOBAL = GNode_New("Global");
   4822 	SCOPE_CMDLINE = GNode_New("Command");
   4823 }
   4824 
   4825 /* Clean up the variables module. */
   4826 void
   4827 Var_End(void)
   4828 {
   4829 	Var_Stats();
   4830 }
   4831 
   4832 void
   4833 Var_Stats(void)
   4834 {
   4835 	HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables");
   4836 }
   4837 
   4838 static int
   4839 StrAsc(const void *sa, const void *sb)
   4840 {
   4841 	return strcmp(
   4842 	    *((const char *const *)sa), *((const char *const *)sb));
   4843 }
   4844 
   4845 
   4846 /* Print all variables in a scope, sorted by name. */
   4847 void
   4848 Var_Dump(GNode *scope)
   4849 {
   4850 	Vector /* of const char * */ vec;
   4851 	HashIter hi;
   4852 	size_t i;
   4853 	const char **varnames;
   4854 
   4855 	Vector_Init(&vec, sizeof(const char *));
   4856 
   4857 	HashIter_Init(&hi, &scope->vars);
   4858 	while (HashIter_Next(&hi))
   4859 		*(const char **)Vector_Push(&vec) = hi.entry->key;
   4860 	varnames = vec.items;
   4861 
   4862 	qsort(varnames, vec.len, sizeof varnames[0], StrAsc);
   4863 
   4864 	for (i = 0; i < vec.len; i++) {
   4865 		const char *varname = varnames[i];
   4866 		const Var *var = HashTable_FindValue(&scope->vars, varname);
   4867 		debug_printf("%-16s = %s%s\n", varname,
   4868 		    var->val.data, ValueDescription(var->val.data));
   4869 	}
   4870 
   4871 	Vector_Done(&vec);
   4872 }
   4873