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