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