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