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