var.c revision 1.807 1 /* $NetBSD: var.c,v 1.807 2021/02/05 05:42:39 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.807 2021/02/05 05:42:39 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, in ${:Ua b c:M*2}, the callback is called 3 times, once for
1302 * each word of "a b c".
1303 */
1304 typedef void (*ModifyWordsCallback)(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 * Modify each of the words of the passed string using the given function.
1788 *
1789 * Input:
1790 * str String whose words should be modified
1791 * modifyWord Function that modifies a single word
1792 * modifyWord_args Custom arguments for modifyWord
1793 *
1794 * Results:
1795 * A string of all the words modified appropriately.
1796 */
1797 static char *
1798 ModifyWords(const char *str,
1799 ModifyWordsCallback modifyWord, void *modifyWord_args,
1800 Boolean oneBigWord, char sep)
1801 {
1802 SepBuf result;
1803 Words words;
1804 size_t i;
1805
1806 if (oneBigWord) {
1807 SepBuf_Init(&result, sep);
1808 modifyWord(str, &result, modifyWord_args);
1809 return SepBuf_DoneData(&result);
1810 }
1811
1812 SepBuf_Init(&result, sep);
1813
1814 words = Str_Words(str, FALSE);
1815
1816 DEBUG2(VAR, "ModifyWords: split \"%s\" into %u words\n",
1817 str, (unsigned)words.len);
1818
1819 for (i = 0; i < words.len; i++) {
1820 modifyWord(words.words[i], &result, modifyWord_args);
1821 if (result.buf.len > 0)
1822 SepBuf_Sep(&result);
1823 }
1824
1825 Words_Free(words);
1826
1827 return SepBuf_DoneData(&result);
1828 }
1829
1830
1831 static char *
1832 Words_JoinFree(Words words)
1833 {
1834 Buffer buf;
1835 size_t i;
1836
1837 Buf_Init(&buf);
1838
1839 for (i = 0; i < words.len; i++) {
1840 if (i != 0) {
1841 /* XXX: Use st->sep instead of ' ', for consistency. */
1842 Buf_AddByte(&buf, ' ');
1843 }
1844 Buf_AddStr(&buf, words.words[i]);
1845 }
1846
1847 Words_Free(words);
1848
1849 return Buf_DoneData(&buf);
1850 }
1851
1852 /* Remove adjacent duplicate words. */
1853 static char *
1854 VarUniq(const char *str)
1855 {
1856 Words words = Str_Words(str, FALSE);
1857
1858 if (words.len > 1) {
1859 size_t i, j;
1860 for (j = 0, i = 1; i < words.len; i++)
1861 if (strcmp(words.words[i], words.words[j]) != 0 &&
1862 (++j != i))
1863 words.words[j] = words.words[i];
1864 words.len = j + 1;
1865 }
1866
1867 return Words_JoinFree(words);
1868 }
1869
1870
1871 /*
1872 * Quote shell meta-characters and space characters in the string.
1873 * If quoteDollar is set, also quote and double any '$' characters.
1874 */
1875 static char *
1876 VarQuote(const char *str, Boolean quoteDollar)
1877 {
1878 Buffer buf;
1879 Buf_Init(&buf);
1880
1881 for (; *str != '\0'; str++) {
1882 if (*str == '\n') {
1883 const char *newline = Shell_GetNewline();
1884 if (newline == NULL)
1885 newline = "\\\n";
1886 Buf_AddStr(&buf, newline);
1887 continue;
1888 }
1889 if (ch_isspace(*str) || is_shell_metachar((unsigned char)*str))
1890 Buf_AddByte(&buf, '\\');
1891 Buf_AddByte(&buf, *str);
1892 if (quoteDollar && *str == '$')
1893 Buf_AddStr(&buf, "\\$");
1894 }
1895
1896 return Buf_DoneData(&buf);
1897 }
1898
1899 /*
1900 * Compute the 32-bit hash of the given string, using the MurmurHash3
1901 * algorithm. Output is encoded as 8 hex digits, in Little Endian order.
1902 */
1903 static char *
1904 VarHash(const char *str)
1905 {
1906 static const char hexdigits[16] = "0123456789abcdef";
1907 const unsigned char *ustr = (const unsigned char *)str;
1908
1909 uint32_t h = 0x971e137bU;
1910 uint32_t c1 = 0x95543787U;
1911 uint32_t c2 = 0x2ad7eb25U;
1912 size_t len2 = strlen(str);
1913
1914 char *buf;
1915 size_t i;
1916
1917 size_t len;
1918 for (len = len2; len != 0;) {
1919 uint32_t k = 0;
1920 switch (len) {
1921 default:
1922 k = ((uint32_t)ustr[3] << 24) |
1923 ((uint32_t)ustr[2] << 16) |
1924 ((uint32_t)ustr[1] << 8) |
1925 (uint32_t)ustr[0];
1926 len -= 4;
1927 ustr += 4;
1928 break;
1929 case 3:
1930 k |= (uint32_t)ustr[2] << 16;
1931 /* FALLTHROUGH */
1932 case 2:
1933 k |= (uint32_t)ustr[1] << 8;
1934 /* FALLTHROUGH */
1935 case 1:
1936 k |= (uint32_t)ustr[0];
1937 len = 0;
1938 }
1939 c1 = c1 * 5 + 0x7b7d159cU;
1940 c2 = c2 * 5 + 0x6bce6396U;
1941 k *= c1;
1942 k = (k << 11) ^ (k >> 21);
1943 k *= c2;
1944 h = (h << 13) ^ (h >> 19);
1945 h = h * 5 + 0x52dce729U;
1946 h ^= k;
1947 }
1948 h ^= (uint32_t)len2;
1949 h *= 0x85ebca6b;
1950 h ^= h >> 13;
1951 h *= 0xc2b2ae35;
1952 h ^= h >> 16;
1953
1954 buf = bmake_malloc(9);
1955 for (i = 0; i < 8; i++) {
1956 buf[i] = hexdigits[h & 0x0f];
1957 h >>= 4;
1958 }
1959 buf[8] = '\0';
1960 return buf;
1961 }
1962
1963 static char *
1964 VarStrftime(const char *fmt, Boolean zulu, time_t tim)
1965 {
1966 char buf[BUFSIZ];
1967
1968 if (tim == 0)
1969 time(&tim);
1970 if (*fmt == '\0')
1971 fmt = "%c";
1972 strftime(buf, sizeof buf, fmt, zulu ? gmtime(&tim) : localtime(&tim));
1973
1974 buf[sizeof buf - 1] = '\0';
1975 return bmake_strdup(buf);
1976 }
1977
1978 /*
1979 * The ApplyModifier functions take an expression that is being evaluated.
1980 * Their task is to apply a single modifier to the expression.
1981 * To do this, they parse the modifier and its parameters from pp and apply
1982 * the parsed modifier to the current value of the expression, generating a
1983 * new value from it.
1984 *
1985 * The modifier typically lasts until the next ':', or a closing '}' or ')'
1986 * (taken from st->endc), or the end of the string (parse error).
1987 *
1988 * The high-level behavior of these functions is:
1989 *
1990 * 1. parse the modifier
1991 * 2. evaluate the modifier
1992 * 3. housekeeping
1993 *
1994 * Parsing the modifier
1995 *
1996 * If parsing succeeds, the parsing position *pp is updated to point to the
1997 * first character following the modifier, which typically is either ':' or
1998 * st->endc. The modifier doesn't have to check for this delimiter character,
1999 * this is done by ApplyModifiers.
2000 *
2001 * XXX: As of 2020-11-15, some modifiers such as :S, :C, :P, :L do not
2002 * need to be followed by a ':' or endc; this was an unintended mistake.
2003 *
2004 * If parsing fails because of a missing delimiter (as in the :S, :C or :@
2005 * modifiers), return AMR_CLEANUP.
2006 *
2007 * If parsing fails because the modifier is unknown, return AMR_UNKNOWN to
2008 * try the SysV modifier ${VAR:from=to} as fallback. This should only be
2009 * done as long as there have been no side effects from evaluating nested
2010 * variables, to avoid evaluating them more than once. In this case, the
2011 * parsing position may or may not be updated. (XXX: Why not? The original
2012 * parsing position is well-known in ApplyModifiers.)
2013 *
2014 * If parsing fails and the SysV modifier ${VAR:from=to} should not be used
2015 * as a fallback, either issue an error message using Error or Parse_Error
2016 * and then return AMR_CLEANUP, or return AMR_BAD for the default error
2017 * message. Both of these return values will stop processing the variable
2018 * expression. (XXX: As of 2020-08-23, evaluation of the whole string
2019 * continues nevertheless after skipping a few bytes, which essentially is
2020 * undefined behavior. Not in the sense of C, but still it's impossible to
2021 * predict what happens in the parser.)
2022 *
2023 * Evaluating the modifier
2024 *
2025 * After parsing, the modifier is evaluated. The side effects from evaluating
2026 * nested variable expressions in the modifier text often already happen
2027 * during parsing though.
2028 *
2029 * Evaluating the modifier usually takes the current value of the variable
2030 * expression from st->val, or the variable name from st->var->name and stores
2031 * the result in st->newVal.
2032 *
2033 * If evaluating fails (as of 2020-08-23), an error message is printed using
2034 * Error. This function has no side-effects, it really just prints the error
2035 * message. Processing the expression continues as if everything were ok.
2036 * XXX: This should be fixed by adding proper error handling to Var_Subst,
2037 * Var_Parse, ApplyModifiers and ModifyWords.
2038 *
2039 * Housekeeping
2040 *
2041 * Some modifiers such as :D and :U turn undefined expressions into defined
2042 * expressions (see VEF_UNDEF, VEF_DEF).
2043 *
2044 * Some modifiers need to free some memory.
2045 */
2046
2047 typedef enum VarExprStatus {
2048 /* The variable expression is based in a regular, defined variable. */
2049 VES_NONE,
2050 /* The variable expression is based on an undefined variable. */
2051 VES_UNDEF,
2052 /*
2053 * The variable expression started as an undefined expression, but one
2054 * of the modifiers (such as :D or :U) has turned the expression from
2055 * undefined to defined.
2056 */
2057 VES_DEF
2058 } VarExprStatus;
2059
2060 static const char * const VarExprStatus_Name[] = {
2061 "none",
2062 "VES_UNDEF",
2063 "VES_DEF"
2064 };
2065
2066 typedef struct ApplyModifiersState {
2067 /* '\0' or '{' or '(' */
2068 const char startc;
2069 /* '\0' or '}' or ')' */
2070 const char endc;
2071 Var *const var;
2072 GNode *const scope;
2073 const VarEvalFlags eflags;
2074 /*
2075 * The new value of the expression, after applying the modifier,
2076 * never NULL.
2077 */
2078 FStr newVal;
2079 /* Word separator in expansions (see the :ts modifier). */
2080 char sep;
2081 /*
2082 * TRUE if some modifiers that otherwise split the variable value
2083 * into words, like :S and :C, treat the variable value as a single
2084 * big word, possibly containing spaces.
2085 */
2086 Boolean oneBigWord;
2087 VarExprStatus exprStatus;
2088 } ApplyModifiersState;
2089
2090 static void
2091 ApplyModifiersState_Define(ApplyModifiersState *st)
2092 {
2093 if (st->exprStatus == VES_UNDEF)
2094 st->exprStatus = VES_DEF;
2095 }
2096
2097 typedef enum ApplyModifierResult {
2098 /* Continue parsing */
2099 AMR_OK,
2100 /* Not a match, try other modifiers as well */
2101 AMR_UNKNOWN,
2102 /* Error out with "Bad modifier" message */
2103 AMR_BAD,
2104 /* Error out without error message */
2105 AMR_CLEANUP
2106 } ApplyModifierResult;
2107
2108 /*
2109 * Allow backslashes to escape the delimiter, $, and \, but don't touch other
2110 * backslashes.
2111 */
2112 static Boolean
2113 IsEscapedModifierPart(const char *p, char delim,
2114 struct ModifyWord_SubstArgs *subst)
2115 {
2116 if (p[0] != '\\')
2117 return FALSE;
2118 if (p[1] == delim || p[1] == '\\' || p[1] == '$')
2119 return TRUE;
2120 return p[1] == '&' && subst != NULL;
2121 }
2122
2123 /* See ParseModifierPart */
2124 static VarParseResult
2125 ParseModifierPartSubst(
2126 const char **pp,
2127 char delim,
2128 VarEvalFlags eflags,
2129 ApplyModifiersState *st,
2130 char **out_part,
2131 /* Optionally stores the length of the returned string, just to save
2132 * another strlen call. */
2133 size_t *out_length,
2134 /* For the first part of the :S modifier, sets the VARP_ANCHOR_END flag
2135 * if the last character of the pattern is a $. */
2136 VarPatternFlags *out_pflags,
2137 /* For the second part of the :S modifier, allow ampersands to be
2138 * escaped and replace unescaped ampersands with subst->lhs. */
2139 struct ModifyWord_SubstArgs *subst
2140 )
2141 {
2142 Buffer buf;
2143 const char *p;
2144
2145 Buf_Init(&buf);
2146
2147 /*
2148 * Skim through until the matching delimiter is found; pick up
2149 * variable expressions on the way.
2150 */
2151 p = *pp;
2152 while (*p != '\0' && *p != delim) {
2153 const char *varstart;
2154
2155 if (IsEscapedModifierPart(p, delim, subst)) {
2156 Buf_AddByte(&buf, p[1]);
2157 p += 2;
2158 continue;
2159 }
2160
2161 if (*p != '$') { /* Unescaped, simple text */
2162 if (subst != NULL && *p == '&')
2163 Buf_AddBytes(&buf, subst->lhs, subst->lhsLen);
2164 else
2165 Buf_AddByte(&buf, *p);
2166 p++;
2167 continue;
2168 }
2169
2170 if (p[1] == delim) { /* Unescaped $ at end of pattern */
2171 if (out_pflags != NULL)
2172 out_pflags->anchorEnd = TRUE;
2173 else
2174 Buf_AddByte(&buf, *p);
2175 p++;
2176 continue;
2177 }
2178
2179 if (eflags & VARE_WANTRES) { /* Nested variable, evaluated */
2180 const char *nested_p = p;
2181 FStr nested_val;
2182 VarEvalFlags nested_eflags =
2183 eflags & ~(unsigned)VARE_KEEP_DOLLAR;
2184
2185 (void)Var_Parse(&nested_p, st->scope, nested_eflags,
2186 &nested_val);
2187 /* TODO: handle errors */
2188 Buf_AddStr(&buf, nested_val.str);
2189 FStr_Done(&nested_val);
2190 p += nested_p - p;
2191 continue;
2192 }
2193
2194 /*
2195 * XXX: This whole block is very similar to Var_Parse without
2196 * VARE_WANTRES. There may be subtle edge cases though that
2197 * are not yet covered in the unit tests and that are parsed
2198 * differently, depending on whether they are evaluated or
2199 * not.
2200 *
2201 * This subtle difference is not documented in the manual
2202 * page, neither is the difference between parsing :D and
2203 * :M documented. No code should ever depend on these
2204 * details, but who knows.
2205 */
2206
2207 varstart = p; /* Nested variable, only parsed */
2208 if (p[1] == '(' || p[1] == '{') {
2209 /*
2210 * Find the end of this variable reference
2211 * and suck it in without further ado.
2212 * It will be interpreted later.
2213 */
2214 char startc = p[1];
2215 int endc = startc == '(' ? ')' : '}';
2216 int depth = 1;
2217
2218 for (p += 2; *p != '\0' && depth > 0; p++) {
2219 if (p[-1] != '\\') {
2220 if (*p == startc)
2221 depth++;
2222 if (*p == endc)
2223 depth--;
2224 }
2225 }
2226 Buf_AddBytesBetween(&buf, varstart, p);
2227 } else {
2228 Buf_AddByte(&buf, *varstart);
2229 p++;
2230 }
2231 }
2232
2233 if (*p != delim) {
2234 *pp = p;
2235 Error("Unfinished modifier for %s ('%c' missing)",
2236 st->var->name.str, delim);
2237 *out_part = NULL;
2238 return VPR_ERR;
2239 }
2240
2241 *pp = p + 1;
2242 if (out_length != NULL)
2243 *out_length = buf.len;
2244
2245 *out_part = Buf_DoneData(&buf);
2246 DEBUG1(VAR, "Modifier part: \"%s\"\n", *out_part);
2247 return VPR_OK;
2248 }
2249
2250 /*
2251 * Parse a part of a modifier such as the "from" and "to" in :S/from/to/ or
2252 * the "var" or "replacement ${var}" in :@var@replacement ${var}@, up to and
2253 * including the next unescaped delimiter. The delimiter, as well as the
2254 * backslash or the dollar, can be escaped with a backslash.
2255 *
2256 * Return the parsed (and possibly expanded) string, or NULL if no delimiter
2257 * was found. On successful return, the parsing position pp points right
2258 * after the delimiter. The delimiter is not included in the returned
2259 * value though.
2260 */
2261 static VarParseResult
2262 ParseModifierPart(
2263 /* The parsing position, updated upon return */
2264 const char **pp,
2265 /* Parsing stops at this delimiter */
2266 char delim,
2267 /* Flags for evaluating nested variables; if VARE_WANTRES is not set,
2268 * the text is only parsed. */
2269 VarEvalFlags eflags,
2270 ApplyModifiersState *st,
2271 char **out_part
2272 )
2273 {
2274 return ParseModifierPartSubst(pp, delim, eflags, st, out_part,
2275 NULL, NULL, NULL);
2276 }
2277
2278 /* Test whether mod starts with modname, followed by a delimiter. */
2279 MAKE_INLINE Boolean
2280 ModMatch(const char *mod, const char *modname, char endc)
2281 {
2282 size_t n = strlen(modname);
2283 return strncmp(mod, modname, n) == 0 &&
2284 (mod[n] == endc || mod[n] == ':');
2285 }
2286
2287 /* Test whether mod starts with modname, followed by a delimiter or '='. */
2288 MAKE_INLINE Boolean
2289 ModMatchEq(const char *mod, const char *modname, char endc)
2290 {
2291 size_t n = strlen(modname);
2292 return strncmp(mod, modname, n) == 0 &&
2293 (mod[n] == endc || mod[n] == ':' || mod[n] == '=');
2294 }
2295
2296 static Boolean
2297 TryParseIntBase0(const char **pp, int *out_num)
2298 {
2299 char *end;
2300 long n;
2301
2302 errno = 0;
2303 n = strtol(*pp, &end, 0);
2304 if ((n == LONG_MIN || n == LONG_MAX) && errno == ERANGE)
2305 return FALSE;
2306 if (n < INT_MIN || n > INT_MAX)
2307 return FALSE;
2308
2309 *pp = end;
2310 *out_num = (int)n;
2311 return TRUE;
2312 }
2313
2314 static Boolean
2315 TryParseSize(const char **pp, size_t *out_num)
2316 {
2317 char *end;
2318 unsigned long n;
2319
2320 if (!ch_isdigit(**pp))
2321 return FALSE;
2322
2323 errno = 0;
2324 n = strtoul(*pp, &end, 10);
2325 if (n == ULONG_MAX && errno == ERANGE)
2326 return FALSE;
2327 if (n > SIZE_MAX)
2328 return FALSE;
2329
2330 *pp = end;
2331 *out_num = (size_t)n;
2332 return TRUE;
2333 }
2334
2335 static Boolean
2336 TryParseChar(const char **pp, int base, char *out_ch)
2337 {
2338 char *end;
2339 unsigned long n;
2340
2341 if (!ch_isalnum(**pp))
2342 return FALSE;
2343
2344 errno = 0;
2345 n = strtoul(*pp, &end, base);
2346 if (n == ULONG_MAX && errno == ERANGE)
2347 return FALSE;
2348 if (n > UCHAR_MAX)
2349 return FALSE;
2350
2351 *pp = end;
2352 *out_ch = (char)n;
2353 return TRUE;
2354 }
2355
2356 /* :@var (at) ...${var}...@ */
2357 static ApplyModifierResult
2358 ApplyModifier_Loop(const char **pp, const char *val, ApplyModifiersState *st)
2359 {
2360 struct ModifyWord_LoopArgs args;
2361 char prev_sep;
2362 VarParseResult res;
2363
2364 args.scope = st->scope;
2365
2366 (*pp)++; /* Skip the first '@' */
2367 res = ParseModifierPart(pp, '@', VARE_NONE, st, &args.tvar);
2368 if (res != VPR_OK)
2369 return AMR_CLEANUP;
2370 if (opts.strict && strchr(args.tvar, '$') != NULL) {
2371 Parse_Error(PARSE_FATAL,
2372 "In the :@ modifier of \"%s\", the variable name \"%s\" "
2373 "must not contain a dollar.",
2374 st->var->name.str, args.tvar);
2375 return AMR_CLEANUP;
2376 }
2377
2378 res = ParseModifierPart(pp, '@', VARE_NONE, st, &args.str);
2379 if (res != VPR_OK)
2380 return AMR_CLEANUP;
2381
2382 args.eflags = st->eflags & ~(unsigned)VARE_KEEP_DOLLAR;
2383 prev_sep = st->sep;
2384 st->sep = ' '; /* XXX: should be st->sep for consistency */
2385 st->newVal = FStr_InitOwn(
2386 ModifyWords(val, ModifyWord_Loop, &args, st->oneBigWord, st->sep));
2387 st->sep = prev_sep;
2388 /* XXX: Consider restoring the previous variable instead of deleting. */
2389 /*
2390 * XXX: The variable name should not be expanded here, see
2391 * ModifyWord_Loop.
2392 */
2393 Var_DeleteExpand(st->scope, args.tvar);
2394 free(args.tvar);
2395 free(args.str);
2396 return AMR_OK;
2397 }
2398
2399 /* :Ddefined or :Uundefined */
2400 static ApplyModifierResult
2401 ApplyModifier_Defined(const char **pp, const char *val, ApplyModifiersState *st)
2402 {
2403 Buffer buf;
2404 const char *p;
2405
2406 VarEvalFlags eflags = VARE_NONE;
2407 if (st->eflags & VARE_WANTRES)
2408 if ((**pp == 'D') == (st->exprStatus == VES_NONE))
2409 eflags = st->eflags;
2410
2411 Buf_Init(&buf);
2412 p = *pp + 1;
2413 while (*p != st->endc && *p != ':' && *p != '\0') {
2414
2415 /* XXX: This code is similar to the one in Var_Parse.
2416 * See if the code can be merged.
2417 * See also ApplyModifier_Match. */
2418
2419 /* Escaped delimiter or other special character */
2420 if (*p == '\\') {
2421 char c = p[1];
2422 if (c == st->endc || c == ':' || c == '$' ||
2423 c == '\\') {
2424 Buf_AddByte(&buf, c);
2425 p += 2;
2426 continue;
2427 }
2428 }
2429
2430 /* Nested variable expression */
2431 if (*p == '$') {
2432 FStr nested_val;
2433
2434 (void)Var_Parse(&p, st->scope, eflags, &nested_val);
2435 /* TODO: handle errors */
2436 Buf_AddStr(&buf, nested_val.str);
2437 FStr_Done(&nested_val);
2438 continue;
2439 }
2440
2441 /* Ordinary text */
2442 Buf_AddByte(&buf, *p);
2443 p++;
2444 }
2445 *pp = p;
2446
2447 ApplyModifiersState_Define(st);
2448
2449 if (eflags & VARE_WANTRES) {
2450 st->newVal = FStr_InitOwn(Buf_DoneData(&buf));
2451 } else {
2452 st->newVal = FStr_InitRefer(val);
2453 Buf_Done(&buf);
2454 }
2455 return AMR_OK;
2456 }
2457
2458 /* :L */
2459 static ApplyModifierResult
2460 ApplyModifier_Literal(const char **pp, ApplyModifiersState *st)
2461 {
2462 ApplyModifiersState_Define(st);
2463 st->newVal = FStr_InitOwn(bmake_strdup(st->var->name.str));
2464 (*pp)++;
2465 return AMR_OK;
2466 }
2467
2468 static Boolean
2469 TryParseTime(const char **pp, time_t *out_time)
2470 {
2471 char *end;
2472 unsigned long n;
2473
2474 if (!ch_isdigit(**pp))
2475 return FALSE;
2476
2477 errno = 0;
2478 n = strtoul(*pp, &end, 10);
2479 if (n == ULONG_MAX && errno == ERANGE)
2480 return FALSE;
2481
2482 *pp = end;
2483 *out_time = (time_t)n; /* ignore possible truncation for now */
2484 return TRUE;
2485 }
2486
2487 /* :gmtime */
2488 static ApplyModifierResult
2489 ApplyModifier_Gmtime(const char **pp, const char *val, ApplyModifiersState *st)
2490 {
2491 time_t utc;
2492
2493 const char *mod = *pp;
2494 if (!ModMatchEq(mod, "gmtime", st->endc))
2495 return AMR_UNKNOWN;
2496
2497 if (mod[6] == '=') {
2498 const char *arg = mod + 7;
2499 if (!TryParseTime(&arg, &utc)) {
2500 Parse_Error(PARSE_FATAL,
2501 "Invalid time value: %s", mod + 7);
2502 return AMR_CLEANUP;
2503 }
2504 *pp = arg;
2505 } else {
2506 utc = 0;
2507 *pp = mod + 6;
2508 }
2509 st->newVal = FStr_InitOwn(VarStrftime(val, TRUE, utc));
2510 return AMR_OK;
2511 }
2512
2513 /* :localtime */
2514 static ApplyModifierResult
2515 ApplyModifier_Localtime(const char **pp, const char *val,
2516 ApplyModifiersState *st)
2517 {
2518 time_t utc;
2519
2520 const char *mod = *pp;
2521 if (!ModMatchEq(mod, "localtime", st->endc))
2522 return AMR_UNKNOWN;
2523
2524 if (mod[9] == '=') {
2525 const char *arg = mod + 10;
2526 if (!TryParseTime(&arg, &utc)) {
2527 Parse_Error(PARSE_FATAL,
2528 "Invalid time value: %s", mod + 10);
2529 return AMR_CLEANUP;
2530 }
2531 *pp = arg;
2532 } else {
2533 utc = 0;
2534 *pp = mod + 9;
2535 }
2536 st->newVal = FStr_InitOwn(VarStrftime(val, FALSE, utc));
2537 return AMR_OK;
2538 }
2539
2540 /* :hash */
2541 static ApplyModifierResult
2542 ApplyModifier_Hash(const char **pp, const char *val, ApplyModifiersState *st)
2543 {
2544 if (!ModMatch(*pp, "hash", st->endc))
2545 return AMR_UNKNOWN;
2546
2547 st->newVal = FStr_InitOwn(VarHash(val));
2548 *pp += 4;
2549 return AMR_OK;
2550 }
2551
2552 /* :P */
2553 static ApplyModifierResult
2554 ApplyModifier_Path(const char **pp, ApplyModifiersState *st)
2555 {
2556 GNode *gn;
2557 char *path;
2558
2559 ApplyModifiersState_Define(st);
2560
2561 gn = Targ_FindNode(st->var->name.str);
2562 if (gn == NULL || gn->type & OP_NOPATH) {
2563 path = NULL;
2564 } else if (gn->path != NULL) {
2565 path = bmake_strdup(gn->path);
2566 } else {
2567 SearchPath *searchPath = Suff_FindPath(gn);
2568 path = Dir_FindFile(st->var->name.str, searchPath);
2569 }
2570 if (path == NULL)
2571 path = bmake_strdup(st->var->name.str);
2572 st->newVal = FStr_InitOwn(path);
2573
2574 (*pp)++;
2575 return AMR_OK;
2576 }
2577
2578 /* :!cmd! */
2579 static ApplyModifierResult
2580 ApplyModifier_ShellCommand(const char **pp, ApplyModifiersState *st)
2581 {
2582 char *cmd;
2583 const char *errfmt;
2584 VarParseResult res;
2585
2586 (*pp)++;
2587 res = ParseModifierPart(pp, '!', st->eflags, st, &cmd);
2588 if (res != VPR_OK)
2589 return AMR_CLEANUP;
2590
2591 errfmt = NULL;
2592 if (st->eflags & VARE_WANTRES)
2593 st->newVal = FStr_InitOwn(Cmd_Exec(cmd, &errfmt));
2594 else
2595 st->newVal = FStr_InitRefer("");
2596 if (errfmt != NULL)
2597 Error(errfmt, cmd); /* XXX: why still return AMR_OK? */
2598 free(cmd);
2599
2600 ApplyModifiersState_Define(st);
2601 return AMR_OK;
2602 }
2603
2604 /*
2605 * The :range modifier generates an integer sequence as long as the words.
2606 * The :range=7 modifier generates an integer sequence from 1 to 7.
2607 */
2608 static ApplyModifierResult
2609 ApplyModifier_Range(const char **pp, const char *val, ApplyModifiersState *st)
2610 {
2611 size_t n;
2612 Buffer buf;
2613 size_t i;
2614
2615 const char *mod = *pp;
2616 if (!ModMatchEq(mod, "range", st->endc))
2617 return AMR_UNKNOWN;
2618
2619 if (mod[5] == '=') {
2620 const char *p = mod + 6;
2621 if (!TryParseSize(&p, &n)) {
2622 Parse_Error(PARSE_FATAL,
2623 "Invalid number: %s", mod + 6);
2624 return AMR_CLEANUP;
2625 }
2626 *pp = p;
2627 } else {
2628 n = 0;
2629 *pp = mod + 5;
2630 }
2631
2632 if (n == 0) {
2633 Words words = Str_Words(val, FALSE);
2634 n = words.len;
2635 Words_Free(words);
2636 }
2637
2638 Buf_Init(&buf);
2639
2640 for (i = 0; i < n; i++) {
2641 if (i != 0) {
2642 /* XXX: Use st->sep instead of ' ', for consistency. */
2643 Buf_AddByte(&buf, ' ');
2644 }
2645 Buf_AddInt(&buf, 1 + (int)i);
2646 }
2647
2648 st->newVal = FStr_InitOwn(Buf_DoneData(&buf));
2649 return AMR_OK;
2650 }
2651
2652 /* :Mpattern or :Npattern */
2653 static ApplyModifierResult
2654 ApplyModifier_Match(const char **pp, const char *val, ApplyModifiersState *st)
2655 {
2656 const char *mod = *pp;
2657 Boolean copy = FALSE; /* pattern should be, or has been, copied */
2658 Boolean needSubst = FALSE;
2659 const char *endpat;
2660 char *pattern;
2661 ModifyWordsCallback callback;
2662
2663 /*
2664 * In the loop below, ignore ':' unless we are at (or back to) the
2665 * original brace level.
2666 * XXX: This will likely not work right if $() and ${} are intermixed.
2667 */
2668 /* XXX: This code is similar to the one in Var_Parse.
2669 * See if the code can be merged.
2670 * See also ApplyModifier_Defined. */
2671 int nest = 0;
2672 const char *p;
2673 for (p = mod + 1; *p != '\0' && !(*p == ':' && nest == 0); p++) {
2674 if (*p == '\\' &&
2675 (p[1] == ':' || p[1] == st->endc || p[1] == st->startc)) {
2676 if (!needSubst)
2677 copy = TRUE;
2678 p++;
2679 continue;
2680 }
2681 if (*p == '$')
2682 needSubst = TRUE;
2683 if (*p == '(' || *p == '{')
2684 nest++;
2685 if (*p == ')' || *p == '}') {
2686 nest--;
2687 if (nest < 0)
2688 break;
2689 }
2690 }
2691 *pp = p;
2692 endpat = p;
2693
2694 if (copy) {
2695 char *dst;
2696 const char *src;
2697
2698 /* Compress the \:'s out of the pattern. */
2699 pattern = bmake_malloc((size_t)(endpat - (mod + 1)) + 1);
2700 dst = pattern;
2701 src = mod + 1;
2702 for (; src < endpat; src++, dst++) {
2703 if (src[0] == '\\' && src + 1 < endpat &&
2704 /* XXX: st->startc is missing here; see above */
2705 (src[1] == ':' || src[1] == st->endc))
2706 src++;
2707 *dst = *src;
2708 }
2709 *dst = '\0';
2710 } else {
2711 pattern = bmake_strsedup(mod + 1, endpat);
2712 }
2713
2714 if (needSubst) {
2715 char *old_pattern = pattern;
2716 (void)Var_Subst(pattern, st->scope, st->eflags, &pattern);
2717 /* TODO: handle errors */
2718 free(old_pattern);
2719 }
2720
2721 DEBUG3(VAR, "Pattern[%s] for [%s] is [%s]\n",
2722 st->var->name.str, val, pattern);
2723
2724 callback = mod[0] == 'M' ? ModifyWord_Match : ModifyWord_NoMatch;
2725 st->newVal = FStr_InitOwn(ModifyWords(val, callback, pattern,
2726 st->oneBigWord, st->sep));
2727 free(pattern);
2728 return AMR_OK;
2729 }
2730
2731 /* :S,from,to, */
2732 static ApplyModifierResult
2733 ApplyModifier_Subst(const char **pp, const char *val, ApplyModifiersState *st)
2734 {
2735 struct ModifyWord_SubstArgs args;
2736 char *lhs, *rhs;
2737 Boolean oneBigWord;
2738 VarParseResult res;
2739
2740 char delim = (*pp)[1];
2741 if (delim == '\0') {
2742 Error("Missing delimiter for :S modifier");
2743 (*pp)++;
2744 return AMR_CLEANUP;
2745 }
2746
2747 *pp += 2;
2748
2749 args.pflags = (VarPatternFlags){ FALSE, FALSE, FALSE, FALSE };
2750 args.matched = FALSE;
2751
2752 /*
2753 * If pattern begins with '^', it is anchored to the
2754 * start of the word -- skip over it and flag pattern.
2755 */
2756 if (**pp == '^') {
2757 args.pflags.anchorStart = TRUE;
2758 (*pp)++;
2759 }
2760
2761 res = ParseModifierPartSubst(pp, delim, st->eflags, st, &lhs,
2762 &args.lhsLen, &args.pflags, NULL);
2763 if (res != VPR_OK)
2764 return AMR_CLEANUP;
2765 args.lhs = lhs;
2766
2767 res = ParseModifierPartSubst(pp, delim, st->eflags, st, &rhs,
2768 &args.rhsLen, NULL, &args);
2769 if (res != VPR_OK)
2770 return AMR_CLEANUP;
2771 args.rhs = rhs;
2772
2773 oneBigWord = st->oneBigWord;
2774 for (;; (*pp)++) {
2775 switch (**pp) {
2776 case 'g':
2777 args.pflags.subGlobal = TRUE;
2778 continue;
2779 case '1':
2780 args.pflags.subOnce = TRUE;
2781 continue;
2782 case 'W':
2783 oneBigWord = TRUE;
2784 continue;
2785 }
2786 break;
2787 }
2788
2789 st->newVal = FStr_InitOwn(ModifyWords(val, ModifyWord_Subst, &args,
2790 oneBigWord, st->sep));
2791
2792 free(lhs);
2793 free(rhs);
2794 return AMR_OK;
2795 }
2796
2797 #ifndef NO_REGEX
2798
2799 /* :C,from,to, */
2800 static ApplyModifierResult
2801 ApplyModifier_Regex(const char **pp, const char *val, ApplyModifiersState *st)
2802 {
2803 char *re;
2804 struct ModifyWord_SubstRegexArgs args;
2805 Boolean oneBigWord;
2806 int error;
2807 VarParseResult res;
2808
2809 char delim = (*pp)[1];
2810 if (delim == '\0') {
2811 Error("Missing delimiter for :C modifier");
2812 (*pp)++;
2813 return AMR_CLEANUP;
2814 }
2815
2816 *pp += 2;
2817
2818 res = ParseModifierPart(pp, delim, st->eflags, st, &re);
2819 if (res != VPR_OK)
2820 return AMR_CLEANUP;
2821
2822 res = ParseModifierPart(pp, delim, st->eflags, st, &args.replace);
2823 if (args.replace == NULL) {
2824 free(re);
2825 return AMR_CLEANUP;
2826 }
2827
2828 args.pflags = (VarPatternFlags){ FALSE, FALSE, FALSE, FALSE };
2829 args.matched = FALSE;
2830 oneBigWord = st->oneBigWord;
2831 for (;; (*pp)++) {
2832 switch (**pp) {
2833 case 'g':
2834 args.pflags.subGlobal = TRUE;
2835 continue;
2836 case '1':
2837 args.pflags.subOnce = TRUE;
2838 continue;
2839 case 'W':
2840 oneBigWord = TRUE;
2841 continue;
2842 }
2843 break;
2844 }
2845
2846 error = regcomp(&args.re, re, REG_EXTENDED);
2847 free(re);
2848 if (error != 0) {
2849 VarREError(error, &args.re, "Regex compilation error");
2850 free(args.replace);
2851 return AMR_CLEANUP;
2852 }
2853
2854 args.nsub = args.re.re_nsub + 1;
2855 if (args.nsub > 10)
2856 args.nsub = 10;
2857 st->newVal = FStr_InitOwn(
2858 ModifyWords(val, ModifyWord_SubstRegex, &args,
2859 oneBigWord, st->sep));
2860 regfree(&args.re);
2861 free(args.replace);
2862 return AMR_OK;
2863 }
2864
2865 #endif
2866
2867 /* :Q, :q */
2868 static ApplyModifierResult
2869 ApplyModifier_Quote(const char **pp, const char *val, ApplyModifiersState *st)
2870 {
2871 if ((*pp)[1] == st->endc || (*pp)[1] == ':') {
2872 st->newVal = FStr_InitOwn(VarQuote(val, **pp == 'q'));
2873 (*pp)++;
2874 return AMR_OK;
2875 } else
2876 return AMR_UNKNOWN;
2877 }
2878
2879 /*ARGSUSED*/
2880 static void
2881 ModifyWord_Copy(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
2882 {
2883 SepBuf_AddStr(buf, word);
2884 }
2885
2886 /* :ts<separator> */
2887 static ApplyModifierResult
2888 ApplyModifier_ToSep(const char **pp, const char *val, ApplyModifiersState *st)
2889 {
2890 const char *sep = *pp + 2;
2891
2892 /* ":ts<any><endc>" or ":ts<any>:" */
2893 if (sep[0] != st->endc && (sep[1] == st->endc || sep[1] == ':')) {
2894 st->sep = sep[0];
2895 *pp = sep + 1;
2896 goto ok;
2897 }
2898
2899 /* ":ts<endc>" or ":ts:" */
2900 if (sep[0] == st->endc || sep[0] == ':') {
2901 st->sep = '\0'; /* no separator */
2902 *pp = sep;
2903 goto ok;
2904 }
2905
2906 /* ":ts<unrecognised><unrecognised>". */
2907 if (sep[0] != '\\') {
2908 (*pp)++; /* just for backwards compatibility */
2909 return AMR_BAD;
2910 }
2911
2912 /* ":ts\n" */
2913 if (sep[1] == 'n') {
2914 st->sep = '\n';
2915 *pp = sep + 2;
2916 goto ok;
2917 }
2918
2919 /* ":ts\t" */
2920 if (sep[1] == 't') {
2921 st->sep = '\t';
2922 *pp = sep + 2;
2923 goto ok;
2924 }
2925
2926 /* ":ts\x40" or ":ts\100" */
2927 {
2928 const char *p = sep + 1;
2929 int base = 8; /* assume octal */
2930
2931 if (sep[1] == 'x') {
2932 base = 16;
2933 p++;
2934 } else if (!ch_isdigit(sep[1])) {
2935 (*pp)++; /* just for backwards compatibility */
2936 return AMR_BAD; /* ":ts<backslash><unrecognised>". */
2937 }
2938
2939 if (!TryParseChar(&p, base, &st->sep)) {
2940 Parse_Error(PARSE_FATAL,
2941 "Invalid character number: %s", p);
2942 return AMR_CLEANUP;
2943 }
2944 if (*p != ':' && *p != st->endc) {
2945 (*pp)++; /* just for backwards compatibility */
2946 return AMR_BAD;
2947 }
2948
2949 *pp = p;
2950 }
2951
2952 ok:
2953 st->newVal = FStr_InitOwn(
2954 ModifyWords(val, ModifyWord_Copy, NULL, st->oneBigWord, st->sep));
2955 return AMR_OK;
2956 }
2957
2958 static char *
2959 str_toupper(const char *str)
2960 {
2961 char *res;
2962 size_t i, len;
2963
2964 len = strlen(str);
2965 res = bmake_malloc(len + 1);
2966 for (i = 0; i < len + 1; i++)
2967 res[i] = ch_toupper(str[i]);
2968
2969 return res;
2970 }
2971
2972 static char *
2973 str_tolower(const char *str)
2974 {
2975 char *res;
2976 size_t i, len;
2977
2978 len = strlen(str);
2979 res = bmake_malloc(len + 1);
2980 for (i = 0; i < len + 1; i++)
2981 res[i] = ch_tolower(str[i]);
2982
2983 return res;
2984 }
2985
2986 /* :tA, :tu, :tl, :ts<separator>, etc. */
2987 static ApplyModifierResult
2988 ApplyModifier_To(const char **pp, const char *val, ApplyModifiersState *st)
2989 {
2990 const char *mod = *pp;
2991 assert(mod[0] == 't');
2992
2993 if (mod[1] == st->endc || mod[1] == ':' || mod[1] == '\0') {
2994 *pp = mod + 1;
2995 return AMR_BAD; /* Found ":t<endc>" or ":t:". */
2996 }
2997
2998 if (mod[1] == 's')
2999 return ApplyModifier_ToSep(pp, val, st);
3000
3001 if (mod[2] != st->endc && mod[2] != ':') {
3002 *pp = mod + 1;
3003 return AMR_BAD; /* Found ":t<unrecognised><unrecognised>". */
3004 }
3005
3006 /* Check for two-character options: ":tu", ":tl" */
3007 if (mod[1] == 'A') { /* absolute path */
3008 st->newVal = FStr_InitOwn(
3009 ModifyWords(val, ModifyWord_Realpath, NULL,
3010 st->oneBigWord, st->sep));
3011 *pp = mod + 2;
3012 return AMR_OK;
3013 }
3014
3015 if (mod[1] == 'u') { /* :tu */
3016 st->newVal = FStr_InitOwn(str_toupper(val));
3017 *pp = mod + 2;
3018 return AMR_OK;
3019 }
3020
3021 if (mod[1] == 'l') { /* :tl */
3022 st->newVal = FStr_InitOwn(str_tolower(val));
3023 *pp = mod + 2;
3024 return AMR_OK;
3025 }
3026
3027 if (mod[1] == 'W' || mod[1] == 'w') { /* :tW, :tw */
3028 st->oneBigWord = mod[1] == 'W';
3029 st->newVal = FStr_InitRefer(val);
3030 *pp = mod + 2;
3031 return AMR_OK;
3032 }
3033
3034 /* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
3035 *pp = mod + 1;
3036 return AMR_BAD;
3037 }
3038
3039 /* :[#], :[1], :[-1..1], etc. */
3040 static ApplyModifierResult
3041 ApplyModifier_Words(const char **pp, const char *val, ApplyModifiersState *st)
3042 {
3043 char *estr;
3044 int first, last;
3045 VarParseResult res;
3046 const char *p;
3047
3048 (*pp)++; /* skip the '[' */
3049 res = ParseModifierPart(pp, ']', st->eflags, st, &estr);
3050 if (res != VPR_OK)
3051 return AMR_CLEANUP;
3052
3053 /* now *pp points just after the closing ']' */
3054 if (**pp != ':' && **pp != st->endc)
3055 goto bad_modifier; /* Found junk after ']' */
3056
3057 if (estr[0] == '\0')
3058 goto bad_modifier; /* empty square brackets in ":[]". */
3059
3060 if (estr[0] == '#' && estr[1] == '\0') { /* Found ":[#]" */
3061 if (st->oneBigWord) {
3062 st->newVal = FStr_InitRefer("1");
3063 } else {
3064 Buffer buf;
3065
3066 Words words = Str_Words(val, FALSE);
3067 size_t ac = words.len;
3068 Words_Free(words);
3069
3070 /* 3 digits + '\0' is usually enough */
3071 Buf_InitSize(&buf, 4);
3072 Buf_AddInt(&buf, (int)ac);
3073 st->newVal = FStr_InitOwn(Buf_DoneData(&buf));
3074 }
3075 goto ok;
3076 }
3077
3078 if (estr[0] == '*' && estr[1] == '\0') {
3079 /* Found ":[*]" */
3080 st->oneBigWord = TRUE;
3081 st->newVal = FStr_InitRefer(val);
3082 goto ok;
3083 }
3084
3085 if (estr[0] == '@' && estr[1] == '\0') {
3086 /* Found ":[@]" */
3087 st->oneBigWord = FALSE;
3088 st->newVal = FStr_InitRefer(val);
3089 goto ok;
3090 }
3091
3092 /*
3093 * We expect estr to contain a single integer for :[N], or two
3094 * integers separated by ".." for :[start..end].
3095 */
3096 p = estr;
3097 if (!TryParseIntBase0(&p, &first))
3098 goto bad_modifier; /* Found junk instead of a number */
3099
3100 if (p[0] == '\0') { /* Found only one integer in :[N] */
3101 last = first;
3102 } else if (p[0] == '.' && p[1] == '.' && p[2] != '\0') {
3103 /* Expecting another integer after ".." */
3104 p += 2;
3105 if (!TryParseIntBase0(&p, &last) || *p != '\0')
3106 goto bad_modifier; /* Found junk after ".." */
3107 } else
3108 goto bad_modifier; /* Found junk instead of ".." */
3109
3110 /*
3111 * Now first and last are properly filled in, but we still have to
3112 * check for 0 as a special case.
3113 */
3114 if (first == 0 && last == 0) {
3115 /* ":[0]" or perhaps ":[0..0]" */
3116 st->oneBigWord = TRUE;
3117 st->newVal = FStr_InitRefer(val);
3118 goto ok;
3119 }
3120
3121 /* ":[0..N]" or ":[N..0]" */
3122 if (first == 0 || last == 0)
3123 goto bad_modifier;
3124
3125 /* Normal case: select the words described by first and last. */
3126 st->newVal = FStr_InitOwn(
3127 VarSelectWords(st->sep, st->oneBigWord, val, first, last));
3128
3129 ok:
3130 free(estr);
3131 return AMR_OK;
3132
3133 bad_modifier:
3134 free(estr);
3135 return AMR_BAD;
3136 }
3137
3138 static int
3139 str_cmp_asc(const void *a, const void *b)
3140 {
3141 return strcmp(*(const char *const *)a, *(const char *const *)b);
3142 }
3143
3144 static int
3145 str_cmp_desc(const void *a, const void *b)
3146 {
3147 return strcmp(*(const char *const *)b, *(const char *const *)a);
3148 }
3149
3150 static void
3151 ShuffleStrings(char **strs, size_t n)
3152 {
3153 size_t i;
3154
3155 for (i = n - 1; i > 0; i--) {
3156 size_t rndidx = (size_t)random() % (i + 1);
3157 char *t = strs[i];
3158 strs[i] = strs[rndidx];
3159 strs[rndidx] = t;
3160 }
3161 }
3162
3163 /* :O (order ascending) or :Or (order descending) or :Ox (shuffle) */
3164 static ApplyModifierResult
3165 ApplyModifier_Order(const char **pp, const char *val, ApplyModifiersState *st)
3166 {
3167 const char *mod = (*pp)++; /* skip past the 'O' in any case */
3168
3169 Words words = Str_Words(val, FALSE);
3170
3171 if (mod[1] == st->endc || mod[1] == ':') {
3172 /* :O sorts ascending */
3173 qsort(words.words, words.len, sizeof words.words[0],
3174 str_cmp_asc);
3175
3176 } else if ((mod[1] == 'r' || mod[1] == 'x') &&
3177 (mod[2] == st->endc || mod[2] == ':')) {
3178 (*pp)++;
3179
3180 if (mod[1] == 'r') { /* :Or sorts descending */
3181 qsort(words.words, words.len, sizeof words.words[0],
3182 str_cmp_desc);
3183 } else
3184 ShuffleStrings(words.words, words.len);
3185 } else {
3186 Words_Free(words);
3187 return AMR_BAD;
3188 }
3189
3190 st->newVal = FStr_InitOwn(Words_JoinFree(words));
3191 return AMR_OK;
3192 }
3193
3194 /* :? then : else */
3195 static ApplyModifierResult
3196 ApplyModifier_IfElse(const char **pp, ApplyModifiersState *st)
3197 {
3198 char *then_expr, *else_expr;
3199 VarParseResult res;
3200
3201 Boolean value = FALSE;
3202 VarEvalFlags then_eflags = VARE_NONE;
3203 VarEvalFlags else_eflags = VARE_NONE;
3204
3205 int cond_rc = COND_PARSE; /* anything other than COND_INVALID */
3206 if (st->eflags & VARE_WANTRES) {
3207 cond_rc = Cond_EvalCondition(st->var->name.str, &value);
3208 if (cond_rc != COND_INVALID && value)
3209 then_eflags = st->eflags;
3210 if (cond_rc != COND_INVALID && !value)
3211 else_eflags = st->eflags;
3212 }
3213
3214 (*pp)++; /* skip past the '?' */
3215 res = ParseModifierPart(pp, ':', then_eflags, st, &then_expr);
3216 if (res != VPR_OK)
3217 return AMR_CLEANUP;
3218
3219 res = ParseModifierPart(pp, st->endc, else_eflags, st, &else_expr);
3220 if (res != VPR_OK)
3221 return AMR_CLEANUP;
3222
3223 (*pp)--;
3224 if (cond_rc == COND_INVALID) {
3225 Error("Bad conditional expression `%s' in %s?%s:%s",
3226 st->var->name.str, st->var->name.str, then_expr, else_expr);
3227 return AMR_CLEANUP;
3228 }
3229
3230 if (value) {
3231 st->newVal = FStr_InitOwn(then_expr);
3232 free(else_expr);
3233 } else {
3234 st->newVal = FStr_InitOwn(else_expr);
3235 free(then_expr);
3236 }
3237 ApplyModifiersState_Define(st);
3238 return AMR_OK;
3239 }
3240
3241 /*
3242 * The ::= modifiers actually assign a value to the variable.
3243 * Their main purpose is in supporting modifiers of .for loop
3244 * iterators and other obscure uses. They always expand to
3245 * nothing. In a target rule that would otherwise expand to an
3246 * empty line they can be preceded with @: to keep make happy.
3247 * Eg.
3248 *
3249 * foo: .USE
3250 * .for i in ${.TARGET} ${.TARGET:R}.gz
3251 * @: ${t::=$i}
3252 * @echo blah ${t:T}
3253 * .endfor
3254 *
3255 * ::=<str> Assigns <str> as the new value of variable.
3256 * ::?=<str> Assigns <str> as value of variable if
3257 * it was not already set.
3258 * ::+=<str> Appends <str> to variable.
3259 * ::!=<cmd> Assigns output of <cmd> as the new value of
3260 * variable.
3261 */
3262 static ApplyModifierResult
3263 ApplyModifier_Assign(const char **pp, ApplyModifiersState *st)
3264 {
3265 GNode *scope;
3266 char delim;
3267 char *val;
3268 VarParseResult res;
3269
3270 const char *mod = *pp;
3271 const char *op = mod + 1;
3272
3273 if (op[0] == '=')
3274 goto ok;
3275 if ((op[0] == '!' || op[0] == '+' || op[0] == '?') && op[1] == '=')
3276 goto ok;
3277 return AMR_UNKNOWN; /* "::<unrecognised>" */
3278 ok:
3279
3280 if (st->var->name.str[0] == '\0') {
3281 *pp = mod + 1;
3282 return AMR_BAD;
3283 }
3284
3285 scope = st->scope; /* scope where v belongs */
3286 if (st->exprStatus == VES_NONE && st->scope != SCOPE_GLOBAL) {
3287 Var *gv = VarFind(st->var->name.str, st->scope, FALSE);
3288 if (gv == NULL)
3289 scope = SCOPE_GLOBAL;
3290 else
3291 VarFreeEnv(gv, TRUE);
3292 }
3293
3294 switch (op[0]) {
3295 case '+':
3296 case '?':
3297 case '!':
3298 *pp = mod + 3;
3299 break;
3300 default:
3301 *pp = mod + 2;
3302 break;
3303 }
3304
3305 delim = st->startc == '(' ? ')' : '}';
3306 res = ParseModifierPart(pp, delim, st->eflags, st, &val);
3307 if (res != VPR_OK)
3308 return AMR_CLEANUP;
3309
3310 (*pp)--;
3311
3312 /* XXX: Expanding the variable name at this point sounds wrong. */
3313 if (st->eflags & VARE_WANTRES) {
3314 switch (op[0]) {
3315 case '+':
3316 Var_AppendExpand(scope, st->var->name.str, val);
3317 break;
3318 case '!': {
3319 const char *errfmt;
3320 char *cmd_output = Cmd_Exec(val, &errfmt);
3321 if (errfmt != NULL)
3322 Error(errfmt, val);
3323 else
3324 Var_SetExpand(scope,
3325 st->var->name.str, cmd_output);
3326 free(cmd_output);
3327 break;
3328 }
3329 case '?':
3330 if (st->exprStatus == VES_NONE)
3331 break;
3332 /* FALLTHROUGH */
3333 default:
3334 Var_SetExpand(scope, st->var->name.str, val);
3335 break;
3336 }
3337 }
3338 free(val);
3339 st->newVal = FStr_InitRefer("");
3340 return AMR_OK;
3341 }
3342
3343 /*
3344 * :_=...
3345 * remember current value
3346 */
3347 static ApplyModifierResult
3348 ApplyModifier_Remember(const char **pp, const char *val,
3349 ApplyModifiersState *st)
3350 {
3351 const char *mod = *pp;
3352 if (!ModMatchEq(mod, "_", st->endc))
3353 return AMR_UNKNOWN;
3354
3355 if (mod[1] == '=') {
3356 size_t n = strcspn(mod + 2, ":)}");
3357 char *name = bmake_strldup(mod + 2, n);
3358 Var_SetExpand(st->scope, name, val);
3359 free(name);
3360 *pp = mod + 2 + n;
3361 } else {
3362 Var_Set(st->scope, "_", val);
3363 *pp = mod + 1;
3364 }
3365 st->newVal = FStr_InitRefer(val);
3366 return AMR_OK;
3367 }
3368
3369 /*
3370 * Apply the given function to each word of the variable value,
3371 * for a single-letter modifier such as :H, :T.
3372 */
3373 static ApplyModifierResult
3374 ApplyModifier_WordFunc(const char **pp, const char *val,
3375 ApplyModifiersState *st, ModifyWordsCallback modifyWord)
3376 {
3377 char delim = (*pp)[1];
3378 if (delim != st->endc && delim != ':')
3379 return AMR_UNKNOWN;
3380
3381 st->newVal = FStr_InitOwn(ModifyWords(val, modifyWord, NULL,
3382 st->oneBigWord, st->sep));
3383 (*pp)++;
3384 return AMR_OK;
3385 }
3386
3387 static ApplyModifierResult
3388 ApplyModifier_Unique(const char **pp, const char *val, ApplyModifiersState *st)
3389 {
3390 if ((*pp)[1] == st->endc || (*pp)[1] == ':') {
3391 st->newVal = FStr_InitOwn(VarUniq(val));
3392 (*pp)++;
3393 return AMR_OK;
3394 } else
3395 return AMR_UNKNOWN;
3396 }
3397
3398 #ifdef SYSVVARSUB
3399 /* :from=to */
3400 static ApplyModifierResult
3401 ApplyModifier_SysV(const char **pp, const char *val, ApplyModifiersState *st)
3402 {
3403 char *lhs, *rhs;
3404 VarParseResult res;
3405
3406 const char *mod = *pp;
3407 Boolean eqFound = FALSE;
3408
3409 /*
3410 * First we make a pass through the string trying to verify it is a
3411 * SysV-make-style translation. It must be: <lhs>=<rhs>
3412 */
3413 int depth = 1;
3414 const char *p = mod;
3415 while (*p != '\0' && depth > 0) {
3416 if (*p == '=') { /* XXX: should also test depth == 1 */
3417 eqFound = TRUE;
3418 /* continue looking for st->endc */
3419 } else if (*p == st->endc)
3420 depth--;
3421 else if (*p == st->startc)
3422 depth++;
3423 if (depth > 0)
3424 p++;
3425 }
3426 if (*p != st->endc || !eqFound)
3427 return AMR_UNKNOWN;
3428
3429 res = ParseModifierPart(pp, '=', st->eflags, st, &lhs);
3430 if (res != VPR_OK)
3431 return AMR_CLEANUP;
3432
3433 /* The SysV modifier lasts until the end of the variable expression. */
3434 res = ParseModifierPart(pp, st->endc, st->eflags, st, &rhs);
3435 if (res != VPR_OK)
3436 return AMR_CLEANUP;
3437
3438 (*pp)--;
3439 if (lhs[0] == '\0' && val[0] == '\0') {
3440 st->newVal = FStr_InitRefer(val); /* special case */
3441 } else {
3442 struct ModifyWord_SYSVSubstArgs args = { st->scope, lhs, rhs };
3443 st->newVal = FStr_InitOwn(
3444 ModifyWords(val, ModifyWord_SYSVSubst, &args,
3445 st->oneBigWord, st->sep));
3446 }
3447 free(lhs);
3448 free(rhs);
3449 return AMR_OK;
3450 }
3451 #endif
3452
3453 #ifdef SUNSHCMD
3454 /* :sh */
3455 static ApplyModifierResult
3456 ApplyModifier_SunShell(const char **pp, const char *val,
3457 ApplyModifiersState *st)
3458 {
3459 const char *p = *pp;
3460 if (p[1] == 'h' && (p[2] == st->endc || p[2] == ':')) {
3461 if (st->eflags & VARE_WANTRES) {
3462 const char *errfmt;
3463 st->newVal = FStr_InitOwn(Cmd_Exec(val, &errfmt));
3464 if (errfmt != NULL)
3465 Error(errfmt, val);
3466 } else
3467 st->newVal = FStr_InitRefer("");
3468 *pp = p + 2;
3469 return AMR_OK;
3470 } else
3471 return AMR_UNKNOWN;
3472 }
3473 #endif
3474
3475 static void
3476 LogBeforeApply(const ApplyModifiersState *st, const char *mod, char endc,
3477 const char *val)
3478 {
3479 char eflags_str[VarEvalFlags_ToStringSize];
3480 char vflags_str[VarFlags_ToStringSize];
3481 Boolean is_single_char = mod[0] != '\0' &&
3482 (mod[1] == endc || mod[1] == ':');
3483
3484 /* At this point, only the first character of the modifier can
3485 * be used since the end of the modifier is not yet known. */
3486 debug_printf("Applying ${%s:%c%s} to \"%s\" (%s, %s, %s)\n",
3487 st->var->name.str, mod[0], is_single_char ? "" : "...", val,
3488 VarEvalFlags_ToString(eflags_str, st->eflags),
3489 VarFlags_ToString(vflags_str, st->var->flags),
3490 VarExprStatus_Name[st->exprStatus]);
3491 }
3492
3493 static void
3494 LogAfterApply(ApplyModifiersState *st, const char *p, const char *mod)
3495 {
3496 char eflags_str[VarEvalFlags_ToStringSize];
3497 char vflags_str[VarFlags_ToStringSize];
3498 const char *quot = st->newVal.str == var_Error ? "" : "\"";
3499 const char *newVal =
3500 st->newVal.str == var_Error ? "error" : st->newVal.str;
3501
3502 debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s, %s)\n",
3503 st->var->name.str, (int)(p - mod), mod, quot, newVal, quot,
3504 VarEvalFlags_ToString(eflags_str, st->eflags),
3505 VarFlags_ToString(vflags_str, st->var->flags),
3506 VarExprStatus_Name[st->exprStatus]);
3507 }
3508
3509 static ApplyModifierResult
3510 ApplyModifier(const char **pp, const char *val, ApplyModifiersState *st)
3511 {
3512 switch (**pp) {
3513 case ':':
3514 return ApplyModifier_Assign(pp, st);
3515 case '@':
3516 return ApplyModifier_Loop(pp, val, st);
3517 case '_':
3518 return ApplyModifier_Remember(pp, val, st);
3519 case 'D':
3520 case 'U':
3521 return ApplyModifier_Defined(pp, val, st);
3522 case 'L':
3523 return ApplyModifier_Literal(pp, st);
3524 case 'P':
3525 return ApplyModifier_Path(pp, st);
3526 case '!':
3527 return ApplyModifier_ShellCommand(pp, st);
3528 case '[':
3529 return ApplyModifier_Words(pp, val, st);
3530 case 'g':
3531 return ApplyModifier_Gmtime(pp, val, st);
3532 case 'h':
3533 return ApplyModifier_Hash(pp, val, st);
3534 case 'l':
3535 return ApplyModifier_Localtime(pp, val, st);
3536 case 't':
3537 return ApplyModifier_To(pp, val, st);
3538 case 'N':
3539 case 'M':
3540 return ApplyModifier_Match(pp, val, st);
3541 case 'S':
3542 return ApplyModifier_Subst(pp, val, st);
3543 case '?':
3544 return ApplyModifier_IfElse(pp, st);
3545 #ifndef NO_REGEX
3546 case 'C':
3547 return ApplyModifier_Regex(pp, val, st);
3548 #endif
3549 case 'q':
3550 case 'Q':
3551 return ApplyModifier_Quote(pp, val, st);
3552 case 'T':
3553 return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Tail);
3554 case 'H':
3555 return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Head);
3556 case 'E':
3557 return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Suffix);
3558 case 'R':
3559 return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Root);
3560 case 'r':
3561 return ApplyModifier_Range(pp, val, st);
3562 case 'O':
3563 return ApplyModifier_Order(pp, val, st);
3564 case 'u':
3565 return ApplyModifier_Unique(pp, val, st);
3566 #ifdef SUNSHCMD
3567 case 's':
3568 return ApplyModifier_SunShell(pp, val, st);
3569 #endif
3570 default:
3571 return AMR_UNKNOWN;
3572 }
3573 }
3574
3575 static FStr ApplyModifiers(const char **, FStr, char, char, Var *,
3576 VarExprStatus *, GNode *, VarEvalFlags);
3577
3578 typedef enum ApplyModifiersIndirectResult {
3579 /* The indirect modifiers have been applied successfully. */
3580 AMIR_CONTINUE,
3581 /* Fall back to the SysV modifier. */
3582 AMIR_APPLY_MODS,
3583 /* Error out. */
3584 AMIR_OUT
3585 } ApplyModifiersIndirectResult;
3586
3587 /*
3588 * While expanding a variable expression, expand and apply indirect modifiers,
3589 * such as in ${VAR:${M_indirect}}.
3590 *
3591 * All indirect modifiers of a group must come from a single variable
3592 * expression. ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
3593 *
3594 * Multiple groups of indirect modifiers can be chained by separating them
3595 * with colons. ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
3596 *
3597 * If the variable expression is not followed by st->endc or ':', fall
3598 * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
3599 *
3600 * The expression ${VAR:${M1}${M2}} is not treated as an indirect
3601 * modifier, and it is neither a SysV modifier but a parse error.
3602 */
3603 static ApplyModifiersIndirectResult
3604 ApplyModifiersIndirect(ApplyModifiersState *st, const char **pp,
3605 FStr *inout_value)
3606 {
3607 const char *p = *pp;
3608 FStr mods;
3609
3610 (void)Var_Parse(&p, st->scope, st->eflags, &mods);
3611 /* TODO: handle errors */
3612
3613 if (mods.str[0] != '\0' && *p != '\0' && *p != ':' && *p != st->endc) {
3614 FStr_Done(&mods);
3615 return AMIR_APPLY_MODS;
3616 }
3617
3618 DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
3619 mods.str, (int)(p - *pp), *pp);
3620
3621 if (mods.str[0] != '\0') {
3622 const char *modsp = mods.str;
3623 FStr newVal = ApplyModifiers(&modsp, *inout_value, '\0', '\0',
3624 st->var, &st->exprStatus, st->scope, st->eflags);
3625 *inout_value = newVal;
3626 if (newVal.str == var_Error || *modsp != '\0') {
3627 FStr_Done(&mods);
3628 *pp = p;
3629 return AMIR_OUT; /* error already reported */
3630 }
3631 }
3632 FStr_Done(&mods);
3633
3634 if (*p == ':')
3635 p++;
3636 else if (*p == '\0' && st->endc != '\0') {
3637 Error("Unclosed variable specification after complex "
3638 "modifier (expecting '%c') for %s",
3639 st->endc, st->var->name.str);
3640 *pp = p;
3641 return AMIR_OUT;
3642 }
3643
3644 *pp = p;
3645 return AMIR_CONTINUE;
3646 }
3647
3648 static ApplyModifierResult
3649 ApplySingleModifier(ApplyModifiersState *st, const char *mod, char endc,
3650 const char **pp, FStr *inout_value)
3651 {
3652 ApplyModifierResult res;
3653 const char *p = *pp;
3654 const char *const val = inout_value->str;
3655
3656 if (DEBUG(VAR))
3657 LogBeforeApply(st, mod, endc, val);
3658
3659 res = ApplyModifier(&p, val, st);
3660
3661 #ifdef SYSVVARSUB
3662 if (res == AMR_UNKNOWN) {
3663 assert(p == mod);
3664 res = ApplyModifier_SysV(&p, val, st);
3665 }
3666 #endif
3667
3668 if (res == AMR_UNKNOWN) {
3669 Parse_Error(PARSE_FATAL, "Unknown modifier '%c'", *mod);
3670 /*
3671 * Guess the end of the current modifier.
3672 * XXX: Skipping the rest of the modifier hides
3673 * errors and leads to wrong results.
3674 * Parsing should rather stop here.
3675 */
3676 for (p++; *p != ':' && *p != st->endc && *p != '\0'; p++)
3677 continue;
3678 st->newVal = FStr_InitRefer(var_Error);
3679 }
3680 if (res == AMR_CLEANUP || res == AMR_BAD) {
3681 *pp = p;
3682 return res;
3683 }
3684
3685 if (DEBUG(VAR))
3686 LogAfterApply(st, p, mod);
3687
3688 if (st->newVal.str != val) {
3689 FStr_Done(inout_value);
3690 *inout_value = st->newVal;
3691 }
3692 if (*p == '\0' && st->endc != '\0') {
3693 Error(
3694 "Unclosed variable specification (expecting '%c') "
3695 "for \"%s\" (value \"%s\") modifier %c",
3696 st->endc, st->var->name.str, inout_value->str, *mod);
3697 } else if (*p == ':') {
3698 p++;
3699 } else if (opts.strict && *p != '\0' && *p != endc) {
3700 Parse_Error(PARSE_FATAL,
3701 "Missing delimiter ':' after modifier \"%.*s\"",
3702 (int)(p - mod), mod);
3703 /*
3704 * TODO: propagate parse error to the enclosing
3705 * expression
3706 */
3707 }
3708 *pp = p;
3709 return AMR_OK;
3710 }
3711
3712 /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
3713 static FStr
3714 ApplyModifiers(
3715 const char **pp, /* the parsing position, updated upon return */
3716 FStr value, /* the current value of the expression */
3717 char startc, /* '(' or '{', or '\0' for indirect modifiers */
3718 char endc, /* ')' or '}', or '\0' for indirect modifiers */
3719 Var *v,
3720 VarExprStatus *exprStatus,
3721 GNode *scope, /* for looking up and modifying variables */
3722 VarEvalFlags eflags
3723 )
3724 {
3725 ApplyModifiersState st = {
3726 startc, endc, v, scope, eflags,
3727 #if defined(lint)
3728 /* lint cannot parse C99 struct initializers yet. */
3729 { var_Error, NULL },
3730 #else
3731 FStr_InitRefer(var_Error), /* .newVal */
3732 #endif
3733 ' ', /* .sep */
3734 FALSE, /* .oneBigWord */
3735 *exprStatus /* .exprStatus */
3736 };
3737 const char *p;
3738 const char *mod;
3739
3740 assert(startc == '(' || startc == '{' || startc == '\0');
3741 assert(endc == ')' || endc == '}' || endc == '\0');
3742 assert(value.str != NULL);
3743
3744 p = *pp;
3745
3746 if (*p == '\0' && endc != '\0') {
3747 Error(
3748 "Unclosed variable expression (expecting '%c') for \"%s\"",
3749 st.endc, st.var->name.str);
3750 goto cleanup;
3751 }
3752
3753 while (*p != '\0' && *p != endc) {
3754 ApplyModifierResult res;
3755
3756 if (*p == '$') {
3757 ApplyModifiersIndirectResult amir;
3758 amir = ApplyModifiersIndirect(&st, &p, &value);
3759 if (amir == AMIR_CONTINUE)
3760 continue;
3761 if (amir == AMIR_OUT)
3762 break;
3763 }
3764
3765 /* default value, in case of errors */
3766 st.newVal = FStr_InitRefer(var_Error);
3767 mod = p;
3768
3769 res = ApplySingleModifier(&st, mod, endc, &p, &value);
3770 if (res == AMR_CLEANUP)
3771 goto cleanup;
3772 if (res == AMR_BAD)
3773 goto bad_modifier;
3774 }
3775
3776 *pp = p;
3777 assert(value.str != NULL); /* Use var_Error or varUndefined instead. */
3778 *exprStatus = st.exprStatus;
3779 return value;
3780
3781 bad_modifier:
3782 /* XXX: The modifier end is only guessed. */
3783 Error("Bad modifier `:%.*s' for %s",
3784 (int)strcspn(mod, ":)}"), mod, st.var->name.str);
3785
3786 cleanup:
3787 *pp = p;
3788 FStr_Done(&value);
3789 *exprStatus = st.exprStatus;
3790 return FStr_InitRefer(var_Error);
3791 }
3792
3793 /*
3794 * Only four of the local variables are treated specially as they are the
3795 * only four that will be set when dynamic sources are expanded.
3796 */
3797 static Boolean
3798 VarnameIsDynamic(const char *name, size_t len)
3799 {
3800 if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
3801 switch (name[0]) {
3802 case '@':
3803 case '%':
3804 case '*':
3805 case '!':
3806 return TRUE;
3807 }
3808 return FALSE;
3809 }
3810
3811 if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
3812 return strcmp(name, ".TARGET") == 0 ||
3813 strcmp(name, ".ARCHIVE") == 0 ||
3814 strcmp(name, ".PREFIX") == 0 ||
3815 strcmp(name, ".MEMBER") == 0;
3816 }
3817
3818 return FALSE;
3819 }
3820
3821 static const char *
3822 UndefinedShortVarValue(char varname, const GNode *scope)
3823 {
3824 if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
3825 /*
3826 * If substituting a local variable in a non-local scope,
3827 * assume it's for dynamic source stuff. We have to handle
3828 * this specially and return the longhand for the variable
3829 * with the dollar sign escaped so it makes it back to the
3830 * caller. Only four of the local variables are treated
3831 * specially as they are the only four that will be set
3832 * when dynamic sources are expanded.
3833 */
3834 switch (varname) {
3835 case '@':
3836 return "$(.TARGET)";
3837 case '%':
3838 return "$(.MEMBER)";
3839 case '*':
3840 return "$(.PREFIX)";
3841 case '!':
3842 return "$(.ARCHIVE)";
3843 }
3844 }
3845 return NULL;
3846 }
3847
3848 /*
3849 * Parse a variable name, until the end character or a colon, whichever
3850 * comes first.
3851 */
3852 static char *
3853 ParseVarname(const char **pp, char startc, char endc,
3854 GNode *scope, VarEvalFlags eflags,
3855 size_t *out_varname_len)
3856 {
3857 Buffer buf;
3858 const char *p = *pp;
3859 int depth = 1;
3860
3861 Buf_Init(&buf);
3862
3863 while (*p != '\0') {
3864 /* Track depth so we can spot parse errors. */
3865 if (*p == startc)
3866 depth++;
3867 if (*p == endc) {
3868 if (--depth == 0)
3869 break;
3870 }
3871 if (*p == ':' && depth == 1)
3872 break;
3873
3874 /* A variable inside a variable, expand. */
3875 if (*p == '$') {
3876 FStr nested_val;
3877 (void)Var_Parse(&p, scope, eflags, &nested_val);
3878 /* TODO: handle errors */
3879 Buf_AddStr(&buf, nested_val.str);
3880 FStr_Done(&nested_val);
3881 } else {
3882 Buf_AddByte(&buf, *p);
3883 p++;
3884 }
3885 }
3886 *pp = p;
3887 *out_varname_len = buf.len;
3888 return Buf_DoneData(&buf);
3889 }
3890
3891 static VarParseResult
3892 ValidShortVarname(char varname, const char *start)
3893 {
3894 switch (varname) {
3895 case '\0':
3896 case ')':
3897 case '}':
3898 case ':':
3899 case '$':
3900 break; /* and continue below */
3901 default:
3902 return VPR_OK;
3903 }
3904
3905 if (!opts.strict)
3906 return VPR_ERR; /* XXX: Missing error message */
3907
3908 if (varname == '$')
3909 Parse_Error(PARSE_FATAL,
3910 "To escape a dollar, use \\$, not $$, at \"%s\"", start);
3911 else if (varname == '\0')
3912 Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
3913 else
3914 Parse_Error(PARSE_FATAL,
3915 "Invalid variable name '%c', at \"%s\"", varname, start);
3916
3917 return VPR_ERR;
3918 }
3919
3920 /*
3921 * Parse a single-character variable name such as $V or $@.
3922 * Return whether to continue parsing.
3923 */
3924 static Boolean
3925 ParseVarnameShort(char startc, const char **pp, GNode *scope,
3926 VarEvalFlags eflags,
3927 VarParseResult *out_FALSE_res, const char **out_FALSE_val,
3928 Var **out_TRUE_var)
3929 {
3930 char name[2];
3931 Var *v;
3932 VarParseResult vpr;
3933
3934 /*
3935 * If it's not bounded by braces of some sort, life is much simpler.
3936 * We just need to check for the first character and return the
3937 * value if it exists.
3938 */
3939
3940 vpr = ValidShortVarname(startc, *pp);
3941 if (vpr != VPR_OK) {
3942 (*pp)++;
3943 *out_FALSE_val = var_Error;
3944 *out_FALSE_res = vpr;
3945 return FALSE;
3946 }
3947
3948 name[0] = startc;
3949 name[1] = '\0';
3950 v = VarFind(name, scope, TRUE);
3951 if (v == NULL) {
3952 const char *val;
3953 *pp += 2;
3954
3955 val = UndefinedShortVarValue(startc, scope);
3956 if (val == NULL)
3957 val = eflags & VARE_UNDEFERR ? var_Error : varUndefined;
3958
3959 if (opts.strict && val == var_Error) {
3960 Parse_Error(PARSE_FATAL,
3961 "Variable \"%s\" is undefined", name);
3962 *out_FALSE_res = VPR_ERR;
3963 *out_FALSE_val = val;
3964 return FALSE;
3965 }
3966
3967 /*
3968 * XXX: This looks completely wrong.
3969 *
3970 * If undefined expressions are not allowed, this should
3971 * rather be VPR_ERR instead of VPR_UNDEF, together with an
3972 * error message.
3973 *
3974 * If undefined expressions are allowed, this should rather
3975 * be VPR_UNDEF instead of VPR_OK.
3976 */
3977 *out_FALSE_res = eflags & VARE_UNDEFERR ? VPR_UNDEF : VPR_OK;
3978 *out_FALSE_val = val;
3979 return FALSE;
3980 }
3981
3982 *out_TRUE_var = v;
3983 return TRUE;
3984 }
3985
3986 /* Find variables like @F or <D. */
3987 static Var *
3988 FindLocalLegacyVar(const char *varname, size_t namelen, GNode *scope,
3989 const char **out_extraModifiers)
3990 {
3991 /* Only resolve these variables if scope is a "real" target. */
3992 if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
3993 return NULL;
3994
3995 if (namelen != 2)
3996 return NULL;
3997 if (varname[1] != 'F' && varname[1] != 'D')
3998 return NULL;
3999 if (strchr("@%?*!<>", varname[0]) == NULL)
4000 return NULL;
4001
4002 {
4003 char name[] = { varname[0], '\0' };
4004 Var *v = VarFind(name, scope, FALSE);
4005
4006 if (v != NULL) {
4007 if (varname[1] == 'D') {
4008 *out_extraModifiers = "H:";
4009 } else { /* F */
4010 *out_extraModifiers = "T:";
4011 }
4012 }
4013 return v;
4014 }
4015 }
4016
4017 static VarParseResult
4018 EvalUndefined(Boolean dynamic, const char *start, const char *p, char *varname,
4019 VarEvalFlags eflags,
4020 FStr *out_val)
4021 {
4022 if (dynamic) {
4023 *out_val = FStr_InitOwn(bmake_strsedup(start, p));
4024 free(varname);
4025 return VPR_OK;
4026 }
4027
4028 if ((eflags & VARE_UNDEFERR) && opts.strict) {
4029 Parse_Error(PARSE_FATAL,
4030 "Variable \"%s\" is undefined", varname);
4031 free(varname);
4032 *out_val = FStr_InitRefer(var_Error);
4033 return VPR_ERR;
4034 }
4035
4036 if (eflags & VARE_UNDEFERR) {
4037 free(varname);
4038 *out_val = FStr_InitRefer(var_Error);
4039 return VPR_UNDEF; /* XXX: Should be VPR_ERR instead. */
4040 }
4041
4042 free(varname);
4043 *out_val = FStr_InitRefer(varUndefined);
4044 return VPR_OK;
4045 }
4046
4047 /*
4048 * Parse a long variable name enclosed in braces or parentheses such as $(VAR)
4049 * or ${VAR}, up to the closing brace or parenthesis, or in the case of
4050 * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
4051 * Return whether to continue parsing.
4052 */
4053 static Boolean
4054 ParseVarnameLong(
4055 const char *p,
4056 char startc,
4057 GNode *scope,
4058 VarEvalFlags eflags,
4059
4060 const char **out_FALSE_pp,
4061 VarParseResult *out_FALSE_res,
4062 FStr *out_FALSE_val,
4063
4064 char *out_TRUE_endc,
4065 const char **out_TRUE_p,
4066 Var **out_TRUE_v,
4067 Boolean *out_TRUE_haveModifier,
4068 const char **out_TRUE_extraModifiers,
4069 Boolean *out_TRUE_dynamic,
4070 VarExprStatus *out_TRUE_exprStatus
4071 )
4072 {
4073 size_t namelen;
4074 char *varname;
4075 Var *v;
4076 Boolean haveModifier;
4077 Boolean dynamic = FALSE;
4078
4079 const char *const start = p;
4080 char endc = startc == '(' ? ')' : '}';
4081
4082 p += 2; /* skip "${" or "$(" or "y(" */
4083 varname = ParseVarname(&p, startc, endc, scope, eflags, &namelen);
4084
4085 if (*p == ':') {
4086 haveModifier = TRUE;
4087 } else if (*p == endc) {
4088 haveModifier = FALSE;
4089 } else {
4090 Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"", varname);
4091 free(varname);
4092 *out_FALSE_pp = p;
4093 *out_FALSE_val = FStr_InitRefer(var_Error);
4094 *out_FALSE_res = VPR_ERR;
4095 return FALSE;
4096 }
4097
4098 v = VarFind(varname, scope, TRUE);
4099
4100 /* At this point, p points just after the variable name,
4101 * either at ':' or at endc. */
4102
4103 if (v == NULL) {
4104 v = FindLocalLegacyVar(varname, namelen, scope,
4105 out_TRUE_extraModifiers);
4106 }
4107
4108 if (v == NULL) {
4109 /*
4110 * Defer expansion of dynamic variables if they appear in
4111 * non-local scope since they are not defined there.
4112 */
4113 dynamic = VarnameIsDynamic(varname, namelen) &&
4114 (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
4115
4116 if (!haveModifier) {
4117 p++; /* skip endc */
4118 *out_FALSE_pp = p;
4119 *out_FALSE_res = EvalUndefined(dynamic, start, p,
4120 varname, eflags, out_FALSE_val);
4121 return FALSE;
4122 }
4123
4124 /*
4125 * The variable expression is based on an undefined variable.
4126 * Nevertheless it needs a Var, for modifiers that access the
4127 * variable name, such as :L or :?.
4128 *
4129 * Most modifiers leave this expression in the "undefined"
4130 * state (VEF_UNDEF), only a few modifiers like :D, :U, :L,
4131 * :P turn this undefined expression into a defined
4132 * expression (VEF_DEF).
4133 *
4134 * At the end, after applying all modifiers, if the expression
4135 * is still undefined, Var_Parse will return an empty string
4136 * instead of the actually computed value.
4137 */
4138 v = VarNew(FStr_InitOwn(varname), "", VAR_NONE);
4139 *out_TRUE_exprStatus = VES_UNDEF;
4140 } else
4141 free(varname);
4142
4143 *out_TRUE_endc = endc;
4144 *out_TRUE_p = p;
4145 *out_TRUE_v = v;
4146 *out_TRUE_haveModifier = haveModifier;
4147 *out_TRUE_dynamic = dynamic;
4148 return TRUE;
4149 }
4150
4151 /* Free the environment variable now since we own it. */
4152 static void
4153 FreeEnvVar(void **out_val_freeIt, Var *v, const char *value)
4154 {
4155 char *varValue = Buf_DoneData(&v->val);
4156 if (value == varValue)
4157 *out_val_freeIt = varValue;
4158 else
4159 free(varValue);
4160
4161 FStr_Done(&v->name);
4162 free(v);
4163 }
4164
4165 /*
4166 * Given the start of a variable expression (such as $v, $(VAR),
4167 * ${VAR:Mpattern}), extract the variable name and value, and the modifiers,
4168 * if any. While doing that, apply the modifiers to the value of the
4169 * expression, forming its final value. A few of the modifiers such as :!cmd!
4170 * or ::= have side effects.
4171 *
4172 * Input:
4173 * *pp The string to parse.
4174 * When parsing a condition in ParseEmptyArg, it may also
4175 * point to the "y" of "empty(VARNAME:Modifiers)", which
4176 * is syntactically the same.
4177 * scope The scope for finding variables
4178 * eflags Control the exact details of parsing
4179 *
4180 * Output:
4181 * *pp The position where to continue parsing.
4182 * TODO: After a parse error, the value of *pp is
4183 * unspecified. It may not have been updated at all,
4184 * point to some random character in the string, to the
4185 * location of the parse error, or at the end of the
4186 * string.
4187 * *out_val The value of the variable expression, never NULL.
4188 * *out_val var_Error if there was a parse error.
4189 * *out_val var_Error if the base variable of the expression was
4190 * undefined, eflags contains VARE_UNDEFERR, and none of
4191 * the modifiers turned the undefined expression into a
4192 * defined expression.
4193 * XXX: It is not guaranteed that an error message has
4194 * been printed.
4195 * *out_val varUndefined if the base variable of the expression
4196 * was undefined, eflags did not contain VARE_UNDEFERR,
4197 * and none of the modifiers turned the undefined
4198 * expression into a defined expression.
4199 * XXX: It is not guaranteed that an error message has
4200 * been printed.
4201 * *out_val_freeIt Must be freed by the caller after using *out_val.
4202 */
4203 /* coverity[+alloc : arg-*4] */
4204 VarParseResult
4205 Var_Parse(const char **pp, GNode *scope, VarEvalFlags eflags, FStr *out_val)
4206 {
4207 const char *p = *pp;
4208 const char *const start = p;
4209 /* TRUE if have modifiers for the variable. */
4210 Boolean haveModifier;
4211 /* Starting character if variable in parens or braces. */
4212 char startc;
4213 /* Ending character if variable in parens or braces. */
4214 char endc;
4215 /*
4216 * TRUE if the variable is local and we're expanding it in a
4217 * non-local scope. This is done to support dynamic sources.
4218 * The result is just the expression, unaltered.
4219 */
4220 Boolean dynamic;
4221 const char *extramodifiers;
4222 Var *v;
4223 FStr value;
4224 char eflags_str[VarEvalFlags_ToStringSize];
4225 VarExprStatus exprStatus = VES_NONE;
4226
4227 DEBUG2(VAR, "Var_Parse: %s with %s\n", start,
4228 VarEvalFlags_ToString(eflags_str, eflags));
4229
4230 *out_val = FStr_InitRefer(NULL);
4231 extramodifiers = NULL; /* extra modifiers to apply first */
4232 dynamic = FALSE;
4233
4234 /*
4235 * Appease GCC, which thinks that the variable might not be
4236 * initialized.
4237 */
4238 endc = '\0';
4239
4240 startc = p[1];
4241 if (startc != '(' && startc != '{') {
4242 VarParseResult res;
4243 if (!ParseVarnameShort(startc, pp, scope, eflags, &res,
4244 &out_val->str, &v))
4245 return res;
4246 haveModifier = FALSE;
4247 p++;
4248 } else {
4249 VarParseResult res;
4250 if (!ParseVarnameLong(p, startc, scope, eflags,
4251 pp, &res, out_val,
4252 &endc, &p, &v, &haveModifier, &extramodifiers,
4253 &dynamic, &exprStatus))
4254 return res;
4255 }
4256
4257 if (v->flags & VAR_IN_USE)
4258 Fatal("Variable %s is recursive.", v->name.str);
4259
4260 /*
4261 * XXX: This assignment creates an alias to the current value of the
4262 * variable. This means that as long as the value of the expression
4263 * stays the same, the value of the variable must not change.
4264 * Using the '::=' modifier, it could be possible to do exactly this.
4265 * At the bottom of this function, the resulting value is compared to
4266 * the then-current value of the variable. This might also invoke
4267 * undefined behavior.
4268 */
4269 value = FStr_InitRefer(v->val.data);
4270
4271 /*
4272 * Before applying any modifiers, expand any nested expressions from
4273 * the variable value.
4274 */
4275 if (strchr(value.str, '$') != NULL && (eflags & VARE_WANTRES)) {
4276 char *expanded;
4277 VarEvalFlags nested_eflags = eflags;
4278 if (opts.strict)
4279 nested_eflags &= ~(unsigned)VARE_UNDEFERR;
4280 v->flags |= VAR_IN_USE;
4281 (void)Var_Subst(value.str, scope, nested_eflags, &expanded);
4282 v->flags &= ~(unsigned)VAR_IN_USE;
4283 /* TODO: handle errors */
4284 value = FStr_InitOwn(expanded);
4285 }
4286
4287 if (haveModifier || extramodifiers != NULL) {
4288 if (extramodifiers != NULL) {
4289 const char *em = extramodifiers;
4290 value = ApplyModifiers(&em, value, '\0', '\0',
4291 v, &exprStatus, scope, eflags);
4292 }
4293
4294 if (haveModifier) {
4295 p++; /* Skip initial colon. */
4296
4297 value = ApplyModifiers(&p, value, startc, endc,
4298 v, &exprStatus, scope, eflags);
4299 }
4300 }
4301
4302 if (*p != '\0') /* Skip past endc if possible. */
4303 p++;
4304
4305 *pp = p;
4306
4307 if (v->flags & VAR_FROM_ENV) {
4308 FreeEnvVar(&value.freeIt, v, value.str);
4309
4310 } else if (exprStatus != VES_NONE) {
4311 if (exprStatus != VES_DEF) {
4312 FStr_Done(&value);
4313 if (dynamic) {
4314 value = FStr_InitOwn(bmake_strsedup(start, p));
4315 } else {
4316 /*
4317 * The expression is still undefined,
4318 * therefore discard the actual value and
4319 * return an error marker instead.
4320 */
4321 value = FStr_InitRefer(eflags & VARE_UNDEFERR
4322 ? var_Error : varUndefined);
4323 }
4324 }
4325 if (value.str != v->val.data)
4326 Buf_Done(&v->val);
4327 FStr_Done(&v->name);
4328 free(v);
4329 }
4330 *out_val = (FStr){ value.str, value.freeIt };
4331 return VPR_OK; /* XXX: Is not correct in all cases */
4332 }
4333
4334 static void
4335 VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalFlags eflags)
4336 {
4337 /*
4338 * A dollar sign may be escaped with another dollar
4339 * sign.
4340 */
4341 if (save_dollars && (eflags & VARE_KEEP_DOLLAR))
4342 Buf_AddByte(res, '$');
4343 Buf_AddByte(res, '$');
4344 *pp += 2;
4345 }
4346
4347 static void
4348 VarSubstExpr(const char **pp, Buffer *buf, GNode *scope,
4349 VarEvalFlags eflags, Boolean *inout_errorReported)
4350 {
4351 const char *p = *pp;
4352 const char *nested_p = p;
4353 FStr val;
4354
4355 (void)Var_Parse(&nested_p, scope, eflags, &val);
4356 /* TODO: handle errors */
4357
4358 if (val.str == var_Error || val.str == varUndefined) {
4359 if (!(eflags & VARE_KEEP_UNDEF)) {
4360 p = nested_p;
4361 } else if ((eflags & VARE_UNDEFERR) || val.str == var_Error) {
4362
4363 /*
4364 * XXX: This condition is wrong. If val == var_Error,
4365 * this doesn't necessarily mean there was an undefined
4366 * variable. It could equally well be a parse error;
4367 * see unit-tests/varmod-order.exp.
4368 */
4369
4370 /*
4371 * If variable is undefined, complain and skip the
4372 * variable. The complaint will stop us from doing
4373 * anything when the file is parsed.
4374 */
4375 if (!*inout_errorReported) {
4376 Parse_Error(PARSE_FATAL,
4377 "Undefined variable \"%.*s\"",
4378 (int)(size_t)(nested_p - p), p);
4379 }
4380 p = nested_p;
4381 *inout_errorReported = TRUE;
4382 } else {
4383 /* Copy the initial '$' of the undefined expression,
4384 * thereby deferring expansion of the expression, but
4385 * expand nested expressions if already possible.
4386 * See unit-tests/varparse-undef-partial.mk. */
4387 Buf_AddByte(buf, *p);
4388 p++;
4389 }
4390 } else {
4391 p = nested_p;
4392 Buf_AddStr(buf, val.str);
4393 }
4394
4395 FStr_Done(&val);
4396
4397 *pp = p;
4398 }
4399
4400 /*
4401 * Skip as many characters as possible -- either to the end of the string
4402 * or to the next dollar sign (variable expression).
4403 */
4404 static void
4405 VarSubstPlain(const char **pp, Buffer *res)
4406 {
4407 const char *p = *pp;
4408 const char *start = p;
4409
4410 for (p++; *p != '$' && *p != '\0'; p++)
4411 continue;
4412 Buf_AddBytesBetween(res, start, p);
4413 *pp = p;
4414 }
4415
4416 /*
4417 * Expand all variable expressions like $V, ${VAR}, $(VAR:Modifiers) in the
4418 * given string.
4419 *
4420 * Input:
4421 * str The string in which the variable expressions are
4422 * expanded.
4423 * scope The scope in which to start searching for
4424 * variables. The other scopes are searched as well.
4425 * eflags Special effects during expansion.
4426 */
4427 VarParseResult
4428 Var_Subst(const char *str, GNode *scope, VarEvalFlags eflags, char **out_res)
4429 {
4430 const char *p = str;
4431 Buffer res;
4432
4433 /* Set true if an error has already been reported,
4434 * to prevent a plethora of messages when recursing */
4435 /* XXX: Why is the 'static' necessary here? */
4436 static Boolean errorReported;
4437
4438 Buf_Init(&res);
4439 errorReported = FALSE;
4440
4441 while (*p != '\0') {
4442 if (p[0] == '$' && p[1] == '$')
4443 VarSubstDollarDollar(&p, &res, eflags);
4444 else if (p[0] == '$')
4445 VarSubstExpr(&p, &res, scope, eflags, &errorReported);
4446 else
4447 VarSubstPlain(&p, &res);
4448 }
4449
4450 *out_res = Buf_DoneDataCompact(&res);
4451 return VPR_OK;
4452 }
4453
4454 /* Initialize the variables module. */
4455 void
4456 Var_Init(void)
4457 {
4458 SCOPE_INTERNAL = GNode_New("Internal");
4459 SCOPE_GLOBAL = GNode_New("Global");
4460 SCOPE_CMDLINE = GNode_New("Command");
4461 }
4462
4463 /* Clean up the variables module. */
4464 void
4465 Var_End(void)
4466 {
4467 Var_Stats();
4468 }
4469
4470 void
4471 Var_Stats(void)
4472 {
4473 HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables");
4474 }
4475
4476 /* Print all variables in a scope, sorted by name. */
4477 void
4478 Var_Dump(GNode *scope)
4479 {
4480 Vector /* of const char * */ vec;
4481 HashIter hi;
4482 size_t i;
4483 const char **varnames;
4484
4485 Vector_Init(&vec, sizeof(const char *));
4486
4487 HashIter_Init(&hi, &scope->vars);
4488 while (HashIter_Next(&hi) != NULL)
4489 *(const char **)Vector_Push(&vec) = hi.entry->key;
4490 varnames = vec.items;
4491
4492 qsort(varnames, vec.len, sizeof varnames[0], str_cmp_asc);
4493
4494 for (i = 0; i < vec.len; i++) {
4495 const char *varname = varnames[i];
4496 Var *var = HashTable_FindValue(&scope->vars, varname);
4497 debug_printf("%-16s = %s\n", varname, var->val.data);
4498 }
4499
4500 Vector_Done(&vec);
4501 }
4502