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