var.c revision 1.382 1 /* $NetBSD: var.c,v 1.382 2020/08/01 16:27:03 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 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: var.c,v 1.382 2020/08/01 16:27:03 rillig Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 #if 0
77 static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 3/19/94";
78 #else
79 __RCSID("$NetBSD: var.c,v 1.382 2020/08/01 16:27:03 rillig Exp $");
80 #endif
81 #endif /* not lint */
82 #endif
83
84 /*-
85 * var.c --
86 * Variable-handling functions
87 *
88 * Interface:
89 * Var_Set Set the value of a variable in the given
90 * context. The variable is created if it doesn't
91 * yet exist.
92 *
93 * Var_Append Append more characters to an existing variable
94 * in the given context. The variable needn't
95 * exist already -- it will be created if it doesn't.
96 * A space is placed between the old value and the
97 * new one.
98 *
99 * Var_Exists See if a variable exists.
100 *
101 * Var_Value Return the unexpanded value of a variable in a
102 * context or NULL if the variable is undefined.
103 *
104 * Var_Subst Substitute either a single variable or all
105 * variables in a string, using the given context.
106 *
107 * Var_Parse Parse a variable expansion from a string and
108 * return the result and the number of characters
109 * consumed.
110 *
111 * Var_Delete Delete a variable in a context.
112 *
113 * Var_Init Initialize this module.
114 *
115 * Debugging:
116 * Var_Dump Print out all variables defined in the given
117 * context.
118 *
119 * XXX: There's a lot of duplication in these functions.
120 */
121
122 #include <sys/stat.h>
123 #ifndef NO_REGEX
124 #include <sys/types.h>
125 #include <regex.h>
126 #endif
127 #include <assert.h>
128 #include <ctype.h>
129 #include <inttypes.h>
130 #include <limits.h>
131 #include <stdlib.h>
132 #include <time.h>
133
134 #include "make.h"
135 #include "buf.h"
136 #include "dir.h"
137 #include "job.h"
138 #include "metachar.h"
139
140 #define VAR_DEBUG(fmt, ...) \
141 if (!DEBUG(VAR)) \
142 (void) 0; \
143 else \
144 fprintf(debug_file, fmt, __VA_ARGS__)
145
146 /*
147 * This lets us tell if we have replaced the original environ
148 * (which we cannot free).
149 */
150 char **savedEnv = NULL;
151
152 /*
153 * This is a harmless return value for Var_Parse that can be used by Var_Subst
154 * to determine if there was an error in parsing -- easier than returning
155 * a flag, as things outside this module don't give a hoot.
156 */
157 char var_Error[] = "";
158
159 /*
160 * Similar to var_Error, but returned when the 'VARE_UNDEFERR' flag for
161 * Var_Parse is not set. Why not just use a constant? Well, GCC likes
162 * to condense identical string instances...
163 */
164 static char varNoError[] = "";
165
166 /*
167 * Traditionally we consume $$ during := like any other expansion.
168 * Other make's do not.
169 * This knob allows controlling the behavior.
170 * FALSE to consume $$ during := assignment.
171 * TRUE to preserve $$ during := assignment.
172 */
173 #define SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
174 static Boolean save_dollars = TRUE;
175
176 /*
177 * Internally, variables are contained in four different contexts.
178 * 1) the environment. They cannot be changed. If an environment
179 * variable is appended to, the result is placed in the global
180 * context.
181 * 2) the global context. Variables set in the Makefile are located in
182 * the global context.
183 * 3) the command-line context. All variables set on the command line
184 * are placed in this context. They are UNALTERABLE once placed here.
185 * 4) the local context. Each target has associated with it a context
186 * list. On this list are located the structures describing such
187 * local variables as $(@) and $(*)
188 * The four contexts are searched in the reverse order from which they are
189 * listed (but see checkEnvFirst).
190 */
191 GNode *VAR_INTERNAL; /* variables from make itself */
192 GNode *VAR_GLOBAL; /* variables from the makefile */
193 GNode *VAR_CMD; /* variables defined on the command-line */
194
195 typedef enum {
196 FIND_CMD = 0x01, /* look in VAR_CMD when searching */
197 FIND_GLOBAL = 0x02, /* look in VAR_GLOBAL as well */
198 FIND_ENV = 0x04 /* look in the environment also */
199 } VarFindFlags;
200
201 typedef enum {
202 VAR_IN_USE = 0x01, /* Variable's value is currently being used
203 * by Var_Parse or Var_Subst.
204 * Used to avoid endless recursion */
205 VAR_FROM_ENV = 0x02, /* Variable comes from the environment */
206 VAR_JUNK = 0x04, /* Variable is a junk variable that
207 * should be destroyed when done with
208 * it. Used by Var_Parse for undefined,
209 * modified variables */
210 VAR_KEEP = 0x08, /* Variable is VAR_JUNK, but we found
211 * a use for it in some modifier and
212 * the value is therefore valid */
213 VAR_EXPORTED = 0x10, /* Variable is exported */
214 VAR_REEXPORT = 0x20, /* Indicate if var needs re-export.
215 * This would be true if it contains $'s */
216 VAR_FROM_CMD = 0x40 /* Variable came from command line */
217 } Var_Flags;
218
219 typedef struct Var {
220 char *name; /* the variable's name */
221 Buffer val; /* its value */
222 Var_Flags flags; /* miscellaneous status flags */
223 } Var;
224
225 /*
226 * Exporting vars is expensive so skip it if we can
227 */
228 typedef enum {
229 VAR_EXPORTED_NONE,
230 VAR_EXPORTED_YES,
231 VAR_EXPORTED_ALL
232 } VarExportedMode;
233 static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE;
234
235 typedef enum {
236 /*
237 * We pass this to Var_Export when doing the initial export
238 * or after updating an exported var.
239 */
240 VAR_EXPORT_PARENT = 0x01,
241 /*
242 * We pass this to Var_Export1 to tell it to leave the value alone.
243 */
244 VAR_EXPORT_LITERAL = 0x02
245 } VarExportFlags;
246
247 /* Flags for pattern matching in the :S and :C modifiers */
248 typedef enum {
249 VARP_SUB_GLOBAL = 0x01, /* Apply substitution globally */
250 VARP_SUB_ONE = 0x02, /* Apply substitution to one word */
251 VARP_SUB_MATCHED = 0x04, /* There was a match */
252 VARP_ANCHOR_START = 0x08, /* Match at start of word */
253 VARP_ANCHOR_END = 0x10 /* Match at end of word */
254 } VarPatternFlags;
255
256 typedef enum {
257 VAR_NO_EXPORT = 0x01 /* do not export */
258 } VarSet_Flags;
259
260 #define BROPEN '{'
261 #define BRCLOSE '}'
262 #define PROPEN '('
263 #define PRCLOSE ')'
264
265 /*-
266 *-----------------------------------------------------------------------
267 * VarFind --
268 * Find the given variable in the given context and any other contexts
269 * indicated.
270 *
271 * Input:
272 * name name to find
273 * ctxt context in which to find it
274 * flags FIND_GLOBAL look in VAR_GLOBAL as well
275 * FIND_CMD look in VAR_CMD as well
276 * FIND_ENV look in the environment as well
277 *
278 * Results:
279 * A pointer to the structure describing the desired variable or
280 * NULL if the variable does not exist.
281 *
282 * Side Effects:
283 * None
284 *-----------------------------------------------------------------------
285 */
286 static Var *
287 VarFind(const char *name, GNode *ctxt, VarFindFlags flags)
288 {
289 /*
290 * If the variable name begins with a '.', it could very well be one of
291 * the local ones. We check the name against all the local variables
292 * and substitute the short version in for 'name' if it matches one of
293 * them.
294 */
295 if (*name == '.' && isupper((unsigned char) name[1])) {
296 switch (name[1]) {
297 case 'A':
298 if (strcmp(name, ".ALLSRC") == 0)
299 name = ALLSRC;
300 if (strcmp(name, ".ARCHIVE") == 0)
301 name = ARCHIVE;
302 break;
303 case 'I':
304 if (strcmp(name, ".IMPSRC") == 0)
305 name = IMPSRC;
306 break;
307 case 'M':
308 if (strcmp(name, ".MEMBER") == 0)
309 name = MEMBER;
310 break;
311 case 'O':
312 if (strcmp(name, ".OODATE") == 0)
313 name = OODATE;
314 break;
315 case 'P':
316 if (strcmp(name, ".PREFIX") == 0)
317 name = PREFIX;
318 break;
319 case 'T':
320 if (strcmp(name, ".TARGET") == 0)
321 name = TARGET;
322 break;
323 }
324 }
325
326 #ifdef notyet
327 /* for compatibility with gmake */
328 if (name[0] == '^' && name[1] == '\0')
329 name = ALLSRC;
330 #endif
331
332 /*
333 * First look for the variable in the given context. If it's not there,
334 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
335 * depending on the FIND_* flags in 'flags'
336 */
337 Hash_Entry *var = Hash_FindEntry(&ctxt->context, name);
338
339 if (var == NULL && (flags & FIND_CMD) && ctxt != VAR_CMD) {
340 var = Hash_FindEntry(&VAR_CMD->context, name);
341 }
342 if (!checkEnvFirst && var == NULL && (flags & FIND_GLOBAL) &&
343 ctxt != VAR_GLOBAL)
344 {
345 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
346 if (var == NULL && ctxt != VAR_INTERNAL) {
347 /* VAR_INTERNAL is subordinate to VAR_GLOBAL */
348 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
349 }
350 }
351 if (var == NULL && (flags & FIND_ENV)) {
352 char *env;
353
354 if ((env = getenv(name)) != NULL) {
355 Var *v = bmake_malloc(sizeof(Var));
356 v->name = bmake_strdup(name);
357
358 int len = (int)strlen(env);
359 Buf_Init(&v->val, len + 1);
360 Buf_AddBytes(&v->val, len, env);
361
362 v->flags = VAR_FROM_ENV;
363 return v;
364 } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
365 ctxt != VAR_GLOBAL)
366 {
367 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
368 if (var == NULL && ctxt != VAR_INTERNAL) {
369 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
370 }
371 if (var == NULL) {
372 return NULL;
373 } else {
374 return (Var *)Hash_GetValue(var);
375 }
376 } else {
377 return NULL;
378 }
379 } else if (var == NULL) {
380 return NULL;
381 } else {
382 return (Var *)Hash_GetValue(var);
383 }
384 }
385
386 /*-
387 *-----------------------------------------------------------------------
388 * VarFreeEnv --
389 * If the variable is an environment variable, free it
390 *
391 * Input:
392 * v the variable
393 * destroy true if the value buffer should be destroyed.
394 *
395 * Results:
396 * 1 if it is an environment variable 0 ow.
397 *
398 * Side Effects:
399 * The variable is free'ed if it is an environent variable.
400 *-----------------------------------------------------------------------
401 */
402 static Boolean
403 VarFreeEnv(Var *v, Boolean destroy)
404 {
405 if (!(v->flags & VAR_FROM_ENV))
406 return FALSE;
407 free(v->name);
408 Buf_Destroy(&v->val, destroy);
409 free(v);
410 return TRUE;
411 }
412
413 /*-
414 *-----------------------------------------------------------------------
415 * VarAdd --
416 * Add a new variable of name name and value val to the given context
417 *
418 * Input:
419 * name name of variable to add
420 * val value to set it to
421 * ctxt context in which to set it
422 *
423 * Side Effects:
424 * The new variable is placed at the front of the given context
425 * The name and val arguments are duplicated so they may
426 * safely be freed.
427 *-----------------------------------------------------------------------
428 */
429 static void
430 VarAdd(const char *name, const char *val, GNode *ctxt)
431 {
432 Var *v = bmake_malloc(sizeof(Var));
433
434 int len = val != NULL ? (int)strlen(val) : 0;
435 Buf_Init(&v->val, len + 1);
436 Buf_AddBytes(&v->val, len, val);
437
438 v->flags = 0;
439
440 Hash_Entry *h = Hash_CreateEntry(&ctxt->context, name, NULL);
441 Hash_SetValue(h, v);
442 v->name = h->name;
443 if (DEBUG(VAR) && !(ctxt->flags & INTERNAL)) {
444 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
445 }
446 }
447
448 /*-
449 *-----------------------------------------------------------------------
450 * Var_Delete --
451 * Remove a variable from a context.
452 *
453 * Side Effects:
454 * The Var structure is removed and freed.
455 *
456 *-----------------------------------------------------------------------
457 */
458 void
459 Var_Delete(const char *name, GNode *ctxt)
460 {
461 Hash_Entry *ln;
462 char *cp;
463
464 if (strchr(name, '$') != NULL) {
465 cp = Var_Subst(name, VAR_GLOBAL, VARE_WANTRES);
466 } else {
467 cp = UNCONST(name);
468 }
469 ln = Hash_FindEntry(&ctxt->context, cp);
470 if (DEBUG(VAR)) {
471 fprintf(debug_file, "%s:delete %s%s\n",
472 ctxt->name, cp, ln ? "" : " (not found)");
473 }
474 if (cp != name)
475 free(cp);
476 if (ln != NULL) {
477 Var *v = (Var *)Hash_GetValue(ln);
478 if (v->flags & VAR_EXPORTED)
479 unsetenv(v->name);
480 if (strcmp(MAKE_EXPORTED, v->name) == 0)
481 var_exportedVars = VAR_EXPORTED_NONE;
482 if (v->name != ln->name)
483 free(v->name);
484 Hash_DeleteEntry(&ctxt->context, ln);
485 Buf_Destroy(&v->val, TRUE);
486 free(v);
487 }
488 }
489
490
491 /*
492 * Export a var.
493 * We ignore make internal variables (those which start with '.')
494 * Also we jump through some hoops to avoid calling setenv
495 * more than necessary since it can leak.
496 * We only manipulate flags of vars if 'parent' is set.
497 */
498 static int
499 Var_Export1(const char *name, VarExportFlags flags)
500 {
501 char tmp[BUFSIZ];
502 Var *v;
503 char *val = NULL;
504 int n;
505 VarExportFlags parent = flags & VAR_EXPORT_PARENT;
506
507 if (*name == '.')
508 return 0; /* skip internals */
509 if (!name[1]) {
510 /*
511 * A single char.
512 * If it is one of the vars that should only appear in
513 * local context, skip it, else we can get Var_Subst
514 * into a loop.
515 */
516 switch (name[0]) {
517 case '@':
518 case '%':
519 case '*':
520 case '!':
521 return 0;
522 }
523 }
524 v = VarFind(name, VAR_GLOBAL, 0);
525 if (v == NULL)
526 return 0;
527 if (!parent && (v->flags & VAR_EXPORTED) && !(v->flags & VAR_REEXPORT))
528 return 0; /* nothing to do */
529 val = Buf_GetAll(&v->val, NULL);
530 if (!(flags & VAR_EXPORT_LITERAL) && strchr(val, '$')) {
531 if (parent) {
532 /*
533 * Flag this as something we need to re-export.
534 * No point actually exporting it now though,
535 * the child can do it at the last minute.
536 */
537 v->flags |= VAR_EXPORTED | VAR_REEXPORT;
538 return 1;
539 }
540 if (v->flags & VAR_IN_USE) {
541 /*
542 * We recursed while exporting in a child.
543 * This isn't going to end well, just skip it.
544 */
545 return 0;
546 }
547 n = snprintf(tmp, sizeof(tmp), "${%s}", name);
548 if (n < (int)sizeof(tmp)) {
549 val = Var_Subst(tmp, VAR_GLOBAL, VARE_WANTRES);
550 setenv(name, val, 1);
551 free(val);
552 }
553 } else {
554 if (parent)
555 v->flags &= ~VAR_REEXPORT; /* once will do */
556 if (parent || !(v->flags & VAR_EXPORTED))
557 setenv(name, val, 1);
558 }
559 /*
560 * This is so Var_Set knows to call Var_Export again...
561 */
562 if (parent) {
563 v->flags |= VAR_EXPORTED;
564 }
565 return 1;
566 }
567
568 static void
569 Var_ExportVars_callback(void *entry, void *unused MAKE_ATTR_UNUSED)
570 {
571 Var *var = entry;
572 Var_Export1(var->name, 0);
573 }
574
575 /*
576 * This gets called from our children.
577 */
578 void
579 Var_ExportVars(void)
580 {
581 char tmp[BUFSIZ];
582 char *val;
583
584 /*
585 * Several make's support this sort of mechanism for tracking
586 * recursion - but each uses a different name.
587 * We allow the makefiles to update MAKELEVEL and ensure
588 * children see a correctly incremented value.
589 */
590 snprintf(tmp, sizeof(tmp), "%d", makelevel + 1);
591 setenv(MAKE_LEVEL_ENV, tmp, 1);
592
593 if (VAR_EXPORTED_NONE == var_exportedVars)
594 return;
595
596 if (VAR_EXPORTED_ALL == var_exportedVars) {
597 /* Ouch! This is crazy... */
598 Hash_ForEach(&VAR_GLOBAL->context, Var_ExportVars_callback, NULL);
599 return;
600 }
601
602 val = Var_Subst("${" MAKE_EXPORTED ":O:u}", VAR_GLOBAL, VARE_WANTRES);
603 if (*val) {
604 char **av;
605 char *as;
606 int ac;
607 int i;
608
609 av = brk_string(val, &ac, FALSE, &as);
610 for (i = 0; i < ac; i++)
611 Var_Export1(av[i], 0);
612 free(as);
613 free(av);
614 }
615 free(val);
616 }
617
618 /*
619 * This is called when .export is seen or
620 * .MAKE.EXPORTED is modified.
621 * It is also called when any exported var is modified.
622 */
623 void
624 Var_Export(char *str, int isExport)
625 {
626 char **av;
627 char *as;
628 VarExportFlags flags;
629 int ac;
630 int i;
631
632 if (isExport && (!str || !str[0])) {
633 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
634 return;
635 }
636
637 flags = 0;
638 if (strncmp(str, "-env", 4) == 0) {
639 str += 4;
640 } else if (strncmp(str, "-literal", 8) == 0) {
641 str += 8;
642 flags |= VAR_EXPORT_LITERAL;
643 } else {
644 flags |= VAR_EXPORT_PARENT;
645 }
646
647 char *val = Var_Subst(str, VAR_GLOBAL, VARE_WANTRES);
648 if (*val) {
649 av = brk_string(val, &ac, FALSE, &as);
650 for (i = 0; i < ac; i++) {
651 const char *name = av[i];
652 if (!name[1]) {
653 /*
654 * A single char.
655 * If it is one of the vars that should only appear in
656 * local context, skip it, else we can get Var_Subst
657 * into a loop.
658 */
659 switch (name[0]) {
660 case '@':
661 case '%':
662 case '*':
663 case '!':
664 continue;
665 }
666 }
667 if (Var_Export1(name, flags)) {
668 if (VAR_EXPORTED_ALL != var_exportedVars)
669 var_exportedVars = VAR_EXPORTED_YES;
670 if (isExport && (flags & VAR_EXPORT_PARENT)) {
671 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
672 }
673 }
674 }
675 free(as);
676 free(av);
677 }
678 free(val);
679 }
680
681
682 extern char **environ;
683
684 /*
685 * This is called when .unexport[-env] is seen.
686 *
687 * str must have the form "unexport[-env] varname...".
688 */
689 void
690 Var_UnExport(char *str)
691 {
692 char tmp[BUFSIZ];
693 char *vlist;
694 char *cp;
695 Boolean unexport_env;
696 int n;
697
698 vlist = NULL;
699
700 str += strlen("unexport");
701 unexport_env = strncmp(str, "-env", 4) == 0;
702 if (unexport_env) {
703 char **newenv;
704
705 cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */
706 if (environ == savedEnv) {
707 /* we have been here before! */
708 newenv = bmake_realloc(environ, 2 * sizeof(char *));
709 } else {
710 if (savedEnv) {
711 free(savedEnv);
712 savedEnv = NULL;
713 }
714 newenv = bmake_malloc(2 * sizeof(char *));
715 }
716 if (!newenv)
717 return;
718 /* Note: we cannot safely free() the original environ. */
719 environ = savedEnv = newenv;
720 newenv[0] = NULL;
721 newenv[1] = NULL;
722 if (cp && *cp)
723 setenv(MAKE_LEVEL_ENV, cp, 1);
724 } else {
725 for (; *str != '\n' && isspace((unsigned char) *str); str++)
726 continue;
727 if (str[0] && str[0] != '\n') {
728 vlist = str;
729 }
730 }
731
732 if (!vlist) {
733 /* Using .MAKE.EXPORTED */
734 vlist = Var_Subst("${" MAKE_EXPORTED ":O:u}", VAR_GLOBAL,
735 VARE_WANTRES);
736 }
737 if (vlist) {
738 Var *v;
739 char **av;
740 char *as;
741 int ac;
742 int i;
743
744 av = brk_string(vlist, &ac, FALSE, &as);
745 for (i = 0; i < ac; i++) {
746 v = VarFind(av[i], VAR_GLOBAL, 0);
747 if (!v)
748 continue;
749 if (!unexport_env &&
750 (v->flags & (VAR_EXPORTED | VAR_REEXPORT)) == VAR_EXPORTED)
751 unsetenv(v->name);
752 v->flags &= ~(VAR_EXPORTED | VAR_REEXPORT);
753 /*
754 * If we are unexporting a list,
755 * remove each one from .MAKE.EXPORTED.
756 * If we are removing them all,
757 * just delete .MAKE.EXPORTED below.
758 */
759 if (vlist == str) {
760 n = snprintf(tmp, sizeof(tmp),
761 "${" MAKE_EXPORTED ":N%s}", v->name);
762 if (n < (int)sizeof(tmp)) {
763 cp = Var_Subst(tmp, VAR_GLOBAL, VARE_WANTRES);
764 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL);
765 free(cp);
766 }
767 }
768 }
769 free(as);
770 free(av);
771 if (vlist != str) {
772 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
773 free(vlist);
774 }
775 }
776 }
777
778 static void
779 Var_Set_with_flags(const char *name, const char *val, GNode *ctxt,
780 VarSet_Flags flags)
781 {
782 Var *v;
783 char *name_freeIt = NULL;
784
785 /*
786 * We only look for a variable in the given context since anything set
787 * here will override anything in a lower context, so there's not much
788 * point in searching them all just to save a bit of memory...
789 */
790 if (strchr(name, '$') != NULL) {
791 const char *unexpanded_name = name;
792 name = name_freeIt = Var_Subst(name, ctxt, VARE_WANTRES);
793 if (name[0] == '\0') {
794 if (DEBUG(VAR)) {
795 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
796 "name expands to empty string - ignored\n",
797 unexpanded_name, val);
798 }
799 free(name_freeIt);
800 return;
801 }
802 }
803 if (ctxt == VAR_GLOBAL) {
804 v = VarFind(name, VAR_CMD, 0);
805 if (v != NULL) {
806 if (v->flags & VAR_FROM_CMD) {
807 if (DEBUG(VAR)) {
808 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
809 }
810 goto out;
811 }
812 VarFreeEnv(v, TRUE);
813 }
814 }
815 v = VarFind(name, ctxt, 0);
816 if (v == NULL) {
817 if (ctxt == VAR_CMD && !(flags & VAR_NO_EXPORT)) {
818 /*
819 * This var would normally prevent the same name being added
820 * to VAR_GLOBAL, so delete it from there if needed.
821 * Otherwise -V name may show the wrong value.
822 */
823 Var_Delete(name, VAR_GLOBAL);
824 }
825 VarAdd(name, val, ctxt);
826 } else {
827 Buf_Empty(&v->val);
828 if (val)
829 Buf_AddStr(&v->val, val);
830
831 if (DEBUG(VAR)) {
832 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
833 }
834 if (v->flags & VAR_EXPORTED) {
835 Var_Export1(name, VAR_EXPORT_PARENT);
836 }
837 }
838 /*
839 * Any variables given on the command line are automatically exported
840 * to the environment (as per POSIX standard)
841 */
842 if (ctxt == VAR_CMD && !(flags & VAR_NO_EXPORT)) {
843 if (v == NULL) {
844 /* we just added it */
845 v = VarFind(name, ctxt, 0);
846 }
847 if (v != NULL)
848 v->flags |= VAR_FROM_CMD;
849 /*
850 * If requested, don't export these in the environment
851 * individually. We still put them in MAKEOVERRIDES so
852 * that the command-line settings continue to override
853 * Makefile settings.
854 */
855 if (varNoExportEnv != TRUE)
856 setenv(name, val ? val : "", 1);
857
858 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
859 }
860 if (name[0] == '.' && strcmp(name, SAVE_DOLLARS) == 0)
861 save_dollars = s2Boolean(val, save_dollars);
862
863 out:
864 free(name_freeIt);
865 if (v != NULL)
866 VarFreeEnv(v, TRUE);
867 }
868
869 /*-
870 *-----------------------------------------------------------------------
871 * Var_Set --
872 * Set the variable name to the value val in the given context.
873 *
874 * Input:
875 * name name of variable to set
876 * val value to give to the variable
877 * ctxt context in which to set it
878 *
879 * Side Effects:
880 * If the variable doesn't yet exist, a new record is created for it.
881 * Else the old value is freed and the new one stuck in its place
882 *
883 * Notes:
884 * The variable is searched for only in its context before being
885 * created in that context. I.e. if the context is VAR_GLOBAL,
886 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
887 * VAR_CMD->context is searched. This is done to avoid the literally
888 * thousands of unnecessary strcmp's that used to be done to
889 * set, say, $(@) or $(<).
890 * If the context is VAR_GLOBAL though, we check if the variable
891 * was set in VAR_CMD from the command line and skip it if so.
892 *-----------------------------------------------------------------------
893 */
894 void
895 Var_Set(const char *name, const char *val, GNode *ctxt)
896 {
897 Var_Set_with_flags(name, val, ctxt, 0);
898 }
899
900 /*-
901 *-----------------------------------------------------------------------
902 * Var_Append --
903 * The variable of the given name has the given value appended to it in
904 * the given context.
905 *
906 * Input:
907 * name name of variable to modify
908 * val String to append to it
909 * ctxt Context in which this should occur
910 *
911 * Side Effects:
912 * If the variable doesn't exist, it is created. Else the strings
913 * are concatenated (with a space in between).
914 *
915 * Notes:
916 * Only if the variable is being sought in the global context is the
917 * environment searched.
918 * XXX: Knows its calling circumstances in that if called with ctxt
919 * an actual target, it will only search that context since only
920 * a local variable could be being appended to. This is actually
921 * a big win and must be tolerated.
922 *-----------------------------------------------------------------------
923 */
924 void
925 Var_Append(const char *name, const char *val, GNode *ctxt)
926 {
927 Var *v;
928 Hash_Entry *h;
929 char *expanded_name = NULL;
930
931 if (strchr(name, '$') != NULL) {
932 expanded_name = Var_Subst(name, ctxt, VARE_WANTRES);
933 if (expanded_name[0] == '\0') {
934 if (DEBUG(VAR)) {
935 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
936 "name expands to empty string - ignored\n",
937 name, val);
938 }
939 free(expanded_name);
940 return;
941 }
942 name = expanded_name;
943 }
944
945 v = VarFind(name, ctxt, ctxt == VAR_GLOBAL ? (FIND_CMD | FIND_ENV) : 0);
946
947 if (v == NULL) {
948 Var_Set(name, val, ctxt);
949 } else if (ctxt == VAR_CMD || !(v->flags & VAR_FROM_CMD)) {
950 Buf_AddByte(&v->val, ' ');
951 Buf_AddStr(&v->val, val);
952
953 if (DEBUG(VAR)) {
954 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
955 Buf_GetAll(&v->val, NULL));
956 }
957
958 if (v->flags & VAR_FROM_ENV) {
959 /*
960 * If the original variable came from the environment, we
961 * have to install it in the global context (we could place
962 * it in the environment, but then we should provide a way to
963 * export other variables...)
964 */
965 v->flags &= ~VAR_FROM_ENV;
966 h = Hash_CreateEntry(&ctxt->context, name, NULL);
967 Hash_SetValue(h, v);
968 }
969 }
970 free(expanded_name);
971 }
972
973 /*-
974 *-----------------------------------------------------------------------
975 * Var_Exists --
976 * See if the given variable exists.
977 *
978 * Input:
979 * name Variable to find
980 * ctxt Context in which to start search
981 *
982 * Results:
983 * TRUE if it does, FALSE if it doesn't
984 *
985 * Side Effects:
986 * None.
987 *
988 *-----------------------------------------------------------------------
989 */
990 Boolean
991 Var_Exists(const char *name, GNode *ctxt)
992 {
993 char *name_freeIt = NULL;
994 if (strchr(name, '$') != NULL)
995 name = name_freeIt = Var_Subst(name, ctxt, VARE_WANTRES);
996
997 Var *v = VarFind(name, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
998 free(name_freeIt);
999 if (v == NULL)
1000 return FALSE;
1001
1002 (void)VarFreeEnv(v, TRUE);
1003 return TRUE;
1004 }
1005
1006 /*-
1007 *-----------------------------------------------------------------------
1008 * Var_Value --
1009 * Return the unexpanded value of the given variable in the given
1010 * context, or the usual contexts.
1011 *
1012 * Input:
1013 * name name to find
1014 * ctxt context in which to search for it
1015 *
1016 * Results:
1017 * The value if the variable exists, NULL if it doesn't.
1018 * If the returned value is not NULL, the caller must free *freeIt
1019 * as soon as the returned value is no longer needed.
1020 *-----------------------------------------------------------------------
1021 */
1022 const char *
1023 Var_Value(const char *name, GNode *ctxt, char **freeIt)
1024 {
1025 Var *v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1026 *freeIt = NULL;
1027 if (v == NULL)
1028 return NULL;
1029
1030 char *p = Buf_GetAll(&v->val, NULL);
1031 if (VarFreeEnv(v, FALSE))
1032 *freeIt = p;
1033 return p;
1034 }
1035
1036
1037 /* SepBuf is a string being built from "words", interleaved with separators. */
1038 typedef struct {
1039 Buffer buf;
1040 Boolean needSep;
1041 char sep;
1042 } SepBuf;
1043
1044 static void
1045 SepBuf_Init(SepBuf *buf, char sep)
1046 {
1047 Buf_Init(&buf->buf, 32 /* bytes */);
1048 buf->needSep = FALSE;
1049 buf->sep = sep;
1050 }
1051
1052 static void
1053 SepBuf_Sep(SepBuf *buf)
1054 {
1055 buf->needSep = TRUE;
1056 }
1057
1058 static void
1059 SepBuf_AddBytes(SepBuf *buf, const char *mem, size_t mem_size)
1060 {
1061 if (mem_size == 0)
1062 return;
1063 if (buf->needSep && buf->sep != '\0') {
1064 Buf_AddByte(&buf->buf, buf->sep);
1065 buf->needSep = FALSE;
1066 }
1067 Buf_AddBytes(&buf->buf, mem_size, mem);
1068 }
1069
1070 static void
1071 SepBuf_AddBytesBetween(SepBuf *buf, const char *start, const char *end)
1072 {
1073 SepBuf_AddBytes(buf, start, (size_t)(end - start));
1074 }
1075
1076 static void
1077 SepBuf_AddStr(SepBuf *buf, const char *str)
1078 {
1079 SepBuf_AddBytes(buf, str, strlen(str));
1080 }
1081
1082 static char *
1083 SepBuf_Destroy(SepBuf *buf, Boolean free_buf)
1084 {
1085 return Buf_Destroy(&buf->buf, free_buf);
1086 }
1087
1088
1089 /* This callback for ModifyWords gets a single word from an expression and
1090 * typically adds a modification of this word to the buffer. It may also do
1091 * nothing or add several words. */
1092 typedef void (*ModifyWordsCallback)(const char *word, SepBuf *buf, void *data);
1093
1094
1095 /* Callback for ModifyWords to implement the :H modifier.
1096 * Add the dirname of the given word to the buffer. */
1097 static void
1098 ModifyWord_Head(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1099 {
1100 const char *slash = strrchr(word, '/');
1101 if (slash != NULL)
1102 SepBuf_AddBytesBetween(buf, word, slash);
1103 else
1104 SepBuf_AddStr(buf, ".");
1105 }
1106
1107 /* Callback for ModifyWords to implement the :T modifier.
1108 * Add the basename of the given word to the buffer. */
1109 static void
1110 ModifyWord_Tail(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1111 {
1112 const char *slash = strrchr(word, '/');
1113 const char *base = slash != NULL ? slash + 1 : word;
1114 SepBuf_AddStr(buf, base);
1115 }
1116
1117 /* Callback for ModifyWords to implement the :E modifier.
1118 * Add the filename suffix of the given word to the buffer, if it exists. */
1119 static void
1120 ModifyWord_Suffix(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1121 {
1122 const char *dot = strrchr(word, '.');
1123 if (dot != NULL)
1124 SepBuf_AddStr(buf, dot + 1);
1125 }
1126
1127 /* Callback for ModifyWords to implement the :R modifier.
1128 * Add the basename of the given word to the buffer. */
1129 static void
1130 ModifyWord_Root(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1131 {
1132 const char *dot = strrchr(word, '.');
1133 size_t len = dot != NULL ? (size_t)(dot - word) : strlen(word);
1134 SepBuf_AddBytes(buf, word, len);
1135 }
1136
1137 /* Callback for ModifyWords to implement the :M modifier.
1138 * Place the word in the buffer if it matches the given pattern. */
1139 static void
1140 ModifyWord_Match(const char *word, SepBuf *buf, void *data)
1141 {
1142 const char *pattern = data;
1143 if (DEBUG(VAR))
1144 fprintf(debug_file, "VarMatch [%s] [%s]\n", word, pattern);
1145 if (Str_Match(word, pattern))
1146 SepBuf_AddStr(buf, word);
1147 }
1148
1149 /* Callback for ModifyWords to implement the :N modifier.
1150 * Place the word in the buffer if it doesn't match the given pattern. */
1151 static void
1152 ModifyWord_NoMatch(const char *word, SepBuf *buf, void *data)
1153 {
1154 const char *pattern = data;
1155 if (!Str_Match(word, pattern))
1156 SepBuf_AddStr(buf, word);
1157 }
1158
1159 #ifdef SYSVVARSUB
1160 /*-
1161 *-----------------------------------------------------------------------
1162 * Str_SYSVMatch --
1163 * Check word against pattern for a match (% is wild),
1164 *
1165 * Input:
1166 * word Word to examine
1167 * pattern Pattern to examine against
1168 *
1169 * Results:
1170 * Returns the start of the match, or NULL.
1171 * *match_len returns the length of the match, if any.
1172 * *hasPercent returns whether the pattern contains a percent.
1173 *-----------------------------------------------------------------------
1174 */
1175 static const char *
1176 Str_SYSVMatch(const char *word, const char *pattern, size_t *match_len,
1177 Boolean *hasPercent)
1178 {
1179 const char *p = pattern;
1180 const char *w = word;
1181
1182 *hasPercent = FALSE;
1183 if (*p == '\0') { /* ${VAR:=suffix} */
1184 *match_len = strlen(w); /* Null pattern is the whole string */
1185 return w;
1186 }
1187
1188 const char *percent = strchr(p, '%');
1189 if (percent != NULL) { /* ${VAR:...%...=...} */
1190 *hasPercent = TRUE;
1191 if (*w == '\0')
1192 return NULL; /* empty word does not match pattern */
1193
1194 /* check that the prefix matches */
1195 for (; p != percent && *w != '\0' && *w == *p; w++, p++)
1196 continue;
1197 if (p != percent)
1198 return NULL; /* No match */
1199
1200 p++; /* Skip the percent */
1201 if (*p == '\0') {
1202 /* No more pattern, return the rest of the string */
1203 *match_len = strlen(w);
1204 return w;
1205 }
1206 }
1207
1208 /* Test whether the tail matches */
1209 size_t w_len = strlen(w);
1210 size_t p_len = strlen(p);
1211 if (w_len < p_len)
1212 return NULL;
1213
1214 const char *w_tail = w + w_len - p_len;
1215 if (memcmp(p, w_tail, p_len) != 0)
1216 return NULL;
1217
1218 *match_len = w_tail - w;
1219 return w;
1220 }
1221
1222 typedef struct {
1223 GNode *ctx;
1224 const char *lhs;
1225 const char *rhs;
1226 } ModifyWord_SYSVSubstArgs;
1227
1228 /* Callback for ModifyWords to implement the :%.from=%.to modifier. */
1229 static void
1230 ModifyWord_SYSVSubst(const char *word, SepBuf *buf, void *data)
1231 {
1232 const ModifyWord_SYSVSubstArgs *args = data;
1233
1234 size_t match_len;
1235 Boolean lhsPercent;
1236 const char *match = Str_SYSVMatch(word, args->lhs, &match_len, &lhsPercent);
1237 if (match == NULL) {
1238 SepBuf_AddStr(buf, word);
1239 return;
1240 }
1241
1242 /* Append rhs to the buffer, substituting the first '%' with the
1243 * match, but only if the lhs had a '%' as well. */
1244
1245 char *rhs_expanded = Var_Subst(args->rhs, args->ctx, VARE_WANTRES);
1246
1247 const char *rhs = rhs_expanded;
1248 const char *percent = strchr(rhs, '%');
1249
1250 if (percent != NULL && lhsPercent) {
1251 /* Copy the prefix of the replacement pattern */
1252 SepBuf_AddBytesBetween(buf, rhs, percent);
1253 rhs = percent + 1;
1254 }
1255 if (percent != NULL || !lhsPercent)
1256 SepBuf_AddBytes(buf, match, match_len);
1257
1258 /* Append the suffix of the replacement pattern */
1259 SepBuf_AddStr(buf, rhs);
1260
1261 free(rhs_expanded);
1262 }
1263 #endif
1264
1265
1266 typedef struct {
1267 const char *lhs;
1268 size_t lhsLen;
1269 const char *rhs;
1270 size_t rhsLen;
1271 VarPatternFlags pflags;
1272 } ModifyWord_SubstArgs;
1273
1274 /* Callback for ModifyWords to implement the :S,from,to, modifier.
1275 * Perform a string substitution on the given word. */
1276 static void
1277 ModifyWord_Subst(const char *word, SepBuf *buf, void *data)
1278 {
1279 size_t wordLen = strlen(word);
1280 ModifyWord_SubstArgs *args = data;
1281 const VarPatternFlags pflags = args->pflags;
1282
1283 if ((pflags & VARP_SUB_ONE) && (pflags & VARP_SUB_MATCHED))
1284 goto nosub;
1285
1286 if (args->pflags & VARP_ANCHOR_START) {
1287 if (wordLen < args->lhsLen ||
1288 memcmp(word, args->lhs, args->lhsLen) != 0)
1289 goto nosub;
1290
1291 if (args->pflags & VARP_ANCHOR_END) {
1292 if (wordLen != args->lhsLen)
1293 goto nosub;
1294
1295 SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
1296 args->pflags |= VARP_SUB_MATCHED;
1297 } else {
1298 SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
1299 SepBuf_AddBytes(buf, word + args->lhsLen, wordLen - args->lhsLen);
1300 args->pflags |= VARP_SUB_MATCHED;
1301 }
1302 return;
1303 }
1304
1305 if (args->pflags & VARP_ANCHOR_END) {
1306 if (wordLen < args->lhsLen)
1307 goto nosub;
1308
1309 const char *start = word + (wordLen - args->lhsLen);
1310 if (memcmp(start, args->lhs, args->lhsLen) != 0)
1311 goto nosub;
1312
1313 SepBuf_AddBytesBetween(buf, word, start);
1314 SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
1315 args->pflags |= VARP_SUB_MATCHED;
1316 return;
1317 }
1318
1319 /* unanchored */
1320 const char *match;
1321 while ((match = Str_FindSubstring(word, args->lhs)) != NULL) {
1322 SepBuf_AddBytesBetween(buf, word, match);
1323 SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
1324 args->pflags |= VARP_SUB_MATCHED;
1325 wordLen -= (match - word) + args->lhsLen;
1326 word += (match - word) + args->lhsLen;
1327 if (wordLen == 0 || !(args->pflags & VARP_SUB_GLOBAL))
1328 break;
1329 }
1330 nosub:
1331 SepBuf_AddBytes(buf, word, wordLen);
1332 }
1333
1334 #ifndef NO_REGEX
1335 /*-
1336 *-----------------------------------------------------------------------
1337 * VarREError --
1338 * Print the error caused by a regcomp or regexec call.
1339 *
1340 * Side Effects:
1341 * An error gets printed.
1342 *
1343 *-----------------------------------------------------------------------
1344 */
1345 static void
1346 VarREError(int reerr, regex_t *pat, const char *str)
1347 {
1348 char *errbuf;
1349 int errlen;
1350
1351 errlen = regerror(reerr, pat, 0, 0);
1352 errbuf = bmake_malloc(errlen);
1353 regerror(reerr, pat, errbuf, errlen);
1354 Error("%s: %s", str, errbuf);
1355 free(errbuf);
1356 }
1357
1358 typedef struct {
1359 regex_t re;
1360 int nsub;
1361 char *replace;
1362 VarPatternFlags pflags;
1363 } ModifyWord_SubstRegexArgs;
1364
1365 /* Callback for ModifyWords to implement the :C/from/to/ modifier.
1366 * Perform a regex substitution on the given word. */
1367 static void
1368 ModifyWord_SubstRegex(const char *word, SepBuf *buf, void *data)
1369 {
1370 ModifyWord_SubstRegexArgs *args = data;
1371 int xrv;
1372 const char *wp = word;
1373 char *rp;
1374 int flags = 0;
1375 regmatch_t m[10];
1376
1377 if ((args->pflags & VARP_SUB_ONE) && (args->pflags & VARP_SUB_MATCHED))
1378 goto nosub;
1379
1380 tryagain:
1381 xrv = regexec(&args->re, wp, args->nsub, m, flags);
1382
1383 switch (xrv) {
1384 case 0:
1385 args->pflags |= VARP_SUB_MATCHED;
1386 SepBuf_AddBytes(buf, wp, m[0].rm_so);
1387
1388 for (rp = args->replace; *rp; rp++) {
1389 if (*rp == '\\' && (rp[1] == '&' || rp[1] == '\\')) {
1390 SepBuf_AddBytes(buf, rp + 1, 1);
1391 rp++;
1392 } else if (*rp == '&' ||
1393 (*rp == '\\' && isdigit((unsigned char)rp[1]))) {
1394 int n;
1395 char errstr[3];
1396
1397 if (*rp == '&') {
1398 n = 0;
1399 errstr[0] = '&';
1400 errstr[1] = '\0';
1401 } else {
1402 n = rp[1] - '0';
1403 errstr[0] = '\\';
1404 errstr[1] = rp[1];
1405 errstr[2] = '\0';
1406 rp++;
1407 }
1408
1409 if (n >= args->nsub) {
1410 Error("No subexpression %s", errstr);
1411 } else if (m[n].rm_so == -1 && m[n].rm_eo == -1) {
1412 Error("No match for subexpression %s", errstr);
1413 } else {
1414 SepBuf_AddBytesBetween(buf, wp + m[n].rm_so,
1415 wp + m[n].rm_eo);
1416 }
1417
1418 } else {
1419 SepBuf_AddBytes(buf, rp, 1);
1420 }
1421 }
1422 wp += m[0].rm_eo;
1423 if (args->pflags & VARP_SUB_GLOBAL) {
1424 flags |= REG_NOTBOL;
1425 if (m[0].rm_so == 0 && m[0].rm_eo == 0) {
1426 SepBuf_AddBytes(buf, wp, 1);
1427 wp++;
1428 }
1429 if (*wp)
1430 goto tryagain;
1431 }
1432 if (*wp) {
1433 SepBuf_AddStr(buf, wp);
1434 }
1435 break;
1436 default:
1437 VarREError(xrv, &args->re, "Unexpected regex error");
1438 /* fall through */
1439 case REG_NOMATCH:
1440 nosub:
1441 SepBuf_AddStr(buf, wp);
1442 break;
1443 }
1444 }
1445 #endif
1446
1447
1448 typedef struct {
1449 GNode *ctx;
1450 char *tvar; /* name of temporary variable */
1451 char *str; /* string to expand */
1452 VarEvalFlags eflags;
1453 } ModifyWord_LoopArgs;
1454
1455 /* Callback for ModifyWords to implement the :@var (at) ...@ modifier of ODE make. */
1456 static void
1457 ModifyWord_Loop(const char *word, SepBuf *buf, void *data)
1458 {
1459 if (word[0] == '\0')
1460 return;
1461
1462 const ModifyWord_LoopArgs *args = data;
1463 Var_Set_with_flags(args->tvar, word, args->ctx, VAR_NO_EXPORT);
1464 char *s = Var_Subst(args->str, args->ctx, args->eflags);
1465 if (DEBUG(VAR)) {
1466 fprintf(debug_file,
1467 "ModifyWord_Loop: in \"%s\", replace \"%s\" with \"%s\" "
1468 "to \"%s\"\n",
1469 word, args->tvar, args->str, s ? s : "(null)");
1470 }
1471
1472 if (s != NULL && s[0] != '\0') {
1473 if (s[0] == '\n' || (buf->buf.count > 0 &&
1474 buf->buf.buffer[buf->buf.count - 1] == '\n'))
1475 buf->needSep = FALSE;
1476 SepBuf_AddStr(buf, s);
1477 }
1478 free(s);
1479 }
1480
1481
1482 /*-
1483 * Implements the :[first..last] modifier.
1484 * This is a special case of ModifyWords since we want to be able
1485 * to scan the list backwards if first > last.
1486 */
1487 static char *
1488 VarSelectWords(Byte sep, Boolean oneBigWord, const char *str, int first,
1489 int last)
1490 {
1491 SepBuf buf;
1492 char **av; /* word list */
1493 char *as; /* word list memory */
1494 int ac, i;
1495 int start, end, step;
1496
1497 SepBuf_Init(&buf, sep);
1498
1499 if (oneBigWord) {
1500 /* fake what brk_string() would do if there were only one word */
1501 ac = 1;
1502 av = bmake_malloc((ac + 1) * sizeof(char *));
1503 as = bmake_strdup(str);
1504 av[0] = as;
1505 av[1] = NULL;
1506 } else {
1507 av = brk_string(str, &ac, FALSE, &as);
1508 }
1509
1510 /*
1511 * Now sanitize seldata.
1512 * If seldata->start or seldata->end are negative, convert them to
1513 * the positive equivalents (-1 gets converted to argc, -2 gets
1514 * converted to (argc-1), etc.).
1515 */
1516 if (first < 0)
1517 first += ac + 1;
1518 if (last < 0)
1519 last += ac + 1;
1520
1521 /*
1522 * We avoid scanning more of the list than we need to.
1523 */
1524 if (first > last) {
1525 start = MIN(ac, first) - 1;
1526 end = MAX(0, last - 1);
1527 step = -1;
1528 } else {
1529 start = MAX(0, first - 1);
1530 end = MIN(ac, last);
1531 step = 1;
1532 }
1533
1534 for (i = start; (step < 0) == (i >= end); i += step) {
1535 SepBuf_AddStr(&buf, av[i]);
1536 SepBuf_Sep(&buf);
1537 }
1538
1539 free(as);
1540 free(av);
1541
1542 return SepBuf_Destroy(&buf, FALSE);
1543 }
1544
1545
1546 /* Callback for ModifyWords to implement the :tA modifier.
1547 * Replace each word with the result of realpath() if successful. */
1548 static void
1549 ModifyWord_Realpath(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
1550 {
1551 struct stat st;
1552 char rbuf[MAXPATHLEN];
1553
1554 const char *rp = cached_realpath(word, rbuf);
1555 if (rp != NULL && *rp == '/' && stat(rp, &st) == 0)
1556 word = rp;
1557
1558 SepBuf_AddStr(buf, word);
1559 }
1560
1561 /*-
1562 *-----------------------------------------------------------------------
1563 * Modify each of the words of the passed string using the given function.
1564 *
1565 * Input:
1566 * str String whose words should be modified
1567 * modifyWord Function that modifies a single word
1568 * data Custom data for modifyWord
1569 *
1570 * Results:
1571 * A string of all the words modified appropriately.
1572 *-----------------------------------------------------------------------
1573 */
1574 static char *
1575 ModifyWords(GNode *ctx, Byte sep, Boolean oneBigWord,
1576 const char *str, ModifyWordsCallback modifyWord, void *data)
1577 {
1578 if (oneBigWord) {
1579 SepBuf result;
1580 SepBuf_Init(&result, sep);
1581 modifyWord(str, &result, data);
1582 return SepBuf_Destroy(&result, FALSE);
1583 }
1584
1585 SepBuf result;
1586 char **av; /* word list */
1587 char *as; /* word list memory */
1588 int ac, i;
1589
1590 SepBuf_Init(&result, sep);
1591
1592 av = brk_string(str, &ac, FALSE, &as);
1593
1594 if (DEBUG(VAR)) {
1595 fprintf(debug_file, "ModifyWords: split \"%s\" into %d words\n",
1596 str, ac);
1597 }
1598
1599 for (i = 0; i < ac; i++) {
1600 modifyWord(av[i], &result, data);
1601 if (result.buf.count > 0)
1602 SepBuf_Sep(&result);
1603 }
1604
1605 free(as);
1606 free(av);
1607
1608 return SepBuf_Destroy(&result, FALSE);
1609 }
1610
1611
1612 static int
1613 VarWordCompare(const void *a, const void *b)
1614 {
1615 int r = strcmp(*(const char * const *)a, *(const char * const *)b);
1616 return r;
1617 }
1618
1619 static int
1620 VarWordCompareReverse(const void *a, const void *b)
1621 {
1622 int r = strcmp(*(const char * const *)b, *(const char * const *)a);
1623 return r;
1624 }
1625
1626 /*-
1627 *-----------------------------------------------------------------------
1628 * VarOrder --
1629 * Order the words in the string.
1630 *
1631 * Input:
1632 * str String whose words should be sorted.
1633 * otype How to order: s - sort, x - random.
1634 *
1635 * Results:
1636 * A string containing the words ordered.
1637 *
1638 * Side Effects:
1639 * None.
1640 *
1641 *-----------------------------------------------------------------------
1642 */
1643 static char *
1644 VarOrder(const char *str, const char otype)
1645 {
1646 Buffer buf; /* Buffer for the new string */
1647 char **av; /* word list */
1648 char *as; /* word list memory */
1649 int ac, i;
1650
1651 Buf_Init(&buf, 0);
1652
1653 av = brk_string(str, &ac, FALSE, &as);
1654
1655 if (ac > 0) {
1656 switch (otype) {
1657 case 'r': /* reverse sort alphabetically */
1658 qsort(av, ac, sizeof(char *), VarWordCompareReverse);
1659 break;
1660 case 's': /* sort alphabetically */
1661 qsort(av, ac, sizeof(char *), VarWordCompare);
1662 break;
1663 case 'x': /* randomize */
1664 /*
1665 * We will use [ac..2] range for mod factors. This will produce
1666 * random numbers in [(ac-1)..0] interval, and minimal
1667 * reasonable value for mod factor is 2 (the mod 1 will produce
1668 * 0 with probability 1).
1669 */
1670 for (i = ac - 1; i > 0; i--) {
1671 int rndidx = random() % (i + 1);
1672 char *t = av[i];
1673 av[i] = av[rndidx];
1674 av[rndidx] = t;
1675 }
1676 }
1677 }
1678
1679 for (i = 0; i < ac; i++) {
1680 if (i != 0)
1681 Buf_AddByte(&buf, ' ');
1682 Buf_AddStr(&buf, av[i]);
1683 }
1684
1685 free(as);
1686 free(av);
1687
1688 return Buf_Destroy(&buf, FALSE);
1689 }
1690
1691
1692 /* Remove adjacent duplicate words. */
1693 static char *
1694 VarUniq(const char *str)
1695 {
1696 Buffer buf; /* Buffer for new string */
1697 char **av; /* List of words to affect */
1698 char *as; /* Word list memory */
1699 int ac, i, j;
1700
1701 Buf_Init(&buf, 0);
1702 av = brk_string(str, &ac, FALSE, &as);
1703
1704 if (ac > 1) {
1705 for (j = 0, i = 1; i < ac; i++)
1706 if (strcmp(av[i], av[j]) != 0 && (++j != i))
1707 av[j] = av[i];
1708 ac = j + 1;
1709 }
1710
1711 for (i = 0; i < ac; i++) {
1712 if (i != 0)
1713 Buf_AddByte(&buf, ' ');
1714 Buf_AddStr(&buf, av[i]);
1715 }
1716
1717 free(as);
1718 free(av);
1719
1720 return Buf_Destroy(&buf, FALSE);
1721 }
1722
1723 /*-
1724 *-----------------------------------------------------------------------
1725 * VarRange --
1726 * Return an integer sequence
1727 *
1728 * Input:
1729 * str String whose words provide default range
1730 * ac range length, if 0 use str words
1731 *
1732 * Side Effects:
1733 * None.
1734 *
1735 *-----------------------------------------------------------------------
1736 */
1737 static char *
1738 VarRange(const char *str, int ac)
1739 {
1740 Buffer buf; /* Buffer for new string */
1741 char **av; /* List of words to affect */
1742 char *as; /* Word list memory */
1743 int i;
1744
1745 Buf_Init(&buf, 0);
1746 if (ac > 0) {
1747 as = NULL;
1748 av = NULL;
1749 } else {
1750 av = brk_string(str, &ac, FALSE, &as);
1751 }
1752 for (i = 0; i < ac; i++) {
1753 if (i != 0)
1754 Buf_AddByte(&buf, ' ');
1755 Buf_AddInt(&buf, 1 + i);
1756 }
1757
1758 free(as);
1759 free(av);
1760
1761 return Buf_Destroy(&buf, FALSE);
1762 }
1763
1764
1765 /*-
1766 * Parse a text part of a modifier such as the "from" and "to" in :S/from/to/
1767 * or the :@ modifier, until the next unescaped delimiter. The delimiter, as
1768 * well as the backslash or the dollar, can be escaped with a backslash.
1769 *
1770 * Return the parsed (and possibly expanded) string, or NULL if no delimiter
1771 * was found.
1772 *
1773 * Nested variables in the text are expanded unless VARE_NOSUBST is set.
1774 *
1775 * If out_length is specified, store the length of the returned string, just
1776 * to save another strlen call.
1777 *
1778 * If out_pflags is specified and the last character of the pattern is a $,
1779 * set the VARP_ANCHOR_END bit of mpflags (for the first part of the :S
1780 * modifier).
1781 *
1782 * If subst is specified, handle escaped ampersands and replace unescaped
1783 * ampersands with the lhs of the pattern (for the second part of the :S
1784 * modifier).
1785 */
1786 static char *
1787 ParseModifierPart(const char **tstr, int delim, VarEvalFlags eflags,
1788 GNode *ctxt, size_t *out_length,
1789 VarPatternFlags *out_pflags, ModifyWord_SubstArgs *subst)
1790 {
1791 const char *cp;
1792 char *rstr;
1793 Buffer buf;
1794 VarEvalFlags errnum = eflags & VARE_UNDEFERR;
1795
1796 Buf_Init(&buf, 0);
1797
1798 /*
1799 * Skim through until the matching delimiter is found;
1800 * pick up variable substitutions on the way. Also allow
1801 * backslashes to quote the delimiter, $, and \, but don't
1802 * touch other backslashes.
1803 */
1804 for (cp = *tstr; *cp != '\0' && *cp != delim; cp++) {
1805 Boolean is_escaped = cp[0] == '\\' && (
1806 cp[1] == delim || cp[1] == '\\' || cp[1] == '$' ||
1807 (cp[1] == '&' && subst != NULL));
1808 if (is_escaped) {
1809 Buf_AddByte(&buf, cp[1]);
1810 cp++;
1811 } else if (*cp == '$') {
1812 if (cp[1] == delim) { /* Unescaped $ at end of pattern */
1813 if (out_pflags != NULL)
1814 *out_pflags |= VARP_ANCHOR_END;
1815 else
1816 Buf_AddByte(&buf, *cp);
1817 } else {
1818 if (eflags & VARE_WANTRES) {
1819 const char *cp2;
1820 int len;
1821 void *freeIt;
1822
1823 /*
1824 * If unescaped dollar sign not before the
1825 * delimiter, assume it's a variable
1826 * substitution and recurse.
1827 */
1828 cp2 = Var_Parse(cp, ctxt, errnum | (eflags & VARE_WANTRES),
1829 &len, &freeIt);
1830 Buf_AddStr(&buf, cp2);
1831 free(freeIt);
1832 cp += len - 1;
1833 } else {
1834 const char *cp2 = &cp[1];
1835
1836 if (*cp2 == PROPEN || *cp2 == BROPEN) {
1837 /*
1838 * Find the end of this variable reference
1839 * and suck it in without further ado.
1840 * It will be interpreted later.
1841 */
1842 int have = *cp2;
1843 int want = *cp2 == PROPEN ? PRCLOSE : BRCLOSE;
1844 int depth = 1;
1845
1846 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
1847 if (cp2[-1] != '\\') {
1848 if (*cp2 == have)
1849 ++depth;
1850 if (*cp2 == want)
1851 --depth;
1852 }
1853 }
1854 Buf_AddBytesBetween(&buf, cp, cp2);
1855 cp = --cp2;
1856 } else
1857 Buf_AddByte(&buf, *cp);
1858 }
1859 }
1860 } else if (subst != NULL && *cp == '&')
1861 Buf_AddBytes(&buf, subst->lhsLen, subst->lhs);
1862 else
1863 Buf_AddByte(&buf, *cp);
1864 }
1865
1866 if (*cp != delim) {
1867 *tstr = cp;
1868 return NULL;
1869 }
1870
1871 *tstr = ++cp;
1872 if (out_length != NULL)
1873 *out_length = Buf_Size(&buf);
1874 rstr = Buf_Destroy(&buf, FALSE);
1875 if (DEBUG(VAR))
1876 fprintf(debug_file, "Modifier part: \"%s\"\n", rstr);
1877 return rstr;
1878 }
1879
1880 /*-
1881 *-----------------------------------------------------------------------
1882 * VarQuote --
1883 * Quote shell meta-characters and space characters in the string
1884 * if quoteDollar is set, also quote and double any '$' characters.
1885 *
1886 * Results:
1887 * The quoted string
1888 *
1889 * Side Effects:
1890 * None.
1891 *
1892 *-----------------------------------------------------------------------
1893 */
1894 static char *
1895 VarQuote(char *str, Boolean quoteDollar)
1896 {
1897 Buffer buf;
1898 Buf_Init(&buf, 0);
1899
1900 for (; *str != '\0'; str++) {
1901 if (*str == '\n') {
1902 const char *newline = Shell_GetNewline();
1903 if (newline == NULL)
1904 newline = "\\\n";
1905 Buf_AddStr(&buf, newline);
1906 continue;
1907 }
1908 if (isspace((unsigned char)*str) || ismeta((unsigned char)*str))
1909 Buf_AddByte(&buf, '\\');
1910 Buf_AddByte(&buf, *str);
1911 if (quoteDollar && *str == '$')
1912 Buf_AddStr(&buf, "\\$");
1913 }
1914
1915 str = Buf_Destroy(&buf, FALSE);
1916 if (DEBUG(VAR))
1917 fprintf(debug_file, "QuoteMeta: [%s]\n", str);
1918 return str;
1919 }
1920
1921 /*-
1922 *-----------------------------------------------------------------------
1923 * VarHash --
1924 * Hash the string using the MurmurHash3 algorithm.
1925 * Output is computed using 32bit Little Endian arithmetic.
1926 *
1927 * Input:
1928 * str String to modify
1929 *
1930 * Results:
1931 * Hash value of str, encoded as 8 hex digits.
1932 *
1933 * Side Effects:
1934 * None.
1935 *
1936 *-----------------------------------------------------------------------
1937 */
1938 static char *
1939 VarHash(const char *str)
1940 {
1941 static const char hexdigits[16] = "0123456789abcdef";
1942 Buffer buf;
1943 size_t len, len2;
1944 const unsigned char *ustr = (const unsigned char *)str;
1945 uint32_t h, k, c1, c2;
1946
1947 h = 0x971e137bU;
1948 c1 = 0x95543787U;
1949 c2 = 0x2ad7eb25U;
1950 len2 = strlen(str);
1951
1952 for (len = len2; len; ) {
1953 k = 0;
1954 switch (len) {
1955 default:
1956 k = ((uint32_t)ustr[3] << 24) |
1957 ((uint32_t)ustr[2] << 16) |
1958 ((uint32_t)ustr[1] << 8) |
1959 (uint32_t)ustr[0];
1960 len -= 4;
1961 ustr += 4;
1962 break;
1963 case 3:
1964 k |= (uint32_t)ustr[2] << 16;
1965 /* FALLTHROUGH */
1966 case 2:
1967 k |= (uint32_t)ustr[1] << 8;
1968 /* FALLTHROUGH */
1969 case 1:
1970 k |= (uint32_t)ustr[0];
1971 len = 0;
1972 }
1973 c1 = c1 * 5 + 0x7b7d159cU;
1974 c2 = c2 * 5 + 0x6bce6396U;
1975 k *= c1;
1976 k = (k << 11) ^ (k >> 21);
1977 k *= c2;
1978 h = (h << 13) ^ (h >> 19);
1979 h = h * 5 + 0x52dce729U;
1980 h ^= k;
1981 }
1982 h ^= len2;
1983 h *= 0x85ebca6b;
1984 h ^= h >> 13;
1985 h *= 0xc2b2ae35;
1986 h ^= h >> 16;
1987
1988 Buf_Init(&buf, 0);
1989 for (len = 0; len < 8; ++len) {
1990 Buf_AddByte(&buf, hexdigits[h & 15]);
1991 h >>= 4;
1992 }
1993
1994 return Buf_Destroy(&buf, FALSE);
1995 }
1996
1997 static char *
1998 VarStrftime(const char *fmt, int zulu, time_t utc)
1999 {
2000 char buf[BUFSIZ];
2001
2002 if (!utc)
2003 time(&utc);
2004 if (!*fmt)
2005 fmt = "%c";
2006 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2007
2008 buf[sizeof(buf) - 1] = '\0';
2009 return bmake_strdup(buf);
2010 }
2011
2012 /* The ApplyModifier functions all work in the same way.
2013 * They parse the modifier (often until the next colon) and store the
2014 * updated position for the parser into st->next
2015 * (except when returning AMR_UNKNOWN).
2016 * They take the st->val and generate st->newVal from it.
2017 * On failure, many of them update st->missing_delim.
2018 */
2019 typedef struct {
2020 const int startc; /* '\0' or '{' or '(' */
2021 const int endc;
2022 Var * const v;
2023 GNode * const ctxt;
2024 const VarEvalFlags eflags;
2025
2026 char *val; /* The value of the expression before the
2027 * modifier is applied */
2028 char *newVal; /* The new value after applying the modifier
2029 * to the expression */
2030 const char *next; /* The position where parsing continues
2031 * after the current modifier. */
2032 char missing_delim; /* For error reporting */
2033
2034 Byte sep; /* Word separator in expansions */
2035 Boolean oneBigWord; /* TRUE if we will treat the variable as a
2036 * single big word, even if it contains
2037 * embedded spaces (as opposed to the
2038 * usual behaviour of treating it as
2039 * several space-separated words). */
2040
2041 } ApplyModifiersState;
2042
2043 typedef enum {
2044 AMR_OK, /* Continue parsing */
2045 AMR_UNKNOWN, /* Not a match, try others as well */
2046 AMR_BAD, /* Error out with message */
2047 AMR_CLEANUP /* Error out with "missing delimiter",
2048 * if st->missing_delim is set. */
2049 } ApplyModifierResult;
2050
2051 /* we now have some modifiers with long names */
2052 static Boolean
2053 ModMatch(const char *mod, const char *modname, char endc)
2054 {
2055 size_t n = strlen(modname);
2056 return strncmp(mod, modname, n) == 0 &&
2057 (mod[n] == endc || mod[n] == ':');
2058 }
2059
2060 static inline Boolean
2061 ModMatchEq(const char *mod, const char *modname, char endc)
2062 {
2063 size_t n = strlen(modname);
2064 return strncmp(mod, modname, n) == 0 &&
2065 (mod[n] == endc || mod[n] == ':' || mod[n] == '=');
2066 }
2067
2068 /* :@var (at) ...${var}...@ */
2069 static ApplyModifierResult
2070 ApplyModifier_Loop(const char *mod, ApplyModifiersState *st) {
2071 ModifyWord_LoopArgs args;
2072
2073 args.ctx = st->ctxt;
2074 st->next = mod + 1;
2075 char delim = '@';
2076 args.tvar = ParseModifierPart(&st->next, delim, st->eflags & ~VARE_WANTRES,
2077 st->ctxt, NULL, NULL, NULL);
2078 if (args.tvar == NULL) {
2079 st->missing_delim = delim;
2080 return AMR_CLEANUP;
2081 }
2082
2083 args.str = ParseModifierPart(&st->next, delim, st->eflags & ~VARE_WANTRES,
2084 st->ctxt, NULL, NULL, NULL);
2085 if (args.str == NULL) {
2086 st->missing_delim = delim;
2087 return AMR_CLEANUP;
2088 }
2089
2090 args.eflags = st->eflags & (VARE_UNDEFERR | VARE_WANTRES);
2091 int prev_sep = st->sep;
2092 st->sep = ' '; /* XXX: this is inconsistent */
2093 st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
2094 ModifyWord_Loop, &args);
2095 st->sep = prev_sep;
2096 Var_Delete(args.tvar, st->ctxt);
2097 free(args.tvar);
2098 free(args.str);
2099 return AMR_OK;
2100 }
2101
2102 /* :Ddefined or :Uundefined */
2103 static ApplyModifierResult
2104 ApplyModifier_Defined(const char *mod, ApplyModifiersState *st)
2105 {
2106 Buffer buf; /* Buffer for patterns */
2107 VarEvalFlags neflags;
2108
2109 if (st->eflags & VARE_WANTRES) {
2110 Boolean wantres;
2111 if (*mod == 'U')
2112 wantres = (st->v->flags & VAR_JUNK) != 0;
2113 else
2114 wantres = (st->v->flags & VAR_JUNK) == 0;
2115 neflags = st->eflags & ~VARE_WANTRES;
2116 if (wantres)
2117 neflags |= VARE_WANTRES;
2118 } else
2119 neflags = st->eflags;
2120
2121 /*
2122 * Pass through mod looking for 1) escaped delimiters,
2123 * '$'s and backslashes (place the escaped character in
2124 * uninterpreted) and 2) unescaped $'s that aren't before
2125 * the delimiter (expand the variable substitution).
2126 * The result is left in the Buffer buf.
2127 */
2128 Buf_Init(&buf, 0);
2129 const char *p = mod + 1;
2130 while (*p != st->endc && *p != ':' && *p != '\0') {
2131 if (*p == '\\' &&
2132 (p[1] == ':' || p[1] == '$' || p[1] == st->endc || p[1] == '\\')) {
2133 Buf_AddByte(&buf, p[1]);
2134 p += 2;
2135 } else if (*p == '$') {
2136 /*
2137 * If unescaped dollar sign, assume it's a
2138 * variable substitution and recurse.
2139 */
2140 const char *cp2;
2141 int len;
2142 void *freeIt;
2143
2144 cp2 = Var_Parse(p, st->ctxt, neflags, &len, &freeIt);
2145 Buf_AddStr(&buf, cp2);
2146 free(freeIt);
2147 p += len;
2148 } else {
2149 Buf_AddByte(&buf, *p);
2150 p++;
2151 }
2152 }
2153
2154 st->next = p;
2155
2156 if (st->v->flags & VAR_JUNK)
2157 st->v->flags |= VAR_KEEP;
2158 if (neflags & VARE_WANTRES) {
2159 st->newVal = Buf_Destroy(&buf, FALSE);
2160 } else {
2161 st->newVal = st->val;
2162 Buf_Destroy(&buf, TRUE);
2163 }
2164 return AMR_OK;
2165 }
2166
2167 /* :gmtime */
2168 static ApplyModifierResult
2169 ApplyModifier_Gmtime(const char *mod, ApplyModifiersState *st)
2170 {
2171 if (!ModMatchEq(mod, "gmtime", st->endc))
2172 return AMR_UNKNOWN;
2173
2174 time_t utc;
2175 if (mod[6] == '=') {
2176 char *ep;
2177 utc = strtoul(mod + 7, &ep, 10);
2178 st->next = ep;
2179 } else {
2180 utc = 0;
2181 st->next = mod + 6;
2182 }
2183 st->newVal = VarStrftime(st->val, 1, utc);
2184 return AMR_OK;
2185 }
2186
2187 /* :localtime */
2188 static Boolean
2189 ApplyModifier_Localtime(const char *mod, ApplyModifiersState *st)
2190 {
2191 if (!ModMatchEq(mod, "localtime", st->endc))
2192 return AMR_UNKNOWN;
2193
2194 time_t utc;
2195 if (mod[9] == '=') {
2196 char *ep;
2197 utc = strtoul(mod + 10, &ep, 10);
2198 st->next = ep;
2199 } else {
2200 utc = 0;
2201 st->next = mod + 9;
2202 }
2203 st->newVal = VarStrftime(st->val, 0, utc);
2204 return AMR_OK;
2205 }
2206
2207 /* :hash */
2208 static ApplyModifierResult
2209 ApplyModifier_Hash(const char *mod, ApplyModifiersState *st)
2210 {
2211 if (!ModMatch(mod, "hash", st->endc))
2212 return AMR_UNKNOWN;
2213
2214 st->newVal = VarHash(st->val);
2215 st->next = mod + 4;
2216 return AMR_OK;
2217 }
2218
2219 /* :P */
2220 static ApplyModifierResult
2221 ApplyModifier_Path(const char *mod, ApplyModifiersState *st)
2222 {
2223 if (st->v->flags & VAR_JUNK)
2224 st->v->flags |= VAR_KEEP;
2225 GNode *gn = Targ_FindNode(st->v->name, TARG_NOCREATE);
2226 if (gn == NULL || gn->type & OP_NOPATH) {
2227 st->newVal = NULL;
2228 } else if (gn->path) {
2229 st->newVal = bmake_strdup(gn->path);
2230 } else {
2231 st->newVal = Dir_FindFile(st->v->name, Suff_FindPath(gn));
2232 }
2233 if (!st->newVal)
2234 st->newVal = bmake_strdup(st->v->name);
2235 st->next = mod + 1;
2236 return AMR_OK;
2237 }
2238
2239 /* :!cmd! */
2240 static ApplyModifierResult
2241 ApplyModifier_Exclam(const char *mod, ApplyModifiersState *st)
2242 {
2243 st->next = mod + 1;
2244 char delim = '!';
2245 char *cmd = ParseModifierPart(&st->next, delim, st->eflags, st->ctxt,
2246 NULL, NULL, NULL);
2247 if (cmd == NULL) {
2248 st->missing_delim = delim;
2249 return AMR_CLEANUP;
2250 }
2251
2252 const char *emsg = NULL;
2253 if (st->eflags & VARE_WANTRES)
2254 st->newVal = Cmd_Exec(cmd, &emsg);
2255 else
2256 st->newVal = varNoError;
2257 free(cmd);
2258
2259 if (emsg)
2260 Error(emsg, st->val); /* XXX: why still return AMR_OK? */
2261
2262 if (st->v->flags & VAR_JUNK)
2263 st->v->flags |= VAR_KEEP;
2264 return AMR_OK;
2265 }
2266
2267 /* :range */
2268 static ApplyModifierResult
2269 ApplyModifier_Range(const char *mod, ApplyModifiersState *st)
2270 {
2271 if (!ModMatchEq(mod, "range", st->endc))
2272 return AMR_UNKNOWN;
2273
2274 int n;
2275 if (mod[5] == '=') {
2276 char *ep;
2277 n = strtoul(mod + 6, &ep, 10);
2278 st->next = ep;
2279 } else {
2280 n = 0;
2281 st->next = mod + 5;
2282 }
2283 st->newVal = VarRange(st->val, n);
2284 return AMR_OK;
2285 }
2286
2287 /* :Mpattern or :Npattern */
2288 static ApplyModifierResult
2289 ApplyModifier_Match(const char *mod, ApplyModifiersState *st)
2290 {
2291 Boolean copy = FALSE; /* pattern should be, or has been, copied */
2292 Boolean needSubst = FALSE;
2293 /*
2294 * In the loop below, ignore ':' unless we are at (or back to) the
2295 * original brace level.
2296 * XXX This will likely not work right if $() and ${} are intermixed.
2297 */
2298 int nest = 1;
2299 const char *p;
2300 for (p = mod + 1; *p != '\0' && !(*p == ':' && nest == 1); p++) {
2301 if (*p == '\\' &&
2302 (p[1] == ':' || p[1] == st->endc || p[1] == st->startc)) {
2303 if (!needSubst)
2304 copy = TRUE;
2305 p++;
2306 continue;
2307 }
2308 if (*p == '$')
2309 needSubst = TRUE;
2310 if (*p == '(' || *p == '{')
2311 ++nest;
2312 if (*p == ')' || *p == '}') {
2313 --nest;
2314 if (nest == 0)
2315 break;
2316 }
2317 }
2318 st->next = p;
2319 const char *endpat = st->next;
2320
2321 char *pattern;
2322 if (copy) {
2323 /* Compress the \:'s out of the pattern. */
2324 pattern = bmake_malloc(endpat - (mod + 1) + 1);
2325 char *dst = pattern;
2326 const char *src = mod + 1;
2327 for (; src < endpat; src++, dst++) {
2328 if (src[0] == '\\' && src + 1 < endpat &&
2329 /* XXX: st->startc is missing here; see above */
2330 (src[1] == ':' || src[1] == st->endc))
2331 src++;
2332 *dst = *src;
2333 }
2334 *dst = '\0';
2335 endpat = dst;
2336 } else {
2337 /*
2338 * Either Var_Subst or ModifyWords will need a
2339 * nul-terminated string soon, so construct one now.
2340 */
2341 pattern = bmake_strndup(mod + 1, endpat - (mod + 1));
2342 }
2343
2344 if (needSubst) {
2345 /* pattern contains embedded '$', so use Var_Subst to expand it. */
2346 char *old_pattern = pattern;
2347 pattern = Var_Subst(pattern, st->ctxt, st->eflags);
2348 free(old_pattern);
2349 }
2350
2351 if (DEBUG(VAR))
2352 fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
2353 st->v->name, st->val, pattern);
2354
2355 ModifyWordsCallback callback = mod[0] == 'M'
2356 ? ModifyWord_Match : ModifyWord_NoMatch;
2357 st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
2358 callback, pattern);
2359 free(pattern);
2360 return AMR_OK;
2361 }
2362
2363 /* :S,from,to, */
2364 static ApplyModifierResult
2365 ApplyModifier_Subst(const char * const mod, ApplyModifiersState *st)
2366 {
2367 char delim = mod[1];
2368 if (delim == '\0') {
2369 Error("Missing delimiter for :S modifier");
2370 st->next = mod + 1;
2371 return AMR_CLEANUP;
2372 }
2373
2374 st->next = mod + 2;
2375
2376 ModifyWord_SubstArgs args;
2377 args.pflags = 0;
2378
2379 /*
2380 * If pattern begins with '^', it is anchored to the
2381 * start of the word -- skip over it and flag pattern.
2382 */
2383 if (*st->next == '^') {
2384 args.pflags |= VARP_ANCHOR_START;
2385 st->next++;
2386 }
2387
2388 char *lhs = ParseModifierPart(&st->next, delim, st->eflags, st->ctxt,
2389 &args.lhsLen, &args.pflags, NULL);
2390 if (lhs == NULL) {
2391 st->missing_delim = delim;
2392 return AMR_CLEANUP;
2393 }
2394 args.lhs = lhs;
2395
2396 char *rhs = ParseModifierPart(&st->next, delim, st->eflags, st->ctxt,
2397 &args.rhsLen, NULL, &args);
2398 if (rhs == NULL) {
2399 st->missing_delim = delim;
2400 return AMR_CLEANUP;
2401 }
2402 args.rhs = rhs;
2403
2404 Boolean oneBigWord = st->oneBigWord;
2405 for (;; st->next++) {
2406 switch (*st->next) {
2407 case 'g':
2408 args.pflags |= VARP_SUB_GLOBAL;
2409 continue;
2410 case '1':
2411 args.pflags |= VARP_SUB_ONE;
2412 continue;
2413 case 'W':
2414 oneBigWord = TRUE;
2415 continue;
2416 }
2417 break;
2418 }
2419
2420 st->newVal = ModifyWords(st->ctxt, st->sep, oneBigWord, st->val,
2421 ModifyWord_Subst, &args);
2422
2423 free(lhs);
2424 free(rhs);
2425 return AMR_OK;
2426 }
2427
2428 #ifndef NO_REGEX
2429
2430 /* :C,from,to, */
2431 static ApplyModifierResult
2432 ApplyModifier_Regex(const char *mod, ApplyModifiersState *st)
2433 {
2434 char delim = mod[1];
2435 if (delim == '\0') {
2436 Error("Missing delimiter for :C modifier");
2437 st->next = mod + 1;
2438 return AMR_CLEANUP;
2439 }
2440
2441 st->next = mod + 2;
2442
2443 char *re = ParseModifierPart(&st->next, delim, st->eflags, st->ctxt,
2444 NULL, NULL, NULL);
2445 if (re == NULL) {
2446 st->missing_delim = delim;
2447 return AMR_CLEANUP;
2448 }
2449
2450 ModifyWord_SubstRegexArgs args;
2451 args.replace = ParseModifierPart(&st->next, delim, st->eflags, st->ctxt,
2452 NULL, NULL, NULL);
2453 if (args.replace == NULL) {
2454 free(re);
2455 st->missing_delim = delim;
2456 return AMR_CLEANUP;
2457 }
2458
2459 args.pflags = 0;
2460 Boolean oneBigWord = st->oneBigWord;
2461 for (;; st->next++) {
2462 switch (*st->next) {
2463 case 'g':
2464 args.pflags |= VARP_SUB_GLOBAL;
2465 continue;
2466 case '1':
2467 args.pflags |= VARP_SUB_ONE;
2468 continue;
2469 case 'W':
2470 oneBigWord = TRUE;
2471 continue;
2472 }
2473 break;
2474 }
2475
2476 int error = regcomp(&args.re, re, REG_EXTENDED);
2477 free(re);
2478 if (error) {
2479 VarREError(error, &args.re, "RE substitution error");
2480 free(args.replace);
2481 return AMR_CLEANUP;
2482 }
2483
2484 args.nsub = args.re.re_nsub + 1;
2485 if (args.nsub < 1)
2486 args.nsub = 1;
2487 if (args.nsub > 10)
2488 args.nsub = 10;
2489 st->newVal = ModifyWords(st->ctxt, st->sep, oneBigWord, st->val,
2490 ModifyWord_SubstRegex, &args);
2491 regfree(&args.re);
2492 free(args.replace);
2493 return AMR_OK;
2494 }
2495 #endif
2496
2497 static void
2498 ModifyWord_Copy(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
2499 {
2500 SepBuf_AddStr(buf, word);
2501 }
2502
2503 /* :ts<separator> */
2504 static ApplyModifierResult
2505 ApplyModifier_ToSep(const char *sep, ApplyModifiersState *st)
2506 {
2507 if (sep[0] != st->endc && (sep[1] == st->endc || sep[1] == ':')) {
2508 /* ":ts<any><endc>" or ":ts<any>:" */
2509 st->sep = sep[0];
2510 st->next = sep + 1;
2511 } else if (sep[0] == st->endc || sep[0] == ':') {
2512 /* ":ts<endc>" or ":ts:" */
2513 st->sep = '\0'; /* no separator */
2514 st->next = sep;
2515 } else if (sep[0] == '\\') {
2516 const char *xp = sep + 1;
2517 int base = 8; /* assume octal */
2518
2519 switch (sep[1]) {
2520 case 'n':
2521 st->sep = '\n';
2522 st->next = sep + 2;
2523 break;
2524 case 't':
2525 st->sep = '\t';
2526 st->next = sep + 2;
2527 break;
2528 case 'x':
2529 base = 16;
2530 xp++;
2531 goto get_numeric;
2532 case '0':
2533 base = 0;
2534 goto get_numeric;
2535 default:
2536 if (!isdigit((unsigned char)sep[1]))
2537 return AMR_BAD; /* ":ts<backslash><unrecognised>". */
2538
2539 char *end;
2540 get_numeric:
2541 st->sep = strtoul(sep + 1 + (sep[1] == 'x'), &end, base);
2542 if (*end != ':' && *end != st->endc)
2543 return AMR_BAD;
2544 st->next = end;
2545 break;
2546 }
2547 } else {
2548 return AMR_BAD; /* Found ":ts<unrecognised><unrecognised>". */
2549 }
2550
2551 st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
2552 ModifyWord_Copy, NULL);
2553 return AMR_OK;
2554 }
2555
2556 /* :tA, :tu, :tl, :ts<separator>, etc. */
2557 static ApplyModifierResult
2558 ApplyModifier_To(const char *mod, ApplyModifiersState *st)
2559 {
2560 assert(mod[0] == 't');
2561
2562 st->next = mod + 1; /* make sure it is set */
2563 if (mod[1] == st->endc || mod[1] == ':' || mod[1] == '\0')
2564 return AMR_BAD; /* Found ":t<endc>" or ":t:". */
2565
2566 if (mod[1] == 's')
2567 return ApplyModifier_ToSep(mod + 2, st);
2568
2569 if (mod[2] != st->endc && mod[2] != ':')
2570 return AMR_BAD; /* Found ":t<unrecognised><unrecognised>". */
2571
2572 /* Check for two-character options: ":tu", ":tl" */
2573 if (mod[1] == 'A') { /* absolute path */
2574 st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
2575 ModifyWord_Realpath, NULL);
2576 st->next = mod + 2;
2577 } else if (mod[1] == 'u') {
2578 size_t len = strlen(st->val);
2579 st->newVal = bmake_malloc(len + 1);
2580 size_t i;
2581 for (i = 0; i < len + 1; i++)
2582 st->newVal[i] = toupper((unsigned char)st->val[i]);
2583 st->next = mod + 2;
2584 } else if (mod[1] == 'l') {
2585 size_t len = strlen(st->val);
2586 st->newVal = bmake_malloc(len + 1);
2587 size_t i;
2588 for (i = 0; i < len + 1; i++)
2589 st->newVal[i] = tolower((unsigned char)st->val[i]);
2590 st->next = mod + 2;
2591 } else if (mod[1] == 'W' || mod[1] == 'w') {
2592 st->oneBigWord = mod[1] == 'W';
2593 st->newVal = st->val;
2594 st->next = mod + 2;
2595 } else {
2596 /* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
2597 return AMR_BAD;
2598 }
2599 return AMR_OK;
2600 }
2601
2602 /* :[#], :[1], etc. */
2603 static ApplyModifierResult
2604 ApplyModifier_Words(const char *mod, ApplyModifiersState *st)
2605 {
2606 st->next = mod + 1; /* point to char after '[' */
2607 char delim = ']'; /* look for closing ']' */
2608 char *estr = ParseModifierPart(&st->next, delim, st->eflags, st->ctxt,
2609 NULL, NULL, NULL);
2610 if (estr == NULL) {
2611 st->missing_delim = delim;
2612 return AMR_CLEANUP;
2613 }
2614
2615 /* now st->next points just after the closing ']' */
2616 if (st->next[0] != ':' && st->next[0] != st->endc)
2617 goto bad_modifier; /* Found junk after ']' */
2618
2619 if (estr[0] == '\0')
2620 goto bad_modifier; /* empty square brackets in ":[]". */
2621
2622 if (estr[0] == '#' && estr[1] == '\0') { /* Found ":[#]" */
2623 if (st->oneBigWord) {
2624 st->newVal = bmake_strdup("1");
2625 } else {
2626 /* XXX: brk_string() is a rather expensive
2627 * way of counting words. */
2628 char *as;
2629 int ac;
2630 char **av = brk_string(st->val, &ac, FALSE, &as);
2631 free(as);
2632 free(av);
2633
2634 Buffer buf;
2635 Buf_Init(&buf, 4); /* 3 digits + '\0' */
2636 Buf_AddInt(&buf, ac);
2637 st->newVal = Buf_Destroy(&buf, FALSE);
2638 }
2639 goto ok;
2640 }
2641
2642 if (estr[0] == '*' && estr[1] == '\0') {
2643 /* Found ":[*]" */
2644 st->oneBigWord = TRUE;
2645 st->newVal = st->val;
2646 goto ok;
2647 }
2648
2649 if (estr[0] == '@' && estr[1] == '\0') {
2650 /* Found ":[@]" */
2651 st->oneBigWord = FALSE;
2652 st->newVal = st->val;
2653 goto ok;
2654 }
2655
2656 /*
2657 * We expect estr to contain a single integer for :[N], or two integers
2658 * separated by ".." for :[start..end].
2659 */
2660 char *ep;
2661 int first = strtol(estr, &ep, 0);
2662 int last;
2663 if (ep == estr) /* Found junk instead of a number */
2664 goto bad_modifier;
2665
2666 if (ep[0] == '\0') { /* Found only one integer in :[N] */
2667 last = first;
2668 } else if (ep[0] == '.' && ep[1] == '.' && ep[2] != '\0') {
2669 /* Expecting another integer after ".." */
2670 ep += 2;
2671 last = strtol(ep, &ep, 0);
2672 if (ep[0] != '\0') /* Found junk after ".." */
2673 goto bad_modifier;
2674 } else
2675 goto bad_modifier; /* Found junk instead of ".." */
2676
2677 /*
2678 * Now seldata is properly filled in, but we still have to check for 0 as
2679 * a special case.
2680 */
2681 if (first == 0 && last == 0) {
2682 /* ":[0]" or perhaps ":[0..0]" */
2683 st->oneBigWord = TRUE;
2684 st->newVal = st->val;
2685 goto ok;
2686 }
2687
2688 /* ":[0..N]" or ":[N..0]" */
2689 if (first == 0 || last == 0)
2690 goto bad_modifier;
2691
2692 /* Normal case: select the words described by seldata. */
2693 st->newVal = VarSelectWords(st->sep, st->oneBigWord, st->val, first, last);
2694
2695 ok:
2696 free(estr);
2697 return AMR_OK;
2698
2699 bad_modifier:
2700 free(estr);
2701 return AMR_BAD;
2702 }
2703
2704 /* :O or :Ox */
2705 static ApplyModifierResult
2706 ApplyModifier_Order(const char *mod, ApplyModifiersState *st)
2707 {
2708 char otype;
2709
2710 st->next = mod + 1; /* skip to the rest in any case */
2711 if (mod[1] == st->endc || mod[1] == ':') {
2712 otype = 's';
2713 } else if ((mod[1] == 'r' || mod[1] == 'x') &&
2714 (mod[2] == st->endc || mod[2] == ':')) {
2715 otype = mod[1];
2716 st->next = mod + 2;
2717 } else {
2718 return AMR_BAD;
2719 }
2720 st->newVal = VarOrder(st->val, otype);
2721 return AMR_OK;
2722 }
2723
2724 /* :? then : else */
2725 static ApplyModifierResult
2726 ApplyModifier_IfElse(const char *mod, ApplyModifiersState *st)
2727 {
2728 Boolean value = FALSE;
2729 int cond_rc = 0;
2730 VarEvalFlags then_eflags = st->eflags & ~VARE_WANTRES;
2731 VarEvalFlags else_eflags = st->eflags & ~VARE_WANTRES;
2732
2733 if (st->eflags & VARE_WANTRES) {
2734 cond_rc = Cond_EvalExpression(NULL, st->v->name, &value, 0, FALSE);
2735 if (cond_rc != COND_INVALID && value)
2736 then_eflags |= VARE_WANTRES;
2737 if (cond_rc != COND_INVALID && !value)
2738 else_eflags |= VARE_WANTRES;
2739 }
2740
2741 st->next = mod + 1;
2742 char delim = ':';
2743 char *then_expr = ParseModifierPart(&st->next, delim, then_eflags, st->ctxt,
2744 NULL, NULL, NULL);
2745 if (then_expr == NULL) {
2746 st->missing_delim = delim;
2747 return AMR_CLEANUP;
2748 }
2749
2750 delim = st->endc; /* BRCLOSE or PRCLOSE */
2751 char *else_expr = ParseModifierPart(&st->next, delim, else_eflags, st->ctxt,
2752 NULL, NULL, NULL);
2753 if (else_expr == NULL) {
2754 st->missing_delim = delim;
2755 return AMR_CLEANUP;
2756 }
2757
2758 st->next--;
2759 if (cond_rc == COND_INVALID) {
2760 Error("Bad conditional expression `%s' in %s?%s:%s",
2761 st->v->name, st->v->name, then_expr, else_expr);
2762 return AMR_CLEANUP;
2763 }
2764
2765 if (value) {
2766 st->newVal = then_expr;
2767 free(else_expr);
2768 } else {
2769 st->newVal = else_expr;
2770 free(then_expr);
2771 }
2772 if (st->v->flags & VAR_JUNK)
2773 st->v->flags |= VAR_KEEP;
2774 return AMR_OK;
2775 }
2776
2777 /*
2778 * The ::= modifiers actually assign a value to the variable.
2779 * Their main purpose is in supporting modifiers of .for loop
2780 * iterators and other obscure uses. They always expand to
2781 * nothing. In a target rule that would otherwise expand to an
2782 * empty line they can be preceded with @: to keep make happy.
2783 * Eg.
2784 *
2785 * foo: .USE
2786 * .for i in ${.TARGET} ${.TARGET:R}.gz
2787 * @: ${t::=$i}
2788 * @echo blah ${t:T}
2789 * .endfor
2790 *
2791 * ::=<str> Assigns <str> as the new value of variable.
2792 * ::?=<str> Assigns <str> as value of variable if
2793 * it was not already set.
2794 * ::+=<str> Appends <str> to variable.
2795 * ::!=<cmd> Assigns output of <cmd> as the new value of
2796 * variable.
2797 */
2798 static ApplyModifierResult
2799 ApplyModifier_Assign(const char *mod, ApplyModifiersState *st)
2800 {
2801 const char *op = mod + 1;
2802 if (!(op[0] == '=' ||
2803 (op[1] == '=' &&
2804 (op[0] == '!' || op[0] == '+' || op[0] == '?'))))
2805 return AMR_UNKNOWN; /* "::<unrecognised>" */
2806
2807 GNode *v_ctxt; /* context where v belongs */
2808
2809 if (st->v->name[0] == 0) {
2810 st->next = mod + 1;
2811 return AMR_BAD;
2812 }
2813
2814 v_ctxt = st->ctxt;
2815 char *sv_name = NULL;
2816 if (st->v->flags & VAR_JUNK) {
2817 /*
2818 * We need to bmake_strdup() it incase ParseModifierPart() recurses.
2819 */
2820 sv_name = st->v->name;
2821 st->v->name = bmake_strdup(st->v->name);
2822 } else if (st->ctxt != VAR_GLOBAL) {
2823 Var *gv = VarFind(st->v->name, st->ctxt, 0);
2824 if (gv == NULL)
2825 v_ctxt = VAR_GLOBAL;
2826 else
2827 VarFreeEnv(gv, TRUE);
2828 }
2829
2830 switch (op[0]) {
2831 case '+':
2832 case '?':
2833 case '!':
2834 st->next = mod + 3;
2835 break;
2836 default:
2837 st->next = mod + 2;
2838 break;
2839 }
2840
2841 char delim = st->startc == PROPEN ? PRCLOSE : BRCLOSE;
2842 char *val = ParseModifierPart(&st->next, delim, st->eflags, st->ctxt,
2843 NULL, NULL, NULL);
2844 if (st->v->flags & VAR_JUNK) {
2845 /* restore original name */
2846 free(st->v->name);
2847 st->v->name = sv_name;
2848 }
2849 if (val == NULL) {
2850 st->missing_delim = delim;
2851 return AMR_CLEANUP;
2852 }
2853
2854 st->next--;
2855
2856 if (st->eflags & VARE_WANTRES) {
2857 switch (op[0]) {
2858 case '+':
2859 Var_Append(st->v->name, val, v_ctxt);
2860 break;
2861 case '!': {
2862 const char *emsg;
2863 st->newVal = Cmd_Exec(val, &emsg);
2864 if (emsg)
2865 Error(emsg, st->val);
2866 else
2867 Var_Set(st->v->name, st->newVal, v_ctxt);
2868 free(st->newVal);
2869 break;
2870 }
2871 case '?':
2872 if (!(st->v->flags & VAR_JUNK))
2873 break;
2874 /* FALLTHROUGH */
2875 default:
2876 Var_Set(st->v->name, val, v_ctxt);
2877 break;
2878 }
2879 }
2880 free(val);
2881 st->newVal = varNoError;
2882 return AMR_OK;
2883 }
2884
2885 /* remember current value */
2886 static ApplyModifierResult
2887 ApplyModifier_Remember(const char *mod, ApplyModifiersState *st)
2888 {
2889 if (!ModMatchEq(mod, "_", st->endc))
2890 return AMR_UNKNOWN;
2891
2892 if (mod[1] == '=') {
2893 size_t n = strcspn(mod + 2, ":)}");
2894 char *name = bmake_strndup(mod + 2, n);
2895 Var_Set(name, st->val, st->ctxt);
2896 free(name);
2897 st->next = mod + 2 + n;
2898 } else {
2899 Var_Set("_", st->val, st->ctxt);
2900 st->next = mod + 1;
2901 }
2902 st->newVal = st->val;
2903 return AMR_OK;
2904 }
2905
2906 #ifdef SYSVVARSUB
2907 /* :from=to */
2908 static ApplyModifierResult
2909 ApplyModifier_SysV(const char *mod, ApplyModifiersState *st)
2910 {
2911 Boolean eqFound = FALSE;
2912
2913 /*
2914 * First we make a pass through the string trying
2915 * to verify it is a SYSV-make-style translation:
2916 * it must be: <string1>=<string2>)
2917 */
2918 st->next = mod;
2919 int nest = 1;
2920 while (*st->next != '\0' && nest > 0) {
2921 if (*st->next == '=') {
2922 eqFound = TRUE;
2923 /* continue looking for st->endc */
2924 } else if (*st->next == st->endc)
2925 nest--;
2926 else if (*st->next == st->startc)
2927 nest++;
2928 if (nest > 0)
2929 st->next++;
2930 }
2931 if (*st->next != st->endc || !eqFound)
2932 return AMR_UNKNOWN;
2933
2934 char delim = '=';
2935 st->next = mod;
2936 char *lhs = ParseModifierPart(&st->next, delim, st->eflags, st->ctxt,
2937 NULL, NULL, NULL);
2938 if (lhs == NULL) {
2939 st->missing_delim = delim;
2940 return AMR_CLEANUP;
2941 }
2942
2943 delim = st->endc;
2944 char *rhs = ParseModifierPart(&st->next, delim, st->eflags, st->ctxt,
2945 NULL, NULL, NULL);
2946 if (rhs == NULL) {
2947 st->missing_delim = delim;
2948 return AMR_CLEANUP;
2949 }
2950
2951 /*
2952 * SYSV modifications happen through the whole
2953 * string. Note the pattern is anchored at the end.
2954 */
2955 st->next--;
2956 if (lhs[0] == '\0' && *st->val == '\0') {
2957 st->newVal = st->val; /* special case */
2958 } else {
2959 ModifyWord_SYSVSubstArgs args = { st->ctxt, lhs, rhs };
2960 st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
2961 ModifyWord_SYSVSubst, &args);
2962 }
2963 free(lhs);
2964 free(rhs);
2965 return AMR_OK;
2966 }
2967 #endif
2968
2969 /*
2970 * Now we need to apply any modifiers the user wants applied.
2971 * These are:
2972 * :M<pattern> words which match the given <pattern>.
2973 * <pattern> is of the standard file
2974 * wildcarding form.
2975 * :N<pattern> words which do not match the given <pattern>.
2976 * :S<d><pat1><d><pat2><d>[1gW]
2977 * Substitute <pat2> for <pat1> in the value
2978 * :C<d><pat1><d><pat2><d>[1gW]
2979 * Substitute <pat2> for regex <pat1> in the value
2980 * :H Substitute the head of each word
2981 * :T Substitute the tail of each word
2982 * :E Substitute the extension (minus '.') of
2983 * each word
2984 * :R Substitute the root of each word
2985 * (pathname minus the suffix).
2986 * :O ("Order") Alphabeticaly sort words in variable.
2987 * :Ox ("intermiX") Randomize words in variable.
2988 * :u ("uniq") Remove adjacent duplicate words.
2989 * :tu Converts the variable contents to uppercase.
2990 * :tl Converts the variable contents to lowercase.
2991 * :ts[c] Sets varSpace - the char used to
2992 * separate words to 'c'. If 'c' is
2993 * omitted then no separation is used.
2994 * :tW Treat the variable contents as a single
2995 * word, even if it contains spaces.
2996 * (Mnemonic: one big 'W'ord.)
2997 * :tw Treat the variable contents as multiple
2998 * space-separated words.
2999 * (Mnemonic: many small 'w'ords.)
3000 * :[index] Select a single word from the value.
3001 * :[start..end] Select multiple words from the value.
3002 * :[*] or :[0] Select the entire value, as a single
3003 * word. Equivalent to :tW.
3004 * :[@] Select the entire value, as multiple
3005 * words. Undoes the effect of :[*].
3006 * Equivalent to :tw.
3007 * :[#] Returns the number of words in the value.
3008 *
3009 * :?<true-value>:<false-value>
3010 * If the variable evaluates to true, return
3011 * true value, else return the second value.
3012 * :lhs=rhs Like :S, but the rhs goes to the end of
3013 * the invocation.
3014 * :sh Treat the current value as a command
3015 * to be run, new value is its output.
3016 * The following added so we can handle ODE makefiles.
3017 * :@<tmpvar>@<newval>@
3018 * Assign a temporary local variable <tmpvar>
3019 * to the current value of each word in turn
3020 * and replace each word with the result of
3021 * evaluating <newval>
3022 * :D<newval> Use <newval> as value if variable defined
3023 * :U<newval> Use <newval> as value if variable undefined
3024 * :L Use the name of the variable as the value.
3025 * :P Use the path of the node that has the same
3026 * name as the variable as the value. This
3027 * basically includes an implied :L so that
3028 * the common method of refering to the path
3029 * of your dependent 'x' in a rule is to use
3030 * the form '${x:P}'.
3031 * :!<cmd>! Run cmd much the same as :sh run's the
3032 * current value of the variable.
3033 * Assignment operators (see ApplyModifier_Assign).
3034 */
3035 static char *
3036 ApplyModifiers(
3037 const char **pp, /* the parsing position, updated upon return */
3038 char *val, /* the current value of the variable */
3039 int const startc, /* '(' or '{' or '\0' */
3040 int const endc, /* ')' or '}' or '\0' */
3041 Var * const v, /* the variable may have its flags changed */
3042 GNode * const ctxt, /* for looking up and modifying variables */
3043 VarEvalFlags const eflags,
3044 void ** const freePtr /* free this after using the return value */
3045 ) {
3046 assert(startc == '(' || startc == '{' || startc == '\0');
3047 assert(endc == ')' || endc == '}' || startc == '\0');
3048
3049 ApplyModifiersState st = {
3050 startc, endc, v, ctxt, eflags,
3051 val, NULL, NULL, '\0', ' ', FALSE
3052 };
3053
3054 const char *p = *pp;
3055 while (*p != '\0' && *p != endc) {
3056
3057 if (*p == '$') {
3058 /*
3059 * We may have some complex modifiers in a variable.
3060 */
3061 void *freeIt;
3062 const char *rval;
3063 int rlen;
3064 int c;
3065
3066 rval = Var_Parse(p, st.ctxt, st.eflags, &rlen, &freeIt);
3067
3068 /*
3069 * If we have not parsed up to st.endc or ':',
3070 * we are not interested.
3071 */
3072 if (rval != NULL && *rval &&
3073 (c = p[rlen]) != '\0' && c != ':' && c != st.endc) {
3074 free(freeIt);
3075 goto apply_mods;
3076 }
3077
3078 if (DEBUG(VAR)) {
3079 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
3080 rval, rlen, p, rlen, p + rlen);
3081 }
3082
3083 p += rlen;
3084
3085 if (rval != NULL && *rval) {
3086 const char *rval_pp = rval;
3087 st.val = ApplyModifiers(&rval_pp, st.val, 0, 0, v,
3088 ctxt, eflags, freePtr);
3089 if (st.val == var_Error
3090 || (st.val == varNoError && !(st.eflags & VARE_UNDEFERR))
3091 || *rval_pp != '\0') {
3092 free(freeIt);
3093 goto out; /* error already reported */
3094 }
3095 }
3096 free(freeIt);
3097 if (*p == ':')
3098 p++;
3099 else if (*p == '\0' && endc != '\0') {
3100 Error("Unclosed variable specification after complex "
3101 "modifier (expecting '%c') for %s", st.endc, st.v->name);
3102 goto out;
3103 }
3104 continue;
3105 }
3106 apply_mods:
3107 if (DEBUG(VAR)) {
3108 fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", st.v->name,
3109 *p, st.val);
3110 }
3111 st.newVal = var_Error; /* default value, in case of errors */
3112 st.next = NULL; /* fail fast if an ApplyModifier forgets to set this */
3113 ApplyModifierResult res = 0;
3114 char modifier = *p;
3115 switch (modifier) {
3116 case ':':
3117 res = ApplyModifier_Assign(p, &st);
3118 break;
3119 case '@':
3120 res = ApplyModifier_Loop(p, &st);
3121 break;
3122 case '_':
3123 res = ApplyModifier_Remember(p, &st);
3124 break;
3125 case 'D':
3126 case 'U':
3127 res = ApplyModifier_Defined(p, &st);
3128 break;
3129 case 'L':
3130 if (st.v->flags & VAR_JUNK)
3131 st.v->flags |= VAR_KEEP;
3132 st.newVal = bmake_strdup(st.v->name);
3133 st.next = p + 1;
3134 res = AMR_OK;
3135 break;
3136 case 'P':
3137 res = ApplyModifier_Path(p, &st);
3138 break;
3139 case '!':
3140 res = ApplyModifier_Exclam(p, &st);
3141 break;
3142 case '[':
3143 res = ApplyModifier_Words(p, &st);
3144 break;
3145 case 'g':
3146 res = ApplyModifier_Gmtime(p, &st);
3147 break;
3148 case 'h':
3149 res = ApplyModifier_Hash(p, &st);
3150 break;
3151 case 'l':
3152 res = ApplyModifier_Localtime(p, &st);
3153 break;
3154 case 't':
3155 res = ApplyModifier_To(p, &st);
3156 break;
3157 case 'N':
3158 case 'M':
3159 res = ApplyModifier_Match(p, &st);
3160 break;
3161 case 'S':
3162 res = ApplyModifier_Subst(p, &st);
3163 break;
3164 case '?':
3165 res = ApplyModifier_IfElse(p, &st);
3166 break;
3167 #ifndef NO_REGEX
3168 case 'C':
3169 res = ApplyModifier_Regex(p, &st);
3170 break;
3171 #endif
3172 case 'q':
3173 case 'Q':
3174 if (p[1] == st.endc || p[1] == ':') {
3175 st.newVal = VarQuote(st.val, modifier == 'q');
3176 st.next = p + 1;
3177 res = AMR_OK;
3178 } else
3179 res = AMR_UNKNOWN;
3180 break;
3181 case 'T':
3182 if (p[1] == st.endc || p[1] == ':') {
3183 st.newVal = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3184 st.val, ModifyWord_Tail, NULL);
3185 st.next = p + 1;
3186 res = AMR_OK;
3187 } else
3188 res = AMR_UNKNOWN;
3189 break;
3190 case 'H':
3191 if (p[1] == st.endc || p[1] == ':') {
3192 st.newVal = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3193 st.val, ModifyWord_Head, NULL);
3194 st.next = p + 1;
3195 res = AMR_OK;
3196 } else
3197 res = AMR_UNKNOWN;
3198 break;
3199 case 'E':
3200 if (p[1] == st.endc || p[1] == ':') {
3201 st.newVal = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3202 st.val, ModifyWord_Suffix, NULL);
3203 st.next = p + 1;
3204 res = AMR_OK;
3205 } else
3206 res = AMR_UNKNOWN;
3207 break;
3208 case 'R':
3209 if (p[1] == st.endc || p[1] == ':') {
3210 st.newVal = ModifyWords(st.ctxt, st.sep, st.oneBigWord,
3211 st.val, ModifyWord_Root, NULL);
3212 st.next = p + 1;
3213 res = AMR_OK;
3214 } else
3215 res = AMR_UNKNOWN;
3216 break;
3217 case 'r':
3218 res = ApplyModifier_Range(p, &st);
3219 break;
3220 case 'O':
3221 res = ApplyModifier_Order(p, &st);
3222 break;
3223 case 'u':
3224 if (p[1] == st.endc || p[1] == ':') {
3225 st.newVal = VarUniq(st.val);
3226 st.next = p + 1;
3227 res = AMR_OK;
3228 } else
3229 res = AMR_UNKNOWN;
3230 break;
3231 #ifdef SUNSHCMD
3232 case 's':
3233 if (p[1] == 'h' && (p[2] == st.endc || p[2] == ':')) {
3234 const char *emsg;
3235 if (st.eflags & VARE_WANTRES) {
3236 st.newVal = Cmd_Exec(st.val, &emsg);
3237 if (emsg)
3238 Error(emsg, st.val);
3239 } else
3240 st.newVal = varNoError;
3241 st.next = p + 2;
3242 res = AMR_OK;
3243 } else
3244 res = AMR_UNKNOWN;
3245 break;
3246 #endif
3247 default:
3248 res = AMR_UNKNOWN;
3249 }
3250
3251 #ifdef SYSVVARSUB
3252 if (res == AMR_UNKNOWN)
3253 res = ApplyModifier_SysV(p, &st);
3254 #endif
3255
3256 if (res == AMR_UNKNOWN) {
3257 Error("Unknown modifier '%c'", *p);
3258 st.next = p + 1;
3259 while (*st.next != ':' && *st.next != st.endc && *st.next != '\0')
3260 st.next++;
3261 st.newVal = var_Error;
3262 }
3263 if (res == AMR_CLEANUP)
3264 goto cleanup;
3265 if (res == AMR_BAD)
3266 goto bad_modifier;
3267
3268 if (DEBUG(VAR)) {
3269 fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
3270 st.v->name, modifier, st.newVal);
3271 }
3272
3273 if (st.newVal != st.val) {
3274 if (*freePtr) {
3275 free(st.val);
3276 *freePtr = NULL;
3277 }
3278 st.val = st.newVal;
3279 if (st.val != var_Error && st.val != varNoError) {
3280 *freePtr = st.val;
3281 }
3282 }
3283 if (*st.next == '\0' && st.endc != '\0') {
3284 Error("Unclosed variable specification (expecting '%c') "
3285 "for \"%s\" (value \"%s\") modifier %c",
3286 st.endc, st.v->name, st.val, modifier);
3287 } else if (*st.next == ':') {
3288 st.next++;
3289 }
3290 p = st.next;
3291 }
3292 out:
3293 *pp = p;
3294 return st.val;
3295
3296 bad_modifier:
3297 Error("Bad modifier `:%.*s' for %s",
3298 (int)strcspn(p, ":)}"), p, st.v->name);
3299
3300 cleanup:
3301 *pp = st.next;
3302 if (st.missing_delim != '\0')
3303 Error("Unclosed substitution for %s (%c missing)",
3304 st.v->name, st.missing_delim);
3305 free(*freePtr);
3306 *freePtr = NULL;
3307 return var_Error;
3308 }
3309
3310 static Boolean
3311 VarIsDynamic(GNode *ctxt, const char *varname, size_t namelen)
3312 {
3313 if ((namelen == 1 ||
3314 (namelen == 2 && (varname[1] == 'F' || varname[1] == 'D'))) &&
3315 (ctxt == VAR_CMD || ctxt == VAR_GLOBAL))
3316 {
3317 /*
3318 * If substituting a local variable in a non-local context,
3319 * assume it's for dynamic source stuff. We have to handle
3320 * this specially and return the longhand for the variable
3321 * with the dollar sign escaped so it makes it back to the
3322 * caller. Only four of the local variables are treated
3323 * specially as they are the only four that will be set
3324 * when dynamic sources are expanded.
3325 */
3326 switch (varname[0]) {
3327 case '@':
3328 case '%':
3329 case '*':
3330 case '!':
3331 return TRUE;
3332 }
3333 return FALSE;
3334 }
3335
3336 if ((namelen == 7 || namelen == 8) && varname[0] == '.' &&
3337 isupper((unsigned char) varname[1]) &&
3338 (ctxt == VAR_CMD || ctxt == VAR_GLOBAL))
3339 {
3340 return strcmp(varname, ".TARGET") == 0 ||
3341 strcmp(varname, ".ARCHIVE") == 0 ||
3342 strcmp(varname, ".PREFIX") == 0 ||
3343 strcmp(varname, ".MEMBER") == 0;
3344 }
3345
3346 return FALSE;
3347 }
3348
3349 /*-
3350 *-----------------------------------------------------------------------
3351 * Var_Parse --
3352 * Given the start of a variable invocation (such as $v, $(VAR),
3353 * ${VAR:Mpattern}), extract the variable name, possibly some
3354 * modifiers and find its value by applying the modifiers to the
3355 * original value.
3356 *
3357 * Input:
3358 * str The string to parse
3359 * ctxt The context for the variable
3360 * flags VARE_UNDEFERR if undefineds are an error
3361 * VARE_WANTRES if we actually want the result
3362 * VARE_ASSIGN if we are in a := assignment
3363 * lengthPtr OUT: The length of the specification
3364 * freePtr OUT: Non-NULL if caller should free *freePtr
3365 *
3366 * Results:
3367 * The (possibly-modified) value of the variable or var_Error if the
3368 * specification is invalid. The length of the specification is
3369 * placed in *lengthPtr (for invalid specifications, this is just
3370 * 2...?).
3371 * If *freePtr is non-NULL then it's a pointer that the caller
3372 * should pass to free() to free memory used by the result.
3373 *
3374 * Side Effects:
3375 * None.
3376 *
3377 *-----------------------------------------------------------------------
3378 */
3379 /* coverity[+alloc : arg-*4] */
3380 const char *
3381 Var_Parse(const char * const str, GNode *ctxt, VarEvalFlags eflags,
3382 int *lengthPtr, void **freePtr)
3383 {
3384 const char *tstr; /* Pointer into str */
3385 Var *v; /* Variable in invocation */
3386 Boolean haveModifier; /* TRUE if have modifiers for the variable */
3387 char endc; /* Ending character when variable in parens
3388 * or braces */
3389 char startc; /* Starting character when variable in parens
3390 * or braces */
3391 char *nstr; /* New string, used during expansion */
3392 Boolean dynamic; /* TRUE if the variable is local and we're
3393 * expanding it in a non-local context. This
3394 * is done to support dynamic sources. The
3395 * result is just the invocation, unaltered */
3396 const char *extramodifiers; /* extra modifiers to apply first */
3397
3398 *freePtr = NULL;
3399 extramodifiers = NULL;
3400 dynamic = FALSE;
3401
3402 startc = str[1];
3403 if (startc != PROPEN && startc != BROPEN) {
3404 /*
3405 * If it's not bounded by braces of some sort, life is much simpler.
3406 * We just need to check for the first character and return the
3407 * value if it exists.
3408 */
3409
3410 /* Error out some really stupid names */
3411 if (startc == '\0' || strchr(")}:$", startc)) {
3412 *lengthPtr = 1;
3413 return var_Error;
3414 }
3415 char name[] = { startc, '\0' };
3416
3417 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3418 if (v == NULL) {
3419 *lengthPtr = 2;
3420
3421 if (ctxt == VAR_CMD || ctxt == VAR_GLOBAL) {
3422 /*
3423 * If substituting a local variable in a non-local context,
3424 * assume it's for dynamic source stuff. We have to handle
3425 * this specially and return the longhand for the variable
3426 * with the dollar sign escaped so it makes it back to the
3427 * caller. Only four of the local variables are treated
3428 * specially as they are the only four that will be set
3429 * when dynamic sources are expanded.
3430 */
3431 switch (str[1]) {
3432 case '@':
3433 return "$(.TARGET)";
3434 case '%':
3435 return "$(.MEMBER)";
3436 case '*':
3437 return "$(.PREFIX)";
3438 case '!':
3439 return "$(.ARCHIVE)";
3440 }
3441 }
3442 return (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
3443 } else {
3444 haveModifier = FALSE;
3445 tstr = str + 1;
3446 endc = str[1];
3447 }
3448 } else {
3449 Buffer namebuf; /* Holds the variable name */
3450 int depth = 1;
3451
3452 endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3453 Buf_Init(&namebuf, 0);
3454
3455 /*
3456 * Skip to the end character or a colon, whichever comes first.
3457 */
3458 for (tstr = str + 2; *tstr != '\0'; tstr++) {
3459 /* Track depth so we can spot parse errors. */
3460 if (*tstr == startc)
3461 depth++;
3462 if (*tstr == endc) {
3463 if (--depth == 0)
3464 break;
3465 }
3466 if (depth == 1 && *tstr == ':')
3467 break;
3468 /* A variable inside a variable, expand. */
3469 if (*tstr == '$') {
3470 int rlen;
3471 void *freeIt;
3472 const char *rval = Var_Parse(tstr, ctxt, eflags, &rlen, &freeIt);
3473 if (rval != NULL)
3474 Buf_AddStr(&namebuf, rval);
3475 free(freeIt);
3476 tstr += rlen - 1;
3477 } else
3478 Buf_AddByte(&namebuf, *tstr);
3479 }
3480 if (*tstr == ':') {
3481 haveModifier = TRUE;
3482 } else if (*tstr == endc) {
3483 haveModifier = FALSE;
3484 } else {
3485 Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"",
3486 Buf_GetAll(&namebuf, NULL));
3487 /*
3488 * If we never did find the end character, return NULL
3489 * right now, setting the length to be the distance to
3490 * the end of the string, since that's what make does.
3491 */
3492 *lengthPtr = tstr - str;
3493 Buf_Destroy(&namebuf, TRUE);
3494 return var_Error;
3495 }
3496
3497 int namelen;
3498 char *varname = Buf_GetAll(&namebuf, &namelen);
3499
3500 /*
3501 * At this point, varname points into newly allocated memory from
3502 * namebuf, containing only the name of the variable.
3503 *
3504 * start and tstr point into the const string that was pointed
3505 * to by the original value of the str parameter. start points
3506 * to the '$' at the beginning of the string, while tstr points
3507 * to the char just after the end of the variable name -- this
3508 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3509 */
3510
3511 v = VarFind(varname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3512 /*
3513 * Check also for bogus D and F forms of local variables since we're
3514 * in a local context and the name is the right length.
3515 */
3516 if (v == NULL && ctxt != VAR_CMD && ctxt != VAR_GLOBAL &&
3517 namelen == 2 && (varname[1] == 'F' || varname[1] == 'D') &&
3518 strchr("@%?*!<>", varname[0]) != NULL) {
3519 /*
3520 * Well, it's local -- go look for it.
3521 */
3522 char name[] = {varname[0], '\0' };
3523 v = VarFind(name, ctxt, 0);
3524
3525 if (v != NULL) {
3526 if (varname[1] == 'D') {
3527 extramodifiers = "H:";
3528 } else { /* F */
3529 extramodifiers = "T:";
3530 }
3531 }
3532 }
3533
3534 if (v == NULL) {
3535 dynamic = VarIsDynamic(ctxt, varname, namelen);
3536
3537 if (!haveModifier) {
3538 /*
3539 * No modifiers -- have specification length so we can return
3540 * now.
3541 */
3542 *lengthPtr = tstr - str + 1;
3543 if (dynamic) {
3544 char *pstr = bmake_strndup(str, *lengthPtr);
3545 *freePtr = pstr;
3546 Buf_Destroy(&namebuf, TRUE);
3547 return pstr;
3548 } else {
3549 Buf_Destroy(&namebuf, TRUE);
3550 return (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
3551 }
3552 } else {
3553 /*
3554 * Still need to get to the end of the variable specification,
3555 * so kludge up a Var structure for the modifications
3556 */
3557 v = bmake_malloc(sizeof(Var));
3558 v->name = varname;
3559 Buf_Init(&v->val, 1);
3560 v->flags = VAR_JUNK;
3561 Buf_Destroy(&namebuf, FALSE);
3562 }
3563 } else
3564 Buf_Destroy(&namebuf, TRUE);
3565 }
3566
3567 if (v->flags & VAR_IN_USE) {
3568 Fatal("Variable %s is recursive.", v->name);
3569 /*NOTREACHED*/
3570 } else {
3571 v->flags |= VAR_IN_USE;
3572 }
3573 /*
3574 * Before doing any modification, we have to make sure the value
3575 * has been fully expanded. If it looks like recursion might be
3576 * necessary (there's a dollar sign somewhere in the variable's value)
3577 * we just call Var_Subst to do any other substitutions that are
3578 * necessary. Note that the value returned by Var_Subst will have
3579 * been dynamically-allocated, so it will need freeing when we
3580 * return.
3581 */
3582 nstr = Buf_GetAll(&v->val, NULL);
3583 if (strchr(nstr, '$') != NULL && (eflags & VARE_WANTRES) != 0) {
3584 nstr = Var_Subst(nstr, ctxt, eflags);
3585 *freePtr = nstr;
3586 }
3587
3588 v->flags &= ~VAR_IN_USE;
3589
3590 if (nstr != NULL && (haveModifier || extramodifiers != NULL)) {
3591 void *extraFree;
3592
3593 extraFree = NULL;
3594 if (extramodifiers != NULL) {
3595 const char *em = extramodifiers;
3596 nstr = ApplyModifiers(&em, nstr, '(', ')',
3597 v, ctxt, eflags, &extraFree);
3598 }
3599
3600 if (haveModifier) {
3601 /* Skip initial colon. */
3602 tstr++;
3603
3604 nstr = ApplyModifiers(&tstr, nstr, startc, endc,
3605 v, ctxt, eflags, freePtr);
3606 free(extraFree);
3607 } else {
3608 *freePtr = extraFree;
3609 }
3610 }
3611 *lengthPtr = tstr - str + (*tstr ? 1 : 0);
3612
3613 if (v->flags & VAR_FROM_ENV) {
3614 Boolean destroy = nstr != Buf_GetAll(&v->val, NULL);
3615 if (!destroy) {
3616 /*
3617 * Returning the value unmodified, so tell the caller to free
3618 * the thing.
3619 */
3620 *freePtr = nstr;
3621 }
3622 (void)VarFreeEnv(v, destroy);
3623 } else if (v->flags & VAR_JUNK) {
3624 /*
3625 * Perform any free'ing needed and set *freePtr to NULL so the caller
3626 * doesn't try to free a static pointer.
3627 * If VAR_KEEP is also set then we want to keep str(?) as is.
3628 */
3629 if (!(v->flags & VAR_KEEP)) {
3630 if (*freePtr != NULL) {
3631 free(*freePtr);
3632 *freePtr = NULL;
3633 }
3634 if (dynamic) {
3635 nstr = bmake_strndup(str, *lengthPtr);
3636 *freePtr = nstr;
3637 } else {
3638 nstr = (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
3639 }
3640 }
3641 if (nstr != Buf_GetAll(&v->val, NULL))
3642 Buf_Destroy(&v->val, TRUE);
3643 free(v->name);
3644 free(v);
3645 }
3646 return nstr;
3647 }
3648
3649 /*-
3650 *-----------------------------------------------------------------------
3651 * Var_Subst --
3652 * Substitute for all variables in the given string in the given context.
3653 * If eflags & VARE_UNDEFERR, Parse_Error will be called when an undefined
3654 * variable is encountered.
3655 *
3656 * Input:
3657 * var Named variable || NULL for all
3658 * str the string which to substitute
3659 * ctxt the context wherein to find variables
3660 * eflags VARE_UNDEFERR if undefineds are an error
3661 * VARE_WANTRES if we actually want the result
3662 * VARE_ASSIGN if we are in a := assignment
3663 *
3664 * Results:
3665 * The resulting string.
3666 *
3667 * Side Effects:
3668 * None.
3669 *-----------------------------------------------------------------------
3670 */
3671 char *
3672 Var_Subst(const char *str, GNode *ctxt, VarEvalFlags eflags)
3673 {
3674 Buffer buf; /* Buffer for forming things */
3675 const char *val; /* Value to substitute for a variable */
3676 int length; /* Length of the variable invocation */
3677 Boolean trailingBslash; /* variable ends in \ */
3678 void *freeIt = NULL; /* Set if it should be freed */
3679 static Boolean errorReported; /* Set true if an error has already
3680 * been reported to prevent a plethora
3681 * of messages when recursing */
3682
3683 Buf_Init(&buf, 0);
3684 errorReported = FALSE;
3685 trailingBslash = FALSE;
3686
3687 while (*str) {
3688 if (*str == '\n' && trailingBslash)
3689 Buf_AddByte(&buf, ' ');
3690 if (*str == '$' && str[1] == '$') {
3691 /*
3692 * A dollar sign may be escaped with another dollar sign.
3693 * In such a case, we skip over the escape character and store the
3694 * dollar sign into the buffer directly.
3695 */
3696 if (save_dollars && (eflags & VARE_ASSIGN))
3697 Buf_AddByte(&buf, '$');
3698 Buf_AddByte(&buf, '$');
3699 str += 2;
3700 } else if (*str != '$') {
3701 /*
3702 * Skip as many characters as possible -- either to the end of
3703 * the string or to the next dollar sign (variable invocation).
3704 */
3705 const char *cp;
3706
3707 for (cp = str++; *str != '$' && *str != '\0'; str++)
3708 continue;
3709 Buf_AddBytesBetween(&buf, cp, str);
3710 } else {
3711 val = Var_Parse(str, ctxt, eflags, &length, &freeIt);
3712
3713 /*
3714 * When we come down here, val should either point to the
3715 * value of this variable, suitably modified, or be NULL.
3716 * Length should be the total length of the potential
3717 * variable invocation (from $ to end character...)
3718 */
3719 if (val == var_Error || val == varNoError) {
3720 /*
3721 * If performing old-time variable substitution, skip over
3722 * the variable and continue with the substitution. Otherwise,
3723 * store the dollar sign and advance str so we continue with
3724 * the string...
3725 */
3726 if (oldVars) {
3727 str += length;
3728 } else if ((eflags & VARE_UNDEFERR) || val == var_Error) {
3729 /*
3730 * If variable is undefined, complain and skip the
3731 * variable. The complaint will stop us from doing anything
3732 * when the file is parsed.
3733 */
3734 if (!errorReported) {
3735 Parse_Error(PARSE_FATAL, "Undefined variable \"%.*s\"",
3736 length, str);
3737 }
3738 str += length;
3739 errorReported = TRUE;
3740 } else {
3741 Buf_AddByte(&buf, *str);
3742 str += 1;
3743 }
3744 } else {
3745 /*
3746 * We've now got a variable structure to store in. But first,
3747 * advance the string pointer.
3748 */
3749 str += length;
3750
3751 /*
3752 * Copy all the characters from the variable value straight
3753 * into the new string.
3754 */
3755 length = strlen(val);
3756 Buf_AddBytes(&buf, length, val);
3757 trailingBslash = length > 0 && val[length - 1] == '\\';
3758 }
3759 free(freeIt);
3760 freeIt = NULL;
3761 }
3762 }
3763
3764 return Buf_DestroyCompact(&buf);
3765 }
3766
3767 /* Initialize the module. */
3768 void
3769 Var_Init(void)
3770 {
3771 VAR_INTERNAL = Targ_NewGN("Internal");
3772 VAR_GLOBAL = Targ_NewGN("Global");
3773 VAR_CMD = Targ_NewGN("Command");
3774 }
3775
3776
3777 void
3778 Var_End(void)
3779 {
3780 Var_Stats();
3781 }
3782
3783 void
3784 Var_Stats(void)
3785 {
3786 Hash_DebugStats(&VAR_GLOBAL->context, "VAR_GLOBAL");
3787 }
3788
3789
3790 /****************** PRINT DEBUGGING INFO *****************/
3791 static void
3792 VarPrintVar(void *vp, void *data MAKE_ATTR_UNUSED)
3793 {
3794 Var *v = (Var *)vp;
3795 fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
3796 }
3797
3798 /*-
3799 *-----------------------------------------------------------------------
3800 * Var_Dump --
3801 * print all variables in a context
3802 *-----------------------------------------------------------------------
3803 */
3804 void
3805 Var_Dump(GNode *ctxt)
3806 {
3807 Hash_ForEach(&ctxt->context, VarPrintVar, NULL);
3808 }
3809