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