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