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