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