Home | History | Annotate | Line # | Download | only in make
var.c revision 1.890
      1 /*	$NetBSD: var.c,v 1.890 2021/03/15 19:15:04 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.890 2021/03/15 19:15:04 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 st->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  * st->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 st->expr->value, or the variable name from st->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 chain whenever an indirect modifier starts or ends.
   2066  *
   2067  * For example, the expression ${VAR:M*:${IND1}:${IND2}:O:u} has 4 chains of
   2068  * modifiers:
   2069  *
   2070  *	Chain 1 is ':M*', consisting of the single modifier ':M*'.
   2071  *	Chain 2 is all modifiers from the value of the variable named 'IND1'.
   2072  *	Chain 3 is all modifiers from the value of the variable named 'IND2'.
   2073  *	Chain 4 is ':O:u', consisting of the 2 modifiers ':O' and ':u'.
   2074  *
   2075  * After such a chain has finished, its properties no longer have any effect.
   2076  *
   2077  * It may or may not have been intended that 'defined' has scope Expr while
   2078  * 'sep' and 'oneBigWord' have smaller scope.
   2079  *
   2080  * See varmod-indirect.mk.
   2081  */
   2082 typedef struct ApplyModifiersState {
   2083 	Expr *expr;
   2084 	/* '\0' or '{' or '(' */
   2085 	const char startc;
   2086 	/* '\0' or '}' or ')' */
   2087 	const char endc;
   2088 	/* Word separator in expansions (see the :ts modifier). */
   2089 	char sep;
   2090 	/*
   2091 	 * TRUE if some modifiers that otherwise split the variable value
   2092 	 * into words, like :S and :C, treat the variable value as a single
   2093 	 * big word, possibly containing spaces.
   2094 	 */
   2095 	Boolean oneBigWord;
   2096 } ApplyModifiersState;
   2097 
   2098 static void
   2099 Expr_Define(Expr *expr)
   2100 {
   2101 	if (expr->defined == DEF_UNDEF)
   2102 		expr->defined = DEF_DEFINED;
   2103 }
   2104 
   2105 static void
   2106 Expr_SetValueOwn(Expr *expr, char *value)
   2107 {
   2108 	FStr_Done(&expr->value);
   2109 	expr->value = FStr_InitOwn(value);
   2110 }
   2111 
   2112 static void
   2113 Expr_SetValueRefer(Expr *expr, const char *value)
   2114 {
   2115 	FStr_Done(&expr->value);
   2116 	expr->value = FStr_InitRefer(value);
   2117 }
   2118 
   2119 typedef enum ApplyModifierResult {
   2120 	/* Continue parsing */
   2121 	AMR_OK,
   2122 	/* Not a match, try other modifiers as well. */
   2123 	AMR_UNKNOWN,
   2124 	/* Error out with "Bad modifier" message. */
   2125 	AMR_BAD,
   2126 	/* Error out without the standard error message. */
   2127 	AMR_CLEANUP
   2128 } ApplyModifierResult;
   2129 
   2130 /*
   2131  * Allow backslashes to escape the delimiter, $, and \, but don't touch other
   2132  * backslashes.
   2133  */
   2134 static Boolean
   2135 IsEscapedModifierPart(const char *p, char delim,
   2136 		      struct ModifyWord_SubstArgs *subst)
   2137 {
   2138 	if (p[0] != '\\')
   2139 		return FALSE;
   2140 	if (p[1] == delim || p[1] == '\\' || p[1] == '$')
   2141 		return TRUE;
   2142 	return p[1] == '&' && subst != NULL;
   2143 }
   2144 
   2145 /* See ParseModifierPart */
   2146 static VarParseResult
   2147 ParseModifierPartSubst(
   2148     const char **pp,
   2149     char delim,
   2150     VarEvalFlags eflags,
   2151     ApplyModifiersState *st,
   2152     char **out_part,
   2153     /* Optionally stores the length of the returned string, just to save
   2154      * another strlen call. */
   2155     size_t *out_length,
   2156     /* For the first part of the :S modifier, sets the VARP_ANCHOR_END flag
   2157      * if the last character of the pattern is a $. */
   2158     VarPatternFlags *out_pflags,
   2159     /* For the second part of the :S modifier, allow ampersands to be
   2160      * escaped and replace unescaped ampersands with subst->lhs. */
   2161     struct ModifyWord_SubstArgs *subst
   2162 )
   2163 {
   2164 	Buffer buf;
   2165 	const char *p;
   2166 
   2167 	Buf_Init(&buf);
   2168 
   2169 	/*
   2170 	 * Skim through until the matching delimiter is found; pick up
   2171 	 * variable expressions on the way.
   2172 	 */
   2173 	p = *pp;
   2174 	while (*p != '\0' && *p != delim) {
   2175 		const char *varstart;
   2176 
   2177 		if (IsEscapedModifierPart(p, delim, subst)) {
   2178 			Buf_AddByte(&buf, p[1]);
   2179 			p += 2;
   2180 			continue;
   2181 		}
   2182 
   2183 		if (*p != '$') {	/* Unescaped, simple text */
   2184 			if (subst != NULL && *p == '&')
   2185 				Buf_AddBytes(&buf, subst->lhs, subst->lhsLen);
   2186 			else
   2187 				Buf_AddByte(&buf, *p);
   2188 			p++;
   2189 			continue;
   2190 		}
   2191 
   2192 		if (p[1] == delim) {	/* Unescaped $ at end of pattern */
   2193 			if (out_pflags != NULL)
   2194 				out_pflags->anchorEnd = TRUE;
   2195 			else
   2196 				Buf_AddByte(&buf, *p);
   2197 			p++;
   2198 			continue;
   2199 		}
   2200 
   2201 		if (eflags.wantRes) {	/* Nested variable, evaluated */
   2202 			const char *nested_p = p;
   2203 			FStr nested_val;
   2204 			VarEvalFlags nested_eflags = eflags;
   2205 			nested_eflags.keepDollar = FALSE;
   2206 
   2207 			(void)Var_Parse(&nested_p, st->expr->scope,
   2208 			    nested_eflags, &nested_val);
   2209 			/* TODO: handle errors */
   2210 			Buf_AddStr(&buf, nested_val.str);
   2211 			FStr_Done(&nested_val);
   2212 			p += nested_p - p;
   2213 			continue;
   2214 		}
   2215 
   2216 		/*
   2217 		 * XXX: This whole block is very similar to Var_Parse without
   2218 		 * VarEvalFlags.wantRes.  There may be subtle edge cases
   2219 		 * though that are not yet covered in the unit tests and that
   2220 		 * are parsed differently, depending on whether they are
   2221 		 * evaluated or not.
   2222 		 *
   2223 		 * This subtle difference is not documented in the manual
   2224 		 * page, neither is the difference between parsing :D and
   2225 		 * :M documented. No code should ever depend on these
   2226 		 * details, but who knows.
   2227 		 */
   2228 
   2229 		varstart = p;	/* Nested variable, only parsed */
   2230 		if (p[1] == '(' || p[1] == '{') {
   2231 			/*
   2232 			 * Find the end of this variable reference
   2233 			 * and suck it in without further ado.
   2234 			 * It will be interpreted later.
   2235 			 */
   2236 			char startc = p[1];
   2237 			int endc = startc == '(' ? ')' : '}';
   2238 			int depth = 1;
   2239 
   2240 			for (p += 2; *p != '\0' && depth > 0; p++) {
   2241 				if (p[-1] != '\\') {
   2242 					if (*p == startc)
   2243 						depth++;
   2244 					if (*p == endc)
   2245 						depth--;
   2246 				}
   2247 			}
   2248 			Buf_AddBytesBetween(&buf, varstart, p);
   2249 		} else {
   2250 			Buf_AddByte(&buf, *varstart);
   2251 			p++;
   2252 		}
   2253 	}
   2254 
   2255 	if (*p != delim) {
   2256 		*pp = p;
   2257 		Error("Unfinished modifier for \"%s\" ('%c' missing)",
   2258 		    st->expr->var->name.str, delim);
   2259 		*out_part = NULL;
   2260 		return VPR_ERR;
   2261 	}
   2262 
   2263 	*pp = p + 1;
   2264 	if (out_length != NULL)
   2265 		*out_length = buf.len;
   2266 
   2267 	*out_part = Buf_DoneData(&buf);
   2268 	DEBUG1(VAR, "Modifier part: \"%s\"\n", *out_part);
   2269 	return VPR_OK;
   2270 }
   2271 
   2272 /*
   2273  * Parse a part of a modifier such as the "from" and "to" in :S/from/to/ or
   2274  * the "var" or "replacement ${var}" in :@var@replacement ${var}@, up to and
   2275  * including the next unescaped delimiter.  The delimiter, as well as the
   2276  * backslash or the dollar, can be escaped with a backslash.
   2277  *
   2278  * Return the parsed (and possibly expanded) string, or NULL if no delimiter
   2279  * was found.  On successful return, the parsing position pp points right
   2280  * after the delimiter.  The delimiter is not included in the returned
   2281  * value though.
   2282  */
   2283 static VarParseResult
   2284 ParseModifierPart(
   2285     /* The parsing position, updated upon return */
   2286     const char **pp,
   2287     /* Parsing stops at this delimiter */
   2288     char delim,
   2289     /* Flags for evaluating nested variables. */
   2290     VarEvalFlags eflags,
   2291     ApplyModifiersState *st,
   2292     char **out_part
   2293 )
   2294 {
   2295 	return ParseModifierPartSubst(pp, delim, eflags, st, out_part,
   2296 	    NULL, NULL, NULL);
   2297 }
   2298 
   2299 MAKE_INLINE Boolean
   2300 IsDelimiter(char ch, const ApplyModifiersState *st)
   2301 {
   2302 	return ch == ':' || ch == st->endc;
   2303 }
   2304 
   2305 /* Test whether mod starts with modname, followed by a delimiter. */
   2306 MAKE_INLINE Boolean
   2307 ModMatch(const char *mod, const char *modname, const ApplyModifiersState *st)
   2308 {
   2309 	size_t n = strlen(modname);
   2310 	return strncmp(mod, modname, n) == 0 && IsDelimiter(mod[n], st);
   2311 }
   2312 
   2313 /* Test whether mod starts with modname, followed by a delimiter or '='. */
   2314 MAKE_INLINE Boolean
   2315 ModMatchEq(const char *mod, const char *modname, const ApplyModifiersState *st)
   2316 {
   2317 	size_t n = strlen(modname);
   2318 	return strncmp(mod, modname, n) == 0 &&
   2319 	       (IsDelimiter(mod[n], st) || mod[n] == '=');
   2320 }
   2321 
   2322 static Boolean
   2323 TryParseIntBase0(const char **pp, int *out_num)
   2324 {
   2325 	char *end;
   2326 	long n;
   2327 
   2328 	errno = 0;
   2329 	n = strtol(*pp, &end, 0);
   2330 
   2331 	if (end == *pp)
   2332 		return FALSE;
   2333 	if ((n == LONG_MIN || n == LONG_MAX) && errno == ERANGE)
   2334 		return FALSE;
   2335 	if (n < INT_MIN || n > INT_MAX)
   2336 		return FALSE;
   2337 
   2338 	*pp = end;
   2339 	*out_num = (int)n;
   2340 	return TRUE;
   2341 }
   2342 
   2343 static Boolean
   2344 TryParseSize(const char **pp, size_t *out_num)
   2345 {
   2346 	char *end;
   2347 	unsigned long n;
   2348 
   2349 	if (!ch_isdigit(**pp))
   2350 		return FALSE;
   2351 
   2352 	errno = 0;
   2353 	n = strtoul(*pp, &end, 10);
   2354 	if (n == ULONG_MAX && errno == ERANGE)
   2355 		return FALSE;
   2356 	if (n > SIZE_MAX)
   2357 		return FALSE;
   2358 
   2359 	*pp = end;
   2360 	*out_num = (size_t)n;
   2361 	return TRUE;
   2362 }
   2363 
   2364 static Boolean
   2365 TryParseChar(const char **pp, int base, char *out_ch)
   2366 {
   2367 	char *end;
   2368 	unsigned long n;
   2369 
   2370 	if (!ch_isalnum(**pp))
   2371 		return FALSE;
   2372 
   2373 	errno = 0;
   2374 	n = strtoul(*pp, &end, base);
   2375 	if (n == ULONG_MAX && errno == ERANGE)
   2376 		return FALSE;
   2377 	if (n > UCHAR_MAX)
   2378 		return FALSE;
   2379 
   2380 	*pp = end;
   2381 	*out_ch = (char)n;
   2382 	return TRUE;
   2383 }
   2384 
   2385 /*
   2386  * Modify each word of the expression using the given function and place the
   2387  * result back in the expression.
   2388  */
   2389 static void
   2390 ModifyWords(ApplyModifiersState *st,
   2391 	    ModifyWordProc modifyWord, void *modifyWord_args,
   2392 	    Boolean oneBigWord)
   2393 {
   2394 	Expr *expr = st->expr;
   2395 	const char *val = expr->value.str;
   2396 	SepBuf result;
   2397 	Words words;
   2398 	size_t i;
   2399 
   2400 	if (oneBigWord) {
   2401 		SepBuf_Init(&result, st->sep);
   2402 		modifyWord(val, &result, modifyWord_args);
   2403 		goto done;
   2404 	}
   2405 
   2406 	words = Str_Words(val, FALSE);
   2407 
   2408 	DEBUG2(VAR, "ModifyWords: split \"%s\" into %u words\n",
   2409 	    val, (unsigned)words.len);
   2410 
   2411 	SepBuf_Init(&result, st->sep);
   2412 	for (i = 0; i < words.len; i++) {
   2413 		modifyWord(words.words[i], &result, modifyWord_args);
   2414 		if (result.buf.len > 0)
   2415 			SepBuf_Sep(&result);
   2416 	}
   2417 
   2418 	Words_Free(words);
   2419 
   2420 done:
   2421 	Expr_SetValueOwn(expr, SepBuf_DoneData(&result));
   2422 }
   2423 
   2424 /* :@var (at) ...${var}...@ */
   2425 static ApplyModifierResult
   2426 ApplyModifier_Loop(const char **pp, ApplyModifiersState *st)
   2427 {
   2428 	Expr *expr = st->expr;
   2429 	struct ModifyWord_LoopArgs args;
   2430 	char prev_sep;
   2431 	VarParseResult res;
   2432 
   2433 	args.scope = expr->scope;
   2434 
   2435 	(*pp)++;		/* Skip the first '@' */
   2436 	res = ParseModifierPart(pp, '@', VARE_PARSE_ONLY, st, &args.tvar);
   2437 	if (res != VPR_OK)
   2438 		return AMR_CLEANUP;
   2439 	if (opts.strict && strchr(args.tvar, '$') != NULL) {
   2440 		Parse_Error(PARSE_FATAL,
   2441 		    "In the :@ modifier of \"%s\", the variable name \"%s\" "
   2442 		    "must not contain a dollar.",
   2443 		    expr->var->name.str, args.tvar);
   2444 		return AMR_CLEANUP;
   2445 	}
   2446 
   2447 	res = ParseModifierPart(pp, '@', VARE_PARSE_ONLY, st, &args.str);
   2448 	if (res != VPR_OK)
   2449 		return AMR_CLEANUP;
   2450 
   2451 	if (!expr->eflags.wantRes)
   2452 		goto done;
   2453 
   2454 	args.eflags = expr->eflags;
   2455 	args.eflags.keepDollar = FALSE;
   2456 	prev_sep = st->sep;
   2457 	st->sep = ' ';		/* XXX: should be st->sep for consistency */
   2458 	ModifyWords(st, ModifyWord_Loop, &args, st->oneBigWord);
   2459 	st->sep = prev_sep;
   2460 	/* XXX: Consider restoring the previous variable instead of deleting. */
   2461 	/*
   2462 	 * XXX: The variable name should not be expanded here, see
   2463 	 * ModifyWord_Loop.
   2464 	 */
   2465 	Var_DeleteExpand(expr->scope, args.tvar);
   2466 
   2467 done:
   2468 	free(args.tvar);
   2469 	free(args.str);
   2470 	return AMR_OK;
   2471 }
   2472 
   2473 /* :Ddefined or :Uundefined */
   2474 static ApplyModifierResult
   2475 ApplyModifier_Defined(const char **pp, ApplyModifiersState *st)
   2476 {
   2477 	Expr *expr = st->expr;
   2478 	Buffer buf;
   2479 	const char *p;
   2480 
   2481 	VarEvalFlags eflags = VARE_PARSE_ONLY;
   2482 	if (expr->eflags.wantRes)
   2483 		if ((**pp == 'D') == (expr->defined == DEF_REGULAR))
   2484 			eflags = expr->eflags;
   2485 
   2486 	Buf_Init(&buf);
   2487 	p = *pp + 1;
   2488 	while (!IsDelimiter(*p, st) && *p != '\0') {
   2489 
   2490 		/* XXX: This code is similar to the one in Var_Parse.
   2491 		 * See if the code can be merged.
   2492 		 * See also ApplyModifier_Match and ParseModifierPart. */
   2493 
   2494 		/* Escaped delimiter or other special character */
   2495 		/* See Buf_AddEscaped in for.c. */
   2496 		if (*p == '\\') {
   2497 			char c = p[1];
   2498 			if (IsDelimiter(c, st) || c == '$' || c == '\\') {
   2499 				Buf_AddByte(&buf, c);
   2500 				p += 2;
   2501 				continue;
   2502 			}
   2503 		}
   2504 
   2505 		/* Nested variable expression */
   2506 		if (*p == '$') {
   2507 			FStr nested_val;
   2508 
   2509 			(void)Var_Parse(&p, expr->scope, eflags, &nested_val);
   2510 			/* TODO: handle errors */
   2511 			if (expr->eflags.wantRes)
   2512 				Buf_AddStr(&buf, nested_val.str);
   2513 			FStr_Done(&nested_val);
   2514 			continue;
   2515 		}
   2516 
   2517 		/* Ordinary text */
   2518 		Buf_AddByte(&buf, *p);
   2519 		p++;
   2520 	}
   2521 	*pp = p;
   2522 
   2523 	Expr_Define(expr);
   2524 
   2525 	if (eflags.wantRes)
   2526 		Expr_SetValueOwn(expr, Buf_DoneData(&buf));
   2527 	else
   2528 		Buf_Done(&buf);
   2529 
   2530 	return AMR_OK;
   2531 }
   2532 
   2533 /* :L */
   2534 static ApplyModifierResult
   2535 ApplyModifier_Literal(const char **pp, ApplyModifiersState *st)
   2536 {
   2537 	Expr *expr = st->expr;
   2538 
   2539 	(*pp)++;
   2540 
   2541 	if (expr->eflags.wantRes) {
   2542 		Expr_Define(expr);
   2543 		Expr_SetValueOwn(expr, bmake_strdup(expr->var->name.str));
   2544 	}
   2545 
   2546 	return AMR_OK;
   2547 }
   2548 
   2549 static Boolean
   2550 TryParseTime(const char **pp, time_t *out_time)
   2551 {
   2552 	char *end;
   2553 	unsigned long n;
   2554 
   2555 	if (!ch_isdigit(**pp))
   2556 		return FALSE;
   2557 
   2558 	errno = 0;
   2559 	n = strtoul(*pp, &end, 10);
   2560 	if (n == ULONG_MAX && errno == ERANGE)
   2561 		return FALSE;
   2562 
   2563 	*pp = end;
   2564 	*out_time = (time_t)n;	/* ignore possible truncation for now */
   2565 	return TRUE;
   2566 }
   2567 
   2568 /* :gmtime */
   2569 static ApplyModifierResult
   2570 ApplyModifier_Gmtime(const char **pp, ApplyModifiersState *st)
   2571 {
   2572 	time_t utc;
   2573 
   2574 	const char *mod = *pp;
   2575 	if (!ModMatchEq(mod, "gmtime", st))
   2576 		return AMR_UNKNOWN;
   2577 
   2578 	if (mod[6] == '=') {
   2579 		const char *p = mod + 7;
   2580 		if (!TryParseTime(&p, &utc)) {
   2581 			Parse_Error(PARSE_FATAL,
   2582 			    "Invalid time value: %s", mod + 7);
   2583 			return AMR_CLEANUP;
   2584 		}
   2585 		*pp = p;
   2586 	} else {
   2587 		utc = 0;
   2588 		*pp = mod + 6;
   2589 	}
   2590 
   2591 	if (st->expr->eflags.wantRes)
   2592 		Expr_SetValueOwn(st->expr,
   2593 		    VarStrftime(st->expr->value.str, TRUE, utc));
   2594 
   2595 	return AMR_OK;
   2596 }
   2597 
   2598 /* :localtime */
   2599 static ApplyModifierResult
   2600 ApplyModifier_Localtime(const char **pp, ApplyModifiersState *st)
   2601 {
   2602 	time_t utc;
   2603 
   2604 	const char *mod = *pp;
   2605 	if (!ModMatchEq(mod, "localtime", st))
   2606 		return AMR_UNKNOWN;
   2607 
   2608 	if (mod[9] == '=') {
   2609 		const char *p = mod + 10;
   2610 		if (!TryParseTime(&p, &utc)) {
   2611 			Parse_Error(PARSE_FATAL,
   2612 			    "Invalid time value: %s", mod + 10);
   2613 			return AMR_CLEANUP;
   2614 		}
   2615 		*pp = p;
   2616 	} else {
   2617 		utc = 0;
   2618 		*pp = mod + 9;
   2619 	}
   2620 
   2621 	if (st->expr->eflags.wantRes)
   2622 		Expr_SetValueOwn(st->expr,
   2623 		    VarStrftime(st->expr->value.str, FALSE, utc));
   2624 
   2625 	return AMR_OK;
   2626 }
   2627 
   2628 /* :hash */
   2629 static ApplyModifierResult
   2630 ApplyModifier_Hash(const char **pp, ApplyModifiersState *st)
   2631 {
   2632 	if (!ModMatch(*pp, "hash", st))
   2633 		return AMR_UNKNOWN;
   2634 	*pp += 4;
   2635 
   2636 	if (st->expr->eflags.wantRes)
   2637 		Expr_SetValueOwn(st->expr, VarHash(st->expr->value.str));
   2638 
   2639 	return AMR_OK;
   2640 }
   2641 
   2642 /* :P */
   2643 static ApplyModifierResult
   2644 ApplyModifier_Path(const char **pp, ApplyModifiersState *st)
   2645 {
   2646 	Expr *expr = st->expr;
   2647 	GNode *gn;
   2648 	char *path;
   2649 
   2650 	(*pp)++;
   2651 
   2652 	if (!st->expr->eflags.wantRes)
   2653 		return AMR_OK;
   2654 
   2655 	Expr_Define(expr);
   2656 
   2657 	gn = Targ_FindNode(expr->var->name.str);
   2658 	if (gn == NULL || gn->type & OP_NOPATH) {
   2659 		path = NULL;
   2660 	} else if (gn->path != NULL) {
   2661 		path = bmake_strdup(gn->path);
   2662 	} else {
   2663 		SearchPath *searchPath = Suff_FindPath(gn);
   2664 		path = Dir_FindFile(expr->var->name.str, searchPath);
   2665 	}
   2666 	if (path == NULL)
   2667 		path = bmake_strdup(expr->var->name.str);
   2668 	Expr_SetValueOwn(expr, path);
   2669 
   2670 	return AMR_OK;
   2671 }
   2672 
   2673 /* :!cmd! */
   2674 static ApplyModifierResult
   2675 ApplyModifier_ShellCommand(const char **pp, ApplyModifiersState *st)
   2676 {
   2677 	Expr *expr = st->expr;
   2678 	char *cmd;
   2679 	const char *errfmt;
   2680 	VarParseResult res;
   2681 
   2682 	(*pp)++;
   2683 	res = ParseModifierPart(pp, '!', expr->eflags, st, &cmd);
   2684 	if (res != VPR_OK)
   2685 		return AMR_CLEANUP;
   2686 
   2687 	errfmt = NULL;
   2688 	if (expr->eflags.wantRes)
   2689 		Expr_SetValueOwn(expr, Cmd_Exec(cmd, &errfmt));
   2690 	else
   2691 		Expr_SetValueRefer(expr, "");
   2692 	if (errfmt != NULL)
   2693 		Error(errfmt, cmd);	/* XXX: why still return AMR_OK? */
   2694 	free(cmd);
   2695 	Expr_Define(expr);
   2696 
   2697 	return AMR_OK;
   2698 }
   2699 
   2700 /*
   2701  * The :range modifier generates an integer sequence as long as the words.
   2702  * The :range=7 modifier generates an integer sequence from 1 to 7.
   2703  */
   2704 static ApplyModifierResult
   2705 ApplyModifier_Range(const char **pp, ApplyModifiersState *st)
   2706 {
   2707 	size_t n;
   2708 	Buffer buf;
   2709 	size_t i;
   2710 
   2711 	const char *mod = *pp;
   2712 	if (!ModMatchEq(mod, "range", st))
   2713 		return AMR_UNKNOWN;
   2714 
   2715 	if (mod[5] == '=') {
   2716 		const char *p = mod + 6;
   2717 		if (!TryParseSize(&p, &n)) {
   2718 			Parse_Error(PARSE_FATAL,
   2719 			    "Invalid number \"%s\" for ':range' modifier",
   2720 			    mod + 6);
   2721 			return AMR_CLEANUP;
   2722 		}
   2723 		*pp = p;
   2724 	} else {
   2725 		n = 0;
   2726 		*pp = mod + 5;
   2727 	}
   2728 
   2729 	if (!st->expr->eflags.wantRes)
   2730 		return AMR_OK;
   2731 
   2732 	if (n == 0) {
   2733 		Words words = Str_Words(st->expr->value.str, FALSE);
   2734 		n = words.len;
   2735 		Words_Free(words);
   2736 	}
   2737 
   2738 	Buf_Init(&buf);
   2739 
   2740 	for (i = 0; i < n; i++) {
   2741 		if (i != 0) {
   2742 			/* XXX: Use st->sep instead of ' ', for consistency. */
   2743 			Buf_AddByte(&buf, ' ');
   2744 		}
   2745 		Buf_AddInt(&buf, 1 + (int)i);
   2746 	}
   2747 
   2748 	Expr_SetValueOwn(st->expr, Buf_DoneData(&buf));
   2749 	return AMR_OK;
   2750 }
   2751 
   2752 /* Parse a ':M' or ':N' modifier. */
   2753 static void
   2754 ParseModifier_Match(const char **pp, const ApplyModifiersState *st,
   2755 		    char **out_pattern)
   2756 {
   2757 	const char *mod = *pp;
   2758 	Expr *expr = st->expr;
   2759 	Boolean copy = FALSE;	/* pattern should be, or has been, copied */
   2760 	Boolean needSubst = FALSE;
   2761 	const char *endpat;
   2762 	char *pattern;
   2763 
   2764 	/*
   2765 	 * In the loop below, ignore ':' unless we are at (or back to) the
   2766 	 * original brace level.
   2767 	 * XXX: This will likely not work right if $() and ${} are intermixed.
   2768 	 */
   2769 	/*
   2770 	 * XXX: This code is similar to the one in Var_Parse.
   2771 	 * See if the code can be merged.
   2772 	 * See also ApplyModifier_Defined.
   2773 	 */
   2774 	int nest = 0;
   2775 	const char *p;
   2776 	for (p = mod + 1; *p != '\0' && !(*p == ':' && nest == 0); p++) {
   2777 		if (*p == '\\' &&
   2778 		    (IsDelimiter(p[1], st) || p[1] == st->startc)) {
   2779 			if (!needSubst)
   2780 				copy = TRUE;
   2781 			p++;
   2782 			continue;
   2783 		}
   2784 		if (*p == '$')
   2785 			needSubst = TRUE;
   2786 		if (*p == '(' || *p == '{')
   2787 			nest++;
   2788 		if (*p == ')' || *p == '}') {
   2789 			nest--;
   2790 			if (nest < 0)
   2791 				break;
   2792 		}
   2793 	}
   2794 	*pp = p;
   2795 	endpat = p;
   2796 
   2797 	if (copy) {
   2798 		char *dst;
   2799 		const char *src;
   2800 
   2801 		/* Compress the \:'s out of the pattern. */
   2802 		pattern = bmake_malloc((size_t)(endpat - (mod + 1)) + 1);
   2803 		dst = pattern;
   2804 		src = mod + 1;
   2805 		for (; src < endpat; src++, dst++) {
   2806 			if (src[0] == '\\' && src + 1 < endpat &&
   2807 			    /* XXX: st->startc is missing here; see above */
   2808 			    IsDelimiter(src[1], st))
   2809 				src++;
   2810 			*dst = *src;
   2811 		}
   2812 		*dst = '\0';
   2813 	} else {
   2814 		pattern = bmake_strsedup(mod + 1, endpat);
   2815 	}
   2816 
   2817 	if (needSubst) {
   2818 		char *old_pattern = pattern;
   2819 		(void)Var_Subst(pattern, expr->scope, expr->eflags, &pattern);
   2820 		/* TODO: handle errors */
   2821 		free(old_pattern);
   2822 	}
   2823 
   2824 	DEBUG3(VAR, "Pattern[%s] for [%s] is [%s]\n",
   2825 	    expr->var->name.str, expr->value.str, pattern);
   2826 
   2827 	*out_pattern = pattern;
   2828 }
   2829 
   2830 /* :Mpattern or :Npattern */
   2831 static ApplyModifierResult
   2832 ApplyModifier_Match(const char **pp, ApplyModifiersState *st)
   2833 {
   2834 	const char mod = **pp;
   2835 	char *pattern;
   2836 
   2837 	ParseModifier_Match(pp, st, &pattern);
   2838 
   2839 	if (st->expr->eflags.wantRes) {
   2840 		ModifyWordProc modifyWord =
   2841 		    mod == 'M' ? ModifyWord_Match : ModifyWord_NoMatch;
   2842 		ModifyWords(st, modifyWord, pattern, st->oneBigWord);
   2843 	}
   2844 
   2845 	free(pattern);
   2846 	return AMR_OK;
   2847 }
   2848 
   2849 static void
   2850 ParsePatternFlags(const char **pp, VarPatternFlags *pflags, Boolean *oneBigWord)
   2851 {
   2852 	for (;; (*pp)++) {
   2853 		if (**pp == 'g')
   2854 			pflags->subGlobal = TRUE;
   2855 		else if (**pp == '1')
   2856 			pflags->subOnce = TRUE;
   2857 		else if (**pp == 'W')
   2858 			*oneBigWord = TRUE;
   2859 		else
   2860 			break;
   2861 	}
   2862 }
   2863 
   2864 /* :S,from,to, */
   2865 static ApplyModifierResult
   2866 ApplyModifier_Subst(const char **pp, ApplyModifiersState *st)
   2867 {
   2868 	struct ModifyWord_SubstArgs args;
   2869 	char *lhs, *rhs;
   2870 	Boolean oneBigWord;
   2871 	VarParseResult res;
   2872 
   2873 	char delim = (*pp)[1];
   2874 	if (delim == '\0') {
   2875 		Error("Missing delimiter for modifier ':S'");
   2876 		(*pp)++;
   2877 		return AMR_CLEANUP;
   2878 	}
   2879 
   2880 	*pp += 2;
   2881 
   2882 	args.pflags = (VarPatternFlags){ FALSE, FALSE, FALSE, FALSE };
   2883 	args.matched = FALSE;
   2884 
   2885 	if (**pp == '^') {
   2886 		args.pflags.anchorStart = TRUE;
   2887 		(*pp)++;
   2888 	}
   2889 
   2890 	res = ParseModifierPartSubst(pp, delim, st->expr->eflags, st, &lhs,
   2891 	    &args.lhsLen, &args.pflags, NULL);
   2892 	if (res != VPR_OK)
   2893 		return AMR_CLEANUP;
   2894 	args.lhs = lhs;
   2895 
   2896 	res = ParseModifierPartSubst(pp, delim, st->expr->eflags, st, &rhs,
   2897 	    &args.rhsLen, NULL, &args);
   2898 	if (res != VPR_OK)
   2899 		return AMR_CLEANUP;
   2900 	args.rhs = rhs;
   2901 
   2902 	oneBigWord = st->oneBigWord;
   2903 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   2904 
   2905 	ModifyWords(st, ModifyWord_Subst, &args, oneBigWord);
   2906 
   2907 	free(lhs);
   2908 	free(rhs);
   2909 	return AMR_OK;
   2910 }
   2911 
   2912 #ifndef NO_REGEX
   2913 
   2914 /* :C,from,to, */
   2915 static ApplyModifierResult
   2916 ApplyModifier_Regex(const char **pp, ApplyModifiersState *st)
   2917 {
   2918 	char *re;
   2919 	struct ModifyWord_SubstRegexArgs args;
   2920 	Boolean oneBigWord;
   2921 	int error;
   2922 	VarParseResult res;
   2923 
   2924 	char delim = (*pp)[1];
   2925 	if (delim == '\0') {
   2926 		Error("Missing delimiter for :C modifier");
   2927 		(*pp)++;
   2928 		return AMR_CLEANUP;
   2929 	}
   2930 
   2931 	*pp += 2;
   2932 
   2933 	res = ParseModifierPart(pp, delim, st->expr->eflags, st, &re);
   2934 	if (res != VPR_OK)
   2935 		return AMR_CLEANUP;
   2936 
   2937 	res = ParseModifierPart(pp, delim, st->expr->eflags, st, &args.replace);
   2938 	if (args.replace == NULL) {
   2939 		free(re);
   2940 		return AMR_CLEANUP;
   2941 	}
   2942 
   2943 	args.pflags = (VarPatternFlags){ FALSE, FALSE, FALSE, FALSE };
   2944 	args.matched = FALSE;
   2945 	oneBigWord = st->oneBigWord;
   2946 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   2947 
   2948 	if (!(st->expr->eflags.wantRes)) {
   2949 		free(args.replace);
   2950 		free(re);
   2951 		return AMR_OK;
   2952 	}
   2953 
   2954 	error = regcomp(&args.re, re, REG_EXTENDED);
   2955 	free(re);
   2956 	if (error != 0) {
   2957 		VarREError(error, &args.re, "Regex compilation error");
   2958 		free(args.replace);
   2959 		return AMR_CLEANUP;
   2960 	}
   2961 
   2962 	args.nsub = args.re.re_nsub + 1;
   2963 	if (args.nsub > 10)
   2964 		args.nsub = 10;
   2965 
   2966 	ModifyWords(st, ModifyWord_SubstRegex, &args, oneBigWord);
   2967 
   2968 	regfree(&args.re);
   2969 	free(args.replace);
   2970 	return AMR_OK;
   2971 }
   2972 
   2973 #endif
   2974 
   2975 /* :Q, :q */
   2976 static ApplyModifierResult
   2977 ApplyModifier_Quote(const char **pp, ApplyModifiersState *st)
   2978 {
   2979 	Boolean quoteDollar = **pp == 'q';
   2980 	if (!IsDelimiter((*pp)[1], st))
   2981 		return AMR_UNKNOWN;
   2982 	(*pp)++;
   2983 
   2984 	if (st->expr->eflags.wantRes)
   2985 		Expr_SetValueOwn(st->expr,
   2986 		    VarQuote(st->expr->value.str, quoteDollar));
   2987 
   2988 	return AMR_OK;
   2989 }
   2990 
   2991 /*ARGSUSED*/
   2992 static void
   2993 ModifyWord_Copy(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   2994 {
   2995 	SepBuf_AddStr(buf, word);
   2996 }
   2997 
   2998 /* :ts<separator> */
   2999 static ApplyModifierResult
   3000 ApplyModifier_ToSep(const char **pp, ApplyModifiersState *st)
   3001 {
   3002 	const char *sep = *pp + 2;
   3003 
   3004 	/*
   3005 	 * Even in parse-only mode, proceed as normal since there is
   3006 	 * neither any observable side effect nor a performance penalty.
   3007 	 * Checking for wantRes for every single piece of code in here
   3008 	 * would make the code in this function too hard to read.
   3009 	 */
   3010 
   3011 	/* ":ts<any><endc>" or ":ts<any>:" */
   3012 	if (sep[0] != st->endc && IsDelimiter(sep[1], st)) {
   3013 		*pp = sep + 1;
   3014 		st->sep = sep[0];
   3015 		goto ok;
   3016 	}
   3017 
   3018 	/* ":ts<endc>" or ":ts:" */
   3019 	if (IsDelimiter(sep[0], st)) {
   3020 		*pp = sep;
   3021 		st->sep = '\0';	/* no separator */
   3022 		goto ok;
   3023 	}
   3024 
   3025 	/* ":ts<unrecognised><unrecognised>". */
   3026 	if (sep[0] != '\\') {
   3027 		(*pp)++;	/* just for backwards compatibility */
   3028 		return AMR_BAD;
   3029 	}
   3030 
   3031 	/* ":ts\n" */
   3032 	if (sep[1] == 'n') {
   3033 		*pp = sep + 2;
   3034 		st->sep = '\n';
   3035 		goto ok;
   3036 	}
   3037 
   3038 	/* ":ts\t" */
   3039 	if (sep[1] == 't') {
   3040 		*pp = sep + 2;
   3041 		st->sep = '\t';
   3042 		goto ok;
   3043 	}
   3044 
   3045 	/* ":ts\x40" or ":ts\100" */
   3046 	{
   3047 		const char *p = sep + 1;
   3048 		int base = 8;	/* assume octal */
   3049 
   3050 		if (sep[1] == 'x') {
   3051 			base = 16;
   3052 			p++;
   3053 		} else if (!ch_isdigit(sep[1])) {
   3054 			(*pp)++;	/* just for backwards compatibility */
   3055 			return AMR_BAD;	/* ":ts<backslash><unrecognised>". */
   3056 		}
   3057 
   3058 		if (!TryParseChar(&p, base, &st->sep)) {
   3059 			Parse_Error(PARSE_FATAL,
   3060 			    "Invalid character number: %s", p);
   3061 			return AMR_CLEANUP;
   3062 		}
   3063 		if (!IsDelimiter(*p, st)) {
   3064 			(*pp)++;	/* just for backwards compatibility */
   3065 			return AMR_BAD;
   3066 		}
   3067 
   3068 		*pp = p;
   3069 	}
   3070 
   3071 ok:
   3072 	ModifyWords(st, ModifyWord_Copy, NULL, st->oneBigWord);
   3073 	return AMR_OK;
   3074 }
   3075 
   3076 static char *
   3077 str_toupper(const char *str)
   3078 {
   3079 	char *res;
   3080 	size_t i, len;
   3081 
   3082 	len = strlen(str);
   3083 	res = bmake_malloc(len + 1);
   3084 	for (i = 0; i < len + 1; i++)
   3085 		res[i] = ch_toupper(str[i]);
   3086 
   3087 	return res;
   3088 }
   3089 
   3090 static char *
   3091 str_tolower(const char *str)
   3092 {
   3093 	char *res;
   3094 	size_t i, len;
   3095 
   3096 	len = strlen(str);
   3097 	res = bmake_malloc(len + 1);
   3098 	for (i = 0; i < len + 1; i++)
   3099 		res[i] = ch_tolower(str[i]);
   3100 
   3101 	return res;
   3102 }
   3103 
   3104 /* :tA, :tu, :tl, :ts<separator>, etc. */
   3105 static ApplyModifierResult
   3106 ApplyModifier_To(const char **pp, ApplyModifiersState *st)
   3107 {
   3108 	Expr *expr = st->expr;
   3109 	const char *mod = *pp;
   3110 	assert(mod[0] == 't');
   3111 
   3112 	if (IsDelimiter(mod[1], st) || mod[1] == '\0') {
   3113 		*pp = mod + 1;
   3114 		return AMR_BAD;	/* Found ":t<endc>" or ":t:". */
   3115 	}
   3116 
   3117 	if (mod[1] == 's')
   3118 		return ApplyModifier_ToSep(pp, st);
   3119 
   3120 	if (!IsDelimiter(mod[2], st)) {			/* :t<unrecognized> */
   3121 		*pp = mod + 1;
   3122 		return AMR_BAD;
   3123 	}
   3124 
   3125 	if (mod[1] == 'A') {				/* :tA */
   3126 		*pp = mod + 2;
   3127 		ModifyWords(st, ModifyWord_Realpath, NULL, st->oneBigWord);
   3128 		return AMR_OK;
   3129 	}
   3130 
   3131 	if (mod[1] == 'u') {				/* :tu */
   3132 		*pp = mod + 2;
   3133 		if (st->expr->eflags.wantRes)
   3134 			Expr_SetValueOwn(expr, str_toupper(expr->value.str));
   3135 		return AMR_OK;
   3136 	}
   3137 
   3138 	if (mod[1] == 'l') {				/* :tl */
   3139 		*pp = mod + 2;
   3140 		if (st->expr->eflags.wantRes)
   3141 			Expr_SetValueOwn(expr, str_tolower(expr->value.str));
   3142 		return AMR_OK;
   3143 	}
   3144 
   3145 	if (mod[1] == 'W' || mod[1] == 'w') {		/* :tW, :tw */
   3146 		*pp = mod + 2;
   3147 		st->oneBigWord = mod[1] == 'W';
   3148 		return AMR_OK;
   3149 	}
   3150 
   3151 	/* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
   3152 	*pp = mod + 1;		/* XXX: unnecessary but observable */
   3153 	return AMR_BAD;
   3154 }
   3155 
   3156 /* :[#], :[1], :[-1..1], etc. */
   3157 static ApplyModifierResult
   3158 ApplyModifier_Words(const char **pp, ApplyModifiersState *st)
   3159 {
   3160 	Expr *expr = st->expr;
   3161 	char *estr;
   3162 	int first, last;
   3163 	VarParseResult res;
   3164 	const char *p;
   3165 
   3166 	(*pp)++;		/* skip the '[' */
   3167 	res = ParseModifierPart(pp, ']', expr->eflags, st, &estr);
   3168 	if (res != VPR_OK)
   3169 		return AMR_CLEANUP;
   3170 
   3171 	if (!IsDelimiter(**pp, st))
   3172 		goto bad_modifier;		/* Found junk after ']' */
   3173 
   3174 	if (!(expr->eflags.wantRes))
   3175 		goto ok;
   3176 
   3177 	if (estr[0] == '\0')
   3178 		goto bad_modifier;			/* Found ":[]". */
   3179 
   3180 	if (estr[0] == '#' && estr[1] == '\0') {	/* Found ":[#]" */
   3181 		if (st->oneBigWord) {
   3182 			Expr_SetValueRefer(expr, "1");
   3183 		} else {
   3184 			Buffer buf;
   3185 
   3186 			Words words = Str_Words(expr->value.str, FALSE);
   3187 			size_t ac = words.len;
   3188 			Words_Free(words);
   3189 
   3190 			/* 3 digits + '\0' is usually enough */
   3191 			Buf_InitSize(&buf, 4);
   3192 			Buf_AddInt(&buf, (int)ac);
   3193 			Expr_SetValueOwn(expr, Buf_DoneData(&buf));
   3194 		}
   3195 		goto ok;
   3196 	}
   3197 
   3198 	if (estr[0] == '*' && estr[1] == '\0') {	/* Found ":[*]" */
   3199 		st->oneBigWord = TRUE;
   3200 		goto ok;
   3201 	}
   3202 
   3203 	if (estr[0] == '@' && estr[1] == '\0') {	/* Found ":[@]" */
   3204 		st->oneBigWord = FALSE;
   3205 		goto ok;
   3206 	}
   3207 
   3208 	/*
   3209 	 * We expect estr to contain a single integer for :[N], or two
   3210 	 * integers separated by ".." for :[start..end].
   3211 	 */
   3212 	p = estr;
   3213 	if (!TryParseIntBase0(&p, &first))
   3214 		goto bad_modifier;	/* Found junk instead of a number */
   3215 
   3216 	if (p[0] == '\0') {		/* Found only one integer in :[N] */
   3217 		last = first;
   3218 	} else if (p[0] == '.' && p[1] == '.' && p[2] != '\0') {
   3219 		/* Expecting another integer after ".." */
   3220 		p += 2;
   3221 		if (!TryParseIntBase0(&p, &last) || *p != '\0')
   3222 			goto bad_modifier; /* Found junk after ".." */
   3223 	} else
   3224 		goto bad_modifier;	/* Found junk instead of ".." */
   3225 
   3226 	/*
   3227 	 * Now first and last are properly filled in, but we still have to
   3228 	 * check for 0 as a special case.
   3229 	 */
   3230 	if (first == 0 && last == 0) {
   3231 		/* ":[0]" or perhaps ":[0..0]" */
   3232 		st->oneBigWord = TRUE;
   3233 		goto ok;
   3234 	}
   3235 
   3236 	/* ":[0..N]" or ":[N..0]" */
   3237 	if (first == 0 || last == 0)
   3238 		goto bad_modifier;
   3239 
   3240 	/* Normal case: select the words described by first and last. */
   3241 	Expr_SetValueOwn(expr,
   3242 	    VarSelectWords(expr->value.str, first, last,
   3243 	        st->sep, st->oneBigWord));
   3244 
   3245 ok:
   3246 	free(estr);
   3247 	return AMR_OK;
   3248 
   3249 bad_modifier:
   3250 	free(estr);
   3251 	return AMR_BAD;
   3252 }
   3253 
   3254 static int
   3255 str_cmp_asc(const void *a, const void *b)
   3256 {
   3257 	return strcmp(*(const char *const *)a, *(const char *const *)b);
   3258 }
   3259 
   3260 static int
   3261 str_cmp_desc(const void *a, const void *b)
   3262 {
   3263 	return strcmp(*(const char *const *)b, *(const char *const *)a);
   3264 }
   3265 
   3266 static void
   3267 ShuffleStrings(char **strs, size_t n)
   3268 {
   3269 	size_t i;
   3270 
   3271 	for (i = n - 1; i > 0; i--) {
   3272 		size_t rndidx = (size_t)random() % (i + 1);
   3273 		char *t = strs[i];
   3274 		strs[i] = strs[rndidx];
   3275 		strs[rndidx] = t;
   3276 	}
   3277 }
   3278 
   3279 /* :O (order ascending) or :Or (order descending) or :Ox (shuffle) */
   3280 static ApplyModifierResult
   3281 ApplyModifier_Order(const char **pp, ApplyModifiersState *st)
   3282 {
   3283 	const char *mod = (*pp)++;	/* skip past the 'O' in any case */
   3284 	Words words;
   3285 	enum SortMode {
   3286 		ASC, DESC, SHUFFLE
   3287 	} mode;
   3288 
   3289 	if (IsDelimiter(mod[1], st)) {
   3290 		mode = ASC;
   3291 	} else if ((mod[1] == 'r' || mod[1] == 'x') &&
   3292 	    IsDelimiter(mod[2], st)) {
   3293 		(*pp)++;
   3294 		mode = mod[1] == 'r' ? DESC : SHUFFLE;
   3295 	} else
   3296 		return AMR_BAD;
   3297 
   3298 	if (!st->expr->eflags.wantRes)
   3299 		return AMR_OK;
   3300 
   3301 	words = Str_Words(st->expr->value.str, FALSE);
   3302 	if (mode == SHUFFLE)
   3303 		ShuffleStrings(words.words, words.len);
   3304 	else
   3305 		qsort(words.words, words.len, sizeof words.words[0],
   3306 		    mode == ASC ? str_cmp_asc : str_cmp_desc);
   3307 	Expr_SetValueOwn(st->expr, Words_JoinFree(words));
   3308 
   3309 	return AMR_OK;
   3310 }
   3311 
   3312 /* :? then : else */
   3313 static ApplyModifierResult
   3314 ApplyModifier_IfElse(const char **pp, ApplyModifiersState *st)
   3315 {
   3316 	Expr *expr = st->expr;
   3317 	char *then_expr, *else_expr;
   3318 	VarParseResult res;
   3319 
   3320 	Boolean value = FALSE;
   3321 	VarEvalFlags then_eflags = VARE_PARSE_ONLY;
   3322 	VarEvalFlags else_eflags = VARE_PARSE_ONLY;
   3323 
   3324 	int cond_rc = COND_PARSE;	/* anything other than COND_INVALID */
   3325 	if (expr->eflags.wantRes) {
   3326 		cond_rc = Cond_EvalCondition(expr->var->name.str, &value);
   3327 		if (cond_rc != COND_INVALID && value)
   3328 			then_eflags = expr->eflags;
   3329 		if (cond_rc != COND_INVALID && !value)
   3330 			else_eflags = expr->eflags;
   3331 	}
   3332 
   3333 	(*pp)++;			/* skip past the '?' */
   3334 	res = ParseModifierPart(pp, ':', then_eflags, st, &then_expr);
   3335 	if (res != VPR_OK)
   3336 		return AMR_CLEANUP;
   3337 
   3338 	res = ParseModifierPart(pp, st->endc, else_eflags, st, &else_expr);
   3339 	if (res != VPR_OK)
   3340 		return AMR_CLEANUP;
   3341 
   3342 	(*pp)--;		/* Go back to the st->endc. */
   3343 
   3344 	if (cond_rc == COND_INVALID) {
   3345 		Error("Bad conditional expression `%s' in %s?%s:%s",
   3346 		    expr->var->name.str, expr->var->name.str,
   3347 		    then_expr, else_expr);
   3348 		return AMR_CLEANUP;
   3349 	}
   3350 
   3351 	if (!expr->eflags.wantRes) {
   3352 		free(then_expr);
   3353 		free(else_expr);
   3354 	} else if (value) {
   3355 		Expr_SetValueOwn(expr, then_expr);
   3356 		free(else_expr);
   3357 	} else {
   3358 		Expr_SetValueOwn(expr, else_expr);
   3359 		free(then_expr);
   3360 	}
   3361 	Expr_Define(expr);
   3362 	return AMR_OK;
   3363 }
   3364 
   3365 /*
   3366  * The ::= modifiers are special in that they do not read the variable value
   3367  * but instead assign to that variable.  They always expand to an empty
   3368  * string.
   3369  *
   3370  * Their main purpose is in supporting .for loops that generate shell commands
   3371  * since an ordinary variable assignment at that point would terminate the
   3372  * dependency group for these targets.  For example:
   3373  *
   3374  * list-targets: .USE
   3375  * .for i in ${.TARGET} ${.TARGET:R}.gz
   3376  *	@${t::=$i}
   3377  *	@echo 'The target is ${t:T}.'
   3378  * .endfor
   3379  *
   3380  *	  ::=<str>	Assigns <str> as the new value of variable.
   3381  *	  ::?=<str>	Assigns <str> as value of variable if
   3382  *			it was not already set.
   3383  *	  ::+=<str>	Appends <str> to variable.
   3384  *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
   3385  *			variable.
   3386  */
   3387 static ApplyModifierResult
   3388 ApplyModifier_Assign(const char **pp, ApplyModifiersState *st)
   3389 {
   3390 	Expr *expr = st->expr;
   3391 	GNode *scope;
   3392 	char *val;
   3393 	VarParseResult res;
   3394 
   3395 	const char *mod = *pp;
   3396 	const char *op = mod + 1;
   3397 
   3398 	if (op[0] == '=')
   3399 		goto ok;
   3400 	if ((op[0] == '!' || op[0] == '+' || op[0] == '?') && op[1] == '=')
   3401 		goto ok;
   3402 	return AMR_UNKNOWN;	/* "::<unrecognised>" */
   3403 
   3404 ok:
   3405 	if (expr->var->name.str[0] == '\0') {
   3406 		*pp = mod + 1;
   3407 		return AMR_BAD;
   3408 	}
   3409 
   3410 	switch (op[0]) {
   3411 	case '+':
   3412 	case '?':
   3413 	case '!':
   3414 		*pp = mod + 3;
   3415 		break;
   3416 	default:
   3417 		*pp = mod + 2;
   3418 		break;
   3419 	}
   3420 
   3421 	res = ParseModifierPart(pp, st->endc, expr->eflags, st, &val);
   3422 	if (res != VPR_OK)
   3423 		return AMR_CLEANUP;
   3424 
   3425 	(*pp)--;		/* Go back to the st->endc. */
   3426 
   3427 	if (!expr->eflags.wantRes)
   3428 		goto done;
   3429 
   3430 	scope = expr->scope;	/* scope where v belongs */
   3431 	if (expr->defined == DEF_REGULAR && expr->scope != SCOPE_GLOBAL) {
   3432 		Var *gv = VarFind(expr->var->name.str, expr->scope, FALSE);
   3433 		if (gv == NULL)
   3434 			scope = SCOPE_GLOBAL;
   3435 		else
   3436 			VarFreeEnv(gv);
   3437 	}
   3438 
   3439 	switch (op[0]) {
   3440 	case '+':
   3441 		Var_Append(scope, expr->var->name.str, val);
   3442 		break;
   3443 	case '!': {
   3444 		const char *errfmt;
   3445 		char *cmd_output = Cmd_Exec(val, &errfmt);
   3446 		if (errfmt != NULL)
   3447 			Error(errfmt, val);
   3448 		else
   3449 			Var_Set(scope, expr->var->name.str, cmd_output);
   3450 		free(cmd_output);
   3451 		break;
   3452 	}
   3453 	case '?':
   3454 		if (expr->defined == DEF_REGULAR)
   3455 			break;
   3456 		/* FALLTHROUGH */
   3457 	default:
   3458 		Var_Set(scope, expr->var->name.str, val);
   3459 		break;
   3460 	}
   3461 	Expr_SetValueRefer(expr, "");
   3462 
   3463 done:
   3464 	free(val);
   3465 	return AMR_OK;
   3466 }
   3467 
   3468 /*
   3469  * :_=...
   3470  * remember current value
   3471  */
   3472 static ApplyModifierResult
   3473 ApplyModifier_Remember(const char **pp, ApplyModifiersState *st)
   3474 {
   3475 	Expr *expr = st->expr;
   3476 	const char *mod = *pp;
   3477 	FStr name;
   3478 
   3479 	if (!ModMatchEq(mod, "_", st))
   3480 		return AMR_UNKNOWN;
   3481 
   3482 	name = FStr_InitRefer("_");
   3483 	if (mod[1] == '=') {
   3484 		/*
   3485 		 * XXX: This ad-hoc call to strcspn deviates from the usual
   3486 		 * behavior defined in ParseModifierPart.  This creates an
   3487 		 * unnecessary, undocumented inconsistency in make.
   3488 		 */
   3489 		const char *arg = mod + 2;
   3490 		size_t argLen = strcspn(arg, ":)}");
   3491 		*pp = arg + argLen;
   3492 		name = FStr_InitOwn(bmake_strldup(arg, argLen));
   3493 	} else
   3494 		*pp = mod + 1;
   3495 
   3496 	if (expr->eflags.wantRes)
   3497 		Var_Set(expr->scope, name.str, expr->value.str);
   3498 	FStr_Done(&name);
   3499 
   3500 	return AMR_OK;
   3501 }
   3502 
   3503 /*
   3504  * Apply the given function to each word of the variable value,
   3505  * for a single-letter modifier such as :H, :T.
   3506  */
   3507 static ApplyModifierResult
   3508 ApplyModifier_WordFunc(const char **pp, ApplyModifiersState *st,
   3509 		       ModifyWordProc modifyWord)
   3510 {
   3511 	if (!IsDelimiter((*pp)[1], st))
   3512 		return AMR_UNKNOWN;
   3513 	(*pp)++;
   3514 
   3515 	if (st->expr->eflags.wantRes)
   3516 		ModifyWords(st, modifyWord, NULL, st->oneBigWord);
   3517 
   3518 	return AMR_OK;
   3519 }
   3520 
   3521 static ApplyModifierResult
   3522 ApplyModifier_Unique(const char **pp, ApplyModifiersState *st)
   3523 {
   3524 	if (!IsDelimiter((*pp)[1], st))
   3525 		return AMR_UNKNOWN;
   3526 	(*pp)++;
   3527 
   3528 	if (st->expr->eflags.wantRes)
   3529 		Expr_SetValueOwn(st->expr, VarUniq(st->expr->value.str));
   3530 
   3531 	return AMR_OK;
   3532 }
   3533 
   3534 #ifdef SYSVVARSUB
   3535 /* :from=to */
   3536 static ApplyModifierResult
   3537 ApplyModifier_SysV(const char **pp, ApplyModifiersState *st)
   3538 {
   3539 	Expr *expr = st->expr;
   3540 	char *lhs, *rhs;
   3541 	VarParseResult res;
   3542 
   3543 	const char *mod = *pp;
   3544 	Boolean eqFound = FALSE;
   3545 
   3546 	/*
   3547 	 * First we make a pass through the string trying to verify it is a
   3548 	 * SysV-make-style translation. It must be: <lhs>=<rhs>
   3549 	 */
   3550 	int depth = 1;
   3551 	const char *p = mod;
   3552 	while (*p != '\0' && depth > 0) {
   3553 		if (*p == '=') {	/* XXX: should also test depth == 1 */
   3554 			eqFound = TRUE;
   3555 			/* continue looking for st->endc */
   3556 		} else if (*p == st->endc)
   3557 			depth--;
   3558 		else if (*p == st->startc)
   3559 			depth++;
   3560 		if (depth > 0)
   3561 			p++;
   3562 	}
   3563 	if (*p != st->endc || !eqFound)
   3564 		return AMR_UNKNOWN;
   3565 
   3566 	res = ParseModifierPart(pp, '=', expr->eflags, st, &lhs);
   3567 	if (res != VPR_OK)
   3568 		return AMR_CLEANUP;
   3569 
   3570 	/* The SysV modifier lasts until the end of the variable expression. */
   3571 	res = ParseModifierPart(pp, st->endc, expr->eflags, st, &rhs);
   3572 	if (res != VPR_OK)
   3573 		return AMR_CLEANUP;
   3574 
   3575 	(*pp)--;		/* Go back to the st->endc. */
   3576 
   3577 	if (lhs[0] == '\0' && expr->value.str[0] == '\0') {
   3578 		/* Do not turn an empty expression into non-empty. */
   3579 	} else {
   3580 		struct ModifyWord_SYSVSubstArgs args = {
   3581 		    expr->scope, lhs, rhs
   3582 		};
   3583 		ModifyWords(st, ModifyWord_SYSVSubst, &args, st->oneBigWord);
   3584 	}
   3585 	free(lhs);
   3586 	free(rhs);
   3587 	return AMR_OK;
   3588 }
   3589 #endif
   3590 
   3591 #ifdef SUNSHCMD
   3592 /* :sh */
   3593 static ApplyModifierResult
   3594 ApplyModifier_SunShell(const char **pp, ApplyModifiersState *st)
   3595 {
   3596 	Expr *expr = st->expr;
   3597 	const char *p = *pp;
   3598 	if (!(p[1] == 'h' && IsDelimiter(p[2], st)))
   3599 		return AMR_UNKNOWN;
   3600 	*pp = p + 2;
   3601 
   3602 	if (expr->eflags.wantRes) {
   3603 		const char *errfmt;
   3604 		char *output = Cmd_Exec(expr->value.str, &errfmt);
   3605 		if (errfmt != NULL)
   3606 			Error(errfmt, expr->value.str);
   3607 		Expr_SetValueOwn(expr, output);
   3608 	}
   3609 
   3610 	return AMR_OK;
   3611 }
   3612 #endif
   3613 
   3614 static void
   3615 LogBeforeApply(const ApplyModifiersState *st, const char *mod)
   3616 {
   3617 	const Expr *expr = st->expr;
   3618 	char vflags_str[VarFlags_ToStringSize];
   3619 	Boolean is_single_char = mod[0] != '\0' && IsDelimiter(mod[1], st);
   3620 
   3621 	/* At this point, only the first character of the modifier can
   3622 	 * be used since the end of the modifier is not yet known. */
   3623 	debug_printf("Applying ${%s:%c%s} to \"%s\" (%s, %s, %s)\n",
   3624 	    expr->var->name.str, mod[0], is_single_char ? "" : "...",
   3625 	    expr->value.str,
   3626 	    VarEvalFlags_ToString(expr->eflags),
   3627 	    VarFlags_ToString(vflags_str, expr->var->flags),
   3628 	    ExprDefined_Name[expr->defined]);
   3629 }
   3630 
   3631 static void
   3632 LogAfterApply(const ApplyModifiersState *st, const char *p, const char *mod)
   3633 {
   3634 	const Expr *expr = st->expr;
   3635 	const char *value = expr->value.str;
   3636 	char vflags_str[VarFlags_ToStringSize];
   3637 	const char *quot = value == var_Error ? "" : "\"";
   3638 
   3639 	debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s, %s)\n",
   3640 	    expr->var->name.str, (int)(p - mod), mod,
   3641 	    quot, value == var_Error ? "error" : value, quot,
   3642 	    VarEvalFlags_ToString(expr->eflags),
   3643 	    VarFlags_ToString(vflags_str, expr->var->flags),
   3644 	    ExprDefined_Name[expr->defined]);
   3645 }
   3646 
   3647 static ApplyModifierResult
   3648 ApplyModifier(const char **pp, ApplyModifiersState *st)
   3649 {
   3650 	switch (**pp) {
   3651 	case '!':
   3652 		return ApplyModifier_ShellCommand(pp, st);
   3653 	case ':':
   3654 		return ApplyModifier_Assign(pp, st);
   3655 	case '?':
   3656 		return ApplyModifier_IfElse(pp, st);
   3657 	case '@':
   3658 		return ApplyModifier_Loop(pp, st);
   3659 	case '[':
   3660 		return ApplyModifier_Words(pp, st);
   3661 	case '_':
   3662 		return ApplyModifier_Remember(pp, st);
   3663 #ifndef NO_REGEX
   3664 	case 'C':
   3665 		return ApplyModifier_Regex(pp, st);
   3666 #endif
   3667 	case 'D':
   3668 		return ApplyModifier_Defined(pp, st);
   3669 	case 'E':
   3670 		return ApplyModifier_WordFunc(pp, st, ModifyWord_Suffix);
   3671 	case 'g':
   3672 		return ApplyModifier_Gmtime(pp, st);
   3673 	case 'H':
   3674 		return ApplyModifier_WordFunc(pp, st, ModifyWord_Head);
   3675 	case 'h':
   3676 		return ApplyModifier_Hash(pp, st);
   3677 	case 'L':
   3678 		return ApplyModifier_Literal(pp, st);
   3679 	case 'l':
   3680 		return ApplyModifier_Localtime(pp, st);
   3681 	case 'M':
   3682 	case 'N':
   3683 		return ApplyModifier_Match(pp, st);
   3684 	case 'O':
   3685 		return ApplyModifier_Order(pp, st);
   3686 	case 'P':
   3687 		return ApplyModifier_Path(pp, st);
   3688 	case 'Q':
   3689 	case 'q':
   3690 		return ApplyModifier_Quote(pp, st);
   3691 	case 'R':
   3692 		return ApplyModifier_WordFunc(pp, st, ModifyWord_Root);
   3693 	case 'r':
   3694 		return ApplyModifier_Range(pp, st);
   3695 	case 'S':
   3696 		return ApplyModifier_Subst(pp, st);
   3697 #ifdef SUNSHCMD
   3698 	case 's':
   3699 		return ApplyModifier_SunShell(pp, st);
   3700 #endif
   3701 	case 'T':
   3702 		return ApplyModifier_WordFunc(pp, st, ModifyWord_Tail);
   3703 	case 't':
   3704 		return ApplyModifier_To(pp, st);
   3705 	case 'U':
   3706 		return ApplyModifier_Defined(pp, st);
   3707 	case 'u':
   3708 		return ApplyModifier_Unique(pp, st);
   3709 	default:
   3710 		return AMR_UNKNOWN;
   3711 	}
   3712 }
   3713 
   3714 static void ApplyModifiers(Expr *, const char **, char, char);
   3715 
   3716 typedef enum ApplyModifiersIndirectResult {
   3717 	/* The indirect modifiers have been applied successfully. */
   3718 	AMIR_CONTINUE,
   3719 	/* Fall back to the SysV modifier. */
   3720 	AMIR_SYSV,
   3721 	/* Error out. */
   3722 	AMIR_OUT
   3723 } ApplyModifiersIndirectResult;
   3724 
   3725 /*
   3726  * While expanding a variable expression, expand and apply indirect modifiers,
   3727  * such as in ${VAR:${M_indirect}}.
   3728  *
   3729  * All indirect modifiers of a group must come from a single variable
   3730  * expression.  ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
   3731  *
   3732  * Multiple groups of indirect modifiers can be chained by separating them
   3733  * with colons.  ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
   3734  *
   3735  * If the variable expression is not followed by st->endc or ':', fall
   3736  * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
   3737  */
   3738 static ApplyModifiersIndirectResult
   3739 ApplyModifiersIndirect(ApplyModifiersState *st, const char **pp)
   3740 {
   3741 	Expr *expr = st->expr;
   3742 	const char *p = *pp;
   3743 	FStr mods;
   3744 
   3745 	(void)Var_Parse(&p, expr->scope, expr->eflags, &mods);
   3746 	/* TODO: handle errors */
   3747 
   3748 	if (mods.str[0] != '\0' && *p != '\0' && !IsDelimiter(*p, st)) {
   3749 		FStr_Done(&mods);
   3750 		return AMIR_SYSV;
   3751 	}
   3752 
   3753 	DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
   3754 	    mods.str, (int)(p - *pp), *pp);
   3755 
   3756 	if (mods.str[0] != '\0') {
   3757 		const char *modsp = mods.str;
   3758 		ApplyModifiers(expr, &modsp, '\0', '\0');
   3759 		if (expr->value.str == var_Error || *modsp != '\0') {
   3760 			FStr_Done(&mods);
   3761 			*pp = p;
   3762 			return AMIR_OUT;	/* error already reported */
   3763 		}
   3764 	}
   3765 	FStr_Done(&mods);
   3766 
   3767 	if (*p == ':')
   3768 		p++;
   3769 	else if (*p == '\0' && st->endc != '\0') {
   3770 		Error("Unclosed variable expression after indirect "
   3771 		      "modifier, expecting '%c' for variable \"%s\"",
   3772 		    st->endc, expr->var->name.str);
   3773 		*pp = p;
   3774 		return AMIR_OUT;
   3775 	}
   3776 
   3777 	*pp = p;
   3778 	return AMIR_CONTINUE;
   3779 }
   3780 
   3781 static ApplyModifierResult
   3782 ApplySingleModifier(const char **pp, ApplyModifiersState *st)
   3783 {
   3784 	ApplyModifierResult res;
   3785 	const char *mod = *pp;
   3786 	const char *p = *pp;
   3787 
   3788 	if (DEBUG(VAR))
   3789 		LogBeforeApply(st, mod);
   3790 
   3791 	res = ApplyModifier(&p, st);
   3792 
   3793 #ifdef SYSVVARSUB
   3794 	if (res == AMR_UNKNOWN) {
   3795 		assert(p == mod);
   3796 		res = ApplyModifier_SysV(&p, st);
   3797 	}
   3798 #endif
   3799 
   3800 	if (res == AMR_UNKNOWN) {
   3801 		/*
   3802 		 * Guess the end of the current modifier.
   3803 		 * XXX: Skipping the rest of the modifier hides
   3804 		 * errors and leads to wrong results.
   3805 		 * Parsing should rather stop here.
   3806 		 */
   3807 		for (p++; !IsDelimiter(*p, st) && *p != '\0'; p++)
   3808 			continue;
   3809 		Parse_Error(PARSE_FATAL, "Unknown modifier \"%.*s\"",
   3810 		    (int)(p - mod), mod);
   3811 		Expr_SetValueRefer(st->expr, var_Error);
   3812 	}
   3813 	if (res == AMR_CLEANUP || res == AMR_BAD) {
   3814 		*pp = p;
   3815 		return res;
   3816 	}
   3817 
   3818 	if (DEBUG(VAR))
   3819 		LogAfterApply(st, p, mod);
   3820 
   3821 	if (*p == '\0' && st->endc != '\0') {
   3822 		Error(
   3823 		    "Unclosed variable expression, expecting '%c' for "
   3824 		    "modifier \"%.*s\" of variable \"%s\" with value \"%s\"",
   3825 		    st->endc,
   3826 		    (int)(p - mod), mod,
   3827 		    st->expr->var->name.str, st->expr->value.str);
   3828 	} else if (*p == ':') {
   3829 		p++;
   3830 	} else if (opts.strict && *p != '\0' && *p != st->endc) {
   3831 		Parse_Error(PARSE_FATAL,
   3832 		    "Missing delimiter ':' after modifier \"%.*s\"",
   3833 		    (int)(p - mod), mod);
   3834 		/*
   3835 		 * TODO: propagate parse error to the enclosing
   3836 		 * expression
   3837 		 */
   3838 	}
   3839 	*pp = p;
   3840 	return AMR_OK;
   3841 }
   3842 
   3843 /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
   3844 static void
   3845 ApplyModifiers(
   3846     Expr *expr,
   3847     const char **pp,	/* the parsing position, updated upon return */
   3848     char startc,	/* '(' or '{'; or '\0' for indirect modifiers */
   3849     char endc		/* ')' or '}'; or '\0' for indirect modifiers */
   3850 )
   3851 {
   3852 	ApplyModifiersState st = {
   3853 	    expr,
   3854 	    startc,
   3855 	    endc,
   3856 	    ' ',		/* .sep */
   3857 	    FALSE		/* .oneBigWord */
   3858 	};
   3859 	const char *p;
   3860 	const char *mod;
   3861 
   3862 	assert(startc == '(' || startc == '{' || startc == '\0');
   3863 	assert(endc == ')' || endc == '}' || endc == '\0');
   3864 	assert(expr->value.str != NULL);
   3865 
   3866 	p = *pp;
   3867 
   3868 	if (*p == '\0' && endc != '\0') {
   3869 		Error(
   3870 		    "Unclosed variable expression (expecting '%c') for \"%s\"",
   3871 		    st.endc, expr->var->name.str);
   3872 		goto cleanup;
   3873 	}
   3874 
   3875 	while (*p != '\0' && *p != endc) {
   3876 		ApplyModifierResult res;
   3877 
   3878 		if (*p == '$') {
   3879 			ApplyModifiersIndirectResult amir =
   3880 			    ApplyModifiersIndirect(&st, &p);
   3881 			if (amir == AMIR_CONTINUE)
   3882 				continue;
   3883 			if (amir == AMIR_OUT)
   3884 				break;
   3885 			/*
   3886 			 * It's neither '${VAR}:' nor '${VAR}}'.  Try to parse
   3887 			 * it as a SysV modifier, as that is the only modifier
   3888 			 * that can start with '$'.
   3889 			 */
   3890 		}
   3891 
   3892 		mod = p;
   3893 
   3894 		res = ApplySingleModifier(&p, &st);
   3895 		if (res == AMR_CLEANUP)
   3896 			goto cleanup;
   3897 		if (res == AMR_BAD)
   3898 			goto bad_modifier;
   3899 	}
   3900 
   3901 	*pp = p;
   3902 	assert(expr->value.str != NULL); /* Use var_Error or varUndefined. */
   3903 	return;
   3904 
   3905 bad_modifier:
   3906 	/* XXX: The modifier end is only guessed. */
   3907 	Error("Bad modifier \":%.*s\" for variable \"%s\"",
   3908 	    (int)strcspn(mod, ":)}"), mod, expr->var->name.str);
   3909 
   3910 cleanup:
   3911 	/*
   3912 	 * TODO: Use p + strlen(p) instead, to stop parsing immediately.
   3913 	 *
   3914 	 * In the unit tests, this generates a few unterminated strings in the
   3915 	 * shell commands though.  Instead of producing these unfinished
   3916 	 * strings, commands with evaluation errors should not be run at all.
   3917 	 *
   3918 	 * To make that happen, Var_Subst must report the actual errors
   3919 	 * instead of returning VPR_OK unconditionally.
   3920 	 */
   3921 	*pp = p;
   3922 	Expr_SetValueRefer(expr, var_Error);
   3923 }
   3924 
   3925 /*
   3926  * Only four of the local variables are treated specially as they are the
   3927  * only four that will be set when dynamic sources are expanded.
   3928  */
   3929 static Boolean
   3930 VarnameIsDynamic(const char *name, size_t len)
   3931 {
   3932 	if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
   3933 		switch (name[0]) {
   3934 		case '@':
   3935 		case '%':
   3936 		case '*':
   3937 		case '!':
   3938 			return TRUE;
   3939 		}
   3940 		return FALSE;
   3941 	}
   3942 
   3943 	if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
   3944 		return strcmp(name, ".TARGET") == 0 ||
   3945 		       strcmp(name, ".ARCHIVE") == 0 ||
   3946 		       strcmp(name, ".PREFIX") == 0 ||
   3947 		       strcmp(name, ".MEMBER") == 0;
   3948 	}
   3949 
   3950 	return FALSE;
   3951 }
   3952 
   3953 static const char *
   3954 UndefinedShortVarValue(char varname, const GNode *scope)
   3955 {
   3956 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
   3957 		/*
   3958 		 * If substituting a local variable in a non-local scope,
   3959 		 * assume it's for dynamic source stuff. We have to handle
   3960 		 * this specially and return the longhand for the variable
   3961 		 * with the dollar sign escaped so it makes it back to the
   3962 		 * caller. Only four of the local variables are treated
   3963 		 * specially as they are the only four that will be set
   3964 		 * when dynamic sources are expanded.
   3965 		 */
   3966 		switch (varname) {
   3967 		case '@':
   3968 			return "$(.TARGET)";
   3969 		case '%':
   3970 			return "$(.MEMBER)";
   3971 		case '*':
   3972 			return "$(.PREFIX)";
   3973 		case '!':
   3974 			return "$(.ARCHIVE)";
   3975 		}
   3976 	}
   3977 	return NULL;
   3978 }
   3979 
   3980 /*
   3981  * Parse a variable name, until the end character or a colon, whichever
   3982  * comes first.
   3983  */
   3984 static char *
   3985 ParseVarname(const char **pp, char startc, char endc,
   3986 	     GNode *scope, VarEvalFlags eflags,
   3987 	     size_t *out_varname_len)
   3988 {
   3989 	Buffer buf;
   3990 	const char *p = *pp;
   3991 	int depth = 0;		/* Track depth so we can spot parse errors. */
   3992 
   3993 	Buf_Init(&buf);
   3994 
   3995 	while (*p != '\0') {
   3996 		if ((*p == endc || *p == ':') && depth == 0)
   3997 			break;
   3998 		if (*p == startc)
   3999 			depth++;
   4000 		if (*p == endc)
   4001 			depth--;
   4002 
   4003 		/* A variable inside a variable, expand. */
   4004 		if (*p == '$') {
   4005 			FStr nested_val;
   4006 			(void)Var_Parse(&p, scope, eflags, &nested_val);
   4007 			/* TODO: handle errors */
   4008 			Buf_AddStr(&buf, nested_val.str);
   4009 			FStr_Done(&nested_val);
   4010 		} else {
   4011 			Buf_AddByte(&buf, *p);
   4012 			p++;
   4013 		}
   4014 	}
   4015 	*pp = p;
   4016 	*out_varname_len = buf.len;
   4017 	return Buf_DoneData(&buf);
   4018 }
   4019 
   4020 static VarParseResult
   4021 ValidShortVarname(char varname, const char *start)
   4022 {
   4023 	if (varname != '$' && varname != ':' && varname != '}' &&
   4024 	    varname != ')' && varname != '\0')
   4025 		return VPR_OK;
   4026 
   4027 	if (!opts.strict)
   4028 		return VPR_ERR;	/* XXX: Missing error message */
   4029 
   4030 	if (varname == '$')
   4031 		Parse_Error(PARSE_FATAL,
   4032 		    "To escape a dollar, use \\$, not $$, at \"%s\"", start);
   4033 	else if (varname == '\0')
   4034 		Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
   4035 	else
   4036 		Parse_Error(PARSE_FATAL,
   4037 		    "Invalid variable name '%c', at \"%s\"", varname, start);
   4038 
   4039 	return VPR_ERR;
   4040 }
   4041 
   4042 /*
   4043  * Parse a single-character variable name such as in $V or $@.
   4044  * Return whether to continue parsing.
   4045  */
   4046 static Boolean
   4047 ParseVarnameShort(char varname, const char **pp, GNode *scope,
   4048 		  VarEvalFlags eflags,
   4049 		  VarParseResult *out_FALSE_res, const char **out_FALSE_val,
   4050 		  Var **out_TRUE_var)
   4051 {
   4052 	char name[2];
   4053 	Var *v;
   4054 	VarParseResult vpr;
   4055 
   4056 	vpr = ValidShortVarname(varname, *pp);
   4057 	if (vpr != VPR_OK) {
   4058 		(*pp)++;
   4059 		*out_FALSE_res = vpr;
   4060 		*out_FALSE_val = var_Error;
   4061 		return FALSE;
   4062 	}
   4063 
   4064 	name[0] = varname;
   4065 	name[1] = '\0';
   4066 	v = VarFind(name, scope, TRUE);
   4067 	if (v == NULL) {
   4068 		const char *val;
   4069 		*pp += 2;
   4070 
   4071 		val = UndefinedShortVarValue(varname, scope);
   4072 		if (val == NULL)
   4073 			val = eflags.undefErr ? var_Error : varUndefined;
   4074 
   4075 		if (opts.strict && val == var_Error) {
   4076 			Parse_Error(PARSE_FATAL,
   4077 			    "Variable \"%s\" is undefined", name);
   4078 			*out_FALSE_res = VPR_ERR;
   4079 			*out_FALSE_val = val;
   4080 			return FALSE;
   4081 		}
   4082 
   4083 		/*
   4084 		 * XXX: This looks completely wrong.
   4085 		 *
   4086 		 * If undefined expressions are not allowed, this should
   4087 		 * rather be VPR_ERR instead of VPR_UNDEF, together with an
   4088 		 * error message.
   4089 		 *
   4090 		 * If undefined expressions are allowed, this should rather
   4091 		 * be VPR_UNDEF instead of VPR_OK.
   4092 		 */
   4093 		*out_FALSE_res = eflags.undefErr ? VPR_UNDEF : VPR_OK;
   4094 		*out_FALSE_val = val;
   4095 		return FALSE;
   4096 	}
   4097 
   4098 	*out_TRUE_var = v;
   4099 	return TRUE;
   4100 }
   4101 
   4102 /* Find variables like @F or <D. */
   4103 static Var *
   4104 FindLocalLegacyVar(const char *varname, size_t namelen, GNode *scope,
   4105 		   const char **out_extraModifiers)
   4106 {
   4107 	/* Only resolve these variables if scope is a "real" target. */
   4108 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
   4109 		return NULL;
   4110 
   4111 	if (namelen != 2)
   4112 		return NULL;
   4113 	if (varname[1] != 'F' && varname[1] != 'D')
   4114 		return NULL;
   4115 	if (strchr("@%?*!<>", varname[0]) == NULL)
   4116 		return NULL;
   4117 
   4118 	{
   4119 		char name[] = { varname[0], '\0' };
   4120 		Var *v = VarFind(name, scope, FALSE);
   4121 
   4122 		if (v != NULL) {
   4123 			if (varname[1] == 'D') {
   4124 				*out_extraModifiers = "H:";
   4125 			} else { /* F */
   4126 				*out_extraModifiers = "T:";
   4127 			}
   4128 		}
   4129 		return v;
   4130 	}
   4131 }
   4132 
   4133 static VarParseResult
   4134 EvalUndefined(Boolean dynamic, const char *start, const char *p, char *varname,
   4135 	      VarEvalFlags eflags,
   4136 	      FStr *out_val)
   4137 {
   4138 	if (dynamic) {
   4139 		*out_val = FStr_InitOwn(bmake_strsedup(start, p));
   4140 		free(varname);
   4141 		return VPR_OK;
   4142 	}
   4143 
   4144 	if (eflags.undefErr && opts.strict) {
   4145 		Parse_Error(PARSE_FATAL,
   4146 		    "Variable \"%s\" is undefined", varname);
   4147 		free(varname);
   4148 		*out_val = FStr_InitRefer(var_Error);
   4149 		return VPR_ERR;
   4150 	}
   4151 
   4152 	if (eflags.undefErr) {
   4153 		free(varname);
   4154 		*out_val = FStr_InitRefer(var_Error);
   4155 		return VPR_UNDEF;	/* XXX: Should be VPR_ERR instead. */
   4156 	}
   4157 
   4158 	free(varname);
   4159 	*out_val = FStr_InitRefer(varUndefined);
   4160 	return VPR_OK;
   4161 }
   4162 
   4163 /*
   4164  * Parse a long variable name enclosed in braces or parentheses such as $(VAR)
   4165  * or ${VAR}, up to the closing brace or parenthesis, or in the case of
   4166  * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
   4167  * Return whether to continue parsing.
   4168  */
   4169 static Boolean
   4170 ParseVarnameLong(
   4171 	const char *p,
   4172 	char startc,
   4173 	GNode *scope,
   4174 	VarEvalFlags eflags,
   4175 
   4176 	const char **out_FALSE_pp,
   4177 	VarParseResult *out_FALSE_res,
   4178 	FStr *out_FALSE_val,
   4179 
   4180 	char *out_TRUE_endc,
   4181 	const char **out_TRUE_p,
   4182 	Var **out_TRUE_v,
   4183 	Boolean *out_TRUE_haveModifier,
   4184 	const char **out_TRUE_extraModifiers,
   4185 	Boolean *out_TRUE_dynamic,
   4186 	ExprDefined *out_TRUE_exprDefined
   4187 )
   4188 {
   4189 	size_t namelen;
   4190 	char *varname;
   4191 	Var *v;
   4192 	Boolean haveModifier;
   4193 	Boolean dynamic = FALSE;
   4194 
   4195 	const char *const start = p;
   4196 	char endc = startc == '(' ? ')' : '}';
   4197 
   4198 	p += 2;			/* skip "${" or "$(" or "y(" */
   4199 	varname = ParseVarname(&p, startc, endc, scope, eflags, &namelen);
   4200 
   4201 	if (*p == ':') {
   4202 		haveModifier = TRUE;
   4203 	} else if (*p == endc) {
   4204 		haveModifier = FALSE;
   4205 	} else {
   4206 		Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"", varname);
   4207 		free(varname);
   4208 		*out_FALSE_pp = p;
   4209 		*out_FALSE_val = FStr_InitRefer(var_Error);
   4210 		*out_FALSE_res = VPR_ERR;
   4211 		return FALSE;
   4212 	}
   4213 
   4214 	v = VarFind(varname, scope, TRUE);
   4215 
   4216 	/* At this point, p points just after the variable name,
   4217 	 * either at ':' or at endc. */
   4218 
   4219 	if (v == NULL) {
   4220 		v = FindLocalLegacyVar(varname, namelen, scope,
   4221 		    out_TRUE_extraModifiers);
   4222 	}
   4223 
   4224 	if (v == NULL) {
   4225 		/*
   4226 		 * Defer expansion of dynamic variables if they appear in
   4227 		 * non-local scope since they are not defined there.
   4228 		 */
   4229 		dynamic = VarnameIsDynamic(varname, namelen) &&
   4230 			  (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
   4231 
   4232 		if (!haveModifier) {
   4233 			p++;	/* skip endc */
   4234 			*out_FALSE_pp = p;
   4235 			*out_FALSE_res = EvalUndefined(dynamic, start, p,
   4236 			    varname, eflags, out_FALSE_val);
   4237 			return FALSE;
   4238 		}
   4239 
   4240 		/*
   4241 		 * The variable expression is based on an undefined variable.
   4242 		 * Nevertheless it needs a Var, for modifiers that access the
   4243 		 * variable name, such as :L or :?.
   4244 		 *
   4245 		 * Most modifiers leave this expression in the "undefined"
   4246 		 * state (VES_UNDEF), only a few modifiers like :D, :U, :L,
   4247 		 * :P turn this undefined expression into a defined
   4248 		 * expression (VES_DEF).
   4249 		 *
   4250 		 * In the end, after applying all modifiers, if the expression
   4251 		 * is still undefined, Var_Parse will return an empty string
   4252 		 * instead of the actually computed value.
   4253 		 */
   4254 		v = VarNew(FStr_InitOwn(varname), "", VFL_NONE);
   4255 		*out_TRUE_exprDefined = DEF_UNDEF;
   4256 	} else
   4257 		free(varname);
   4258 
   4259 	*out_TRUE_endc = endc;
   4260 	*out_TRUE_p = p;
   4261 	*out_TRUE_v = v;
   4262 	*out_TRUE_haveModifier = haveModifier;
   4263 	*out_TRUE_dynamic = dynamic;
   4264 	return TRUE;
   4265 }
   4266 
   4267 /* Free the environment variable now since we own it. */
   4268 static void
   4269 FreeEnvVar(Var *v, FStr *inout_val)
   4270 {
   4271 	char *varValue = Buf_DoneData(&v->val);
   4272 	if (inout_val->str == varValue)
   4273 		inout_val->freeIt = varValue;
   4274 	else
   4275 		free(varValue);
   4276 
   4277 	FStr_Done(&v->name);
   4278 	free(v);
   4279 }
   4280 
   4281 /*
   4282  * Given the start of a variable expression (such as $v, $(VAR),
   4283  * ${VAR:Mpattern}), extract the variable name and value, and the modifiers,
   4284  * if any.  While doing that, apply the modifiers to the value of the
   4285  * expression, forming its final value.  A few of the modifiers such as :!cmd!
   4286  * or ::= have side effects.
   4287  *
   4288  * Input:
   4289  *	*pp		The string to parse.
   4290  *			When parsing a condition in ParseEmptyArg, it may also
   4291  *			point to the "y" of "empty(VARNAME:Modifiers)", which
   4292  *			is syntactically the same.
   4293  *	scope		The scope for finding variables
   4294  *	eflags		Control the exact details of parsing
   4295  *
   4296  * Output:
   4297  *	*pp		The position where to continue parsing.
   4298  *			TODO: After a parse error, the value of *pp is
   4299  *			unspecified.  It may not have been updated at all,
   4300  *			point to some random character in the string, to the
   4301  *			location of the parse error, or at the end of the
   4302  *			string.
   4303  *	*out_val	The value of the variable expression, never NULL.
   4304  *	*out_val	var_Error if there was a parse error.
   4305  *	*out_val	var_Error if the base variable of the expression was
   4306  *			undefined, eflags has undefErr set, and none of
   4307  *			the modifiers turned the undefined expression into a
   4308  *			defined expression.
   4309  *			XXX: It is not guaranteed that an error message has
   4310  *			been printed.
   4311  *	*out_val	varUndefined if the base variable of the expression
   4312  *			was undefined, eflags did not have undefErr set,
   4313  *			and none of the modifiers turned the undefined
   4314  *			expression into a defined expression.
   4315  *			XXX: It is not guaranteed that an error message has
   4316  *			been printed.
   4317  */
   4318 VarParseResult
   4319 Var_Parse(const char **pp, GNode *scope, VarEvalFlags eflags, FStr *out_val)
   4320 {
   4321 	const char *p = *pp;
   4322 	const char *const start = p;
   4323 	/* TRUE if have modifiers for the variable. */
   4324 	Boolean haveModifier;
   4325 	/* Starting character if variable in parens or braces. */
   4326 	char startc;
   4327 	/* Ending character if variable in parens or braces. */
   4328 	char endc;
   4329 	/*
   4330 	 * TRUE if the variable is local and we're expanding it in a
   4331 	 * non-local scope. This is done to support dynamic sources.
   4332 	 * The result is just the expression, unaltered.
   4333 	 */
   4334 	Boolean dynamic;
   4335 	const char *extramodifiers;
   4336 	Var *v;
   4337 
   4338 	Expr expr = {
   4339 		NULL,
   4340 #if defined(lint)
   4341 		/* NetBSD lint cannot fully parse C99 struct initializers. */
   4342 		{ NULL, NULL },
   4343 #else
   4344 		FStr_InitRefer(NULL),
   4345 #endif
   4346 		eflags,
   4347 		scope,
   4348 		DEF_REGULAR
   4349 	};
   4350 
   4351 	DEBUG2(VAR, "Var_Parse: %s (%s)\n", start,
   4352 	    VarEvalFlags_ToString(eflags));
   4353 
   4354 	*out_val = FStr_InitRefer(NULL);
   4355 	extramodifiers = NULL;	/* extra modifiers to apply first */
   4356 	dynamic = FALSE;
   4357 
   4358 	/*
   4359 	 * Appease GCC, which thinks that the variable might not be
   4360 	 * initialized.
   4361 	 */
   4362 	endc = '\0';
   4363 
   4364 	startc = p[1];
   4365 	if (startc != '(' && startc != '{') {
   4366 		VarParseResult res;
   4367 		if (!ParseVarnameShort(startc, pp, scope, eflags, &res,
   4368 		    &out_val->str, &expr.var))
   4369 			return res;
   4370 		haveModifier = FALSE;
   4371 		p++;
   4372 	} else {
   4373 		VarParseResult res;
   4374 		if (!ParseVarnameLong(p, startc, scope, eflags,
   4375 		    pp, &res, out_val,
   4376 		    &endc, &p, &expr.var, &haveModifier, &extramodifiers,
   4377 		    &dynamic, &expr.defined))
   4378 			return res;
   4379 	}
   4380 
   4381 	v = expr.var;
   4382 	if (v->flags & VFL_IN_USE)
   4383 		Fatal("Variable %s is recursive.", v->name.str);
   4384 
   4385 	/*
   4386 	 * XXX: This assignment creates an alias to the current value of the
   4387 	 * variable.  This means that as long as the value of the expression
   4388 	 * stays the same, the value of the variable must not change.
   4389 	 * Using the '::=' modifier, it could be possible to do exactly this.
   4390 	 * At the bottom of this function, the resulting value is compared to
   4391 	 * the then-current value of the variable.  This might also invoke
   4392 	 * undefined behavior.
   4393 	 */
   4394 	expr.value = FStr_InitRefer(v->val.data);
   4395 
   4396 	/*
   4397 	 * Before applying any modifiers, expand any nested expressions from
   4398 	 * the variable value.
   4399 	 */
   4400 	if (strchr(expr.value.str, '$') != NULL && eflags.wantRes) {
   4401 		char *expanded;
   4402 		VarEvalFlags nested_eflags = eflags;
   4403 		if (opts.strict)
   4404 			nested_eflags.undefErr = FALSE;
   4405 		v->flags |= VFL_IN_USE;
   4406 		(void)Var_Subst(expr.value.str, scope, nested_eflags,
   4407 		    &expanded);
   4408 		v->flags &= ~(unsigned)VFL_IN_USE;
   4409 		/* TODO: handle errors */
   4410 		Expr_SetValueOwn(&expr, expanded);
   4411 	}
   4412 
   4413 	if (extramodifiers != NULL) {
   4414 		const char *em = extramodifiers;
   4415 		ApplyModifiers(&expr, &em, '\0', '\0');
   4416 	}
   4417 
   4418 	if (haveModifier) {
   4419 		p++;	/* Skip initial colon. */
   4420 		ApplyModifiers(&expr, &p, startc, endc);
   4421 	}
   4422 
   4423 	if (*p != '\0')		/* Skip past endc if possible. */
   4424 		p++;
   4425 
   4426 	*pp = p;
   4427 
   4428 	if (v->flags & VFL_FROM_ENV) {
   4429 		FreeEnvVar(v, &expr.value);
   4430 
   4431 	} else if (expr.defined != DEF_REGULAR) {
   4432 		if (expr.defined == DEF_UNDEF) {
   4433 			if (dynamic) {
   4434 				Expr_SetValueOwn(&expr,
   4435 				    bmake_strsedup(start, p));
   4436 			} else {
   4437 				/*
   4438 				 * The expression is still undefined,
   4439 				 * therefore discard the actual value and
   4440 				 * return an error marker instead.
   4441 				 */
   4442 				Expr_SetValueRefer(&expr,
   4443 				    eflags.undefErr
   4444 					? var_Error : varUndefined);
   4445 			}
   4446 		}
   4447 		/* XXX: This is not standard memory management. */
   4448 		if (expr.value.str != v->val.data)
   4449 			Buf_Done(&v->val);
   4450 		FStr_Done(&v->name);
   4451 		free(v);
   4452 	}
   4453 	*out_val = expr.value;
   4454 	return VPR_OK;		/* XXX: Is not correct in all cases */
   4455 }
   4456 
   4457 static void
   4458 VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalFlags eflags)
   4459 {
   4460 	/* A dollar sign may be escaped with another dollar sign. */
   4461 	if (save_dollars && eflags.keepDollar)
   4462 		Buf_AddByte(res, '$');
   4463 	Buf_AddByte(res, '$');
   4464 	*pp += 2;
   4465 }
   4466 
   4467 static void
   4468 VarSubstExpr(const char **pp, Buffer *buf, GNode *scope,
   4469 	     VarEvalFlags eflags, Boolean *inout_errorReported)
   4470 {
   4471 	const char *p = *pp;
   4472 	const char *nested_p = p;
   4473 	FStr val;
   4474 
   4475 	(void)Var_Parse(&nested_p, scope, eflags, &val);
   4476 	/* TODO: handle errors */
   4477 
   4478 	if (val.str == var_Error || val.str == varUndefined) {
   4479 		if (!eflags.keepUndef) {
   4480 			p = nested_p;
   4481 		} else if (eflags.undefErr || val.str == var_Error) {
   4482 
   4483 			/*
   4484 			 * XXX: This condition is wrong.  If val == var_Error,
   4485 			 * this doesn't necessarily mean there was an undefined
   4486 			 * variable.  It could equally well be a parse error;
   4487 			 * see unit-tests/varmod-order.exp.
   4488 			 */
   4489 
   4490 			/*
   4491 			 * If variable is undefined, complain and skip the
   4492 			 * variable. The complaint will stop us from doing
   4493 			 * anything when the file is parsed.
   4494 			 */
   4495 			if (!*inout_errorReported) {
   4496 				Parse_Error(PARSE_FATAL,
   4497 				    "Undefined variable \"%.*s\"",
   4498 				    (int)(size_t)(nested_p - p), p);
   4499 			}
   4500 			p = nested_p;
   4501 			*inout_errorReported = TRUE;
   4502 		} else {
   4503 			/* Copy the initial '$' of the undefined expression,
   4504 			 * thereby deferring expansion of the expression, but
   4505 			 * expand nested expressions if already possible.
   4506 			 * See unit-tests/varparse-undef-partial.mk. */
   4507 			Buf_AddByte(buf, *p);
   4508 			p++;
   4509 		}
   4510 	} else {
   4511 		p = nested_p;
   4512 		Buf_AddStr(buf, val.str);
   4513 	}
   4514 
   4515 	FStr_Done(&val);
   4516 
   4517 	*pp = p;
   4518 }
   4519 
   4520 /*
   4521  * Skip as many characters as possible -- either to the end of the string
   4522  * or to the next dollar sign (variable expression).
   4523  */
   4524 static void
   4525 VarSubstPlain(const char **pp, Buffer *res)
   4526 {
   4527 	const char *p = *pp;
   4528 	const char *start = p;
   4529 
   4530 	for (p++; *p != '$' && *p != '\0'; p++)
   4531 		continue;
   4532 	Buf_AddBytesBetween(res, start, p);
   4533 	*pp = p;
   4534 }
   4535 
   4536 /*
   4537  * Expand all variable expressions like $V, ${VAR}, $(VAR:Modifiers) in the
   4538  * given string.
   4539  *
   4540  * Input:
   4541  *	str		The string in which the variable expressions are
   4542  *			expanded.
   4543  *	scope		The scope in which to start searching for
   4544  *			variables.  The other scopes are searched as well.
   4545  *	eflags		Special effects during expansion.
   4546  */
   4547 VarParseResult
   4548 Var_Subst(const char *str, GNode *scope, VarEvalFlags eflags, char **out_res)
   4549 {
   4550 	const char *p = str;
   4551 	Buffer res;
   4552 
   4553 	/* Set true if an error has already been reported,
   4554 	 * to prevent a plethora of messages when recursing */
   4555 	/* XXX: Why is the 'static' necessary here? */
   4556 	static Boolean errorReported;
   4557 
   4558 	Buf_Init(&res);
   4559 	errorReported = FALSE;
   4560 
   4561 	while (*p != '\0') {
   4562 		if (p[0] == '$' && p[1] == '$')
   4563 			VarSubstDollarDollar(&p, &res, eflags);
   4564 		else if (p[0] == '$')
   4565 			VarSubstExpr(&p, &res, scope, eflags, &errorReported);
   4566 		else
   4567 			VarSubstPlain(&p, &res);
   4568 	}
   4569 
   4570 	*out_res = Buf_DoneDataCompact(&res);
   4571 	return VPR_OK;
   4572 }
   4573 
   4574 /* Initialize the variables module. */
   4575 void
   4576 Var_Init(void)
   4577 {
   4578 	SCOPE_INTERNAL = GNode_New("Internal");
   4579 	SCOPE_GLOBAL = GNode_New("Global");
   4580 	SCOPE_CMDLINE = GNode_New("Command");
   4581 }
   4582 
   4583 /* Clean up the variables module. */
   4584 void
   4585 Var_End(void)
   4586 {
   4587 	Var_Stats();
   4588 }
   4589 
   4590 void
   4591 Var_Stats(void)
   4592 {
   4593 	HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables");
   4594 }
   4595 
   4596 /* Print all variables in a scope, sorted by name. */
   4597 void
   4598 Var_Dump(GNode *scope)
   4599 {
   4600 	Vector /* of const char * */ vec;
   4601 	HashIter hi;
   4602 	size_t i;
   4603 	const char **varnames;
   4604 
   4605 	Vector_Init(&vec, sizeof(const char *));
   4606 
   4607 	HashIter_Init(&hi, &scope->vars);
   4608 	while (HashIter_Next(&hi) != NULL)
   4609 		*(const char **)Vector_Push(&vec) = hi.entry->key;
   4610 	varnames = vec.items;
   4611 
   4612 	qsort(varnames, vec.len, sizeof varnames[0], str_cmp_asc);
   4613 
   4614 	for (i = 0; i < vec.len; i++) {
   4615 		const char *varname = varnames[i];
   4616 		Var *var = HashTable_FindValue(&scope->vars, varname);
   4617 		debug_printf("%-16s = %s\n", varname, var->val.data);
   4618 	}
   4619 
   4620 	Vector_Done(&vec);
   4621 }
   4622