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