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