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