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