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