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