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