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