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