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