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