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