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