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