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