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