Home | History | Annotate | Line # | Download | only in make
var.c revision 1.802
      1 /*	$NetBSD: var.c,v 1.802 2021/02/04 21:42:46 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.802 2021/02/04 21:42:46 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 		Var_Delete(varname, SCOPE_GLOBAL);
    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 		Var_Delete(MAKE_EXPORTED, SCOPE_GLOBAL);
    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 /*
   1067  * Append the value to the named variable.
   1068  *
   1069  * If the variable doesn't exist, it is created.  Otherwise a single space
   1070  * and the given value are appended.
   1071  */
   1072 void
   1073 Var_Append(const char *name, const char *val, GNode *scope)
   1074 {
   1075 	Var *v;
   1076 
   1077 	v = VarFind(name, scope, scope == SCOPE_GLOBAL);
   1078 
   1079 	if (v == NULL) {
   1080 		Var_SetWithFlags(name, val, scope, VAR_SET_NONE);
   1081 	} else if (v->flags & VAR_READONLY) {
   1082 		DEBUG1(VAR, "Ignoring append to %s since it is read-only\n",
   1083 		    name);
   1084 	} else if (scope == SCOPE_CMDLINE || !(v->flags & VAR_FROM_CMD)) {
   1085 		Buf_AddByte(&v->val, ' ');
   1086 		Buf_AddStr(&v->val, val);
   1087 
   1088 		DEBUG3(VAR, "%s:%s = %s\n", scope->name, name, v->val.data);
   1089 
   1090 		if (v->flags & VAR_FROM_ENV) {
   1091 			/*
   1092 			 * If the original variable came from the environment,
   1093 			 * we have to install it in the global scope (we
   1094 			 * could place it in the environment, but then we
   1095 			 * should provide a way to export other variables...)
   1096 			 */
   1097 			v->flags &= ~(unsigned)VAR_FROM_ENV;
   1098 			/*
   1099 			 * This is the only place where a variable is
   1100 			 * created whose v->name is not the same as
   1101 			 * scope->vars->key.
   1102 			 */
   1103 			HashTable_Set(&scope->vars, name, v);
   1104 		}
   1105 	}
   1106 }
   1107 
   1108 /*
   1109  * The variable of the given name has the given value appended to it in the
   1110  * given scope.
   1111  *
   1112  * If the variable doesn't exist, it is created. Otherwise the strings are
   1113  * concatenated, with a space in between.
   1114  *
   1115  * Input:
   1116  *	name		name of the variable to modify, is expanded once
   1117  *	val		string to append to it
   1118  *	scope		scope in which this should occur
   1119  *
   1120  * Notes:
   1121  *	Only if the variable is being sought in the global scope is the
   1122  *	environment searched.
   1123  *	XXX: Knows its calling circumstances in that if called with scope
   1124  *	an actual target, it will only search that scope since only
   1125  *	a local variable could be being appended to. This is actually
   1126  *	a big win and must be tolerated.
   1127  */
   1128 void
   1129 Var_AppendExpand(const char *name, const char *val, GNode *scope)
   1130 {
   1131 	char *name_freeIt = NULL;
   1132 
   1133 	assert(val != NULL);
   1134 
   1135 	if (strchr(name, '$') != NULL) {
   1136 		const char *unexpanded_name = name;
   1137 		(void)Var_Subst(name, scope, VARE_WANTRES, &name_freeIt);
   1138 		/* TODO: handle errors */
   1139 		name = name_freeIt;
   1140 		if (name[0] == '\0') {
   1141 			/* TODO: update function name in the debug message */
   1142 			DEBUG2(VAR, "Var_Append(\"%s\", \"%s\", ...) "
   1143 				    "name expands to empty string - ignored\n",
   1144 			    unexpanded_name, val);
   1145 			free(name_freeIt);
   1146 			return;
   1147 		}
   1148 	}
   1149 
   1150 	Var_Append(name, val, scope);
   1151 
   1152 	free(name_freeIt);
   1153 }
   1154 
   1155 void
   1156 Global_Append(const char *name, const char *value)
   1157 {
   1158 	Var_Append(name, value, SCOPE_GLOBAL);
   1159 }
   1160 
   1161 Boolean
   1162 Var_Exists(const char *name, GNode *scope)
   1163 {
   1164 	Var *v = VarFind(name, scope, TRUE);
   1165 	if (v == NULL)
   1166 		return FALSE;
   1167 
   1168 	(void)VarFreeEnv(v, TRUE);
   1169 	return TRUE;
   1170 }
   1171 
   1172 /*
   1173  * See if the given variable exists, in the given scope or in other
   1174  * fallback scopes.
   1175  *
   1176  * Input:
   1177  *	name		Variable to find, is expanded once
   1178  *	scope		Scope in which to start search
   1179  */
   1180 Boolean
   1181 Var_ExistsExpand(const char *name, GNode *scope)
   1182 {
   1183 	FStr varname = FStr_InitRefer(name);
   1184 	Boolean exists;
   1185 
   1186 	if (strchr(varname.str, '$') != NULL) {
   1187 		char *expanded;
   1188 		(void)Var_Subst(varname.str, scope, VARE_WANTRES, &expanded);
   1189 		/* TODO: handle errors */
   1190 		varname = FStr_InitOwn(expanded);
   1191 	}
   1192 
   1193 	exists = Var_Exists(varname.str, scope);
   1194 	FStr_Done(&varname);
   1195 	return exists;
   1196 }
   1197 
   1198 /*
   1199  * Return the unexpanded value of the given variable in the given scope,
   1200  * or the usual scopes.
   1201  *
   1202  * Input:
   1203  *	name		name to find, is not expanded any further
   1204  *	scope		scope in which to search for it
   1205  *
   1206  * Results:
   1207  *	The value if the variable exists, NULL if it doesn't.
   1208  *	If the returned value is not NULL, the caller must free
   1209  *	out_freeIt when the returned value is no longer needed.
   1210  */
   1211 FStr
   1212 Var_Value(const char *name, GNode *scope)
   1213 {
   1214 	Var *v = VarFind(name, scope, TRUE);
   1215 	char *value;
   1216 
   1217 	if (v == NULL)
   1218 		return FStr_InitRefer(NULL);
   1219 
   1220 	value = v->val.data;
   1221 	return VarFreeEnv(v, FALSE)
   1222 	    ? FStr_InitOwn(value)
   1223 	    : FStr_InitRefer(value);
   1224 }
   1225 
   1226 /*
   1227  * Return the unexpanded variable value from this node, without trying to look
   1228  * up the variable in any other scope.
   1229  */
   1230 const char *
   1231 Var_ValueDirect(const char *name, GNode *scope)
   1232 {
   1233 	Var *v = VarFind(name, scope, FALSE);
   1234 	return v != NULL ? v->val.data : NULL;
   1235 }
   1236 
   1237 
   1238 static void
   1239 SepBuf_Init(SepBuf *buf, char sep)
   1240 {
   1241 	Buf_InitSize(&buf->buf, 32);
   1242 	buf->needSep = FALSE;
   1243 	buf->sep = sep;
   1244 }
   1245 
   1246 static void
   1247 SepBuf_Sep(SepBuf *buf)
   1248 {
   1249 	buf->needSep = TRUE;
   1250 }
   1251 
   1252 static void
   1253 SepBuf_AddBytes(SepBuf *buf, const char *mem, size_t mem_size)
   1254 {
   1255 	if (mem_size == 0)
   1256 		return;
   1257 	if (buf->needSep && buf->sep != '\0') {
   1258 		Buf_AddByte(&buf->buf, buf->sep);
   1259 		buf->needSep = FALSE;
   1260 	}
   1261 	Buf_AddBytes(&buf->buf, mem, mem_size);
   1262 }
   1263 
   1264 static void
   1265 SepBuf_AddBytesBetween(SepBuf *buf, const char *start, const char *end)
   1266 {
   1267 	SepBuf_AddBytes(buf, start, (size_t)(end - start));
   1268 }
   1269 
   1270 static void
   1271 SepBuf_AddStr(SepBuf *buf, const char *str)
   1272 {
   1273 	SepBuf_AddBytes(buf, str, strlen(str));
   1274 }
   1275 
   1276 static char *
   1277 SepBuf_DoneData(SepBuf *buf)
   1278 {
   1279 	return Buf_DoneData(&buf->buf);
   1280 }
   1281 
   1282 
   1283 /*
   1284  * This callback for ModifyWords gets a single word from a variable expression
   1285  * and typically adds a modification of this word to the buffer. It may also
   1286  * do nothing or add several words.
   1287  *
   1288  * For example, in ${:Ua b c:M*2}, the callback is called 3 times, once for
   1289  * each word of "a b c".
   1290  */
   1291 typedef void (*ModifyWordsCallback)(const char *word, SepBuf *buf, void *data);
   1292 
   1293 
   1294 /*
   1295  * Callback for ModifyWords to implement the :H modifier.
   1296  * Add the dirname of the given word to the buffer.
   1297  */
   1298 /*ARGSUSED*/
   1299 static void
   1300 ModifyWord_Head(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1301 {
   1302 	const char *slash = strrchr(word, '/');
   1303 	if (slash != NULL)
   1304 		SepBuf_AddBytesBetween(buf, word, slash);
   1305 	else
   1306 		SepBuf_AddStr(buf, ".");
   1307 }
   1308 
   1309 /*
   1310  * Callback for ModifyWords to implement the :T modifier.
   1311  * Add the basename of the given word to the buffer.
   1312  */
   1313 /*ARGSUSED*/
   1314 static void
   1315 ModifyWord_Tail(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1316 {
   1317 	SepBuf_AddStr(buf, str_basename(word));
   1318 }
   1319 
   1320 /*
   1321  * Callback for ModifyWords to implement the :E modifier.
   1322  * Add the filename suffix of the given word to the buffer, if it exists.
   1323  */
   1324 /*ARGSUSED*/
   1325 static void
   1326 ModifyWord_Suffix(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1327 {
   1328 	const char *lastDot = strrchr(word, '.');
   1329 	if (lastDot != NULL)
   1330 		SepBuf_AddStr(buf, lastDot + 1);
   1331 }
   1332 
   1333 /*
   1334  * Callback for ModifyWords to implement the :R modifier.
   1335  * Add the basename of the given word to the buffer.
   1336  */
   1337 /*ARGSUSED*/
   1338 static void
   1339 ModifyWord_Root(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1340 {
   1341 	const char *lastDot = strrchr(word, '.');
   1342 	size_t len = lastDot != NULL ? (size_t)(lastDot - word) : strlen(word);
   1343 	SepBuf_AddBytes(buf, word, len);
   1344 }
   1345 
   1346 /*
   1347  * Callback for ModifyWords to implement the :M modifier.
   1348  * Place the word in the buffer if it matches the given pattern.
   1349  */
   1350 static void
   1351 ModifyWord_Match(const char *word, SepBuf *buf, void *data)
   1352 {
   1353 	const char *pattern = data;
   1354 	DEBUG2(VAR, "VarMatch [%s] [%s]\n", word, pattern);
   1355 	if (Str_Match(word, pattern))
   1356 		SepBuf_AddStr(buf, word);
   1357 }
   1358 
   1359 /*
   1360  * Callback for ModifyWords to implement the :N modifier.
   1361  * Place the word in the buffer if it doesn't match the given pattern.
   1362  */
   1363 static void
   1364 ModifyWord_NoMatch(const char *word, SepBuf *buf, void *data)
   1365 {
   1366 	const char *pattern = data;
   1367 	if (!Str_Match(word, pattern))
   1368 		SepBuf_AddStr(buf, word);
   1369 }
   1370 
   1371 #ifdef SYSVVARSUB
   1372 
   1373 /*
   1374  * Check word against pattern for a match (% is a wildcard).
   1375  *
   1376  * Input:
   1377  *	word		Word to examine
   1378  *	pattern		Pattern to examine against
   1379  *
   1380  * Results:
   1381  *	Returns the start of the match, or NULL.
   1382  *	out_match_len returns the length of the match, if any.
   1383  *	out_hasPercent returns whether the pattern contains a percent.
   1384  */
   1385 static const char *
   1386 SysVMatch(const char *word, const char *pattern,
   1387 	  size_t *out_match_len, Boolean *out_hasPercent)
   1388 {
   1389 	const char *p = pattern;
   1390 	const char *w = word;
   1391 	const char *percent;
   1392 	size_t w_len;
   1393 	size_t p_len;
   1394 	const char *w_tail;
   1395 
   1396 	*out_hasPercent = FALSE;
   1397 	percent = strchr(p, '%');
   1398 	if (percent != NULL) {	/* ${VAR:...%...=...} */
   1399 		*out_hasPercent = TRUE;
   1400 		if (w[0] == '\0')
   1401 			return NULL;	/* empty word does not match pattern */
   1402 
   1403 		/* check that the prefix matches */
   1404 		for (; p != percent && *w != '\0' && *w == *p; w++, p++)
   1405 			continue;
   1406 		if (p != percent)
   1407 			return NULL;	/* No match */
   1408 
   1409 		p++;		/* Skip the percent */
   1410 		if (*p == '\0') {
   1411 			/* No more pattern, return the rest of the string */
   1412 			*out_match_len = strlen(w);
   1413 			return w;
   1414 		}
   1415 	}
   1416 
   1417 	/* Test whether the tail matches */
   1418 	w_len = strlen(w);
   1419 	p_len = strlen(p);
   1420 	if (w_len < p_len)
   1421 		return NULL;
   1422 
   1423 	w_tail = w + w_len - p_len;
   1424 	if (memcmp(p, w_tail, p_len) != 0)
   1425 		return NULL;
   1426 
   1427 	*out_match_len = (size_t)(w_tail - w);
   1428 	return w;
   1429 }
   1430 
   1431 struct ModifyWord_SYSVSubstArgs {
   1432 	GNode *ctx;
   1433 	const char *lhs;
   1434 	const char *rhs;
   1435 };
   1436 
   1437 /* Callback for ModifyWords to implement the :%.from=%.to modifier. */
   1438 static void
   1439 ModifyWord_SYSVSubst(const char *word, SepBuf *buf, void *data)
   1440 {
   1441 	const struct ModifyWord_SYSVSubstArgs *args = data;
   1442 	char *rhs_expanded;
   1443 	const char *rhs;
   1444 	const char *percent;
   1445 
   1446 	size_t match_len;
   1447 	Boolean lhsPercent;
   1448 	const char *match = SysVMatch(word, args->lhs, &match_len, &lhsPercent);
   1449 	if (match == NULL) {
   1450 		SepBuf_AddStr(buf, word);
   1451 		return;
   1452 	}
   1453 
   1454 	/*
   1455 	 * Append rhs to the buffer, substituting the first '%' with the
   1456 	 * match, but only if the lhs had a '%' as well.
   1457 	 */
   1458 
   1459 	(void)Var_Subst(args->rhs, args->ctx, VARE_WANTRES, &rhs_expanded);
   1460 	/* TODO: handle errors */
   1461 
   1462 	rhs = rhs_expanded;
   1463 	percent = strchr(rhs, '%');
   1464 
   1465 	if (percent != NULL && lhsPercent) {
   1466 		/* Copy the prefix of the replacement pattern */
   1467 		SepBuf_AddBytesBetween(buf, rhs, percent);
   1468 		rhs = percent + 1;
   1469 	}
   1470 	if (percent != NULL || !lhsPercent)
   1471 		SepBuf_AddBytes(buf, match, match_len);
   1472 
   1473 	/* Append the suffix of the replacement pattern */
   1474 	SepBuf_AddStr(buf, rhs);
   1475 
   1476 	free(rhs_expanded);
   1477 }
   1478 #endif
   1479 
   1480 
   1481 struct ModifyWord_SubstArgs {
   1482 	const char *lhs;
   1483 	size_t lhsLen;
   1484 	const char *rhs;
   1485 	size_t rhsLen;
   1486 	VarPatternFlags pflags;
   1487 	Boolean matched;
   1488 };
   1489 
   1490 /*
   1491  * Callback for ModifyWords to implement the :S,from,to, modifier.
   1492  * Perform a string substitution on the given word.
   1493  */
   1494 static void
   1495 ModifyWord_Subst(const char *word, SepBuf *buf, void *data)
   1496 {
   1497 	size_t wordLen = strlen(word);
   1498 	struct ModifyWord_SubstArgs *args = data;
   1499 	const char *match;
   1500 
   1501 	if (args->pflags.subOnce && args->matched)
   1502 		goto nosub;
   1503 
   1504 	if (args->pflags.anchorStart) {
   1505 		if (wordLen < args->lhsLen ||
   1506 		    memcmp(word, args->lhs, args->lhsLen) != 0)
   1507 			goto nosub;
   1508 
   1509 		if ((args->pflags.anchorEnd) && wordLen != args->lhsLen)
   1510 			goto nosub;
   1511 
   1512 		/* :S,^prefix,replacement, or :S,^whole$,replacement, */
   1513 		SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
   1514 		SepBuf_AddBytes(buf, word + args->lhsLen,
   1515 		    wordLen - args->lhsLen);
   1516 		args->matched = TRUE;
   1517 		return;
   1518 	}
   1519 
   1520 	if (args->pflags.anchorEnd) {
   1521 		const char *start;
   1522 
   1523 		if (wordLen < args->lhsLen)
   1524 			goto nosub;
   1525 
   1526 		start = word + (wordLen - args->lhsLen);
   1527 		if (memcmp(start, args->lhs, args->lhsLen) != 0)
   1528 			goto nosub;
   1529 
   1530 		/* :S,suffix$,replacement, */
   1531 		SepBuf_AddBytesBetween(buf, word, start);
   1532 		SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
   1533 		args->matched = TRUE;
   1534 		return;
   1535 	}
   1536 
   1537 	if (args->lhs[0] == '\0')
   1538 		goto nosub;
   1539 
   1540 	/* unanchored case, may match more than once */
   1541 	while ((match = strstr(word, args->lhs)) != NULL) {
   1542 		SepBuf_AddBytesBetween(buf, word, match);
   1543 		SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
   1544 		args->matched = TRUE;
   1545 		wordLen -= (size_t)(match - word) + args->lhsLen;
   1546 		word += (size_t)(match - word) + args->lhsLen;
   1547 		if (wordLen == 0 || !args->pflags.subGlobal)
   1548 			break;
   1549 	}
   1550 nosub:
   1551 	SepBuf_AddBytes(buf, word, wordLen);
   1552 }
   1553 
   1554 #ifndef NO_REGEX
   1555 /* Print the error caused by a regcomp or regexec call. */
   1556 static void
   1557 VarREError(int reerr, const regex_t *pat, const char *str)
   1558 {
   1559 	size_t errlen = regerror(reerr, pat, NULL, 0);
   1560 	char *errbuf = bmake_malloc(errlen);
   1561 	regerror(reerr, pat, errbuf, errlen);
   1562 	Error("%s: %s", str, errbuf);
   1563 	free(errbuf);
   1564 }
   1565 
   1566 struct ModifyWord_SubstRegexArgs {
   1567 	regex_t re;
   1568 	size_t nsub;
   1569 	char *replace;
   1570 	VarPatternFlags pflags;
   1571 	Boolean matched;
   1572 };
   1573 
   1574 /*
   1575  * Callback for ModifyWords to implement the :C/from/to/ modifier.
   1576  * Perform a regex substitution on the given word.
   1577  */
   1578 static void
   1579 ModifyWord_SubstRegex(const char *word, SepBuf *buf, void *data)
   1580 {
   1581 	struct ModifyWord_SubstRegexArgs *args = data;
   1582 	int xrv;
   1583 	const char *wp = word;
   1584 	char *rp;
   1585 	int flags = 0;
   1586 	regmatch_t m[10];
   1587 
   1588 	if (args->pflags.subOnce && args->matched)
   1589 		goto nosub;
   1590 
   1591 tryagain:
   1592 	xrv = regexec(&args->re, wp, args->nsub, m, flags);
   1593 
   1594 	switch (xrv) {
   1595 	case 0:
   1596 		args->matched = TRUE;
   1597 		SepBuf_AddBytes(buf, wp, (size_t)m[0].rm_so);
   1598 
   1599 		for (rp = args->replace; *rp != '\0'; rp++) {
   1600 			if (*rp == '\\' && (rp[1] == '&' || rp[1] == '\\')) {
   1601 				SepBuf_AddBytes(buf, rp + 1, 1);
   1602 				rp++;
   1603 				continue;
   1604 			}
   1605 
   1606 			if (*rp == '&') {
   1607 				SepBuf_AddBytesBetween(buf,
   1608 				    wp + m[0].rm_so, wp + m[0].rm_eo);
   1609 				continue;
   1610 			}
   1611 
   1612 			if (*rp != '\\' || !ch_isdigit(rp[1])) {
   1613 				SepBuf_AddBytes(buf, rp, 1);
   1614 				continue;
   1615 			}
   1616 
   1617 			{	/* \0 to \9 backreference */
   1618 				size_t n = (size_t)(rp[1] - '0');
   1619 				rp++;
   1620 
   1621 				if (n >= args->nsub) {
   1622 					Error("No subexpression \\%u",
   1623 					    (unsigned)n);
   1624 				} else if (m[n].rm_so == -1) {
   1625 					Error(
   1626 					    "No match for subexpression \\%u",
   1627 					    (unsigned)n);
   1628 				} else {
   1629 					SepBuf_AddBytesBetween(buf,
   1630 					    wp + m[n].rm_so, wp + m[n].rm_eo);
   1631 				}
   1632 			}
   1633 		}
   1634 
   1635 		wp += m[0].rm_eo;
   1636 		if (args->pflags.subGlobal) {
   1637 			flags |= REG_NOTBOL;
   1638 			if (m[0].rm_so == 0 && m[0].rm_eo == 0) {
   1639 				SepBuf_AddBytes(buf, wp, 1);
   1640 				wp++;
   1641 			}
   1642 			if (*wp != '\0')
   1643 				goto tryagain;
   1644 		}
   1645 		if (*wp != '\0')
   1646 			SepBuf_AddStr(buf, wp);
   1647 		break;
   1648 	default:
   1649 		VarREError(xrv, &args->re, "Unexpected regex error");
   1650 		/* FALLTHROUGH */
   1651 	case REG_NOMATCH:
   1652 	nosub:
   1653 		SepBuf_AddStr(buf, wp);
   1654 		break;
   1655 	}
   1656 }
   1657 #endif
   1658 
   1659 
   1660 struct ModifyWord_LoopArgs {
   1661 	GNode *ctx;
   1662 	char *tvar;		/* name of temporary variable */
   1663 	char *str;		/* string to expand */
   1664 	VarEvalFlags eflags;
   1665 };
   1666 
   1667 /* Callback for ModifyWords to implement the :@var (at) ...@ modifier of ODE make. */
   1668 static void
   1669 ModifyWord_Loop(const char *word, SepBuf *buf, void *data)
   1670 {
   1671 	const struct ModifyWord_LoopArgs *args;
   1672 	char *s;
   1673 
   1674 	if (word[0] == '\0')
   1675 		return;
   1676 
   1677 	args = data;
   1678 	/* XXX: The variable name should not be expanded here. */
   1679 	Var_SetExpandWithFlags(args->tvar, word, args->ctx, VAR_SET_NO_EXPORT);
   1680 	(void)Var_Subst(args->str, args->ctx, args->eflags, &s);
   1681 	/* TODO: handle errors */
   1682 
   1683 	DEBUG4(VAR, "ModifyWord_Loop: "
   1684 		    "in \"%s\", replace \"%s\" with \"%s\" to \"%s\"\n",
   1685 	    word, args->tvar, args->str, s);
   1686 
   1687 	if (s[0] == '\n' || Buf_EndsWith(&buf->buf, '\n'))
   1688 		buf->needSep = FALSE;
   1689 	SepBuf_AddStr(buf, s);
   1690 	free(s);
   1691 }
   1692 
   1693 
   1694 /*
   1695  * The :[first..last] modifier selects words from the expression.
   1696  * It can also reverse the words.
   1697  */
   1698 static char *
   1699 VarSelectWords(char sep, Boolean oneBigWord, const char *str, int first,
   1700 	       int last)
   1701 {
   1702 	Words words;
   1703 	int len, start, end, step;
   1704 	int i;
   1705 
   1706 	SepBuf buf;
   1707 	SepBuf_Init(&buf, sep);
   1708 
   1709 	if (oneBigWord) {
   1710 		/* fake what Str_Words() would do if there were only one word */
   1711 		words.len = 1;
   1712 		words.words = bmake_malloc(
   1713 		    (words.len + 1) * sizeof(words.words[0]));
   1714 		words.freeIt = bmake_strdup(str);
   1715 		words.words[0] = words.freeIt;
   1716 		words.words[1] = NULL;
   1717 	} else {
   1718 		words = Str_Words(str, FALSE);
   1719 	}
   1720 
   1721 	/*
   1722 	 * Now sanitize the given range.  If first or last are negative,
   1723 	 * convert them to the positive equivalents (-1 gets converted to len,
   1724 	 * -2 gets converted to (len - 1), etc.).
   1725 	 */
   1726 	len = (int)words.len;
   1727 	if (first < 0)
   1728 		first += len + 1;
   1729 	if (last < 0)
   1730 		last += len + 1;
   1731 
   1732 	/* We avoid scanning more of the list than we need to. */
   1733 	if (first > last) {
   1734 		start = (first > len ? len : first) - 1;
   1735 		end = last < 1 ? 0 : last - 1;
   1736 		step = -1;
   1737 	} else {
   1738 		start = first < 1 ? 0 : first - 1;
   1739 		end = last > len ? len : last;
   1740 		step = 1;
   1741 	}
   1742 
   1743 	for (i = start; (step < 0) == (i >= end); i += step) {
   1744 		SepBuf_AddStr(&buf, words.words[i]);
   1745 		SepBuf_Sep(&buf);
   1746 	}
   1747 
   1748 	Words_Free(words);
   1749 
   1750 	return SepBuf_DoneData(&buf);
   1751 }
   1752 
   1753 
   1754 /*
   1755  * Callback for ModifyWords to implement the :tA modifier.
   1756  * Replace each word with the result of realpath() if successful.
   1757  */
   1758 /*ARGSUSED*/
   1759 static void
   1760 ModifyWord_Realpath(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   1761 {
   1762 	struct stat st;
   1763 	char rbuf[MAXPATHLEN];
   1764 
   1765 	const char *rp = cached_realpath(word, rbuf);
   1766 	if (rp != NULL && *rp == '/' && stat(rp, &st) == 0)
   1767 		word = rp;
   1768 
   1769 	SepBuf_AddStr(buf, word);
   1770 }
   1771 
   1772 /*
   1773  * Modify each of the words of the passed string using the given function.
   1774  *
   1775  * Input:
   1776  *	str		String whose words should be modified
   1777  *	modifyWord	Function that modifies a single word
   1778  *	modifyWord_args Custom arguments for modifyWord
   1779  *
   1780  * Results:
   1781  *	A string of all the words modified appropriately.
   1782  */
   1783 static char *
   1784 ModifyWords(const char *str,
   1785 	    ModifyWordsCallback modifyWord, void *modifyWord_args,
   1786 	    Boolean oneBigWord, char sep)
   1787 {
   1788 	SepBuf result;
   1789 	Words words;
   1790 	size_t i;
   1791 
   1792 	if (oneBigWord) {
   1793 		SepBuf_Init(&result, sep);
   1794 		modifyWord(str, &result, modifyWord_args);
   1795 		return SepBuf_DoneData(&result);
   1796 	}
   1797 
   1798 	SepBuf_Init(&result, sep);
   1799 
   1800 	words = Str_Words(str, FALSE);
   1801 
   1802 	DEBUG2(VAR, "ModifyWords: split \"%s\" into %u words\n",
   1803 	    str, (unsigned)words.len);
   1804 
   1805 	for (i = 0; i < words.len; i++) {
   1806 		modifyWord(words.words[i], &result, modifyWord_args);
   1807 		if (result.buf.len > 0)
   1808 			SepBuf_Sep(&result);
   1809 	}
   1810 
   1811 	Words_Free(words);
   1812 
   1813 	return SepBuf_DoneData(&result);
   1814 }
   1815 
   1816 
   1817 static char *
   1818 Words_JoinFree(Words words)
   1819 {
   1820 	Buffer buf;
   1821 	size_t i;
   1822 
   1823 	Buf_Init(&buf);
   1824 
   1825 	for (i = 0; i < words.len; i++) {
   1826 		if (i != 0) {
   1827 			/* XXX: Use st->sep instead of ' ', for consistency. */
   1828 			Buf_AddByte(&buf, ' ');
   1829 		}
   1830 		Buf_AddStr(&buf, words.words[i]);
   1831 	}
   1832 
   1833 	Words_Free(words);
   1834 
   1835 	return Buf_DoneData(&buf);
   1836 }
   1837 
   1838 /* Remove adjacent duplicate words. */
   1839 static char *
   1840 VarUniq(const char *str)
   1841 {
   1842 	Words words = Str_Words(str, FALSE);
   1843 
   1844 	if (words.len > 1) {
   1845 		size_t i, j;
   1846 		for (j = 0, i = 1; i < words.len; i++)
   1847 			if (strcmp(words.words[i], words.words[j]) != 0 &&
   1848 			    (++j != i))
   1849 				words.words[j] = words.words[i];
   1850 		words.len = j + 1;
   1851 	}
   1852 
   1853 	return Words_JoinFree(words);
   1854 }
   1855 
   1856 
   1857 /*
   1858  * Quote shell meta-characters and space characters in the string.
   1859  * If quoteDollar is set, also quote and double any '$' characters.
   1860  */
   1861 static char *
   1862 VarQuote(const char *str, Boolean quoteDollar)
   1863 {
   1864 	Buffer buf;
   1865 	Buf_Init(&buf);
   1866 
   1867 	for (; *str != '\0'; str++) {
   1868 		if (*str == '\n') {
   1869 			const char *newline = Shell_GetNewline();
   1870 			if (newline == NULL)
   1871 				newline = "\\\n";
   1872 			Buf_AddStr(&buf, newline);
   1873 			continue;
   1874 		}
   1875 		if (ch_isspace(*str) || is_shell_metachar((unsigned char)*str))
   1876 			Buf_AddByte(&buf, '\\');
   1877 		Buf_AddByte(&buf, *str);
   1878 		if (quoteDollar && *str == '$')
   1879 			Buf_AddStr(&buf, "\\$");
   1880 	}
   1881 
   1882 	return Buf_DoneData(&buf);
   1883 }
   1884 
   1885 /*
   1886  * Compute the 32-bit hash of the given string, using the MurmurHash3
   1887  * algorithm. Output is encoded as 8 hex digits, in Little Endian order.
   1888  */
   1889 static char *
   1890 VarHash(const char *str)
   1891 {
   1892 	static const char hexdigits[16] = "0123456789abcdef";
   1893 	const unsigned char *ustr = (const unsigned char *)str;
   1894 
   1895 	uint32_t h = 0x971e137bU;
   1896 	uint32_t c1 = 0x95543787U;
   1897 	uint32_t c2 = 0x2ad7eb25U;
   1898 	size_t len2 = strlen(str);
   1899 
   1900 	char *buf;
   1901 	size_t i;
   1902 
   1903 	size_t len;
   1904 	for (len = len2; len != 0;) {
   1905 		uint32_t k = 0;
   1906 		switch (len) {
   1907 		default:
   1908 			k = ((uint32_t)ustr[3] << 24) |
   1909 			    ((uint32_t)ustr[2] << 16) |
   1910 			    ((uint32_t)ustr[1] << 8) |
   1911 			    (uint32_t)ustr[0];
   1912 			len -= 4;
   1913 			ustr += 4;
   1914 			break;
   1915 		case 3:
   1916 			k |= (uint32_t)ustr[2] << 16;
   1917 			/* FALLTHROUGH */
   1918 		case 2:
   1919 			k |= (uint32_t)ustr[1] << 8;
   1920 			/* FALLTHROUGH */
   1921 		case 1:
   1922 			k |= (uint32_t)ustr[0];
   1923 			len = 0;
   1924 		}
   1925 		c1 = c1 * 5 + 0x7b7d159cU;
   1926 		c2 = c2 * 5 + 0x6bce6396U;
   1927 		k *= c1;
   1928 		k = (k << 11) ^ (k >> 21);
   1929 		k *= c2;
   1930 		h = (h << 13) ^ (h >> 19);
   1931 		h = h * 5 + 0x52dce729U;
   1932 		h ^= k;
   1933 	}
   1934 	h ^= (uint32_t)len2;
   1935 	h *= 0x85ebca6b;
   1936 	h ^= h >> 13;
   1937 	h *= 0xc2b2ae35;
   1938 	h ^= h >> 16;
   1939 
   1940 	buf = bmake_malloc(9);
   1941 	for (i = 0; i < 8; i++) {
   1942 		buf[i] = hexdigits[h & 0x0f];
   1943 		h >>= 4;
   1944 	}
   1945 	buf[8] = '\0';
   1946 	return buf;
   1947 }
   1948 
   1949 static char *
   1950 VarStrftime(const char *fmt, Boolean zulu, time_t tim)
   1951 {
   1952 	char buf[BUFSIZ];
   1953 
   1954 	if (tim == 0)
   1955 		time(&tim);
   1956 	if (*fmt == '\0')
   1957 		fmt = "%c";
   1958 	strftime(buf, sizeof buf, fmt, zulu ? gmtime(&tim) : localtime(&tim));
   1959 
   1960 	buf[sizeof buf - 1] = '\0';
   1961 	return bmake_strdup(buf);
   1962 }
   1963 
   1964 /*
   1965  * The ApplyModifier functions take an expression that is being evaluated.
   1966  * Their task is to apply a single modifier to the expression.
   1967  * To do this, they parse the modifier and its parameters from pp and apply
   1968  * the parsed modifier to the current value of the expression, generating a
   1969  * new value from it.
   1970  *
   1971  * The modifier typically lasts until the next ':', or a closing '}' or ')'
   1972  * (taken from st->endc), or the end of the string (parse error).
   1973  *
   1974  * The high-level behavior of these functions is:
   1975  *
   1976  * 1. parse the modifier
   1977  * 2. evaluate the modifier
   1978  * 3. housekeeping
   1979  *
   1980  * Parsing the modifier
   1981  *
   1982  * If parsing succeeds, the parsing position *pp is updated to point to the
   1983  * first character following the modifier, which typically is either ':' or
   1984  * st->endc.  The modifier doesn't have to check for this delimiter character,
   1985  * this is done by ApplyModifiers.
   1986  *
   1987  * XXX: As of 2020-11-15, some modifiers such as :S, :C, :P, :L do not
   1988  * need to be followed by a ':' or endc; this was an unintended mistake.
   1989  *
   1990  * If parsing fails because of a missing delimiter (as in the :S, :C or :@
   1991  * modifiers), return AMR_CLEANUP.
   1992  *
   1993  * If parsing fails because the modifier is unknown, return AMR_UNKNOWN to
   1994  * try the SysV modifier ${VAR:from=to} as fallback.  This should only be
   1995  * done as long as there have been no side effects from evaluating nested
   1996  * variables, to avoid evaluating them more than once.  In this case, the
   1997  * parsing position may or may not be updated.  (XXX: Why not? The original
   1998  * parsing position is well-known in ApplyModifiers.)
   1999  *
   2000  * If parsing fails and the SysV modifier ${VAR:from=to} should not be used
   2001  * as a fallback, either issue an error message using Error or Parse_Error
   2002  * and then return AMR_CLEANUP, or return AMR_BAD for the default error
   2003  * message.  Both of these return values will stop processing the variable
   2004  * expression.  (XXX: As of 2020-08-23, evaluation of the whole string
   2005  * continues nevertheless after skipping a few bytes, which essentially is
   2006  * undefined behavior.  Not in the sense of C, but still it's impossible to
   2007  * predict what happens in the parser.)
   2008  *
   2009  * Evaluating the modifier
   2010  *
   2011  * After parsing, the modifier is evaluated.  The side effects from evaluating
   2012  * nested variable expressions in the modifier text often already happen
   2013  * during parsing though.
   2014  *
   2015  * Evaluating the modifier usually takes the current value of the variable
   2016  * expression from st->val, or the variable name from st->var->name and stores
   2017  * the result in st->newVal.
   2018  *
   2019  * If evaluating fails (as of 2020-08-23), an error message is printed using
   2020  * Error.  This function has no side-effects, it really just prints the error
   2021  * message.  Processing the expression continues as if everything were ok.
   2022  * XXX: This should be fixed by adding proper error handling to Var_Subst,
   2023  * Var_Parse, ApplyModifiers and ModifyWords.
   2024  *
   2025  * Housekeeping
   2026  *
   2027  * Some modifiers such as :D and :U turn undefined expressions into defined
   2028  * expressions (see VEF_UNDEF, VEF_DEF).
   2029  *
   2030  * Some modifiers need to free some memory.
   2031  */
   2032 
   2033 typedef enum VarExprStatus {
   2034 	/* The variable expression is based in a regular, defined variable. */
   2035 	VES_NONE,
   2036 	/* The variable expression is based on an undefined variable. */
   2037 	VES_UNDEF,
   2038 	/*
   2039 	 * The variable expression started as an undefined expression, but one
   2040 	 * of the modifiers (such as :D or :U) has turned the expression from
   2041 	 * undefined to defined.
   2042 	 */
   2043 	VES_DEF
   2044 } VarExprStatus;
   2045 
   2046 static const char * const VarExprStatus_Name[] = {
   2047 	    "none",
   2048 	    "VES_UNDEF",
   2049 	    "VES_DEF"
   2050 };
   2051 
   2052 typedef struct ApplyModifiersState {
   2053 	/* '\0' or '{' or '(' */
   2054 	const char startc;
   2055 	/* '\0' or '}' or ')' */
   2056 	const char endc;
   2057 	Var *const var;
   2058 	GNode *const scope;
   2059 	const VarEvalFlags eflags;
   2060 	/*
   2061 	 * The new value of the expression, after applying the modifier,
   2062 	 * never NULL.
   2063 	 */
   2064 	FStr newVal;
   2065 	/* Word separator in expansions (see the :ts modifier). */
   2066 	char sep;
   2067 	/*
   2068 	 * TRUE if some modifiers that otherwise split the variable value
   2069 	 * into words, like :S and :C, treat the variable value as a single
   2070 	 * big word, possibly containing spaces.
   2071 	 */
   2072 	Boolean oneBigWord;
   2073 	VarExprStatus exprStatus;
   2074 } ApplyModifiersState;
   2075 
   2076 static void
   2077 ApplyModifiersState_Define(ApplyModifiersState *st)
   2078 {
   2079 	if (st->exprStatus == VES_UNDEF)
   2080 		st->exprStatus = VES_DEF;
   2081 }
   2082 
   2083 typedef enum ApplyModifierResult {
   2084 	/* Continue parsing */
   2085 	AMR_OK,
   2086 	/* Not a match, try other modifiers as well */
   2087 	AMR_UNKNOWN,
   2088 	/* Error out with "Bad modifier" message */
   2089 	AMR_BAD,
   2090 	/* Error out without error message */
   2091 	AMR_CLEANUP
   2092 } ApplyModifierResult;
   2093 
   2094 /*
   2095  * Allow backslashes to escape the delimiter, $, and \, but don't touch other
   2096  * backslashes.
   2097  */
   2098 static Boolean
   2099 IsEscapedModifierPart(const char *p, char delim,
   2100 		      struct ModifyWord_SubstArgs *subst)
   2101 {
   2102 	if (p[0] != '\\')
   2103 		return FALSE;
   2104 	if (p[1] == delim || p[1] == '\\' || p[1] == '$')
   2105 		return TRUE;
   2106 	return p[1] == '&' && subst != NULL;
   2107 }
   2108 
   2109 /* See ParseModifierPart */
   2110 static VarParseResult
   2111 ParseModifierPartSubst(
   2112     const char **pp,
   2113     char delim,
   2114     VarEvalFlags eflags,
   2115     ApplyModifiersState *st,
   2116     char **out_part,
   2117     /* Optionally stores the length of the returned string, just to save
   2118      * another strlen call. */
   2119     size_t *out_length,
   2120     /* For the first part of the :S modifier, sets the VARP_ANCHOR_END flag
   2121      * if the last character of the pattern is a $. */
   2122     VarPatternFlags *out_pflags,
   2123     /* For the second part of the :S modifier, allow ampersands to be
   2124      * escaped and replace unescaped ampersands with subst->lhs. */
   2125     struct ModifyWord_SubstArgs *subst
   2126 )
   2127 {
   2128 	Buffer buf;
   2129 	const char *p;
   2130 
   2131 	Buf_Init(&buf);
   2132 
   2133 	/*
   2134 	 * Skim through until the matching delimiter is found; pick up
   2135 	 * variable expressions on the way.
   2136 	 */
   2137 	p = *pp;
   2138 	while (*p != '\0' && *p != delim) {
   2139 		const char *varstart;
   2140 
   2141 		if (IsEscapedModifierPart(p, delim, subst)) {
   2142 			Buf_AddByte(&buf, p[1]);
   2143 			p += 2;
   2144 			continue;
   2145 		}
   2146 
   2147 		if (*p != '$') {	/* Unescaped, simple text */
   2148 			if (subst != NULL && *p == '&')
   2149 				Buf_AddBytes(&buf, subst->lhs, subst->lhsLen);
   2150 			else
   2151 				Buf_AddByte(&buf, *p);
   2152 			p++;
   2153 			continue;
   2154 		}
   2155 
   2156 		if (p[1] == delim) {	/* Unescaped $ at end of pattern */
   2157 			if (out_pflags != NULL)
   2158 				out_pflags->anchorEnd = TRUE;
   2159 			else
   2160 				Buf_AddByte(&buf, *p);
   2161 			p++;
   2162 			continue;
   2163 		}
   2164 
   2165 		if (eflags & VARE_WANTRES) { /* Nested variable, evaluated */
   2166 			const char *nested_p = p;
   2167 			FStr nested_val;
   2168 			VarEvalFlags nested_eflags =
   2169 			    eflags & ~(unsigned)VARE_KEEP_DOLLAR;
   2170 
   2171 			(void)Var_Parse(&nested_p, st->scope, nested_eflags,
   2172 			    &nested_val);
   2173 			/* TODO: handle errors */
   2174 			Buf_AddStr(&buf, nested_val.str);
   2175 			FStr_Done(&nested_val);
   2176 			p += nested_p - p;
   2177 			continue;
   2178 		}
   2179 
   2180 		/*
   2181 		 * XXX: This whole block is very similar to Var_Parse without
   2182 		 * VARE_WANTRES.  There may be subtle edge cases though that
   2183 		 * are not yet covered in the unit tests and that are parsed
   2184 		 * differently, depending on whether they are evaluated or
   2185 		 * not.
   2186 		 *
   2187 		 * This subtle difference is not documented in the manual
   2188 		 * page, neither is the difference between parsing :D and
   2189 		 * :M documented. No code should ever depend on these
   2190 		 * details, but who knows.
   2191 		 */
   2192 
   2193 		varstart = p;	/* Nested variable, only parsed */
   2194 		if (p[1] == '(' || p[1] == '{') {
   2195 			/*
   2196 			 * Find the end of this variable reference
   2197 			 * and suck it in without further ado.
   2198 			 * It will be interpreted later.
   2199 			 */
   2200 			char startc = p[1];
   2201 			int endc = startc == '(' ? ')' : '}';
   2202 			int depth = 1;
   2203 
   2204 			for (p += 2; *p != '\0' && depth > 0; p++) {
   2205 				if (p[-1] != '\\') {
   2206 					if (*p == startc)
   2207 						depth++;
   2208 					if (*p == endc)
   2209 						depth--;
   2210 				}
   2211 			}
   2212 			Buf_AddBytesBetween(&buf, varstart, p);
   2213 		} else {
   2214 			Buf_AddByte(&buf, *varstart);
   2215 			p++;
   2216 		}
   2217 	}
   2218 
   2219 	if (*p != delim) {
   2220 		*pp = p;
   2221 		Error("Unfinished modifier for %s ('%c' missing)",
   2222 		    st->var->name.str, delim);
   2223 		*out_part = NULL;
   2224 		return VPR_ERR;
   2225 	}
   2226 
   2227 	*pp = p + 1;
   2228 	if (out_length != NULL)
   2229 		*out_length = buf.len;
   2230 
   2231 	*out_part = Buf_DoneData(&buf);
   2232 	DEBUG1(VAR, "Modifier part: \"%s\"\n", *out_part);
   2233 	return VPR_OK;
   2234 }
   2235 
   2236 /*
   2237  * Parse a part of a modifier such as the "from" and "to" in :S/from/to/ or
   2238  * the "var" or "replacement ${var}" in :@var@replacement ${var}@, up to and
   2239  * including the next unescaped delimiter.  The delimiter, as well as the
   2240  * backslash or the dollar, can be escaped with a backslash.
   2241  *
   2242  * Return the parsed (and possibly expanded) string, or NULL if no delimiter
   2243  * was found.  On successful return, the parsing position pp points right
   2244  * after the delimiter.  The delimiter is not included in the returned
   2245  * value though.
   2246  */
   2247 static VarParseResult
   2248 ParseModifierPart(
   2249     /* The parsing position, updated upon return */
   2250     const char **pp,
   2251     /* Parsing stops at this delimiter */
   2252     char delim,
   2253     /* Flags for evaluating nested variables; if VARE_WANTRES is not set,
   2254      * the text is only parsed. */
   2255     VarEvalFlags eflags,
   2256     ApplyModifiersState *st,
   2257     char **out_part
   2258 )
   2259 {
   2260 	return ParseModifierPartSubst(pp, delim, eflags, st, out_part,
   2261 	    NULL, NULL, NULL);
   2262 }
   2263 
   2264 /* Test whether mod starts with modname, followed by a delimiter. */
   2265 MAKE_INLINE Boolean
   2266 ModMatch(const char *mod, const char *modname, char endc)
   2267 {
   2268 	size_t n = strlen(modname);
   2269 	return strncmp(mod, modname, n) == 0 &&
   2270 	       (mod[n] == endc || mod[n] == ':');
   2271 }
   2272 
   2273 /* Test whether mod starts with modname, followed by a delimiter or '='. */
   2274 MAKE_INLINE Boolean
   2275 ModMatchEq(const char *mod, const char *modname, char endc)
   2276 {
   2277 	size_t n = strlen(modname);
   2278 	return strncmp(mod, modname, n) == 0 &&
   2279 	       (mod[n] == endc || mod[n] == ':' || mod[n] == '=');
   2280 }
   2281 
   2282 static Boolean
   2283 TryParseIntBase0(const char **pp, int *out_num)
   2284 {
   2285 	char *end;
   2286 	long n;
   2287 
   2288 	errno = 0;
   2289 	n = strtol(*pp, &end, 0);
   2290 	if ((n == LONG_MIN || n == LONG_MAX) && errno == ERANGE)
   2291 		return FALSE;
   2292 	if (n < INT_MIN || n > INT_MAX)
   2293 		return FALSE;
   2294 
   2295 	*pp = end;
   2296 	*out_num = (int)n;
   2297 	return TRUE;
   2298 }
   2299 
   2300 static Boolean
   2301 TryParseSize(const char **pp, size_t *out_num)
   2302 {
   2303 	char *end;
   2304 	unsigned long n;
   2305 
   2306 	if (!ch_isdigit(**pp))
   2307 		return FALSE;
   2308 
   2309 	errno = 0;
   2310 	n = strtoul(*pp, &end, 10);
   2311 	if (n == ULONG_MAX && errno == ERANGE)
   2312 		return FALSE;
   2313 	if (n > SIZE_MAX)
   2314 		return FALSE;
   2315 
   2316 	*pp = end;
   2317 	*out_num = (size_t)n;
   2318 	return TRUE;
   2319 }
   2320 
   2321 static Boolean
   2322 TryParseChar(const char **pp, int base, char *out_ch)
   2323 {
   2324 	char *end;
   2325 	unsigned long n;
   2326 
   2327 	if (!ch_isalnum(**pp))
   2328 		return FALSE;
   2329 
   2330 	errno = 0;
   2331 	n = strtoul(*pp, &end, base);
   2332 	if (n == ULONG_MAX && errno == ERANGE)
   2333 		return FALSE;
   2334 	if (n > UCHAR_MAX)
   2335 		return FALSE;
   2336 
   2337 	*pp = end;
   2338 	*out_ch = (char)n;
   2339 	return TRUE;
   2340 }
   2341 
   2342 /* :@var (at) ...${var}...@ */
   2343 static ApplyModifierResult
   2344 ApplyModifier_Loop(const char **pp, const char *val, ApplyModifiersState *st)
   2345 {
   2346 	struct ModifyWord_LoopArgs args;
   2347 	char prev_sep;
   2348 	VarParseResult res;
   2349 
   2350 	args.ctx = st->scope;
   2351 
   2352 	(*pp)++;		/* Skip the first '@' */
   2353 	res = ParseModifierPart(pp, '@', VARE_NONE, st, &args.tvar);
   2354 	if (res != VPR_OK)
   2355 		return AMR_CLEANUP;
   2356 	if (opts.strict && strchr(args.tvar, '$') != NULL) {
   2357 		Parse_Error(PARSE_FATAL,
   2358 		    "In the :@ modifier of \"%s\", the variable name \"%s\" "
   2359 		    "must not contain a dollar.",
   2360 		    st->var->name.str, args.tvar);
   2361 		return AMR_CLEANUP;
   2362 	}
   2363 
   2364 	res = ParseModifierPart(pp, '@', VARE_NONE, st, &args.str);
   2365 	if (res != VPR_OK)
   2366 		return AMR_CLEANUP;
   2367 
   2368 	args.eflags = st->eflags & ~(unsigned)VARE_KEEP_DOLLAR;
   2369 	prev_sep = st->sep;
   2370 	st->sep = ' ';		/* XXX: should be st->sep for consistency */
   2371 	st->newVal = FStr_InitOwn(
   2372 	    ModifyWords(val, ModifyWord_Loop, &args, st->oneBigWord, st->sep));
   2373 	st->sep = prev_sep;
   2374 	/* XXX: Consider restoring the previous variable instead of deleting. */
   2375 	Var_DeleteExpand(args.tvar, st->scope);
   2376 	free(args.tvar);
   2377 	free(args.str);
   2378 	return AMR_OK;
   2379 }
   2380 
   2381 /* :Ddefined or :Uundefined */
   2382 static ApplyModifierResult
   2383 ApplyModifier_Defined(const char **pp, const char *val, ApplyModifiersState *st)
   2384 {
   2385 	Buffer buf;
   2386 	const char *p;
   2387 
   2388 	VarEvalFlags eflags = VARE_NONE;
   2389 	if (st->eflags & VARE_WANTRES)
   2390 		if ((**pp == 'D') == (st->exprStatus == VES_NONE))
   2391 			eflags = st->eflags;
   2392 
   2393 	Buf_Init(&buf);
   2394 	p = *pp + 1;
   2395 	while (*p != st->endc && *p != ':' && *p != '\0') {
   2396 
   2397 		/* XXX: This code is similar to the one in Var_Parse.
   2398 		 * See if the code can be merged.
   2399 		 * See also ApplyModifier_Match. */
   2400 
   2401 		/* Escaped delimiter or other special character */
   2402 		if (*p == '\\') {
   2403 			char c = p[1];
   2404 			if (c == st->endc || c == ':' || c == '$' ||
   2405 			    c == '\\') {
   2406 				Buf_AddByte(&buf, c);
   2407 				p += 2;
   2408 				continue;
   2409 			}
   2410 		}
   2411 
   2412 		/* Nested variable expression */
   2413 		if (*p == '$') {
   2414 			FStr nested_val;
   2415 
   2416 			(void)Var_Parse(&p, st->scope, eflags, &nested_val);
   2417 			/* TODO: handle errors */
   2418 			Buf_AddStr(&buf, nested_val.str);
   2419 			FStr_Done(&nested_val);
   2420 			continue;
   2421 		}
   2422 
   2423 		/* Ordinary text */
   2424 		Buf_AddByte(&buf, *p);
   2425 		p++;
   2426 	}
   2427 	*pp = p;
   2428 
   2429 	ApplyModifiersState_Define(st);
   2430 
   2431 	if (eflags & VARE_WANTRES) {
   2432 		st->newVal = FStr_InitOwn(Buf_DoneData(&buf));
   2433 	} else {
   2434 		st->newVal = FStr_InitRefer(val);
   2435 		Buf_Done(&buf);
   2436 	}
   2437 	return AMR_OK;
   2438 }
   2439 
   2440 /* :L */
   2441 static ApplyModifierResult
   2442 ApplyModifier_Literal(const char **pp, ApplyModifiersState *st)
   2443 {
   2444 	ApplyModifiersState_Define(st);
   2445 	st->newVal = FStr_InitOwn(bmake_strdup(st->var->name.str));
   2446 	(*pp)++;
   2447 	return AMR_OK;
   2448 }
   2449 
   2450 static Boolean
   2451 TryParseTime(const char **pp, time_t *out_time)
   2452 {
   2453 	char *end;
   2454 	unsigned long n;
   2455 
   2456 	if (!ch_isdigit(**pp))
   2457 		return FALSE;
   2458 
   2459 	errno = 0;
   2460 	n = strtoul(*pp, &end, 10);
   2461 	if (n == ULONG_MAX && errno == ERANGE)
   2462 		return FALSE;
   2463 
   2464 	*pp = end;
   2465 	*out_time = (time_t)n;	/* ignore possible truncation for now */
   2466 	return TRUE;
   2467 }
   2468 
   2469 /* :gmtime */
   2470 static ApplyModifierResult
   2471 ApplyModifier_Gmtime(const char **pp, const char *val, ApplyModifiersState *st)
   2472 {
   2473 	time_t utc;
   2474 
   2475 	const char *mod = *pp;
   2476 	if (!ModMatchEq(mod, "gmtime", st->endc))
   2477 		return AMR_UNKNOWN;
   2478 
   2479 	if (mod[6] == '=') {
   2480 		const char *arg = mod + 7;
   2481 		if (!TryParseTime(&arg, &utc)) {
   2482 			Parse_Error(PARSE_FATAL,
   2483 			    "Invalid time value: %s", mod + 7);
   2484 			return AMR_CLEANUP;
   2485 		}
   2486 		*pp = arg;
   2487 	} else {
   2488 		utc = 0;
   2489 		*pp = mod + 6;
   2490 	}
   2491 	st->newVal = FStr_InitOwn(VarStrftime(val, TRUE, utc));
   2492 	return AMR_OK;
   2493 }
   2494 
   2495 /* :localtime */
   2496 static ApplyModifierResult
   2497 ApplyModifier_Localtime(const char **pp, const char *val,
   2498 			ApplyModifiersState *st)
   2499 {
   2500 	time_t utc;
   2501 
   2502 	const char *mod = *pp;
   2503 	if (!ModMatchEq(mod, "localtime", st->endc))
   2504 		return AMR_UNKNOWN;
   2505 
   2506 	if (mod[9] == '=') {
   2507 		const char *arg = mod + 10;
   2508 		if (!TryParseTime(&arg, &utc)) {
   2509 			Parse_Error(PARSE_FATAL,
   2510 			    "Invalid time value: %s", mod + 10);
   2511 			return AMR_CLEANUP;
   2512 		}
   2513 		*pp = arg;
   2514 	} else {
   2515 		utc = 0;
   2516 		*pp = mod + 9;
   2517 	}
   2518 	st->newVal = FStr_InitOwn(VarStrftime(val, FALSE, utc));
   2519 	return AMR_OK;
   2520 }
   2521 
   2522 /* :hash */
   2523 static ApplyModifierResult
   2524 ApplyModifier_Hash(const char **pp, const char *val, ApplyModifiersState *st)
   2525 {
   2526 	if (!ModMatch(*pp, "hash", st->endc))
   2527 		return AMR_UNKNOWN;
   2528 
   2529 	st->newVal = FStr_InitOwn(VarHash(val));
   2530 	*pp += 4;
   2531 	return AMR_OK;
   2532 }
   2533 
   2534 /* :P */
   2535 static ApplyModifierResult
   2536 ApplyModifier_Path(const char **pp, ApplyModifiersState *st)
   2537 {
   2538 	GNode *gn;
   2539 	char *path;
   2540 
   2541 	ApplyModifiersState_Define(st);
   2542 
   2543 	gn = Targ_FindNode(st->var->name.str);
   2544 	if (gn == NULL || gn->type & OP_NOPATH) {
   2545 		path = NULL;
   2546 	} else if (gn->path != NULL) {
   2547 		path = bmake_strdup(gn->path);
   2548 	} else {
   2549 		SearchPath *searchPath = Suff_FindPath(gn);
   2550 		path = Dir_FindFile(st->var->name.str, searchPath);
   2551 	}
   2552 	if (path == NULL)
   2553 		path = bmake_strdup(st->var->name.str);
   2554 	st->newVal = FStr_InitOwn(path);
   2555 
   2556 	(*pp)++;
   2557 	return AMR_OK;
   2558 }
   2559 
   2560 /* :!cmd! */
   2561 static ApplyModifierResult
   2562 ApplyModifier_ShellCommand(const char **pp, ApplyModifiersState *st)
   2563 {
   2564 	char *cmd;
   2565 	const char *errfmt;
   2566 	VarParseResult res;
   2567 
   2568 	(*pp)++;
   2569 	res = ParseModifierPart(pp, '!', st->eflags, st, &cmd);
   2570 	if (res != VPR_OK)
   2571 		return AMR_CLEANUP;
   2572 
   2573 	errfmt = NULL;
   2574 	if (st->eflags & VARE_WANTRES)
   2575 		st->newVal = FStr_InitOwn(Cmd_Exec(cmd, &errfmt));
   2576 	else
   2577 		st->newVal = FStr_InitRefer("");
   2578 	if (errfmt != NULL)
   2579 		Error(errfmt, cmd);	/* XXX: why still return AMR_OK? */
   2580 	free(cmd);
   2581 
   2582 	ApplyModifiersState_Define(st);
   2583 	return AMR_OK;
   2584 }
   2585 
   2586 /*
   2587  * The :range modifier generates an integer sequence as long as the words.
   2588  * The :range=7 modifier generates an integer sequence from 1 to 7.
   2589  */
   2590 static ApplyModifierResult
   2591 ApplyModifier_Range(const char **pp, const char *val, ApplyModifiersState *st)
   2592 {
   2593 	size_t n;
   2594 	Buffer buf;
   2595 	size_t i;
   2596 
   2597 	const char *mod = *pp;
   2598 	if (!ModMatchEq(mod, "range", st->endc))
   2599 		return AMR_UNKNOWN;
   2600 
   2601 	if (mod[5] == '=') {
   2602 		const char *p = mod + 6;
   2603 		if (!TryParseSize(&p, &n)) {
   2604 			Parse_Error(PARSE_FATAL,
   2605 			    "Invalid number: %s", mod + 6);
   2606 			return AMR_CLEANUP;
   2607 		}
   2608 		*pp = p;
   2609 	} else {
   2610 		n = 0;
   2611 		*pp = mod + 5;
   2612 	}
   2613 
   2614 	if (n == 0) {
   2615 		Words words = Str_Words(val, FALSE);
   2616 		n = words.len;
   2617 		Words_Free(words);
   2618 	}
   2619 
   2620 	Buf_Init(&buf);
   2621 
   2622 	for (i = 0; i < n; i++) {
   2623 		if (i != 0) {
   2624 			/* XXX: Use st->sep instead of ' ', for consistency. */
   2625 			Buf_AddByte(&buf, ' ');
   2626 		}
   2627 		Buf_AddInt(&buf, 1 + (int)i);
   2628 	}
   2629 
   2630 	st->newVal = FStr_InitOwn(Buf_DoneData(&buf));
   2631 	return AMR_OK;
   2632 }
   2633 
   2634 /* :Mpattern or :Npattern */
   2635 static ApplyModifierResult
   2636 ApplyModifier_Match(const char **pp, const char *val, ApplyModifiersState *st)
   2637 {
   2638 	const char *mod = *pp;
   2639 	Boolean copy = FALSE;	/* pattern should be, or has been, copied */
   2640 	Boolean needSubst = FALSE;
   2641 	const char *endpat;
   2642 	char *pattern;
   2643 	ModifyWordsCallback callback;
   2644 
   2645 	/*
   2646 	 * In the loop below, ignore ':' unless we are at (or back to) the
   2647 	 * original brace level.
   2648 	 * XXX: This will likely not work right if $() and ${} are intermixed.
   2649 	 */
   2650 	/* XXX: This code is similar to the one in Var_Parse.
   2651 	 * See if the code can be merged.
   2652 	 * See also ApplyModifier_Defined. */
   2653 	int nest = 0;
   2654 	const char *p;
   2655 	for (p = mod + 1; *p != '\0' && !(*p == ':' && nest == 0); p++) {
   2656 		if (*p == '\\' &&
   2657 		    (p[1] == ':' || p[1] == st->endc || p[1] == st->startc)) {
   2658 			if (!needSubst)
   2659 				copy = TRUE;
   2660 			p++;
   2661 			continue;
   2662 		}
   2663 		if (*p == '$')
   2664 			needSubst = TRUE;
   2665 		if (*p == '(' || *p == '{')
   2666 			nest++;
   2667 		if (*p == ')' || *p == '}') {
   2668 			nest--;
   2669 			if (nest < 0)
   2670 				break;
   2671 		}
   2672 	}
   2673 	*pp = p;
   2674 	endpat = p;
   2675 
   2676 	if (copy) {
   2677 		char *dst;
   2678 		const char *src;
   2679 
   2680 		/* Compress the \:'s out of the pattern. */
   2681 		pattern = bmake_malloc((size_t)(endpat - (mod + 1)) + 1);
   2682 		dst = pattern;
   2683 		src = mod + 1;
   2684 		for (; src < endpat; src++, dst++) {
   2685 			if (src[0] == '\\' && src + 1 < endpat &&
   2686 			    /* XXX: st->startc is missing here; see above */
   2687 			    (src[1] == ':' || src[1] == st->endc))
   2688 				src++;
   2689 			*dst = *src;
   2690 		}
   2691 		*dst = '\0';
   2692 	} else {
   2693 		pattern = bmake_strsedup(mod + 1, endpat);
   2694 	}
   2695 
   2696 	if (needSubst) {
   2697 		char *old_pattern = pattern;
   2698 		(void)Var_Subst(pattern, st->scope, st->eflags, &pattern);
   2699 		/* TODO: handle errors */
   2700 		free(old_pattern);
   2701 	}
   2702 
   2703 	DEBUG3(VAR, "Pattern[%s] for [%s] is [%s]\n",
   2704 	    st->var->name.str, val, pattern);
   2705 
   2706 	callback = mod[0] == 'M' ? ModifyWord_Match : ModifyWord_NoMatch;
   2707 	st->newVal = FStr_InitOwn(ModifyWords(val, callback, pattern,
   2708 	    st->oneBigWord, st->sep));
   2709 	free(pattern);
   2710 	return AMR_OK;
   2711 }
   2712 
   2713 /* :S,from,to, */
   2714 static ApplyModifierResult
   2715 ApplyModifier_Subst(const char **pp, const char *val, ApplyModifiersState *st)
   2716 {
   2717 	struct ModifyWord_SubstArgs args;
   2718 	char *lhs, *rhs;
   2719 	Boolean oneBigWord;
   2720 	VarParseResult res;
   2721 
   2722 	char delim = (*pp)[1];
   2723 	if (delim == '\0') {
   2724 		Error("Missing delimiter for :S modifier");
   2725 		(*pp)++;
   2726 		return AMR_CLEANUP;
   2727 	}
   2728 
   2729 	*pp += 2;
   2730 
   2731 	args.pflags = (VarPatternFlags){ FALSE, FALSE, FALSE, FALSE };
   2732 	args.matched = FALSE;
   2733 
   2734 	/*
   2735 	 * If pattern begins with '^', it is anchored to the
   2736 	 * start of the word -- skip over it and flag pattern.
   2737 	 */
   2738 	if (**pp == '^') {
   2739 		args.pflags.anchorStart = TRUE;
   2740 		(*pp)++;
   2741 	}
   2742 
   2743 	res = ParseModifierPartSubst(pp, delim, st->eflags, st, &lhs,
   2744 	    &args.lhsLen, &args.pflags, NULL);
   2745 	if (res != VPR_OK)
   2746 		return AMR_CLEANUP;
   2747 	args.lhs = lhs;
   2748 
   2749 	res = ParseModifierPartSubst(pp, delim, st->eflags, st, &rhs,
   2750 	    &args.rhsLen, NULL, &args);
   2751 	if (res != VPR_OK)
   2752 		return AMR_CLEANUP;
   2753 	args.rhs = rhs;
   2754 
   2755 	oneBigWord = st->oneBigWord;
   2756 	for (;; (*pp)++) {
   2757 		switch (**pp) {
   2758 		case 'g':
   2759 			args.pflags.subGlobal = TRUE;
   2760 			continue;
   2761 		case '1':
   2762 			args.pflags.subOnce = TRUE;
   2763 			continue;
   2764 		case 'W':
   2765 			oneBigWord = TRUE;
   2766 			continue;
   2767 		}
   2768 		break;
   2769 	}
   2770 
   2771 	st->newVal = FStr_InitOwn(ModifyWords(val, ModifyWord_Subst, &args,
   2772 	    oneBigWord, st->sep));
   2773 
   2774 	free(lhs);
   2775 	free(rhs);
   2776 	return AMR_OK;
   2777 }
   2778 
   2779 #ifndef NO_REGEX
   2780 
   2781 /* :C,from,to, */
   2782 static ApplyModifierResult
   2783 ApplyModifier_Regex(const char **pp, const char *val, ApplyModifiersState *st)
   2784 {
   2785 	char *re;
   2786 	struct ModifyWord_SubstRegexArgs args;
   2787 	Boolean oneBigWord;
   2788 	int error;
   2789 	VarParseResult res;
   2790 
   2791 	char delim = (*pp)[1];
   2792 	if (delim == '\0') {
   2793 		Error("Missing delimiter for :C modifier");
   2794 		(*pp)++;
   2795 		return AMR_CLEANUP;
   2796 	}
   2797 
   2798 	*pp += 2;
   2799 
   2800 	res = ParseModifierPart(pp, delim, st->eflags, st, &re);
   2801 	if (res != VPR_OK)
   2802 		return AMR_CLEANUP;
   2803 
   2804 	res = ParseModifierPart(pp, delim, st->eflags, st, &args.replace);
   2805 	if (args.replace == NULL) {
   2806 		free(re);
   2807 		return AMR_CLEANUP;
   2808 	}
   2809 
   2810 	args.pflags = (VarPatternFlags){ FALSE, FALSE, FALSE, FALSE };
   2811 	args.matched = FALSE;
   2812 	oneBigWord = st->oneBigWord;
   2813 	for (;; (*pp)++) {
   2814 		switch (**pp) {
   2815 		case 'g':
   2816 			args.pflags.subGlobal = TRUE;
   2817 			continue;
   2818 		case '1':
   2819 			args.pflags.subOnce = TRUE;
   2820 			continue;
   2821 		case 'W':
   2822 			oneBigWord = TRUE;
   2823 			continue;
   2824 		}
   2825 		break;
   2826 	}
   2827 
   2828 	error = regcomp(&args.re, re, REG_EXTENDED);
   2829 	free(re);
   2830 	if (error != 0) {
   2831 		VarREError(error, &args.re, "Regex compilation error");
   2832 		free(args.replace);
   2833 		return AMR_CLEANUP;
   2834 	}
   2835 
   2836 	args.nsub = args.re.re_nsub + 1;
   2837 	if (args.nsub > 10)
   2838 		args.nsub = 10;
   2839 	st->newVal = FStr_InitOwn(
   2840 	    ModifyWords(val, ModifyWord_SubstRegex, &args,
   2841 		oneBigWord, st->sep));
   2842 	regfree(&args.re);
   2843 	free(args.replace);
   2844 	return AMR_OK;
   2845 }
   2846 
   2847 #endif
   2848 
   2849 /* :Q, :q */
   2850 static ApplyModifierResult
   2851 ApplyModifier_Quote(const char **pp, const char *val, ApplyModifiersState *st)
   2852 {
   2853 	if ((*pp)[1] == st->endc || (*pp)[1] == ':') {
   2854 		st->newVal = FStr_InitOwn(VarQuote(val, **pp == 'q'));
   2855 		(*pp)++;
   2856 		return AMR_OK;
   2857 	} else
   2858 		return AMR_UNKNOWN;
   2859 }
   2860 
   2861 /*ARGSUSED*/
   2862 static void
   2863 ModifyWord_Copy(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   2864 {
   2865 	SepBuf_AddStr(buf, word);
   2866 }
   2867 
   2868 /* :ts<separator> */
   2869 static ApplyModifierResult
   2870 ApplyModifier_ToSep(const char **pp, const char *val, ApplyModifiersState *st)
   2871 {
   2872 	const char *sep = *pp + 2;
   2873 
   2874 	/* ":ts<any><endc>" or ":ts<any>:" */
   2875 	if (sep[0] != st->endc && (sep[1] == st->endc || sep[1] == ':')) {
   2876 		st->sep = sep[0];
   2877 		*pp = sep + 1;
   2878 		goto ok;
   2879 	}
   2880 
   2881 	/* ":ts<endc>" or ":ts:" */
   2882 	if (sep[0] == st->endc || sep[0] == ':') {
   2883 		st->sep = '\0';	/* no separator */
   2884 		*pp = sep;
   2885 		goto ok;
   2886 	}
   2887 
   2888 	/* ":ts<unrecognised><unrecognised>". */
   2889 	if (sep[0] != '\\') {
   2890 		(*pp)++;	/* just for backwards compatibility */
   2891 		return AMR_BAD;
   2892 	}
   2893 
   2894 	/* ":ts\n" */
   2895 	if (sep[1] == 'n') {
   2896 		st->sep = '\n';
   2897 		*pp = sep + 2;
   2898 		goto ok;
   2899 	}
   2900 
   2901 	/* ":ts\t" */
   2902 	if (sep[1] == 't') {
   2903 		st->sep = '\t';
   2904 		*pp = sep + 2;
   2905 		goto ok;
   2906 	}
   2907 
   2908 	/* ":ts\x40" or ":ts\100" */
   2909 	{
   2910 		const char *p = sep + 1;
   2911 		int base = 8;	/* assume octal */
   2912 
   2913 		if (sep[1] == 'x') {
   2914 			base = 16;
   2915 			p++;
   2916 		} else if (!ch_isdigit(sep[1])) {
   2917 			(*pp)++;	/* just for backwards compatibility */
   2918 			return AMR_BAD;	/* ":ts<backslash><unrecognised>". */
   2919 		}
   2920 
   2921 		if (!TryParseChar(&p, base, &st->sep)) {
   2922 			Parse_Error(PARSE_FATAL,
   2923 			    "Invalid character number: %s", p);
   2924 			return AMR_CLEANUP;
   2925 		}
   2926 		if (*p != ':' && *p != st->endc) {
   2927 			(*pp)++;	/* just for backwards compatibility */
   2928 			return AMR_BAD;
   2929 		}
   2930 
   2931 		*pp = p;
   2932 	}
   2933 
   2934 ok:
   2935 	st->newVal = FStr_InitOwn(
   2936 	    ModifyWords(val, ModifyWord_Copy, NULL, st->oneBigWord, st->sep));
   2937 	return AMR_OK;
   2938 }
   2939 
   2940 static char *
   2941 str_toupper(const char *str)
   2942 {
   2943 	char *res;
   2944 	size_t i, len;
   2945 
   2946 	len = strlen(str);
   2947 	res = bmake_malloc(len + 1);
   2948 	for (i = 0; i < len + 1; i++)
   2949 		res[i] = ch_toupper(str[i]);
   2950 
   2951 	return res;
   2952 }
   2953 
   2954 static char *
   2955 str_tolower(const char *str)
   2956 {
   2957 	char *res;
   2958 	size_t i, len;
   2959 
   2960 	len = strlen(str);
   2961 	res = bmake_malloc(len + 1);
   2962 	for (i = 0; i < len + 1; i++)
   2963 		res[i] = ch_tolower(str[i]);
   2964 
   2965 	return res;
   2966 }
   2967 
   2968 /* :tA, :tu, :tl, :ts<separator>, etc. */
   2969 static ApplyModifierResult
   2970 ApplyModifier_To(const char **pp, const char *val, ApplyModifiersState *st)
   2971 {
   2972 	const char *mod = *pp;
   2973 	assert(mod[0] == 't');
   2974 
   2975 	if (mod[1] == st->endc || mod[1] == ':' || mod[1] == '\0') {
   2976 		*pp = mod + 1;
   2977 		return AMR_BAD;	/* Found ":t<endc>" or ":t:". */
   2978 	}
   2979 
   2980 	if (mod[1] == 's')
   2981 		return ApplyModifier_ToSep(pp, val, st);
   2982 
   2983 	if (mod[2] != st->endc && mod[2] != ':') {
   2984 		*pp = mod + 1;
   2985 		return AMR_BAD;	/* Found ":t<unrecognised><unrecognised>". */
   2986 	}
   2987 
   2988 	/* Check for two-character options: ":tu", ":tl" */
   2989 	if (mod[1] == 'A') {	/* absolute path */
   2990 		st->newVal = FStr_InitOwn(
   2991 		    ModifyWords(val, ModifyWord_Realpath, NULL,
   2992 		        st->oneBigWord, st->sep));
   2993 		*pp = mod + 2;
   2994 		return AMR_OK;
   2995 	}
   2996 
   2997 	if (mod[1] == 'u') {	/* :tu */
   2998 		st->newVal = FStr_InitOwn(str_toupper(val));
   2999 		*pp = mod + 2;
   3000 		return AMR_OK;
   3001 	}
   3002 
   3003 	if (mod[1] == 'l') {	/* :tl */
   3004 		st->newVal = FStr_InitOwn(str_tolower(val));
   3005 		*pp = mod + 2;
   3006 		return AMR_OK;
   3007 	}
   3008 
   3009 	if (mod[1] == 'W' || mod[1] == 'w') { /* :tW, :tw */
   3010 		st->oneBigWord = mod[1] == 'W';
   3011 		st->newVal = FStr_InitRefer(val);
   3012 		*pp = mod + 2;
   3013 		return AMR_OK;
   3014 	}
   3015 
   3016 	/* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
   3017 	*pp = mod + 1;
   3018 	return AMR_BAD;
   3019 }
   3020 
   3021 /* :[#], :[1], :[-1..1], etc. */
   3022 static ApplyModifierResult
   3023 ApplyModifier_Words(const char **pp, const char *val, ApplyModifiersState *st)
   3024 {
   3025 	char *estr;
   3026 	int first, last;
   3027 	VarParseResult res;
   3028 	const char *p;
   3029 
   3030 	(*pp)++;		/* skip the '[' */
   3031 	res = ParseModifierPart(pp, ']', st->eflags, st, &estr);
   3032 	if (res != VPR_OK)
   3033 		return AMR_CLEANUP;
   3034 
   3035 	/* now *pp points just after the closing ']' */
   3036 	if (**pp != ':' && **pp != st->endc)
   3037 		goto bad_modifier;	/* Found junk after ']' */
   3038 
   3039 	if (estr[0] == '\0')
   3040 		goto bad_modifier;	/* empty square brackets in ":[]". */
   3041 
   3042 	if (estr[0] == '#' && estr[1] == '\0') { /* Found ":[#]" */
   3043 		if (st->oneBigWord) {
   3044 			st->newVal = FStr_InitRefer("1");
   3045 		} else {
   3046 			Buffer buf;
   3047 
   3048 			Words words = Str_Words(val, FALSE);
   3049 			size_t ac = words.len;
   3050 			Words_Free(words);
   3051 
   3052 			/* 3 digits + '\0' is usually enough */
   3053 			Buf_InitSize(&buf, 4);
   3054 			Buf_AddInt(&buf, (int)ac);
   3055 			st->newVal = FStr_InitOwn(Buf_DoneData(&buf));
   3056 		}
   3057 		goto ok;
   3058 	}
   3059 
   3060 	if (estr[0] == '*' && estr[1] == '\0') {
   3061 		/* Found ":[*]" */
   3062 		st->oneBigWord = TRUE;
   3063 		st->newVal = FStr_InitRefer(val);
   3064 		goto ok;
   3065 	}
   3066 
   3067 	if (estr[0] == '@' && estr[1] == '\0') {
   3068 		/* Found ":[@]" */
   3069 		st->oneBigWord = FALSE;
   3070 		st->newVal = FStr_InitRefer(val);
   3071 		goto ok;
   3072 	}
   3073 
   3074 	/*
   3075 	 * We expect estr to contain a single integer for :[N], or two
   3076 	 * integers separated by ".." for :[start..end].
   3077 	 */
   3078 	p = estr;
   3079 	if (!TryParseIntBase0(&p, &first))
   3080 		goto bad_modifier;	/* Found junk instead of a number */
   3081 
   3082 	if (p[0] == '\0') {		/* Found only one integer in :[N] */
   3083 		last = first;
   3084 	} else if (p[0] == '.' && p[1] == '.' && p[2] != '\0') {
   3085 		/* Expecting another integer after ".." */
   3086 		p += 2;
   3087 		if (!TryParseIntBase0(&p, &last) || *p != '\0')
   3088 			goto bad_modifier; /* Found junk after ".." */
   3089 	} else
   3090 		goto bad_modifier;	/* Found junk instead of ".." */
   3091 
   3092 	/*
   3093 	 * Now first and last are properly filled in, but we still have to
   3094 	 * check for 0 as a special case.
   3095 	 */
   3096 	if (first == 0 && last == 0) {
   3097 		/* ":[0]" or perhaps ":[0..0]" */
   3098 		st->oneBigWord = TRUE;
   3099 		st->newVal = FStr_InitRefer(val);
   3100 		goto ok;
   3101 	}
   3102 
   3103 	/* ":[0..N]" or ":[N..0]" */
   3104 	if (first == 0 || last == 0)
   3105 		goto bad_modifier;
   3106 
   3107 	/* Normal case: select the words described by first and last. */
   3108 	st->newVal = FStr_InitOwn(
   3109 	    VarSelectWords(st->sep, st->oneBigWord, val, first, last));
   3110 
   3111 ok:
   3112 	free(estr);
   3113 	return AMR_OK;
   3114 
   3115 bad_modifier:
   3116 	free(estr);
   3117 	return AMR_BAD;
   3118 }
   3119 
   3120 static int
   3121 str_cmp_asc(const void *a, const void *b)
   3122 {
   3123 	return strcmp(*(const char *const *)a, *(const char *const *)b);
   3124 }
   3125 
   3126 static int
   3127 str_cmp_desc(const void *a, const void *b)
   3128 {
   3129 	return strcmp(*(const char *const *)b, *(const char *const *)a);
   3130 }
   3131 
   3132 static void
   3133 ShuffleStrings(char **strs, size_t n)
   3134 {
   3135 	size_t i;
   3136 
   3137 	for (i = n - 1; i > 0; i--) {
   3138 		size_t rndidx = (size_t)random() % (i + 1);
   3139 		char *t = strs[i];
   3140 		strs[i] = strs[rndidx];
   3141 		strs[rndidx] = t;
   3142 	}
   3143 }
   3144 
   3145 /* :O (order ascending) or :Or (order descending) or :Ox (shuffle) */
   3146 static ApplyModifierResult
   3147 ApplyModifier_Order(const char **pp, const char *val, ApplyModifiersState *st)
   3148 {
   3149 	const char *mod = (*pp)++;	/* skip past the 'O' in any case */
   3150 
   3151 	Words words = Str_Words(val, FALSE);
   3152 
   3153 	if (mod[1] == st->endc || mod[1] == ':') {
   3154 		/* :O sorts ascending */
   3155 		qsort(words.words, words.len, sizeof words.words[0],
   3156 		    str_cmp_asc);
   3157 
   3158 	} else if ((mod[1] == 'r' || mod[1] == 'x') &&
   3159 		   (mod[2] == st->endc || mod[2] == ':')) {
   3160 		(*pp)++;
   3161 
   3162 		if (mod[1] == 'r') {	/* :Or sorts descending */
   3163 			qsort(words.words, words.len, sizeof words.words[0],
   3164 			    str_cmp_desc);
   3165 		} else
   3166 			ShuffleStrings(words.words, words.len);
   3167 	} else {
   3168 		Words_Free(words);
   3169 		return AMR_BAD;
   3170 	}
   3171 
   3172 	st->newVal = FStr_InitOwn(Words_JoinFree(words));
   3173 	return AMR_OK;
   3174 }
   3175 
   3176 /* :? then : else */
   3177 static ApplyModifierResult
   3178 ApplyModifier_IfElse(const char **pp, ApplyModifiersState *st)
   3179 {
   3180 	char *then_expr, *else_expr;
   3181 	VarParseResult res;
   3182 
   3183 	Boolean value = FALSE;
   3184 	VarEvalFlags then_eflags = VARE_NONE;
   3185 	VarEvalFlags else_eflags = VARE_NONE;
   3186 
   3187 	int cond_rc = COND_PARSE;	/* anything other than COND_INVALID */
   3188 	if (st->eflags & VARE_WANTRES) {
   3189 		cond_rc = Cond_EvalCondition(st->var->name.str, &value);
   3190 		if (cond_rc != COND_INVALID && value)
   3191 			then_eflags = st->eflags;
   3192 		if (cond_rc != COND_INVALID && !value)
   3193 			else_eflags = st->eflags;
   3194 	}
   3195 
   3196 	(*pp)++;			/* skip past the '?' */
   3197 	res = ParseModifierPart(pp, ':', then_eflags, st, &then_expr);
   3198 	if (res != VPR_OK)
   3199 		return AMR_CLEANUP;
   3200 
   3201 	res = ParseModifierPart(pp, st->endc, else_eflags, st, &else_expr);
   3202 	if (res != VPR_OK)
   3203 		return AMR_CLEANUP;
   3204 
   3205 	(*pp)--;
   3206 	if (cond_rc == COND_INVALID) {
   3207 		Error("Bad conditional expression `%s' in %s?%s:%s",
   3208 		    st->var->name.str, st->var->name.str, then_expr, else_expr);
   3209 		return AMR_CLEANUP;
   3210 	}
   3211 
   3212 	if (value) {
   3213 		st->newVal = FStr_InitOwn(then_expr);
   3214 		free(else_expr);
   3215 	} else {
   3216 		st->newVal = FStr_InitOwn(else_expr);
   3217 		free(then_expr);
   3218 	}
   3219 	ApplyModifiersState_Define(st);
   3220 	return AMR_OK;
   3221 }
   3222 
   3223 /*
   3224  * The ::= modifiers actually assign a value to the variable.
   3225  * Their main purpose is in supporting modifiers of .for loop
   3226  * iterators and other obscure uses.  They always expand to
   3227  * nothing.  In a target rule that would otherwise expand to an
   3228  * empty line they can be preceded with @: to keep make happy.
   3229  * Eg.
   3230  *
   3231  * foo:	.USE
   3232  * .for i in ${.TARGET} ${.TARGET:R}.gz
   3233  *	@: ${t::=$i}
   3234  *	@echo blah ${t:T}
   3235  * .endfor
   3236  *
   3237  *	  ::=<str>	Assigns <str> as the new value of variable.
   3238  *	  ::?=<str>	Assigns <str> as value of variable if
   3239  *			it was not already set.
   3240  *	  ::+=<str>	Appends <str> to variable.
   3241  *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
   3242  *			variable.
   3243  */
   3244 static ApplyModifierResult
   3245 ApplyModifier_Assign(const char **pp, ApplyModifiersState *st)
   3246 {
   3247 	GNode *scope;
   3248 	char delim;
   3249 	char *val;
   3250 	VarParseResult res;
   3251 
   3252 	const char *mod = *pp;
   3253 	const char *op = mod + 1;
   3254 
   3255 	if (op[0] == '=')
   3256 		goto ok;
   3257 	if ((op[0] == '!' || op[0] == '+' || op[0] == '?') && op[1] == '=')
   3258 		goto ok;
   3259 	return AMR_UNKNOWN;	/* "::<unrecognised>" */
   3260 ok:
   3261 
   3262 	if (st->var->name.str[0] == '\0') {
   3263 		*pp = mod + 1;
   3264 		return AMR_BAD;
   3265 	}
   3266 
   3267 	scope = st->scope;	/* scope where v belongs */
   3268 	if (st->exprStatus == VES_NONE && st->scope != SCOPE_GLOBAL) {
   3269 		Var *gv = VarFind(st->var->name.str, st->scope, FALSE);
   3270 		if (gv == NULL)
   3271 			scope = SCOPE_GLOBAL;
   3272 		else
   3273 			VarFreeEnv(gv, TRUE);
   3274 	}
   3275 
   3276 	switch (op[0]) {
   3277 	case '+':
   3278 	case '?':
   3279 	case '!':
   3280 		*pp = mod + 3;
   3281 		break;
   3282 	default:
   3283 		*pp = mod + 2;
   3284 		break;
   3285 	}
   3286 
   3287 	delim = st->startc == '(' ? ')' : '}';
   3288 	res = ParseModifierPart(pp, delim, st->eflags, st, &val);
   3289 	if (res != VPR_OK)
   3290 		return AMR_CLEANUP;
   3291 
   3292 	(*pp)--;
   3293 
   3294 	/* XXX: Expanding the variable name at this point sounds wrong. */
   3295 	if (st->eflags & VARE_WANTRES) {
   3296 		switch (op[0]) {
   3297 		case '+':
   3298 			Var_AppendExpand(st->var->name.str, val, scope);
   3299 			break;
   3300 		case '!': {
   3301 			const char *errfmt;
   3302 			char *cmd_output = Cmd_Exec(val, &errfmt);
   3303 			if (errfmt != NULL)
   3304 				Error(errfmt, val);
   3305 			else
   3306 				Var_SetExpand(st->var->name.str, cmd_output,
   3307 				    scope);
   3308 			free(cmd_output);
   3309 			break;
   3310 		}
   3311 		case '?':
   3312 			if (st->exprStatus == VES_NONE)
   3313 				break;
   3314 			/* FALLTHROUGH */
   3315 		default:
   3316 			Var_SetExpand(st->var->name.str, val, scope);
   3317 			break;
   3318 		}
   3319 	}
   3320 	free(val);
   3321 	st->newVal = FStr_InitRefer("");
   3322 	return AMR_OK;
   3323 }
   3324 
   3325 /*
   3326  * :_=...
   3327  * remember current value
   3328  */
   3329 static ApplyModifierResult
   3330 ApplyModifier_Remember(const char **pp, const char *val,
   3331 		       ApplyModifiersState *st)
   3332 {
   3333 	const char *mod = *pp;
   3334 	if (!ModMatchEq(mod, "_", st->endc))
   3335 		return AMR_UNKNOWN;
   3336 
   3337 	if (mod[1] == '=') {
   3338 		size_t n = strcspn(mod + 2, ":)}");
   3339 		char *name = bmake_strldup(mod + 2, n);
   3340 		Var_SetExpand(name, val, st->scope);
   3341 		free(name);
   3342 		*pp = mod + 2 + n;
   3343 	} else {
   3344 		Var_Set("_", val, st->scope);
   3345 		*pp = mod + 1;
   3346 	}
   3347 	st->newVal = FStr_InitRefer(val);
   3348 	return AMR_OK;
   3349 }
   3350 
   3351 /*
   3352  * Apply the given function to each word of the variable value,
   3353  * for a single-letter modifier such as :H, :T.
   3354  */
   3355 static ApplyModifierResult
   3356 ApplyModifier_WordFunc(const char **pp, const char *val,
   3357 		       ApplyModifiersState *st, ModifyWordsCallback modifyWord)
   3358 {
   3359 	char delim = (*pp)[1];
   3360 	if (delim != st->endc && delim != ':')
   3361 		return AMR_UNKNOWN;
   3362 
   3363 	st->newVal = FStr_InitOwn(ModifyWords(val, modifyWord, NULL,
   3364 	    st->oneBigWord, st->sep));
   3365 	(*pp)++;
   3366 	return AMR_OK;
   3367 }
   3368 
   3369 static ApplyModifierResult
   3370 ApplyModifier_Unique(const char **pp, const char *val, ApplyModifiersState *st)
   3371 {
   3372 	if ((*pp)[1] == st->endc || (*pp)[1] == ':') {
   3373 		st->newVal = FStr_InitOwn(VarUniq(val));
   3374 		(*pp)++;
   3375 		return AMR_OK;
   3376 	} else
   3377 		return AMR_UNKNOWN;
   3378 }
   3379 
   3380 #ifdef SYSVVARSUB
   3381 /* :from=to */
   3382 static ApplyModifierResult
   3383 ApplyModifier_SysV(const char **pp, const char *val, ApplyModifiersState *st)
   3384 {
   3385 	char *lhs, *rhs;
   3386 	VarParseResult res;
   3387 
   3388 	const char *mod = *pp;
   3389 	Boolean eqFound = FALSE;
   3390 
   3391 	/*
   3392 	 * First we make a pass through the string trying to verify it is a
   3393 	 * SysV-make-style translation. It must be: <lhs>=<rhs>
   3394 	 */
   3395 	int depth = 1;
   3396 	const char *p = mod;
   3397 	while (*p != '\0' && depth > 0) {
   3398 		if (*p == '=') {	/* XXX: should also test depth == 1 */
   3399 			eqFound = TRUE;
   3400 			/* continue looking for st->endc */
   3401 		} else if (*p == st->endc)
   3402 			depth--;
   3403 		else if (*p == st->startc)
   3404 			depth++;
   3405 		if (depth > 0)
   3406 			p++;
   3407 	}
   3408 	if (*p != st->endc || !eqFound)
   3409 		return AMR_UNKNOWN;
   3410 
   3411 	res = ParseModifierPart(pp, '=', st->eflags, st, &lhs);
   3412 	if (res != VPR_OK)
   3413 		return AMR_CLEANUP;
   3414 
   3415 	/* The SysV modifier lasts until the end of the variable expression. */
   3416 	res = ParseModifierPart(pp, st->endc, st->eflags, st, &rhs);
   3417 	if (res != VPR_OK)
   3418 		return AMR_CLEANUP;
   3419 
   3420 	(*pp)--;
   3421 	if (lhs[0] == '\0' && val[0] == '\0') {
   3422 		st->newVal = FStr_InitRefer(val); /* special case */
   3423 	} else {
   3424 		struct ModifyWord_SYSVSubstArgs args = { st->scope, lhs, rhs };
   3425 		st->newVal = FStr_InitOwn(
   3426 		    ModifyWords(val, ModifyWord_SYSVSubst, &args,
   3427 			st->oneBigWord, st->sep));
   3428 	}
   3429 	free(lhs);
   3430 	free(rhs);
   3431 	return AMR_OK;
   3432 }
   3433 #endif
   3434 
   3435 #ifdef SUNSHCMD
   3436 /* :sh */
   3437 static ApplyModifierResult
   3438 ApplyModifier_SunShell(const char **pp, const char *val,
   3439 		       ApplyModifiersState *st)
   3440 {
   3441 	const char *p = *pp;
   3442 	if (p[1] == 'h' && (p[2] == st->endc || p[2] == ':')) {
   3443 		if (st->eflags & VARE_WANTRES) {
   3444 			const char *errfmt;
   3445 			st->newVal = FStr_InitOwn(Cmd_Exec(val, &errfmt));
   3446 			if (errfmt != NULL)
   3447 				Error(errfmt, val);
   3448 		} else
   3449 			st->newVal = FStr_InitRefer("");
   3450 		*pp = p + 2;
   3451 		return AMR_OK;
   3452 	} else
   3453 		return AMR_UNKNOWN;
   3454 }
   3455 #endif
   3456 
   3457 static void
   3458 LogBeforeApply(const ApplyModifiersState *st, const char *mod, char endc,
   3459 	       const char *val)
   3460 {
   3461 	char eflags_str[VarEvalFlags_ToStringSize];
   3462 	char vflags_str[VarFlags_ToStringSize];
   3463 	Boolean is_single_char = mod[0] != '\0' &&
   3464 				 (mod[1] == endc || mod[1] == ':');
   3465 
   3466 	/* At this point, only the first character of the modifier can
   3467 	 * be used since the end of the modifier is not yet known. */
   3468 	debug_printf("Applying ${%s:%c%s} to \"%s\" (%s, %s, %s)\n",
   3469 	    st->var->name.str, mod[0], is_single_char ? "" : "...", val,
   3470 	    VarEvalFlags_ToString(eflags_str, st->eflags),
   3471 	    VarFlags_ToString(vflags_str, st->var->flags),
   3472 	    VarExprStatus_Name[st->exprStatus]);
   3473 }
   3474 
   3475 static void
   3476 LogAfterApply(ApplyModifiersState *st, const char *p, const char *mod)
   3477 {
   3478 	char eflags_str[VarEvalFlags_ToStringSize];
   3479 	char vflags_str[VarFlags_ToStringSize];
   3480 	const char *quot = st->newVal.str == var_Error ? "" : "\"";
   3481 	const char *newVal =
   3482 	    st->newVal.str == var_Error ? "error" : st->newVal.str;
   3483 
   3484 	debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s, %s)\n",
   3485 	    st->var->name.str, (int)(p - mod), mod, quot, newVal, quot,
   3486 	    VarEvalFlags_ToString(eflags_str, st->eflags),
   3487 	    VarFlags_ToString(vflags_str, st->var->flags),
   3488 	    VarExprStatus_Name[st->exprStatus]);
   3489 }
   3490 
   3491 static ApplyModifierResult
   3492 ApplyModifier(const char **pp, const char *val, ApplyModifiersState *st)
   3493 {
   3494 	switch (**pp) {
   3495 	case ':':
   3496 		return ApplyModifier_Assign(pp, st);
   3497 	case '@':
   3498 		return ApplyModifier_Loop(pp, val, st);
   3499 	case '_':
   3500 		return ApplyModifier_Remember(pp, val, st);
   3501 	case 'D':
   3502 	case 'U':
   3503 		return ApplyModifier_Defined(pp, val, st);
   3504 	case 'L':
   3505 		return ApplyModifier_Literal(pp, st);
   3506 	case 'P':
   3507 		return ApplyModifier_Path(pp, st);
   3508 	case '!':
   3509 		return ApplyModifier_ShellCommand(pp, st);
   3510 	case '[':
   3511 		return ApplyModifier_Words(pp, val, st);
   3512 	case 'g':
   3513 		return ApplyModifier_Gmtime(pp, val, st);
   3514 	case 'h':
   3515 		return ApplyModifier_Hash(pp, val, st);
   3516 	case 'l':
   3517 		return ApplyModifier_Localtime(pp, val, st);
   3518 	case 't':
   3519 		return ApplyModifier_To(pp, val, st);
   3520 	case 'N':
   3521 	case 'M':
   3522 		return ApplyModifier_Match(pp, val, st);
   3523 	case 'S':
   3524 		return ApplyModifier_Subst(pp, val, st);
   3525 	case '?':
   3526 		return ApplyModifier_IfElse(pp, st);
   3527 #ifndef NO_REGEX
   3528 	case 'C':
   3529 		return ApplyModifier_Regex(pp, val, st);
   3530 #endif
   3531 	case 'q':
   3532 	case 'Q':
   3533 		return ApplyModifier_Quote(pp, val, st);
   3534 	case 'T':
   3535 		return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Tail);
   3536 	case 'H':
   3537 		return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Head);
   3538 	case 'E':
   3539 		return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Suffix);
   3540 	case 'R':
   3541 		return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Root);
   3542 	case 'r':
   3543 		return ApplyModifier_Range(pp, val, st);
   3544 	case 'O':
   3545 		return ApplyModifier_Order(pp, val, st);
   3546 	case 'u':
   3547 		return ApplyModifier_Unique(pp, val, st);
   3548 #ifdef SUNSHCMD
   3549 	case 's':
   3550 		return ApplyModifier_SunShell(pp, val, st);
   3551 #endif
   3552 	default:
   3553 		return AMR_UNKNOWN;
   3554 	}
   3555 }
   3556 
   3557 static FStr ApplyModifiers(const char **, FStr, char, char, Var *,
   3558 			    VarExprStatus *, GNode *, VarEvalFlags);
   3559 
   3560 typedef enum ApplyModifiersIndirectResult {
   3561 	/* The indirect modifiers have been applied successfully. */
   3562 	AMIR_CONTINUE,
   3563 	/* Fall back to the SysV modifier. */
   3564 	AMIR_APPLY_MODS,
   3565 	/* Error out. */
   3566 	AMIR_OUT
   3567 } ApplyModifiersIndirectResult;
   3568 
   3569 /*
   3570  * While expanding a variable expression, expand and apply indirect modifiers,
   3571  * such as in ${VAR:${M_indirect}}.
   3572  *
   3573  * All indirect modifiers of a group must come from a single variable
   3574  * expression.  ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
   3575  *
   3576  * Multiple groups of indirect modifiers can be chained by separating them
   3577  * with colons.  ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
   3578  *
   3579  * If the variable expression is not followed by st->endc or ':', fall
   3580  * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
   3581  *
   3582  * The expression ${VAR:${M1}${M2}} is not treated as an indirect
   3583  * modifier, and it is neither a SysV modifier but a parse error.
   3584  */
   3585 static ApplyModifiersIndirectResult
   3586 ApplyModifiersIndirect(ApplyModifiersState *st, const char **pp,
   3587 		       FStr *inout_value)
   3588 {
   3589 	const char *p = *pp;
   3590 	FStr mods;
   3591 
   3592 	(void)Var_Parse(&p, st->scope, st->eflags, &mods);
   3593 	/* TODO: handle errors */
   3594 
   3595 	if (mods.str[0] != '\0' && *p != '\0' && *p != ':' && *p != st->endc) {
   3596 		FStr_Done(&mods);
   3597 		return AMIR_APPLY_MODS;
   3598 	}
   3599 
   3600 	DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
   3601 	    mods.str, (int)(p - *pp), *pp);
   3602 
   3603 	if (mods.str[0] != '\0') {
   3604 		const char *modsp = mods.str;
   3605 		FStr newVal = ApplyModifiers(&modsp, *inout_value, '\0', '\0',
   3606 		    st->var, &st->exprStatus, st->scope, st->eflags);
   3607 		*inout_value = newVal;
   3608 		if (newVal.str == var_Error || *modsp != '\0') {
   3609 			FStr_Done(&mods);
   3610 			*pp = p;
   3611 			return AMIR_OUT;	/* error already reported */
   3612 		}
   3613 	}
   3614 	FStr_Done(&mods);
   3615 
   3616 	if (*p == ':')
   3617 		p++;
   3618 	else if (*p == '\0' && st->endc != '\0') {
   3619 		Error("Unclosed variable specification after complex "
   3620 		      "modifier (expecting '%c') for %s",
   3621 		    st->endc, st->var->name.str);
   3622 		*pp = p;
   3623 		return AMIR_OUT;
   3624 	}
   3625 
   3626 	*pp = p;
   3627 	return AMIR_CONTINUE;
   3628 }
   3629 
   3630 static ApplyModifierResult
   3631 ApplySingleModifier(ApplyModifiersState *st, const char *mod, char endc,
   3632 		    const char **pp, FStr *inout_value)
   3633 {
   3634 	ApplyModifierResult res;
   3635 	const char *p = *pp;
   3636 	const char *const val = inout_value->str;
   3637 
   3638 	if (DEBUG(VAR))
   3639 		LogBeforeApply(st, mod, endc, val);
   3640 
   3641 	res = ApplyModifier(&p, val, st);
   3642 
   3643 #ifdef SYSVVARSUB
   3644 	if (res == AMR_UNKNOWN) {
   3645 		assert(p == mod);
   3646 		res = ApplyModifier_SysV(&p, val, st);
   3647 	}
   3648 #endif
   3649 
   3650 	if (res == AMR_UNKNOWN) {
   3651 		Parse_Error(PARSE_FATAL, "Unknown modifier '%c'", *mod);
   3652 		/*
   3653 		 * Guess the end of the current modifier.
   3654 		 * XXX: Skipping the rest of the modifier hides
   3655 		 * errors and leads to wrong results.
   3656 		 * Parsing should rather stop here.
   3657 		 */
   3658 		for (p++; *p != ':' && *p != st->endc && *p != '\0'; p++)
   3659 			continue;
   3660 		st->newVal = FStr_InitRefer(var_Error);
   3661 	}
   3662 	if (res == AMR_CLEANUP || res == AMR_BAD) {
   3663 		*pp = p;
   3664 		return res;
   3665 	}
   3666 
   3667 	if (DEBUG(VAR))
   3668 		LogAfterApply(st, p, mod);
   3669 
   3670 	if (st->newVal.str != val) {
   3671 		FStr_Done(inout_value);
   3672 		*inout_value = st->newVal;
   3673 	}
   3674 	if (*p == '\0' && st->endc != '\0') {
   3675 		Error(
   3676 		    "Unclosed variable specification (expecting '%c') "
   3677 		    "for \"%s\" (value \"%s\") modifier %c",
   3678 		    st->endc, st->var->name.str, inout_value->str, *mod);
   3679 	} else if (*p == ':') {
   3680 		p++;
   3681 	} else if (opts.strict && *p != '\0' && *p != endc) {
   3682 		Parse_Error(PARSE_FATAL,
   3683 		    "Missing delimiter ':' after modifier \"%.*s\"",
   3684 		    (int)(p - mod), mod);
   3685 		/*
   3686 		 * TODO: propagate parse error to the enclosing
   3687 		 * expression
   3688 		 */
   3689 	}
   3690 	*pp = p;
   3691 	return AMR_OK;
   3692 }
   3693 
   3694 /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
   3695 static FStr
   3696 ApplyModifiers(
   3697     const char **pp,		/* the parsing position, updated upon return */
   3698     FStr value,			/* the current value of the expression */
   3699     char startc,		/* '(' or '{', or '\0' for indirect modifiers */
   3700     char endc,			/* ')' or '}', or '\0' for indirect modifiers */
   3701     Var *v,
   3702     VarExprStatus *exprStatus,
   3703     GNode *scope,		/* for looking up and modifying variables */
   3704     VarEvalFlags eflags
   3705 )
   3706 {
   3707 	ApplyModifiersState st = {
   3708 	    startc, endc, v, scope, eflags,
   3709 #if defined(lint)
   3710 	    /* lint cannot parse C99 struct initializers yet. */
   3711 	    { var_Error, NULL },
   3712 #else
   3713 	    FStr_InitRefer(var_Error), /* .newVal */
   3714 #endif
   3715 	    ' ',		/* .sep */
   3716 	    FALSE,		/* .oneBigWord */
   3717 	    *exprStatus		/* .exprStatus */
   3718 	};
   3719 	const char *p;
   3720 	const char *mod;
   3721 
   3722 	assert(startc == '(' || startc == '{' || startc == '\0');
   3723 	assert(endc == ')' || endc == '}' || endc == '\0');
   3724 	assert(value.str != NULL);
   3725 
   3726 	p = *pp;
   3727 
   3728 	if (*p == '\0' && endc != '\0') {
   3729 		Error(
   3730 		    "Unclosed variable expression (expecting '%c') for \"%s\"",
   3731 		    st.endc, st.var->name.str);
   3732 		goto cleanup;
   3733 	}
   3734 
   3735 	while (*p != '\0' && *p != endc) {
   3736 		ApplyModifierResult res;
   3737 
   3738 		if (*p == '$') {
   3739 			ApplyModifiersIndirectResult amir;
   3740 			amir = ApplyModifiersIndirect(&st, &p, &value);
   3741 			if (amir == AMIR_CONTINUE)
   3742 				continue;
   3743 			if (amir == AMIR_OUT)
   3744 				break;
   3745 		}
   3746 
   3747 		/* default value, in case of errors */
   3748 		st.newVal = FStr_InitRefer(var_Error);
   3749 		mod = p;
   3750 
   3751 		res = ApplySingleModifier(&st, mod, endc, &p, &value);
   3752 		if (res == AMR_CLEANUP)
   3753 			goto cleanup;
   3754 		if (res == AMR_BAD)
   3755 			goto bad_modifier;
   3756 	}
   3757 
   3758 	*pp = p;
   3759 	assert(value.str != NULL); /* Use var_Error or varUndefined instead. */
   3760 	*exprStatus = st.exprStatus;
   3761 	return value;
   3762 
   3763 bad_modifier:
   3764 	/* XXX: The modifier end is only guessed. */
   3765 	Error("Bad modifier `:%.*s' for %s",
   3766 	    (int)strcspn(mod, ":)}"), mod, st.var->name.str);
   3767 
   3768 cleanup:
   3769 	*pp = p;
   3770 	FStr_Done(&value);
   3771 	*exprStatus = st.exprStatus;
   3772 	return FStr_InitRefer(var_Error);
   3773 }
   3774 
   3775 /*
   3776  * Only four of the local variables are treated specially as they are the
   3777  * only four that will be set when dynamic sources are expanded.
   3778  */
   3779 static Boolean
   3780 VarnameIsDynamic(const char *name, size_t len)
   3781 {
   3782 	if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
   3783 		switch (name[0]) {
   3784 		case '@':
   3785 		case '%':
   3786 		case '*':
   3787 		case '!':
   3788 			return TRUE;
   3789 		}
   3790 		return FALSE;
   3791 	}
   3792 
   3793 	if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
   3794 		return strcmp(name, ".TARGET") == 0 ||
   3795 		       strcmp(name, ".ARCHIVE") == 0 ||
   3796 		       strcmp(name, ".PREFIX") == 0 ||
   3797 		       strcmp(name, ".MEMBER") == 0;
   3798 	}
   3799 
   3800 	return FALSE;
   3801 }
   3802 
   3803 static const char *
   3804 UndefinedShortVarValue(char varname, const GNode *scope)
   3805 {
   3806 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
   3807 		/*
   3808 		 * If substituting a local variable in a non-local scope,
   3809 		 * assume it's for dynamic source stuff. We have to handle
   3810 		 * this specially and return the longhand for the variable
   3811 		 * with the dollar sign escaped so it makes it back to the
   3812 		 * caller. Only four of the local variables are treated
   3813 		 * specially as they are the only four that will be set
   3814 		 * when dynamic sources are expanded.
   3815 		 */
   3816 		switch (varname) {
   3817 		case '@':
   3818 			return "$(.TARGET)";
   3819 		case '%':
   3820 			return "$(.MEMBER)";
   3821 		case '*':
   3822 			return "$(.PREFIX)";
   3823 		case '!':
   3824 			return "$(.ARCHIVE)";
   3825 		}
   3826 	}
   3827 	return NULL;
   3828 }
   3829 
   3830 /*
   3831  * Parse a variable name, until the end character or a colon, whichever
   3832  * comes first.
   3833  */
   3834 static char *
   3835 ParseVarname(const char **pp, char startc, char endc,
   3836 	     GNode *scope, VarEvalFlags eflags,
   3837 	     size_t *out_varname_len)
   3838 {
   3839 	Buffer buf;
   3840 	const char *p = *pp;
   3841 	int depth = 1;
   3842 
   3843 	Buf_Init(&buf);
   3844 
   3845 	while (*p != '\0') {
   3846 		/* Track depth so we can spot parse errors. */
   3847 		if (*p == startc)
   3848 			depth++;
   3849 		if (*p == endc) {
   3850 			if (--depth == 0)
   3851 				break;
   3852 		}
   3853 		if (*p == ':' && depth == 1)
   3854 			break;
   3855 
   3856 		/* A variable inside a variable, expand. */
   3857 		if (*p == '$') {
   3858 			FStr nested_val;
   3859 			(void)Var_Parse(&p, scope, eflags, &nested_val);
   3860 			/* TODO: handle errors */
   3861 			Buf_AddStr(&buf, nested_val.str);
   3862 			FStr_Done(&nested_val);
   3863 		} else {
   3864 			Buf_AddByte(&buf, *p);
   3865 			p++;
   3866 		}
   3867 	}
   3868 	*pp = p;
   3869 	*out_varname_len = buf.len;
   3870 	return Buf_DoneData(&buf);
   3871 }
   3872 
   3873 static VarParseResult
   3874 ValidShortVarname(char varname, const char *start)
   3875 {
   3876 	switch (varname) {
   3877 	case '\0':
   3878 	case ')':
   3879 	case '}':
   3880 	case ':':
   3881 	case '$':
   3882 		break;		/* and continue below */
   3883 	default:
   3884 		return VPR_OK;
   3885 	}
   3886 
   3887 	if (!opts.strict)
   3888 		return VPR_ERR;	/* XXX: Missing error message */
   3889 
   3890 	if (varname == '$')
   3891 		Parse_Error(PARSE_FATAL,
   3892 		    "To escape a dollar, use \\$, not $$, at \"%s\"", start);
   3893 	else if (varname == '\0')
   3894 		Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
   3895 	else
   3896 		Parse_Error(PARSE_FATAL,
   3897 		    "Invalid variable name '%c', at \"%s\"", varname, start);
   3898 
   3899 	return VPR_ERR;
   3900 }
   3901 
   3902 /*
   3903  * Parse a single-character variable name such as $V or $@.
   3904  * Return whether to continue parsing.
   3905  */
   3906 static Boolean
   3907 ParseVarnameShort(char startc, const char **pp, GNode *scope,
   3908 		  VarEvalFlags eflags,
   3909 		  VarParseResult *out_FALSE_res, const char **out_FALSE_val,
   3910 		  Var **out_TRUE_var)
   3911 {
   3912 	char name[2];
   3913 	Var *v;
   3914 	VarParseResult vpr;
   3915 
   3916 	/*
   3917 	 * If it's not bounded by braces of some sort, life is much simpler.
   3918 	 * We just need to check for the first character and return the
   3919 	 * value if it exists.
   3920 	 */
   3921 
   3922 	vpr = ValidShortVarname(startc, *pp);
   3923 	if (vpr != VPR_OK) {
   3924 		(*pp)++;
   3925 		*out_FALSE_val = var_Error;
   3926 		*out_FALSE_res = vpr;
   3927 		return FALSE;
   3928 	}
   3929 
   3930 	name[0] = startc;
   3931 	name[1] = '\0';
   3932 	v = VarFind(name, scope, TRUE);
   3933 	if (v == NULL) {
   3934 		const char *val;
   3935 		*pp += 2;
   3936 
   3937 		val = UndefinedShortVarValue(startc, scope);
   3938 		if (val == NULL)
   3939 			val = eflags & VARE_UNDEFERR ? var_Error : varUndefined;
   3940 
   3941 		if (opts.strict && val == var_Error) {
   3942 			Parse_Error(PARSE_FATAL,
   3943 			    "Variable \"%s\" is undefined", name);
   3944 			*out_FALSE_res = VPR_ERR;
   3945 			*out_FALSE_val = val;
   3946 			return FALSE;
   3947 		}
   3948 
   3949 		/*
   3950 		 * XXX: This looks completely wrong.
   3951 		 *
   3952 		 * If undefined expressions are not allowed, this should
   3953 		 * rather be VPR_ERR instead of VPR_UNDEF, together with an
   3954 		 * error message.
   3955 		 *
   3956 		 * If undefined expressions are allowed, this should rather
   3957 		 * be VPR_UNDEF instead of VPR_OK.
   3958 		 */
   3959 		*out_FALSE_res = eflags & VARE_UNDEFERR ? VPR_UNDEF : VPR_OK;
   3960 		*out_FALSE_val = val;
   3961 		return FALSE;
   3962 	}
   3963 
   3964 	*out_TRUE_var = v;
   3965 	return TRUE;
   3966 }
   3967 
   3968 /* Find variables like @F or <D. */
   3969 static Var *
   3970 FindLocalLegacyVar(const char *varname, size_t namelen, GNode *scope,
   3971 		   const char **out_extraModifiers)
   3972 {
   3973 	/* Only resolve these variables if scope is a "real" target. */
   3974 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
   3975 		return NULL;
   3976 
   3977 	if (namelen != 2)
   3978 		return NULL;
   3979 	if (varname[1] != 'F' && varname[1] != 'D')
   3980 		return NULL;
   3981 	if (strchr("@%?*!<>", varname[0]) == NULL)
   3982 		return NULL;
   3983 
   3984 	{
   3985 		char name[] = { varname[0], '\0' };
   3986 		Var *v = VarFind(name, scope, FALSE);
   3987 
   3988 		if (v != NULL) {
   3989 			if (varname[1] == 'D') {
   3990 				*out_extraModifiers = "H:";
   3991 			} else { /* F */
   3992 				*out_extraModifiers = "T:";
   3993 			}
   3994 		}
   3995 		return v;
   3996 	}
   3997 }
   3998 
   3999 static VarParseResult
   4000 EvalUndefined(Boolean dynamic, const char *start, const char *p, char *varname,
   4001 	      VarEvalFlags eflags,
   4002 	      FStr *out_val)
   4003 {
   4004 	if (dynamic) {
   4005 		*out_val = FStr_InitOwn(bmake_strsedup(start, p));
   4006 		free(varname);
   4007 		return VPR_OK;
   4008 	}
   4009 
   4010 	if ((eflags & VARE_UNDEFERR) && opts.strict) {
   4011 		Parse_Error(PARSE_FATAL,
   4012 		    "Variable \"%s\" is undefined", varname);
   4013 		free(varname);
   4014 		*out_val = FStr_InitRefer(var_Error);
   4015 		return VPR_ERR;
   4016 	}
   4017 
   4018 	if (eflags & VARE_UNDEFERR) {
   4019 		free(varname);
   4020 		*out_val = FStr_InitRefer(var_Error);
   4021 		return VPR_UNDEF;	/* XXX: Should be VPR_ERR instead. */
   4022 	}
   4023 
   4024 	free(varname);
   4025 	*out_val = FStr_InitRefer(varUndefined);
   4026 	return VPR_OK;
   4027 }
   4028 
   4029 /*
   4030  * Parse a long variable name enclosed in braces or parentheses such as $(VAR)
   4031  * or ${VAR}, up to the closing brace or parenthesis, or in the case of
   4032  * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
   4033  * Return whether to continue parsing.
   4034  */
   4035 static Boolean
   4036 ParseVarnameLong(
   4037 	const char *p,
   4038 	char startc,
   4039 	GNode *scope,
   4040 	VarEvalFlags eflags,
   4041 
   4042 	const char **out_FALSE_pp,
   4043 	VarParseResult *out_FALSE_res,
   4044 	FStr *out_FALSE_val,
   4045 
   4046 	char *out_TRUE_endc,
   4047 	const char **out_TRUE_p,
   4048 	Var **out_TRUE_v,
   4049 	Boolean *out_TRUE_haveModifier,
   4050 	const char **out_TRUE_extraModifiers,
   4051 	Boolean *out_TRUE_dynamic,
   4052 	VarExprStatus *out_TRUE_exprStatus
   4053 )
   4054 {
   4055 	size_t namelen;
   4056 	char *varname;
   4057 	Var *v;
   4058 	Boolean haveModifier;
   4059 	Boolean dynamic = FALSE;
   4060 
   4061 	const char *const start = p;
   4062 	char endc = startc == '(' ? ')' : '}';
   4063 
   4064 	p += 2;			/* skip "${" or "$(" or "y(" */
   4065 	varname = ParseVarname(&p, startc, endc, scope, eflags, &namelen);
   4066 
   4067 	if (*p == ':') {
   4068 		haveModifier = TRUE;
   4069 	} else if (*p == endc) {
   4070 		haveModifier = FALSE;
   4071 	} else {
   4072 		Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"", varname);
   4073 		free(varname);
   4074 		*out_FALSE_pp = p;
   4075 		*out_FALSE_val = FStr_InitRefer(var_Error);
   4076 		*out_FALSE_res = VPR_ERR;
   4077 		return FALSE;
   4078 	}
   4079 
   4080 	v = VarFind(varname, scope, TRUE);
   4081 
   4082 	/* At this point, p points just after the variable name,
   4083 	 * either at ':' or at endc. */
   4084 
   4085 	if (v == NULL) {
   4086 		v = FindLocalLegacyVar(varname, namelen, scope,
   4087 		    out_TRUE_extraModifiers);
   4088 	}
   4089 
   4090 	if (v == NULL) {
   4091 		/*
   4092 		 * Defer expansion of dynamic variables if they appear in
   4093 		 * non-local scope since they are not defined there.
   4094 		 */
   4095 		dynamic = VarnameIsDynamic(varname, namelen) &&
   4096 			  (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
   4097 
   4098 		if (!haveModifier) {
   4099 			p++;	/* skip endc */
   4100 			*out_FALSE_pp = p;
   4101 			*out_FALSE_res = EvalUndefined(dynamic, start, p,
   4102 			    varname, eflags, out_FALSE_val);
   4103 			return FALSE;
   4104 		}
   4105 
   4106 		/*
   4107 		 * The variable expression is based on an undefined variable.
   4108 		 * Nevertheless it needs a Var, for modifiers that access the
   4109 		 * variable name, such as :L or :?.
   4110 		 *
   4111 		 * Most modifiers leave this expression in the "undefined"
   4112 		 * state (VEF_UNDEF), only a few modifiers like :D, :U, :L,
   4113 		 * :P turn this undefined expression into a defined
   4114 		 * expression (VEF_DEF).
   4115 		 *
   4116 		 * At the end, after applying all modifiers, if the expression
   4117 		 * is still undefined, Var_Parse will return an empty string
   4118 		 * instead of the actually computed value.
   4119 		 */
   4120 		v = VarNew(FStr_InitOwn(varname), "", VAR_NONE);
   4121 		*out_TRUE_exprStatus = VES_UNDEF;
   4122 	} else
   4123 		free(varname);
   4124 
   4125 	*out_TRUE_endc = endc;
   4126 	*out_TRUE_p = p;
   4127 	*out_TRUE_v = v;
   4128 	*out_TRUE_haveModifier = haveModifier;
   4129 	*out_TRUE_dynamic = dynamic;
   4130 	return TRUE;
   4131 }
   4132 
   4133 /* Free the environment variable now since we own it. */
   4134 static void
   4135 FreeEnvVar(void **out_val_freeIt, Var *v, const char *value)
   4136 {
   4137 	char *varValue = Buf_DoneData(&v->val);
   4138 	if (value == varValue)
   4139 		*out_val_freeIt = varValue;
   4140 	else
   4141 		free(varValue);
   4142 
   4143 	FStr_Done(&v->name);
   4144 	free(v);
   4145 }
   4146 
   4147 /*
   4148  * Given the start of a variable expression (such as $v, $(VAR),
   4149  * ${VAR:Mpattern}), extract the variable name and value, and the modifiers,
   4150  * if any.  While doing that, apply the modifiers to the value of the
   4151  * expression, forming its final value.  A few of the modifiers such as :!cmd!
   4152  * or ::= have side effects.
   4153  *
   4154  * Input:
   4155  *	*pp		The string to parse.
   4156  *			When parsing a condition in ParseEmptyArg, it may also
   4157  *			point to the "y" of "empty(VARNAME:Modifiers)", which
   4158  *			is syntactically the same.
   4159  *	scope		The scope for finding variables
   4160  *	eflags		Control the exact details of parsing
   4161  *
   4162  * Output:
   4163  *	*pp		The position where to continue parsing.
   4164  *			TODO: After a parse error, the value of *pp is
   4165  *			unspecified.  It may not have been updated at all,
   4166  *			point to some random character in the string, to the
   4167  *			location of the parse error, or at the end of the
   4168  *			string.
   4169  *	*out_val	The value of the variable expression, never NULL.
   4170  *	*out_val	var_Error if there was a parse error.
   4171  *	*out_val	var_Error if the base variable of the expression was
   4172  *			undefined, eflags contains VARE_UNDEFERR, and none of
   4173  *			the modifiers turned the undefined expression into a
   4174  *			defined expression.
   4175  *			XXX: It is not guaranteed that an error message has
   4176  *			been printed.
   4177  *	*out_val	varUndefined if the base variable of the expression
   4178  *			was undefined, eflags did not contain VARE_UNDEFERR,
   4179  *			and none of the modifiers turned the undefined
   4180  *			expression into a defined expression.
   4181  *			XXX: It is not guaranteed that an error message has
   4182  *			been printed.
   4183  *	*out_val_freeIt	Must be freed by the caller after using *out_val.
   4184  */
   4185 /* coverity[+alloc : arg-*4] */
   4186 VarParseResult
   4187 Var_Parse(const char **pp, GNode *scope, VarEvalFlags eflags, FStr *out_val)
   4188 {
   4189 	const char *p = *pp;
   4190 	const char *const start = p;
   4191 	/* TRUE if have modifiers for the variable. */
   4192 	Boolean haveModifier;
   4193 	/* Starting character if variable in parens or braces. */
   4194 	char startc;
   4195 	/* Ending character if variable in parens or braces. */
   4196 	char endc;
   4197 	/*
   4198 	 * TRUE if the variable is local and we're expanding it in a
   4199 	 * non-local scope. This is done to support dynamic sources.
   4200 	 * The result is just the expression, unaltered.
   4201 	 */
   4202 	Boolean dynamic;
   4203 	const char *extramodifiers;
   4204 	Var *v;
   4205 	FStr value;
   4206 	char eflags_str[VarEvalFlags_ToStringSize];
   4207 	VarExprStatus exprStatus = VES_NONE;
   4208 
   4209 	DEBUG2(VAR, "Var_Parse: %s with %s\n", start,
   4210 	    VarEvalFlags_ToString(eflags_str, eflags));
   4211 
   4212 	*out_val = FStr_InitRefer(NULL);
   4213 	extramodifiers = NULL;	/* extra modifiers to apply first */
   4214 	dynamic = FALSE;
   4215 
   4216 	/*
   4217 	 * Appease GCC, which thinks that the variable might not be
   4218 	 * initialized.
   4219 	 */
   4220 	endc = '\0';
   4221 
   4222 	startc = p[1];
   4223 	if (startc != '(' && startc != '{') {
   4224 		VarParseResult res;
   4225 		if (!ParseVarnameShort(startc, pp, scope, eflags, &res,
   4226 		    &out_val->str, &v))
   4227 			return res;
   4228 		haveModifier = FALSE;
   4229 		p++;
   4230 	} else {
   4231 		VarParseResult res;
   4232 		if (!ParseVarnameLong(p, startc, scope, eflags,
   4233 		    pp, &res, out_val,
   4234 		    &endc, &p, &v, &haveModifier, &extramodifiers,
   4235 		    &dynamic, &exprStatus))
   4236 			return res;
   4237 	}
   4238 
   4239 	if (v->flags & VAR_IN_USE)
   4240 		Fatal("Variable %s is recursive.", v->name.str);
   4241 
   4242 	/*
   4243 	 * XXX: This assignment creates an alias to the current value of the
   4244 	 * variable.  This means that as long as the value of the expression
   4245 	 * stays the same, the value of the variable must not change.
   4246 	 * Using the '::=' modifier, it could be possible to do exactly this.
   4247 	 * At the bottom of this function, the resulting value is compared to
   4248 	 * the then-current value of the variable.  This might also invoke
   4249 	 * undefined behavior.
   4250 	 */
   4251 	value = FStr_InitRefer(v->val.data);
   4252 
   4253 	/*
   4254 	 * Before applying any modifiers, expand any nested expressions from
   4255 	 * the variable value.
   4256 	 */
   4257 	if (strchr(value.str, '$') != NULL && (eflags & VARE_WANTRES)) {
   4258 		char *expanded;
   4259 		VarEvalFlags nested_eflags = eflags;
   4260 		if (opts.strict)
   4261 			nested_eflags &= ~(unsigned)VARE_UNDEFERR;
   4262 		v->flags |= VAR_IN_USE;
   4263 		(void)Var_Subst(value.str, scope, nested_eflags, &expanded);
   4264 		v->flags &= ~(unsigned)VAR_IN_USE;
   4265 		/* TODO: handle errors */
   4266 		value = FStr_InitOwn(expanded);
   4267 	}
   4268 
   4269 	if (haveModifier || extramodifiers != NULL) {
   4270 		if (extramodifiers != NULL) {
   4271 			const char *em = extramodifiers;
   4272 			value = ApplyModifiers(&em, value, '\0', '\0',
   4273 			    v, &exprStatus, scope, eflags);
   4274 		}
   4275 
   4276 		if (haveModifier) {
   4277 			p++;	/* Skip initial colon. */
   4278 
   4279 			value = ApplyModifiers(&p, value, startc, endc,
   4280 			    v, &exprStatus, scope, eflags);
   4281 		}
   4282 	}
   4283 
   4284 	if (*p != '\0')		/* Skip past endc if possible. */
   4285 		p++;
   4286 
   4287 	*pp = p;
   4288 
   4289 	if (v->flags & VAR_FROM_ENV) {
   4290 		FreeEnvVar(&value.freeIt, v, value.str);
   4291 
   4292 	} else if (exprStatus != VES_NONE) {
   4293 		if (exprStatus != VES_DEF) {
   4294 			FStr_Done(&value);
   4295 			if (dynamic) {
   4296 				value = FStr_InitOwn(bmake_strsedup(start, p));
   4297 			} else {
   4298 				/*
   4299 				 * The expression is still undefined,
   4300 				 * therefore discard the actual value and
   4301 				 * return an error marker instead.
   4302 				 */
   4303 				value = FStr_InitRefer(eflags & VARE_UNDEFERR
   4304 				    ? var_Error : varUndefined);
   4305 			}
   4306 		}
   4307 		if (value.str != v->val.data)
   4308 			Buf_Done(&v->val);
   4309 		FStr_Done(&v->name);
   4310 		free(v);
   4311 	}
   4312 	*out_val = (FStr){ value.str, value.freeIt };
   4313 	return VPR_OK;		/* XXX: Is not correct in all cases */
   4314 }
   4315 
   4316 static void
   4317 VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalFlags eflags)
   4318 {
   4319 	/*
   4320 	 * A dollar sign may be escaped with another dollar
   4321 	 * sign.
   4322 	 */
   4323 	if (save_dollars && (eflags & VARE_KEEP_DOLLAR))
   4324 		Buf_AddByte(res, '$');
   4325 	Buf_AddByte(res, '$');
   4326 	*pp += 2;
   4327 }
   4328 
   4329 static void
   4330 VarSubstExpr(const char **pp, Buffer *buf, GNode *scope,
   4331 	     VarEvalFlags eflags, Boolean *inout_errorReported)
   4332 {
   4333 	const char *p = *pp;
   4334 	const char *nested_p = p;
   4335 	FStr val;
   4336 
   4337 	(void)Var_Parse(&nested_p, scope, eflags, &val);
   4338 	/* TODO: handle errors */
   4339 
   4340 	if (val.str == var_Error || val.str == varUndefined) {
   4341 		if (!(eflags & VARE_KEEP_UNDEF)) {
   4342 			p = nested_p;
   4343 		} else if ((eflags & VARE_UNDEFERR) || val.str == var_Error) {
   4344 
   4345 			/*
   4346 			 * XXX: This condition is wrong.  If val == var_Error,
   4347 			 * this doesn't necessarily mean there was an undefined
   4348 			 * variable.  It could equally well be a parse error;
   4349 			 * see unit-tests/varmod-order.exp.
   4350 			 */
   4351 
   4352 			/*
   4353 			 * If variable is undefined, complain and skip the
   4354 			 * variable. The complaint will stop us from doing
   4355 			 * anything when the file is parsed.
   4356 			 */
   4357 			if (!*inout_errorReported) {
   4358 				Parse_Error(PARSE_FATAL,
   4359 				    "Undefined variable \"%.*s\"",
   4360 				    (int)(size_t)(nested_p - p), p);
   4361 			}
   4362 			p = nested_p;
   4363 			*inout_errorReported = TRUE;
   4364 		} else {
   4365 			/* Copy the initial '$' of the undefined expression,
   4366 			 * thereby deferring expansion of the expression, but
   4367 			 * expand nested expressions if already possible.
   4368 			 * See unit-tests/varparse-undef-partial.mk. */
   4369 			Buf_AddByte(buf, *p);
   4370 			p++;
   4371 		}
   4372 	} else {
   4373 		p = nested_p;
   4374 		Buf_AddStr(buf, val.str);
   4375 	}
   4376 
   4377 	FStr_Done(&val);
   4378 
   4379 	*pp = p;
   4380 }
   4381 
   4382 /*
   4383  * Skip as many characters as possible -- either to the end of the string
   4384  * or to the next dollar sign (variable expression).
   4385  */
   4386 static void
   4387 VarSubstPlain(const char **pp, Buffer *res)
   4388 {
   4389 	const char *p = *pp;
   4390 	const char *start = p;
   4391 
   4392 	for (p++; *p != '$' && *p != '\0'; p++)
   4393 		continue;
   4394 	Buf_AddBytesBetween(res, start, p);
   4395 	*pp = p;
   4396 }
   4397 
   4398 /*
   4399  * Expand all variable expressions like $V, ${VAR}, $(VAR:Modifiers) in the
   4400  * given string.
   4401  *
   4402  * Input:
   4403  *	str		The string in which the variable expressions are
   4404  *			expanded.
   4405  *	scope		The scope in which to start searching for
   4406  *			variables.  The other scopes are searched as well.
   4407  *	eflags		Special effects during expansion.
   4408  */
   4409 VarParseResult
   4410 Var_Subst(const char *str, GNode *scope, VarEvalFlags eflags, char **out_res)
   4411 {
   4412 	const char *p = str;
   4413 	Buffer res;
   4414 
   4415 	/* Set true if an error has already been reported,
   4416 	 * to prevent a plethora of messages when recursing */
   4417 	/* XXX: Why is the 'static' necessary here? */
   4418 	static Boolean errorReported;
   4419 
   4420 	Buf_Init(&res);
   4421 	errorReported = FALSE;
   4422 
   4423 	while (*p != '\0') {
   4424 		if (p[0] == '$' && p[1] == '$')
   4425 			VarSubstDollarDollar(&p, &res, eflags);
   4426 		else if (p[0] == '$')
   4427 			VarSubstExpr(&p, &res, scope, eflags, &errorReported);
   4428 		else
   4429 			VarSubstPlain(&p, &res);
   4430 	}
   4431 
   4432 	*out_res = Buf_DoneDataCompact(&res);
   4433 	return VPR_OK;
   4434 }
   4435 
   4436 /* Initialize the variables module. */
   4437 void
   4438 Var_Init(void)
   4439 {
   4440 	SCOPE_INTERNAL = GNode_New("Internal");
   4441 	SCOPE_GLOBAL = GNode_New("Global");
   4442 	SCOPE_CMDLINE = GNode_New("Command");
   4443 }
   4444 
   4445 /* Clean up the variables module. */
   4446 void
   4447 Var_End(void)
   4448 {
   4449 	Var_Stats();
   4450 }
   4451 
   4452 void
   4453 Var_Stats(void)
   4454 {
   4455 	HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables");
   4456 }
   4457 
   4458 /* Print all variables in a scope, sorted by name. */
   4459 void
   4460 Var_Dump(GNode *scope)
   4461 {
   4462 	Vector /* of const char * */ vec;
   4463 	HashIter hi;
   4464 	size_t i;
   4465 	const char **varnames;
   4466 
   4467 	Vector_Init(&vec, sizeof(const char *));
   4468 
   4469 	HashIter_Init(&hi, &scope->vars);
   4470 	while (HashIter_Next(&hi) != NULL)
   4471 		*(const char **)Vector_Push(&vec) = hi.entry->key;
   4472 	varnames = vec.items;
   4473 
   4474 	qsort(varnames, vec.len, sizeof varnames[0], str_cmp_asc);
   4475 
   4476 	for (i = 0; i < vec.len; i++) {
   4477 		const char *varname = varnames[i];
   4478 		Var *var = HashTable_FindValue(&scope->vars, varname);
   4479 		debug_printf("%-16s = %s\n", varname, var->val.data);
   4480 	}
   4481 
   4482 	Vector_Done(&vec);
   4483 }
   4484