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