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