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