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