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