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