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