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