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