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