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