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