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