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