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