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