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