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