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