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