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