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