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