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