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