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