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