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