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