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