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