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