var.c revision 1.757 1 /* $NetBSD: var.c,v 1.757 2020/12/21 00:11:29 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.757 2020/12/21 00:11:29 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 MFStr 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 = MFStr_InitOwn(
2229 ModifyWords(val, ModifyWord_Loop, &args, 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 = MFStr_InitOwn(Buf_Destroy(&buf, FALSE));
2290 } else {
2291 st->newVal = MFStr_InitRefer(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 = MFStr_InitOwn(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 = MFStr_InitOwn(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 = MFStr_InitOwn(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 = MFStr_InitOwn(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 = MFStr_InitOwn(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 = MFStr_InitOwn(Cmd_Exec(cmd, &errfmt));
2434 else
2435 st->newVal = MFStr_InitOwn(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 = MFStr_InitOwn(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 = MFStr_InitOwn(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 = MFStr_InitOwn(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 = MFStr_InitOwn(
2698 ModifyWords(val, ModifyWord_SubstRegex, &args,
2699 oneBigWord, st->sep));
2700 regfree(&args.re);
2701 free(args.replace);
2702 return AMR_OK;
2703 }
2704
2705 #endif
2706
2707 /* :Q, :q */
2708 static ApplyModifierResult
2709 ApplyModifier_Quote(const char **pp, const char *val, ApplyModifiersState *st)
2710 {
2711 if ((*pp)[1] == st->endc || (*pp)[1] == ':') {
2712 st->newVal = MFStr_InitOwn(VarQuote(val, **pp == 'q'));
2713 (*pp)++;
2714 return AMR_OK;
2715 } else
2716 return AMR_UNKNOWN;
2717 }
2718
2719 static void
2720 ModifyWord_Copy(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
2721 {
2722 SepBuf_AddStr(buf, word);
2723 }
2724
2725 /* :ts<separator> */
2726 static ApplyModifierResult
2727 ApplyModifier_ToSep(const char **pp, const char *val, ApplyModifiersState *st)
2728 {
2729 const char *sep = *pp + 2;
2730
2731 /* ":ts<any><endc>" or ":ts<any>:" */
2732 if (sep[0] != st->endc && (sep[1] == st->endc || sep[1] == ':')) {
2733 st->sep = sep[0];
2734 *pp = sep + 1;
2735 goto ok;
2736 }
2737
2738 /* ":ts<endc>" or ":ts:" */
2739 if (sep[0] == st->endc || sep[0] == ':') {
2740 st->sep = '\0'; /* no separator */
2741 *pp = sep;
2742 goto ok;
2743 }
2744
2745 /* ":ts<unrecognised><unrecognised>". */
2746 if (sep[0] != '\\') {
2747 (*pp)++; /* just for backwards compatibility */
2748 return AMR_BAD;
2749 }
2750
2751 /* ":ts\n" */
2752 if (sep[1] == 'n') {
2753 st->sep = '\n';
2754 *pp = sep + 2;
2755 goto ok;
2756 }
2757
2758 /* ":ts\t" */
2759 if (sep[1] == 't') {
2760 st->sep = '\t';
2761 *pp = sep + 2;
2762 goto ok;
2763 }
2764
2765 /* ":ts\x40" or ":ts\100" */
2766 {
2767 const char *p = sep + 1;
2768 int base = 8; /* assume octal */
2769
2770 if (sep[1] == 'x') {
2771 base = 16;
2772 p++;
2773 } else if (!ch_isdigit(sep[1])) {
2774 (*pp)++; /* just for backwards compatibility */
2775 return AMR_BAD; /* ":ts<backslash><unrecognised>". */
2776 }
2777
2778 if (!TryParseChar(&p, base, &st->sep)) {
2779 Parse_Error(PARSE_FATAL,
2780 "Invalid character number: %s\n", p);
2781 return AMR_CLEANUP;
2782 }
2783 if (*p != ':' && *p != st->endc) {
2784 (*pp)++; /* just for backwards compatibility */
2785 return AMR_BAD;
2786 }
2787
2788 *pp = p;
2789 }
2790
2791 ok:
2792 st->newVal = MFStr_InitOwn(
2793 ModifyWords(val, ModifyWord_Copy, NULL, st->oneBigWord, st->sep));
2794 return AMR_OK;
2795 }
2796
2797 static char *
2798 str_toupper(const char *str)
2799 {
2800 char *res;
2801 size_t i, len;
2802
2803 len = strlen(str);
2804 res = bmake_malloc(len + 1);
2805 for (i = 0; i < len + 1; i++)
2806 res[i] = ch_toupper(str[i]);
2807
2808 return res;
2809 }
2810
2811 static char *
2812 str_tolower(const char *str)
2813 {
2814 char *res;
2815 size_t i, len;
2816
2817 len = strlen(str);
2818 res = bmake_malloc(len + 1);
2819 for (i = 0; i < len + 1; i++)
2820 res[i] = ch_tolower(str[i]);
2821
2822 return res;
2823 }
2824
2825 /* :tA, :tu, :tl, :ts<separator>, etc. */
2826 static ApplyModifierResult
2827 ApplyModifier_To(const char **pp, char *val, ApplyModifiersState *st)
2828 {
2829 const char *mod = *pp;
2830 assert(mod[0] == 't');
2831
2832 if (mod[1] == st->endc || mod[1] == ':' || mod[1] == '\0') {
2833 *pp = mod + 1;
2834 return AMR_BAD; /* Found ":t<endc>" or ":t:". */
2835 }
2836
2837 if (mod[1] == 's')
2838 return ApplyModifier_ToSep(pp, val, st);
2839
2840 if (mod[2] != st->endc && mod[2] != ':') {
2841 *pp = mod + 1;
2842 return AMR_BAD; /* Found ":t<unrecognised><unrecognised>". */
2843 }
2844
2845 /* Check for two-character options: ":tu", ":tl" */
2846 if (mod[1] == 'A') { /* absolute path */
2847 st->newVal = MFStr_InitOwn(
2848 ModifyWords(val, ModifyWord_Realpath, NULL,
2849 st->oneBigWord, st->sep));
2850 *pp = mod + 2;
2851 return AMR_OK;
2852 }
2853
2854 if (mod[1] == 'u') { /* :tu */
2855 st->newVal = MFStr_InitOwn(str_toupper(val));
2856 *pp = mod + 2;
2857 return AMR_OK;
2858 }
2859
2860 if (mod[1] == 'l') { /* :tl */
2861 st->newVal = MFStr_InitOwn(str_tolower(val));
2862 *pp = mod + 2;
2863 return AMR_OK;
2864 }
2865
2866 if (mod[1] == 'W' || mod[1] == 'w') { /* :tW, :tw */
2867 st->oneBigWord = mod[1] == 'W';
2868 st->newVal = MFStr_InitRefer(val);
2869 *pp = mod + 2;
2870 return AMR_OK;
2871 }
2872
2873 /* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
2874 *pp = mod + 1;
2875 return AMR_BAD;
2876 }
2877
2878 /* :[#], :[1], :[-1..1], etc. */
2879 static ApplyModifierResult
2880 ApplyModifier_Words(const char **pp, char *val, ApplyModifiersState *st)
2881 {
2882 char *estr;
2883 int first, last;
2884 VarParseResult res;
2885 const char *p;
2886
2887 (*pp)++; /* skip the '[' */
2888 res = ParseModifierPart(pp, ']', st->eflags, st,
2889 &estr, NULL, NULL, NULL);
2890 if (res != VPR_OK)
2891 return AMR_CLEANUP;
2892
2893 /* now *pp points just after the closing ']' */
2894 if (**pp != ':' && **pp != st->endc)
2895 goto bad_modifier; /* Found junk after ']' */
2896
2897 if (estr[0] == '\0')
2898 goto bad_modifier; /* empty square brackets in ":[]". */
2899
2900 if (estr[0] == '#' && estr[1] == '\0') { /* Found ":[#]" */
2901 if (st->oneBigWord) {
2902 st->newVal = MFStr_InitOwn(bmake_strdup("1"));
2903 } else {
2904 Buffer buf;
2905
2906 Words words = Str_Words(val, FALSE);
2907 size_t ac = words.len;
2908 Words_Free(words);
2909
2910 /* 3 digits + '\0' is usually enough */
2911 Buf_InitSize(&buf, 4);
2912 Buf_AddInt(&buf, (int)ac);
2913 st->newVal = MFStr_InitOwn(Buf_Destroy(&buf, FALSE));
2914 }
2915 goto ok;
2916 }
2917
2918 if (estr[0] == '*' && estr[1] == '\0') {
2919 /* Found ":[*]" */
2920 st->oneBigWord = TRUE;
2921 st->newVal = MFStr_InitRefer(val);
2922 goto ok;
2923 }
2924
2925 if (estr[0] == '@' && estr[1] == '\0') {
2926 /* Found ":[@]" */
2927 st->oneBigWord = FALSE;
2928 st->newVal = MFStr_InitRefer(val);
2929 goto ok;
2930 }
2931
2932 /*
2933 * We expect estr to contain a single integer for :[N], or two
2934 * integers separated by ".." for :[start..end].
2935 */
2936 p = estr;
2937 if (!TryParseIntBase0(&p, &first))
2938 goto bad_modifier; /* Found junk instead of a number */
2939
2940 if (p[0] == '\0') { /* Found only one integer in :[N] */
2941 last = first;
2942 } else if (p[0] == '.' && p[1] == '.' && p[2] != '\0') {
2943 /* Expecting another integer after ".." */
2944 p += 2;
2945 if (!TryParseIntBase0(&p, &last) || *p != '\0')
2946 goto bad_modifier; /* Found junk after ".." */
2947 } else
2948 goto bad_modifier; /* Found junk instead of ".." */
2949
2950 /*
2951 * Now first and last are properly filled in, but we still have to
2952 * check for 0 as a special case.
2953 */
2954 if (first == 0 && last == 0) {
2955 /* ":[0]" or perhaps ":[0..0]" */
2956 st->oneBigWord = TRUE;
2957 st->newVal = MFStr_InitRefer(val);
2958 goto ok;
2959 }
2960
2961 /* ":[0..N]" or ":[N..0]" */
2962 if (first == 0 || last == 0)
2963 goto bad_modifier;
2964
2965 /* Normal case: select the words described by first and last. */
2966 st->newVal = MFStr_InitOwn(
2967 VarSelectWords(st->sep, st->oneBigWord, val, first, last));
2968
2969 ok:
2970 free(estr);
2971 return AMR_OK;
2972
2973 bad_modifier:
2974 free(estr);
2975 return AMR_BAD;
2976 }
2977
2978 static int
2979 str_cmp_asc(const void *a, const void *b)
2980 {
2981 return strcmp(*(const char *const *)a, *(const char *const *)b);
2982 }
2983
2984 static int
2985 str_cmp_desc(const void *a, const void *b)
2986 {
2987 return strcmp(*(const char *const *)b, *(const char *const *)a);
2988 }
2989
2990 static void
2991 ShuffleStrings(char **strs, size_t n)
2992 {
2993 size_t i;
2994
2995 for (i = n - 1; i > 0; i--) {
2996 size_t rndidx = (size_t)random() % (i + 1);
2997 char *t = strs[i];
2998 strs[i] = strs[rndidx];
2999 strs[rndidx] = t;
3000 }
3001 }
3002
3003 /* :O (order ascending) or :Or (order descending) or :Ox (shuffle) */
3004 static ApplyModifierResult
3005 ApplyModifier_Order(const char **pp, const char *val, ApplyModifiersState *st)
3006 {
3007 const char *mod = (*pp)++; /* skip past the 'O' in any case */
3008
3009 Words words = Str_Words(val, FALSE);
3010
3011 if (mod[1] == st->endc || mod[1] == ':') {
3012 /* :O sorts ascending */
3013 qsort(words.words, words.len, sizeof words.words[0],
3014 str_cmp_asc);
3015
3016 } else if ((mod[1] == 'r' || mod[1] == 'x') &&
3017 (mod[2] == st->endc || mod[2] == ':')) {
3018 (*pp)++;
3019
3020 if (mod[1] == 'r') { /* :Or sorts descending */
3021 qsort(words.words, words.len, sizeof words.words[0],
3022 str_cmp_desc);
3023 } else
3024 ShuffleStrings(words.words, words.len);
3025 } else {
3026 Words_Free(words);
3027 return AMR_BAD;
3028 }
3029
3030 st->newVal = MFStr_InitOwn(Words_JoinFree(words));
3031 return AMR_OK;
3032 }
3033
3034 /* :? then : else */
3035 static ApplyModifierResult
3036 ApplyModifier_IfElse(const char **pp, const char *val, ApplyModifiersState *st)
3037 {
3038 char *then_expr, *else_expr;
3039 VarParseResult res;
3040
3041 Boolean value = FALSE;
3042 VarEvalFlags then_eflags = VARE_NONE;
3043 VarEvalFlags else_eflags = VARE_NONE;
3044
3045 int cond_rc = COND_PARSE; /* anything other than COND_INVALID */
3046 if (st->eflags & VARE_WANTRES) {
3047 cond_rc = Cond_EvalCondition(st->var->name.str, &value);
3048 if (cond_rc != COND_INVALID && value)
3049 then_eflags = st->eflags;
3050 if (cond_rc != COND_INVALID && !value)
3051 else_eflags = st->eflags;
3052 }
3053
3054 (*pp)++; /* skip past the '?' */
3055 res = ParseModifierPart(pp, ':', then_eflags, st,
3056 &then_expr, NULL, NULL, NULL);
3057 if (res != VPR_OK)
3058 return AMR_CLEANUP;
3059
3060 res = ParseModifierPart(pp, st->endc, else_eflags, st,
3061 &else_expr, NULL, NULL, NULL);
3062 if (res != VPR_OK)
3063 return AMR_CLEANUP;
3064
3065 (*pp)--;
3066 if (cond_rc == COND_INVALID) {
3067 Error("Bad conditional expression `%s' in %s?%s:%s",
3068 st->var->name.str, st->var->name.str, then_expr, else_expr);
3069 return AMR_CLEANUP;
3070 }
3071
3072 if (value) {
3073 st->newVal = MFStr_InitOwn(then_expr);
3074 free(else_expr);
3075 } else {
3076 st->newVal = MFStr_InitOwn(else_expr);
3077 free(then_expr);
3078 }
3079 ApplyModifiersState_Define(st);
3080 return AMR_OK;
3081 }
3082
3083 /*
3084 * The ::= modifiers actually assign a value to the variable.
3085 * Their main purpose is in supporting modifiers of .for loop
3086 * iterators and other obscure uses. They always expand to
3087 * nothing. In a target rule that would otherwise expand to an
3088 * empty line they can be preceded with @: to keep make happy.
3089 * Eg.
3090 *
3091 * foo: .USE
3092 * .for i in ${.TARGET} ${.TARGET:R}.gz
3093 * @: ${t::=$i}
3094 * @echo blah ${t:T}
3095 * .endfor
3096 *
3097 * ::=<str> Assigns <str> as the new value of variable.
3098 * ::?=<str> Assigns <str> as value of variable if
3099 * it was not already set.
3100 * ::+=<str> Appends <str> to variable.
3101 * ::!=<cmd> Assigns output of <cmd> as the new value of
3102 * variable.
3103 */
3104 static ApplyModifierResult
3105 ApplyModifier_Assign(const char **pp, ApplyModifiersState *st)
3106 {
3107 GNode *ctxt;
3108 char delim;
3109 char *val;
3110 VarParseResult res;
3111
3112 const char *mod = *pp;
3113 const char *op = mod + 1;
3114
3115 if (op[0] == '=')
3116 goto ok;
3117 if ((op[0] == '!' || op[0] == '+' || op[0] == '?') && op[1] == '=')
3118 goto ok;
3119 return AMR_UNKNOWN; /* "::<unrecognised>" */
3120 ok:
3121
3122 if (st->var->name.str[0] == '\0') {
3123 *pp = mod + 1;
3124 return AMR_BAD;
3125 }
3126
3127 ctxt = st->ctxt; /* context where v belongs */
3128 if (!(st->exprFlags & VEF_UNDEF) && st->ctxt != VAR_GLOBAL) {
3129 Var *gv = VarFind(st->var->name.str, st->ctxt, FALSE);
3130 if (gv == NULL)
3131 ctxt = VAR_GLOBAL;
3132 else
3133 VarFreeEnv(gv, TRUE);
3134 }
3135
3136 switch (op[0]) {
3137 case '+':
3138 case '?':
3139 case '!':
3140 *pp = mod + 3;
3141 break;
3142 default:
3143 *pp = mod + 2;
3144 break;
3145 }
3146
3147 delim = st->startc == '(' ? ')' : '}';
3148 res = ParseModifierPart(pp, delim, st->eflags, st, &val, NULL, NULL,
3149 NULL);
3150 if (res != VPR_OK)
3151 return AMR_CLEANUP;
3152
3153 (*pp)--;
3154
3155 if (st->eflags & VARE_WANTRES) {
3156 switch (op[0]) {
3157 case '+':
3158 Var_Append(st->var->name.str, val, ctxt);
3159 break;
3160 case '!': {
3161 const char *errfmt;
3162 char *cmd_output = Cmd_Exec(val, &errfmt);
3163 if (errfmt != NULL)
3164 Error(errfmt, val);
3165 else
3166 Var_Set(st->var->name.str, cmd_output, ctxt);
3167 free(cmd_output);
3168 break;
3169 }
3170 case '?':
3171 if (!(st->exprFlags & VEF_UNDEF))
3172 break;
3173 /* FALLTHROUGH */
3174 default:
3175 Var_Set(st->var->name.str, val, ctxt);
3176 break;
3177 }
3178 }
3179 free(val);
3180 st->newVal = MFStr_InitOwn(bmake_strdup(""));
3181 return AMR_OK;
3182 }
3183
3184 /* :_=...
3185 * remember current value */
3186 static ApplyModifierResult
3187 ApplyModifier_Remember(const char **pp, char *val, ApplyModifiersState *st)
3188 {
3189 const char *mod = *pp;
3190 if (!ModMatchEq(mod, "_", st->endc))
3191 return AMR_UNKNOWN;
3192
3193 if (mod[1] == '=') {
3194 size_t n = strcspn(mod + 2, ":)}");
3195 char *name = bmake_strldup(mod + 2, n);
3196 Var_Set(name, val, st->ctxt);
3197 free(name);
3198 *pp = mod + 2 + n;
3199 } else {
3200 Var_Set("_", val, st->ctxt);
3201 *pp = mod + 1;
3202 }
3203 st->newVal = MFStr_InitRefer(val);
3204 return AMR_OK;
3205 }
3206
3207 /* Apply the given function to each word of the variable value,
3208 * for a single-letter modifier such as :H, :T. */
3209 static ApplyModifierResult
3210 ApplyModifier_WordFunc(const char **pp, const char *val,
3211 ApplyModifiersState *st, ModifyWordsCallback modifyWord)
3212 {
3213 char delim = (*pp)[1];
3214 if (delim != st->endc && delim != ':')
3215 return AMR_UNKNOWN;
3216
3217 st->newVal = MFStr_InitOwn(ModifyWords(val, modifyWord, NULL,
3218 st->oneBigWord, st->sep));
3219 (*pp)++;
3220 return AMR_OK;
3221 }
3222
3223 static ApplyModifierResult
3224 ApplyModifier_Unique(const char **pp, const char *val, ApplyModifiersState *st)
3225 {
3226 if ((*pp)[1] == st->endc || (*pp)[1] == ':') {
3227 st->newVal = MFStr_InitOwn(VarUniq(val));
3228 (*pp)++;
3229 return AMR_OK;
3230 } else
3231 return AMR_UNKNOWN;
3232 }
3233
3234 #ifdef SYSVVARSUB
3235 /* :from=to */
3236 static ApplyModifierResult
3237 ApplyModifier_SysV(const char **pp, char *val, ApplyModifiersState *st)
3238 {
3239 char *lhs, *rhs;
3240 VarParseResult res;
3241
3242 const char *mod = *pp;
3243 Boolean eqFound = FALSE;
3244
3245 /*
3246 * First we make a pass through the string trying to verify it is a
3247 * SysV-make-style translation. It must be: <lhs>=<rhs>
3248 */
3249 int depth = 1;
3250 const char *p = mod;
3251 while (*p != '\0' && depth > 0) {
3252 if (*p == '=') { /* XXX: should also test depth == 1 */
3253 eqFound = TRUE;
3254 /* continue looking for st->endc */
3255 } else if (*p == st->endc)
3256 depth--;
3257 else if (*p == st->startc)
3258 depth++;
3259 if (depth > 0)
3260 p++;
3261 }
3262 if (*p != st->endc || !eqFound)
3263 return AMR_UNKNOWN;
3264
3265 res = ParseModifierPart(pp, '=', st->eflags, st,
3266 &lhs, NULL, NULL, NULL);
3267 if (res != VPR_OK)
3268 return AMR_CLEANUP;
3269
3270 /* The SysV modifier lasts until the end of the variable expression. */
3271 res = ParseModifierPart(pp, st->endc, st->eflags, st,
3272 &rhs, NULL, NULL, NULL);
3273 if (res != VPR_OK)
3274 return AMR_CLEANUP;
3275
3276 (*pp)--;
3277 if (lhs[0] == '\0' && val[0] == '\0') {
3278 st->newVal = MFStr_InitRefer(val); /* special case */
3279 } else {
3280 struct ModifyWord_SYSVSubstArgs args = { st->ctxt, lhs, rhs };
3281 st->newVal = MFStr_InitOwn(
3282 ModifyWords(val, ModifyWord_SYSVSubst, &args,
3283 st->oneBigWord, st->sep));
3284 }
3285 free(lhs);
3286 free(rhs);
3287 return AMR_OK;
3288 }
3289 #endif
3290
3291 #ifdef SUNSHCMD
3292 /* :sh */
3293 static ApplyModifierResult
3294 ApplyModifier_SunShell(const char **pp, const char *val,
3295 ApplyModifiersState *st)
3296 {
3297 const char *p = *pp;
3298 if (p[1] == 'h' && (p[2] == st->endc || p[2] == ':')) {
3299 if (st->eflags & VARE_WANTRES) {
3300 const char *errfmt;
3301 st->newVal = MFStr_InitOwn(Cmd_Exec(val, &errfmt));
3302 if (errfmt != NULL)
3303 Error(errfmt, val);
3304 } else
3305 st->newVal = MFStr_InitOwn(bmake_strdup(""));
3306 *pp = p + 2;
3307 return AMR_OK;
3308 } else
3309 return AMR_UNKNOWN;
3310 }
3311 #endif
3312
3313 static void
3314 LogBeforeApply(const ApplyModifiersState *st, const char *mod, char endc,
3315 const char *val)
3316 {
3317 char eflags_str[VarEvalFlags_ToStringSize];
3318 char vflags_str[VarFlags_ToStringSize];
3319 char exprflags_str[VarExprFlags_ToStringSize];
3320 Boolean is_single_char = mod[0] != '\0' &&
3321 (mod[1] == endc || mod[1] == ':');
3322
3323 /* At this point, only the first character of the modifier can
3324 * be used since the end of the modifier is not yet known. */
3325 debug_printf("Applying ${%s:%c%s} to \"%s\" (%s, %s, %s)\n",
3326 st->var->name.str, mod[0], is_single_char ? "" : "...", val,
3327 Enum_FlagsToString(eflags_str, sizeof eflags_str,
3328 st->eflags, VarEvalFlags_ToStringSpecs),
3329 Enum_FlagsToString(vflags_str, sizeof vflags_str,
3330 st->var->flags, VarFlags_ToStringSpecs),
3331 Enum_FlagsToString(exprflags_str, sizeof exprflags_str,
3332 st->exprFlags,
3333 VarExprFlags_ToStringSpecs));
3334 }
3335
3336 static void
3337 LogAfterApply(ApplyModifiersState *st, const char *p, const char *mod)
3338 {
3339 char eflags_str[VarEvalFlags_ToStringSize];
3340 char vflags_str[VarFlags_ToStringSize];
3341 char exprflags_str[VarExprFlags_ToStringSize];
3342 const char *quot = st->newVal.str == var_Error ? "" : "\"";
3343 const char *newVal =
3344 st->newVal.str == var_Error ? "error" : st->newVal.str;
3345
3346 debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s, %s)\n",
3347 st->var->name.str, (int)(p - mod), mod, quot, newVal, quot,
3348 Enum_FlagsToString(eflags_str, sizeof eflags_str,
3349 st->eflags, VarEvalFlags_ToStringSpecs),
3350 Enum_FlagsToString(vflags_str, sizeof vflags_str,
3351 st->var->flags, VarFlags_ToStringSpecs),
3352 Enum_FlagsToString(exprflags_str, sizeof exprflags_str,
3353 st->exprFlags,
3354 VarExprFlags_ToStringSpecs));
3355 }
3356
3357 static ApplyModifierResult
3358 ApplyModifier(const char **pp, char *val, ApplyModifiersState *st)
3359 {
3360 switch (**pp) {
3361 case ':':
3362 return ApplyModifier_Assign(pp, st);
3363 case '@':
3364 return ApplyModifier_Loop(pp, val, st);
3365 case '_':
3366 return ApplyModifier_Remember(pp, val, st);
3367 case 'D':
3368 case 'U':
3369 return ApplyModifier_Defined(pp, val, st);
3370 case 'L':
3371 return ApplyModifier_Literal(pp, st);
3372 case 'P':
3373 return ApplyModifier_Path(pp, st);
3374 case '!':
3375 return ApplyModifier_ShellCommand(pp, st);
3376 case '[':
3377 return ApplyModifier_Words(pp, val, st);
3378 case 'g':
3379 return ApplyModifier_Gmtime(pp, val, st);
3380 case 'h':
3381 return ApplyModifier_Hash(pp, val, st);
3382 case 'l':
3383 return ApplyModifier_Localtime(pp, val, st);
3384 case 't':
3385 return ApplyModifier_To(pp, val, st);
3386 case 'N':
3387 case 'M':
3388 return ApplyModifier_Match(pp, val, st);
3389 case 'S':
3390 return ApplyModifier_Subst(pp, val, st);
3391 case '?':
3392 return ApplyModifier_IfElse(pp, val, st);
3393 #ifndef NO_REGEX
3394 case 'C':
3395 return ApplyModifier_Regex(pp, val, st);
3396 #endif
3397 case 'q':
3398 case 'Q':
3399 return ApplyModifier_Quote(pp, val, st);
3400 case 'T':
3401 return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Tail);
3402 case 'H':
3403 return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Head);
3404 case 'E':
3405 return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Suffix);
3406 case 'R':
3407 return ApplyModifier_WordFunc(pp, val, st, ModifyWord_Root);
3408 case 'r':
3409 return ApplyModifier_Range(pp, val, st);
3410 case 'O':
3411 return ApplyModifier_Order(pp, val, st);
3412 case 'u':
3413 return ApplyModifier_Unique(pp, val, st);
3414 #ifdef SUNSHCMD
3415 case 's':
3416 return ApplyModifier_SunShell(pp, val, st);
3417 #endif
3418 default:
3419 return AMR_UNKNOWN;
3420 }
3421 }
3422
3423 static MFStr ApplyModifiers(const char **, MFStr, char, char, Var *,
3424 VarExprFlags *, GNode *, VarEvalFlags);
3425
3426 typedef enum ApplyModifiersIndirectResult {
3427 /* The indirect modifiers have been applied successfully. */
3428 AMIR_CONTINUE,
3429 /* Fall back to the SysV modifier. */
3430 AMIR_APPLY_MODS,
3431 /* Error out. */
3432 AMIR_OUT
3433 } ApplyModifiersIndirectResult;
3434
3435 /*
3436 * While expanding a variable expression, expand and apply indirect modifiers,
3437 * such as in ${VAR:${M_indirect}}.
3438 *
3439 * All indirect modifiers of a group must come from a single variable
3440 * expression. ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
3441 *
3442 * Multiple groups of indirect modifiers can be chained by separating them
3443 * with colons. ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
3444 *
3445 * If the variable expression is not followed by st->endc or ':', fall
3446 * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
3447 *
3448 * The expression ${VAR:${M1}${M2}} is not treated as an indirect
3449 * modifier, and it is neither a SysV modifier but a parse error.
3450 */
3451 static ApplyModifiersIndirectResult
3452 ApplyModifiersIndirect(ApplyModifiersState *st, const char **pp,
3453 MFStr *inout_value)
3454 {
3455 const char *p = *pp;
3456 FStr mods;
3457
3458 (void)Var_Parse(&p, st->ctxt, st->eflags, &mods);
3459 /* TODO: handle errors */
3460
3461 if (mods.str[0] != '\0' && *p != '\0' && *p != ':' && *p != st->endc) {
3462 FStr_Done(&mods);
3463 return AMIR_APPLY_MODS;
3464 }
3465
3466 DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
3467 mods.str, (int)(p - *pp), *pp);
3468
3469 if (mods.str[0] != '\0') {
3470 const char *modsp = mods.str;
3471 MFStr newVal = ApplyModifiers(&modsp, *inout_value, '\0', '\0',
3472 st->var, &st->exprFlags, st->ctxt, st->eflags);
3473 *inout_value = newVal;
3474 if (newVal.str == var_Error || newVal.str == varUndefined ||
3475 *modsp != '\0') {
3476 FStr_Done(&mods);
3477 *pp = p;
3478 return AMIR_OUT; /* error already reported */
3479 }
3480 }
3481 FStr_Done(&mods);
3482
3483 if (*p == ':')
3484 p++;
3485 else if (*p == '\0' && st->endc != '\0') {
3486 Error("Unclosed variable specification after complex "
3487 "modifier (expecting '%c') for %s",
3488 st->endc, st->var->name.str);
3489 *pp = p;
3490 return AMIR_OUT;
3491 }
3492
3493 *pp = p;
3494 return AMIR_CONTINUE;
3495 }
3496
3497 static ApplyModifierResult
3498 ApplySingleModifier(ApplyModifiersState *st, const char *mod, char endc,
3499 const char **pp, MFStr *inout_value)
3500 {
3501 ApplyModifierResult res;
3502 const char *p = *pp;
3503 char *const val = inout_value->str;
3504
3505 if (DEBUG(VAR))
3506 LogBeforeApply(st, mod, endc, val);
3507
3508 res = ApplyModifier(&p, val, st);
3509
3510 #ifdef SYSVVARSUB
3511 if (res == AMR_UNKNOWN) {
3512 assert(p == mod);
3513 res = ApplyModifier_SysV(&p, val, st);
3514 }
3515 #endif
3516
3517 if (res == AMR_UNKNOWN) {
3518 Parse_Error(PARSE_FATAL, "Unknown modifier '%c'", *mod);
3519 /*
3520 * Guess the end of the current modifier.
3521 * XXX: Skipping the rest of the modifier hides
3522 * errors and leads to wrong results.
3523 * Parsing should rather stop here.
3524 */
3525 for (p++; *p != ':' && *p != st->endc && *p != '\0'; p++)
3526 continue;
3527 st->newVal = MFStr_InitRefer(var_Error);
3528 }
3529 if (res == AMR_CLEANUP || res == AMR_BAD) {
3530 *pp = p;
3531 return res;
3532 }
3533
3534 if (DEBUG(VAR))
3535 LogAfterApply(st, p, mod);
3536
3537 if (st->newVal.str != val) {
3538 MFStr_Done(inout_value);
3539 *inout_value = st->newVal;
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, inout_value->str, *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 return AMR_OK;
3559 }
3560
3561 /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
3562 static MFStr
3563 ApplyModifiers(
3564 const char **pp, /* the parsing position, updated upon return */
3565 MFStr value, /* the current value of the expression */
3566 char startc, /* '(' or '{', or '\0' for indirect modifiers */
3567 char endc, /* ')' or '}', or '\0' for indirect modifiers */
3568 Var *v,
3569 VarExprFlags *exprFlags,
3570 GNode *ctxt, /* for looking up and modifying variables */
3571 VarEvalFlags eflags
3572 )
3573 {
3574 ApplyModifiersState st = {
3575 startc, endc, v, ctxt, eflags,
3576 MFStr_InitRefer(var_Error), /* .newVal */
3577 ' ', /* .sep */
3578 FALSE, /* .oneBigWord */
3579 *exprFlags /* .exprFlags */
3580 };
3581 const char *p;
3582 const char *mod;
3583
3584 assert(startc == '(' || startc == '{' || startc == '\0');
3585 assert(endc == ')' || endc == '}' || endc == '\0');
3586 assert(value.str != NULL);
3587
3588 p = *pp;
3589
3590 if (*p == '\0' && endc != '\0') {
3591 Error(
3592 "Unclosed variable expression (expecting '%c') for \"%s\"",
3593 st.endc, st.var->name.str);
3594 goto cleanup;
3595 }
3596
3597 while (*p != '\0' && *p != endc) {
3598 ApplyModifierResult res;
3599
3600 if (*p == '$') {
3601 ApplyModifiersIndirectResult amir;
3602 amir = ApplyModifiersIndirect(&st, &p, &value);
3603 if (amir == AMIR_CONTINUE)
3604 continue;
3605 if (amir == AMIR_OUT)
3606 break;
3607 }
3608
3609 /* default value, in case of errors */
3610 st.newVal = MFStr_InitRefer(var_Error);
3611 mod = p;
3612
3613 res = ApplySingleModifier(&st, mod, endc, &p, &value);
3614 if (res == AMR_CLEANUP)
3615 goto cleanup;
3616 if (res == AMR_BAD)
3617 goto bad_modifier;
3618 }
3619
3620 *pp = p;
3621 assert(value.str != NULL); /* Use var_Error or varUndefined instead. */
3622 *exprFlags = st.exprFlags;
3623 return value;
3624
3625 bad_modifier:
3626 /* XXX: The modifier end is only guessed. */
3627 Error("Bad modifier `:%.*s' for %s",
3628 (int)strcspn(mod, ":)}"), mod, st.var->name.str);
3629
3630 cleanup:
3631 *pp = p;
3632 MFStr_Done(&value);
3633 *exprFlags = st.exprFlags;
3634 return MFStr_InitRefer(var_Error);
3635 }
3636
3637 /* Only four of the local variables are treated specially as they are the
3638 * only four that will be set when dynamic sources are expanded. */
3639 static Boolean
3640 VarnameIsDynamic(const char *name, size_t len)
3641 {
3642 if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
3643 switch (name[0]) {
3644 case '@':
3645 case '%':
3646 case '*':
3647 case '!':
3648 return TRUE;
3649 }
3650 return FALSE;
3651 }
3652
3653 if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
3654 return strcmp(name, ".TARGET") == 0 ||
3655 strcmp(name, ".ARCHIVE") == 0 ||
3656 strcmp(name, ".PREFIX") == 0 ||
3657 strcmp(name, ".MEMBER") == 0;
3658 }
3659
3660 return FALSE;
3661 }
3662
3663 static const char *
3664 UndefinedShortVarValue(char varname, const GNode *ctxt, VarEvalFlags eflags)
3665 {
3666 if (ctxt == VAR_CMDLINE || ctxt == VAR_GLOBAL) {
3667 /*
3668 * If substituting a local variable in a non-local context,
3669 * assume it's for dynamic source stuff. We have to handle
3670 * this specially and return the longhand for the variable
3671 * with the dollar sign escaped so it makes it back to the
3672 * caller. Only four of the local variables are treated
3673 * specially as they are the only four that will be set
3674 * when dynamic sources are expanded.
3675 */
3676 switch (varname) {
3677 case '@':
3678 return "$(.TARGET)";
3679 case '%':
3680 return "$(.MEMBER)";
3681 case '*':
3682 return "$(.PREFIX)";
3683 case '!':
3684 return "$(.ARCHIVE)";
3685 }
3686 }
3687 return eflags & VARE_UNDEFERR ? var_Error : varUndefined;
3688 }
3689
3690 /* Parse a variable name, until the end character or a colon, whichever
3691 * comes first. */
3692 static char *
3693 ParseVarname(const char **pp, char startc, char endc,
3694 GNode *ctxt, VarEvalFlags eflags,
3695 size_t *out_varname_len)
3696 {
3697 Buffer buf;
3698 const char *p = *pp;
3699 int depth = 1;
3700
3701 Buf_Init(&buf);
3702
3703 while (*p != '\0') {
3704 /* Track depth so we can spot parse errors. */
3705 if (*p == startc)
3706 depth++;
3707 if (*p == endc) {
3708 if (--depth == 0)
3709 break;
3710 }
3711 if (*p == ':' && depth == 1)
3712 break;
3713
3714 /* A variable inside a variable, expand. */
3715 if (*p == '$') {
3716 FStr nested_val;
3717 (void)Var_Parse(&p, ctxt, eflags, &nested_val);
3718 /* TODO: handle errors */
3719 Buf_AddStr(&buf, nested_val.str);
3720 FStr_Done(&nested_val);
3721 } else {
3722 Buf_AddByte(&buf, *p);
3723 p++;
3724 }
3725 }
3726 *pp = p;
3727 *out_varname_len = Buf_Len(&buf);
3728 return Buf_Destroy(&buf, FALSE);
3729 }
3730
3731 static VarParseResult
3732 ValidShortVarname(char varname, const char *start)
3733 {
3734 switch (varname) {
3735 case '\0':
3736 case ')':
3737 case '}':
3738 case ':':
3739 case '$':
3740 break; /* and continue below */
3741 default:
3742 return VPR_OK;
3743 }
3744
3745 if (!opts.lint)
3746 return VPR_PARSE_SILENT;
3747
3748 if (varname == '$')
3749 Parse_Error(PARSE_FATAL,
3750 "To escape a dollar, use \\$, not $$, at \"%s\"", start);
3751 else if (varname == '\0')
3752 Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
3753 else
3754 Parse_Error(PARSE_FATAL,
3755 "Invalid variable name '%c', at \"%s\"", varname, start);
3756
3757 return VPR_PARSE_MSG;
3758 }
3759
3760 /* Parse a single-character variable name such as $V or $@.
3761 * Return whether to continue parsing. */
3762 static Boolean
3763 ParseVarnameShort(char startc, const char **pp, GNode *ctxt,
3764 VarEvalFlags eflags,
3765 VarParseResult *out_FALSE_res, const char **out_FALSE_val,
3766 Var **out_TRUE_var)
3767 {
3768 char name[2];
3769 Var *v;
3770 VarParseResult vpr;
3771
3772 /*
3773 * If it's not bounded by braces of some sort, life is much simpler.
3774 * We just need to check for the first character and return the
3775 * value if it exists.
3776 */
3777
3778 vpr = ValidShortVarname(startc, *pp);
3779 if (vpr != VPR_OK) {
3780 (*pp)++;
3781 *out_FALSE_val = var_Error;
3782 *out_FALSE_res = vpr;
3783 return FALSE;
3784 }
3785
3786 name[0] = startc;
3787 name[1] = '\0';
3788 v = VarFind(name, ctxt, TRUE);
3789 if (v == NULL) {
3790 *pp += 2;
3791
3792 *out_FALSE_val = UndefinedShortVarValue(startc, ctxt, eflags);
3793 if (opts.lint && *out_FALSE_val == var_Error) {
3794 Parse_Error(PARSE_FATAL,
3795 "Variable \"%s\" is undefined", name);
3796 *out_FALSE_res = VPR_UNDEF_MSG;
3797 return FALSE;
3798 }
3799 *out_FALSE_res =
3800 eflags & VARE_UNDEFERR ? VPR_UNDEF_SILENT : VPR_OK;
3801 return FALSE;
3802 }
3803
3804 *out_TRUE_var = v;
3805 return TRUE;
3806 }
3807
3808 /* Find variables like @F or <D. */
3809 static Var *
3810 FindLocalLegacyVar(const char *varname, size_t namelen, GNode *ctxt,
3811 const char **out_extraModifiers)
3812 {
3813 /* Only resolve these variables if ctxt is a "real" target. */
3814 if (ctxt == VAR_CMDLINE || ctxt == VAR_GLOBAL)
3815 return NULL;
3816
3817 if (namelen != 2)
3818 return NULL;
3819 if (varname[1] != 'F' && varname[1] != 'D')
3820 return NULL;
3821 if (strchr("@%?*!<>", varname[0]) == NULL)
3822 return NULL;
3823
3824 {
3825 char name[] = { varname[0], '\0' };
3826 Var *v = VarFind(name, ctxt, FALSE);
3827
3828 if (v != NULL) {
3829 if (varname[1] == 'D') {
3830 *out_extraModifiers = "H:";
3831 } else { /* F */
3832 *out_extraModifiers = "T:";
3833 }
3834 }
3835 return v;
3836 }
3837 }
3838
3839 static VarParseResult
3840 EvalUndefined(Boolean dynamic, const char *start, const char *p, char *varname,
3841 VarEvalFlags eflags,
3842 FStr *out_val)
3843 {
3844 if (dynamic) {
3845 *out_val = FStr_InitOwn(bmake_strsedup(start, p));
3846 free(varname);
3847 return VPR_OK;
3848 }
3849
3850 if ((eflags & VARE_UNDEFERR) && opts.lint) {
3851 Parse_Error(PARSE_FATAL,
3852 "Variable \"%s\" is undefined", varname);
3853 free(varname);
3854 *out_val = FStr_InitRefer(var_Error);
3855 return VPR_UNDEF_MSG;
3856 }
3857
3858 if (eflags & VARE_UNDEFERR) {
3859 free(varname);
3860 *out_val = FStr_InitRefer(var_Error);
3861 return VPR_UNDEF_SILENT;
3862 }
3863
3864 free(varname);
3865 *out_val = FStr_InitRefer(varUndefined);
3866 return VPR_OK;
3867 }
3868
3869 /* Parse a long variable name enclosed in braces or parentheses such as $(VAR)
3870 * or ${VAR}, up to the closing brace or parenthesis, or in the case of
3871 * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
3872 * Return whether to continue parsing. */
3873 static Boolean
3874 ParseVarnameLong(
3875 const char *p,
3876 char startc,
3877 GNode *ctxt,
3878 VarEvalFlags eflags,
3879
3880 const char **out_FALSE_pp,
3881 VarParseResult *out_FALSE_res,
3882 FStr *out_FALSE_val,
3883
3884 char *out_TRUE_endc,
3885 const char **out_TRUE_p,
3886 Var **out_TRUE_v,
3887 Boolean *out_TRUE_haveModifier,
3888 const char **out_TRUE_extraModifiers,
3889 Boolean *out_TRUE_dynamic,
3890 VarExprFlags *out_TRUE_exprFlags
3891 )
3892 {
3893 size_t namelen;
3894 char *varname;
3895 Var *v;
3896 Boolean haveModifier;
3897 Boolean dynamic = FALSE;
3898
3899 const char *const start = p;
3900 char endc = startc == '(' ? ')' : '}';
3901
3902 p += 2; /* skip "${" or "$(" or "y(" */
3903 varname = ParseVarname(&p, startc, endc, ctxt, eflags, &namelen);
3904
3905 if (*p == ':') {
3906 haveModifier = TRUE;
3907 } else if (*p == endc) {
3908 haveModifier = FALSE;
3909 } else {
3910 Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"", varname);
3911 free(varname);
3912 *out_FALSE_pp = p;
3913 *out_FALSE_val = FStr_InitRefer(var_Error);
3914 *out_FALSE_res = VPR_PARSE_MSG;
3915 return FALSE;
3916 }
3917
3918 v = VarFind(varname, ctxt, TRUE);
3919
3920 /* At this point, p points just after the variable name,
3921 * either at ':' or at endc. */
3922
3923 if (v == NULL) {
3924 v = FindLocalLegacyVar(varname, namelen, ctxt,
3925 out_TRUE_extraModifiers);
3926 }
3927
3928 if (v == NULL) {
3929 /*
3930 * Defer expansion of dynamic variables if they appear in
3931 * non-local context since they are not defined there.
3932 */
3933 dynamic = VarnameIsDynamic(varname, namelen) &&
3934 (ctxt == VAR_CMDLINE || ctxt == VAR_GLOBAL);
3935
3936 if (!haveModifier) {
3937 p++; /* skip endc */
3938 *out_FALSE_pp = p;
3939 *out_FALSE_res = EvalUndefined(dynamic, start, p,
3940 varname, eflags, out_FALSE_val);
3941 return FALSE;
3942 }
3943
3944 /*
3945 * The variable expression is based on an undefined variable.
3946 * Nevertheless it needs a Var, for modifiers that access the
3947 * variable name, such as :L or :?.
3948 *
3949 * Most modifiers leave this expression in the "undefined"
3950 * state (VEF_UNDEF), only a few modifiers like :D, :U, :L,
3951 * :P turn this undefined expression into a defined
3952 * expression (VEF_DEF).
3953 *
3954 * At the end, after applying all modifiers, if the expression
3955 * is still undefined, Var_Parse will return an empty string
3956 * instead of the actually computed value.
3957 */
3958 v = VarNew(FStr_InitOwn(varname), "", VAR_NONE);
3959 *out_TRUE_exprFlags = VEF_UNDEF;
3960 } else
3961 free(varname);
3962
3963 *out_TRUE_endc = endc;
3964 *out_TRUE_p = p;
3965 *out_TRUE_v = v;
3966 *out_TRUE_haveModifier = haveModifier;
3967 *out_TRUE_dynamic = dynamic;
3968 return TRUE;
3969 }
3970
3971 /* Free the environment variable now since we own it. */
3972 static void
3973 FreeEnvVar(void **out_val_freeIt, Var *v, const char *value)
3974 {
3975 char *varValue = Buf_Destroy(&v->val, FALSE);
3976 if (value == varValue)
3977 *out_val_freeIt = varValue;
3978 else
3979 free(varValue);
3980
3981 FStr_Done(&v->name);
3982 free(v);
3983 }
3984
3985 /*
3986 * Given the start of a variable expression (such as $v, $(VAR),
3987 * ${VAR:Mpattern}), extract the variable name and value, and the modifiers,
3988 * if any. While doing that, apply the modifiers to the value of the
3989 * expression, forming its final value. A few of the modifiers such as :!cmd!
3990 * or ::= have side effects.
3991 *
3992 * Input:
3993 * *pp The string to parse.
3994 * When parsing a condition in ParseEmptyArg, it may also
3995 * point to the "y" of "empty(VARNAME:Modifiers)", which
3996 * is syntactically the same.
3997 * ctxt The context for finding variables
3998 * eflags Control the exact details of parsing
3999 *
4000 * Output:
4001 * *pp The position where to continue parsing.
4002 * TODO: After a parse error, the value of *pp is
4003 * unspecified. It may not have been updated at all,
4004 * point to some random character in the string, to the
4005 * location of the parse error, or at the end of the
4006 * string.
4007 * *out_val The value of the variable expression, never NULL.
4008 * *out_val var_Error if there was a parse error.
4009 * *out_val var_Error if the base variable of the expression was
4010 * undefined, eflags contains VARE_UNDEFERR, and none of
4011 * the modifiers turned the undefined expression into a
4012 * defined expression.
4013 * XXX: It is not guaranteed that an error message has
4014 * been printed.
4015 * *out_val varUndefined if the base variable of the expression
4016 * was undefined, eflags did not contain VARE_UNDEFERR,
4017 * and none of the modifiers turned the undefined
4018 * expression into a defined expression.
4019 * XXX: It is not guaranteed that an error message has
4020 * been printed.
4021 * *out_val_freeIt Must be freed by the caller after using *out_val.
4022 */
4023 /* coverity[+alloc : arg-*4] */
4024 VarParseResult
4025 Var_Parse(const char **pp, GNode *ctxt, VarEvalFlags eflags, FStr *out_val)
4026 {
4027 const char *p = *pp;
4028 const char *const start = p;
4029 /* TRUE if have modifiers for the variable. */
4030 Boolean haveModifier;
4031 /* Starting character if variable in parens or braces. */
4032 char startc;
4033 /* Ending character if variable in parens or braces. */
4034 char endc;
4035 /*
4036 * TRUE if the variable is local and we're expanding it in a
4037 * non-local context. This is done to support dynamic sources.
4038 * The result is just the expression, unaltered.
4039 */
4040 Boolean dynamic;
4041 const char *extramodifiers;
4042 Var *v;
4043 MFStr value;
4044 char eflags_str[VarEvalFlags_ToStringSize];
4045 VarExprFlags exprFlags = VEF_NONE;
4046
4047 DEBUG2(VAR, "Var_Parse: %s with %s\n", start,
4048 Enum_FlagsToString(eflags_str, sizeof eflags_str, eflags,
4049 VarEvalFlags_ToStringSpecs));
4050
4051 *out_val = FStr_InitRefer(NULL);
4052 extramodifiers = NULL; /* extra modifiers to apply first */
4053 dynamic = FALSE;
4054
4055 /*
4056 * Appease GCC, which thinks that the variable might not be
4057 * initialized.
4058 */
4059 endc = '\0';
4060
4061 startc = p[1];
4062 if (startc != '(' && startc != '{') {
4063 VarParseResult res;
4064 if (!ParseVarnameShort(startc, pp, ctxt, eflags, &res,
4065 &out_val->str, &v))
4066 return res;
4067 haveModifier = FALSE;
4068 p++;
4069 } else {
4070 VarParseResult res;
4071 if (!ParseVarnameLong(p, startc, ctxt, eflags,
4072 pp, &res, out_val,
4073 &endc, &p, &v, &haveModifier, &extramodifiers,
4074 &dynamic, &exprFlags))
4075 return res;
4076 }
4077
4078 if (v->flags & VAR_IN_USE)
4079 Fatal("Variable %s is recursive.", v->name.str);
4080
4081 /*
4082 * XXX: This assignment creates an alias to the current value of the
4083 * variable. This means that as long as the value of the expression
4084 * stays the same, the value of the variable must not change.
4085 * Using the '::=' modifier, it could be possible to do exactly this.
4086 * At the bottom of this function, the resulting value is compared to
4087 * the then-current value of the variable. This might also invoke
4088 * undefined behavior.
4089 */
4090 value = MFStr_InitRefer(Buf_GetAll(&v->val, NULL));
4091
4092 /*
4093 * Before applying any modifiers, expand any nested expressions from
4094 * the variable value.
4095 */
4096 if (strchr(value.str, '$') != NULL && (eflags & VARE_WANTRES)) {
4097 char *expanded;
4098 VarEvalFlags nested_eflags = eflags;
4099 if (opts.lint)
4100 nested_eflags &= ~(unsigned)VARE_UNDEFERR;
4101 v->flags |= VAR_IN_USE;
4102 (void)Var_Subst(value.str, ctxt, nested_eflags, &expanded);
4103 v->flags &= ~(unsigned)VAR_IN_USE;
4104 /* TODO: handle errors */
4105 value = MFStr_InitOwn(expanded);
4106 }
4107
4108 if (haveModifier || extramodifiers != NULL) {
4109 if (extramodifiers != NULL) {
4110 const char *em = extramodifiers;
4111 value = ApplyModifiers(&em, value, '\0', '\0',
4112 v, &exprFlags, ctxt, eflags);
4113 }
4114
4115 if (haveModifier) {
4116 p++; /* Skip initial colon. */
4117
4118 value = ApplyModifiers(&p, value, startc, endc,
4119 v, &exprFlags, ctxt, eflags);
4120 }
4121 }
4122
4123 if (*p != '\0') /* Skip past endc if possible. */
4124 p++;
4125
4126 *pp = p;
4127
4128 if (v->flags & VAR_FROM_ENV) {
4129 FreeEnvVar(&value.freeIt, v, value.str);
4130
4131 } else if (exprFlags & VEF_UNDEF) {
4132 if (!(exprFlags & VEF_DEF)) {
4133 MFStr_Done(&value);
4134 if (dynamic) {
4135 value = MFStr_InitOwn(bmake_strsedup(start, p));
4136 } else {
4137 /*
4138 * The expression is still undefined,
4139 * therefore discard the actual value and
4140 * return an error marker instead.
4141 */
4142 value = MFStr_InitRefer(eflags & VARE_UNDEFERR
4143 ? var_Error : varUndefined);
4144 }
4145 }
4146 if (value.str != Buf_GetAll(&v->val, NULL))
4147 Buf_Destroy(&v->val, TRUE);
4148 FStr_Done(&v->name);
4149 free(v);
4150 }
4151 *out_val = (FStr){ value.str, value.freeIt };
4152 return VPR_UNKNOWN;
4153 }
4154
4155 static void
4156 VarSubstNested(const char **pp, Buffer *buf, GNode *ctxt,
4157 VarEvalFlags eflags, Boolean *inout_errorReported)
4158 {
4159 const char *p = *pp;
4160 const char *nested_p = p;
4161 FStr val;
4162
4163 (void)Var_Parse(&nested_p, ctxt, eflags, &val);
4164 /* TODO: handle errors */
4165
4166 if (val.str == var_Error || val.str == varUndefined) {
4167 if (!preserveUndefined) {
4168 p = nested_p;
4169 } else if ((eflags & VARE_UNDEFERR) || val.str == var_Error) {
4170
4171 /*
4172 * XXX: This condition is wrong. If val == var_Error,
4173 * this doesn't necessarily mean there was an undefined
4174 * variable. It could equally well be a parse error;
4175 * see unit-tests/varmod-order.exp.
4176 */
4177
4178 /*
4179 * If variable is undefined, complain and skip the
4180 * variable. The complaint will stop us from doing
4181 * anything when the file is parsed.
4182 */
4183 if (!*inout_errorReported) {
4184 Parse_Error(PARSE_FATAL,
4185 "Undefined variable \"%.*s\"",
4186 (int)(size_t)(nested_p - p), p);
4187 }
4188 p = nested_p;
4189 *inout_errorReported = TRUE;
4190 } else {
4191 /* Copy the initial '$' of the undefined expression,
4192 * thereby deferring expansion of the expression, but
4193 * expand nested expressions if already possible.
4194 * See unit-tests/varparse-undef-partial.mk. */
4195 Buf_AddByte(buf, *p);
4196 p++;
4197 }
4198 } else {
4199 p = nested_p;
4200 Buf_AddStr(buf, val.str);
4201 }
4202
4203 FStr_Done(&val);
4204
4205 *pp = p;
4206 }
4207
4208 /* Expand all variable expressions like $V, ${VAR}, $(VAR:Modifiers) in the
4209 * given string.
4210 *
4211 * Input:
4212 * str The string in which the variable expressions are
4213 * expanded.
4214 * ctxt The context in which to start searching for
4215 * variables. The other contexts are searched as well.
4216 * eflags Special effects during expansion.
4217 */
4218 VarParseResult
4219 Var_Subst(const char *str, GNode *ctxt, VarEvalFlags eflags, char **out_res)
4220 {
4221 const char *p = str;
4222 Buffer res;
4223
4224 /* Set true if an error has already been reported,
4225 * to prevent a plethora of messages when recursing */
4226 /* XXX: Why is the 'static' necessary here? */
4227 static Boolean errorReported;
4228
4229 Buf_Init(&res);
4230 errorReported = FALSE;
4231
4232 while (*p != '\0') {
4233 if (p[0] == '$' && p[1] == '$') {
4234 /*
4235 * A dollar sign may be escaped with another dollar
4236 * sign.
4237 */
4238 if (save_dollars && (eflags & VARE_KEEP_DOLLAR))
4239 Buf_AddByte(&res, '$');
4240 Buf_AddByte(&res, '$');
4241 p += 2;
4242
4243 } else if (p[0] == '$') {
4244 VarSubstNested(&p, &res, ctxt, eflags, &errorReported);
4245
4246 } else {
4247 /*
4248 * Skip as many characters as possible -- either to
4249 * the end of the string or to the next dollar sign
4250 * (variable expression).
4251 */
4252 const char *plainStart = p;
4253
4254 for (p++; *p != '$' && *p != '\0'; p++)
4255 continue;
4256 Buf_AddBytesBetween(&res, plainStart, p);
4257 }
4258 }
4259
4260 *out_res = Buf_DestroyCompact(&res);
4261 return VPR_OK;
4262 }
4263
4264 /* Initialize the variables module. */
4265 void
4266 Var_Init(void)
4267 {
4268 VAR_INTERNAL = GNode_New("Internal");
4269 VAR_GLOBAL = GNode_New("Global");
4270 VAR_CMDLINE = GNode_New("Command");
4271 }
4272
4273 /* Clean up the variables module. */
4274 void
4275 Var_End(void)
4276 {
4277 Var_Stats();
4278 }
4279
4280 void
4281 Var_Stats(void)
4282 {
4283 HashTable_DebugStats(&VAR_GLOBAL->vars, "VAR_GLOBAL");
4284 }
4285
4286 /* Print all variables in a context, sorted by name. */
4287 void
4288 Var_Dump(GNode *ctxt)
4289 {
4290 Vector /* of const char * */ vec;
4291 HashIter hi;
4292 size_t i;
4293 const char **varnames;
4294
4295 Vector_Init(&vec, sizeof(const char *));
4296
4297 HashIter_Init(&hi, &ctxt->vars);
4298 while (HashIter_Next(&hi) != NULL)
4299 *(const char **)Vector_Push(&vec) = hi.entry->key;
4300 varnames = vec.items;
4301
4302 qsort(varnames, vec.len, sizeof varnames[0], str_cmp_asc);
4303
4304 for (i = 0; i < vec.len; i++) {
4305 const char *varname = varnames[i];
4306 Var *var = HashTable_FindValue(&ctxt->vars, varname);
4307 debug_printf("%-16s = %s\n",
4308 varname, Buf_GetAll(&var->val, NULL));
4309 }
4310
4311 Vector_Done(&vec);
4312 }
4313