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