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