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