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