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