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