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