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