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