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