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