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