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