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