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