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