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