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