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