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