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