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