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