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