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