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