1 /* $NetBSD: var.c,v 1.154 2009/09/08 17:29:20 sjg Exp $ */
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
39 * This code is derived from software contributed to Berkeley by
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
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.
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
72 static char rcsid
[] = "$NetBSD: var.c,v 1.154 2009/09/08 17:29:20 sjg Exp $";
74 #include <sys/cdefs.h>
77 static char sccsid
[] = "@(#)var.c 8.3 (Berkeley) 3/19/94";
79 __RCSID("$NetBSD: var.c,v 1.154 2009/09/08 17:29:20 sjg Exp $");
86 * Variable-handling functions
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
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
100 * Var_Exists See if a variable exists.
102 * Var_Value Return the value of a variable in a context or
103 * NULL if the variable is undefined.
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.
111 * Var_Parse Parse a variable expansion from a string and
112 * return the result and the number of characters
115 * Var_Delete Delete a variable in a context.
117 * Var_Init Initialize this module.
120 * Var_Dump Print out all variables defined in the given
123 * XXX: There's a lot of duplication in these functions.
127 #include <sys/types.h>
140 * This is a harmless return value for Var_Parse that can be used by Var_Subst
141 * to determine if there was an error in parsing -- easier than returning
142 * a flag, as things outside this module don't give a hoot.
144 char var_Error
[] = "";
147 * Similar to var_Error, but returned when the 'errnum' flag for Var_Parse is
148 * set false. Why not just use a constant? Well, gcc likes to condense
149 * identical string instances...
151 static char varNoError
[] = "";
154 * Internally, variables are contained in four different contexts.
155 * 1) the environment. They may not be changed. If an environment
156 * variable is appended-to, the result is placed in the global
158 * 2) the global context. Variables set in the Makefile are located in
159 * the global context. It is the penultimate context searched when
161 * 3) the command-line context. All variables set on the command line
162 * are placed in this context. They are UNALTERABLE once placed here.
163 * 4) the local context. Each target has associated with it a context
164 * list. On this list are located the structures describing such
165 * local variables as $(@) and $(*)
166 * The four contexts are searched in the reverse order from which they are
169 GNode
*VAR_GLOBAL
; /* variables from the makefile */
170 GNode
*VAR_CMD
; /* variables defined on the command-line */
172 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
173 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
174 #define FIND_ENV 0x4 /* look in the environment also */
177 char *name
; /* the variable's name */
178 Buffer val
; /* its value */
179 int flags
; /* miscellaneous status flags */
180 #define VAR_IN_USE 1 /* Variable's value currently being used.
181 * Used to avoid recursion */
182 #define VAR_FROM_ENV 2 /* Variable comes from the environment */
183 #define VAR_JUNK 4 /* Variable is a junk variable that
184 * should be destroyed when done with
185 * it. Used by Var_Parse for undefined,
186 * modified variables */
187 #define VAR_KEEP 8 /* Variable is VAR_JUNK, but we found
188 * a use for it in some modifier and
189 * the value is therefore valid */
190 #define VAR_EXPORTED 16 /* Variable is exported */
191 #define VAR_REEXPORT 32 /* Indicate if var needs re-export.
192 * This would be true if it contains $'s
194 #define VAR_FROM_CMD 64 /* Variable came from command line */
198 * Exporting vars is expensive so skip it if we can
200 #define VAR_EXPORTED_NONE 0
201 #define VAR_EXPORTED_YES 1
202 #define VAR_EXPORTED_ALL 2
203 static int var_exportedVars
= VAR_EXPORTED_NONE
;
205 * We pass this to Var_Export when doing the initial export
206 * or after updating an exported var.
208 #define VAR_EXPORT_PARENT 1
210 /* Var*Pattern flags */
211 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
212 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
213 #define VAR_SUB_MATCHED 0x04 /* There was a match */
214 #define VAR_MATCH_START 0x08 /* Match at start of word */
215 #define VAR_MATCH_END 0x10 /* Match at end of word */
216 #define VAR_NOSUBST 0x20 /* don't expand vars in VarGetPattern */
219 #define VAR_NO_EXPORT 0x01 /* do not export */
223 * The following fields are set by Var_Parse() when it
224 * encounters modifiers that need to keep state for use by
225 * subsequent modifiers within the same variable expansion.
227 Byte varSpace
; /* Word separator in expansions */
228 Boolean oneBigWord
; /* TRUE if we will treat the variable as a
229 * single big word, even if it contains
230 * embedded spaces (as opposed to the
231 * usual behaviour of treating it as
232 * several space-separated words). */
235 /* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/",
236 * to VarSYSVMatch() for ":lhs=rhs". */
238 const char *lhs
; /* String to match */
239 int leftLen
; /* Length of string */
240 const char *rhs
; /* Replacement string (w/ &'s removed) */
241 int rightLen
; /* Length of replacement */
245 /* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */
247 GNode
*ctxt
; /* variable context */
248 char *tvar
; /* name of temp var */
250 char *str
; /* string to expand */
252 int errnum
; /* errnum for not defined */
256 /* struct passed as 'void *' to VarRESubstitute() for ":C///" */
266 /* struct passed to VarSelectWords() for ":[start..end]" */
268 int start
; /* first word to select */
269 int end
; /* last word to select */
272 static Var
*VarFind(const char *, GNode
*, int);
273 static void VarAdd(const char *, const char *, GNode
*);
274 static Boolean
VarHead(GNode
*, Var_Parse_State
*,
275 char *, Boolean
, Buffer
*, void *);
276 static Boolean
VarTail(GNode
*, Var_Parse_State
*,
277 char *, Boolean
, Buffer
*, void *);
278 static Boolean
VarSuffix(GNode
*, Var_Parse_State
*,
279 char *, Boolean
, Buffer
*, void *);
280 static Boolean
VarRoot(GNode
*, Var_Parse_State
*,
281 char *, Boolean
, Buffer
*, void *);
282 static Boolean
VarMatch(GNode
*, Var_Parse_State
*,
283 char *, Boolean
, Buffer
*, void *);
285 static Boolean
VarSYSVMatch(GNode
*, Var_Parse_State
*,
286 char *, Boolean
, Buffer
*, void *);
288 static Boolean
VarNoMatch(GNode
*, Var_Parse_State
*,
289 char *, Boolean
, Buffer
*, void *);
291 static void VarREError(int, regex_t
*, const char *);
292 static Boolean
VarRESubstitute(GNode
*, Var_Parse_State
*,
293 char *, Boolean
, Buffer
*, void *);
295 static Boolean
VarSubstitute(GNode
*, Var_Parse_State
*,
296 char *, Boolean
, Buffer
*, void *);
297 static Boolean
VarLoopExpand(GNode
*, Var_Parse_State
*,
298 char *, Boolean
, Buffer
*, void *);
299 static char *VarGetPattern(GNode
*, Var_Parse_State
*,
300 int, const char **, int, int *, int *,
302 static char *VarQuote(char *);
303 static char *VarChangeCase(char *, int);
304 static char *VarModify(GNode
*, Var_Parse_State
*,
306 Boolean (*)(GNode
*, Var_Parse_State
*, char *, Boolean
, Buffer
*, void *),
308 static char *VarOrder(const char *, const char);
309 static char *VarUniq(const char *);
310 static int VarWordCompare(const void *, const void *);
311 static void VarPrintVar(void *);
319 *-----------------------------------------------------------------------
321 * Find the given variable in the given context and any other contexts
326 * ctxt context in which to find it
327 * flags FIND_GLOBAL set means to look in the
328 * VAR_GLOBAL context as well. FIND_CMD set means
329 * to look in the VAR_CMD context also. FIND_ENV
330 * set means to look in the environment
333 * A pointer to the structure describing the desired variable or
334 * NULL if the variable does not exist.
338 *-----------------------------------------------------------------------
341 VarFind(const char *name
, GNode
*ctxt
, int flags
)
347 * If the variable name begins with a '.', it could very well be one of
348 * the local ones. We check the name against all the local variables
349 * and substitute the short version in for 'name' if it matches one of
352 if (*name
== '.' && isupper((unsigned char) name
[1]))
355 if (!strcmp(name
, ".ALLSRC"))
357 if (!strcmp(name
, ".ARCHIVE"))
361 if (!strcmp(name
, ".IMPSRC"))
365 if (!strcmp(name
, ".MEMBER"))
369 if (!strcmp(name
, ".OODATE"))
373 if (!strcmp(name
, ".PREFIX"))
377 if (!strcmp(name
, ".TARGET"))
382 * First look for the variable in the given context. If it's not there,
383 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
384 * depending on the FIND_* flags in 'flags'
386 var
= Hash_FindEntry(&ctxt
->context
, name
);
388 if ((var
== NULL
) && (flags
& FIND_CMD
) && (ctxt
!= VAR_CMD
)) {
389 var
= Hash_FindEntry(&VAR_CMD
->context
, name
);
391 if (!checkEnvFirst
&& (var
== NULL
) && (flags
& FIND_GLOBAL
) &&
392 (ctxt
!= VAR_GLOBAL
))
394 var
= Hash_FindEntry(&VAR_GLOBAL
->context
, name
);
396 if ((var
== NULL
) && (flags
& FIND_ENV
)) {
399 if ((env
= getenv(name
)) != NULL
) {
402 v
= bmake_malloc(sizeof(Var
));
403 v
->name
= bmake_strdup(name
);
407 Buf_Init(&v
->val
, len
+ 1);
408 Buf_AddBytes(&v
->val
, len
, env
);
410 v
->flags
= VAR_FROM_ENV
;
412 } else if (checkEnvFirst
&& (flags
& FIND_GLOBAL
) &&
413 (ctxt
!= VAR_GLOBAL
))
415 var
= Hash_FindEntry(&VAR_GLOBAL
->context
, name
);
419 return ((Var
*)Hash_GetValue(var
));
424 } else if (var
== NULL
) {
427 return ((Var
*)Hash_GetValue(var
));
432 *-----------------------------------------------------------------------
434 * If the variable is an environment variable, free it
438 * destroy true if the value buffer should be destroyed.
441 * 1 if it is an environment variable 0 ow.
444 * The variable is free'ed if it is an environent variable.
445 *-----------------------------------------------------------------------
448 VarFreeEnv(Var
*v
, Boolean destroy
)
450 if ((v
->flags
& VAR_FROM_ENV
) == 0)
453 Buf_Destroy(&v
->val
, destroy
);
459 *-----------------------------------------------------------------------
461 * Add a new variable of name name and value val to the given context
464 * name name of variable to add
465 * val value to set it to
466 * ctxt context in which to set it
472 * The new variable is placed at the front of the given context
473 * The name and val arguments are duplicated so they may
475 *-----------------------------------------------------------------------
478 VarAdd(const char *name
, const char *val
, GNode
*ctxt
)
484 v
= bmake_malloc(sizeof(Var
));
486 len
= val
? strlen(val
) : 0;
487 Buf_Init(&v
->val
, len
+1);
488 Buf_AddBytes(&v
->val
, len
, val
);
492 h
= Hash_CreateEntry(&ctxt
->context
, name
, NULL
);
496 fprintf(debug_file
, "%s:%s = %s\n", ctxt
->name
, name
, val
);
501 *-----------------------------------------------------------------------
503 * Remove a variable from a context.
509 * The Var structure is removed and freed.
511 *-----------------------------------------------------------------------
514 Var_Delete(const char *name
, GNode
*ctxt
)
518 ln
= Hash_FindEntry(&ctxt
->context
, name
);
520 fprintf(debug_file
, "%s:delete %s%s\n",
521 ctxt
->name
, name
, ln
? "" : " (not found)");
526 v
= (Var
*)Hash_GetValue(ln
);
527 if ((v
->flags
& VAR_EXPORTED
)) {
530 if (strcmp(MAKE_EXPORTED
, v
->name
) == 0) {
531 var_exportedVars
= VAR_EXPORTED_NONE
;
533 if (v
->name
!= ln
->name
)
535 Hash_DeleteEntry(&ctxt
->context
, ln
);
536 Buf_Destroy(&v
->val
, TRUE
);
544 * We ignore make internal variables (those which start with '.')
545 * Also we jump through some hoops to avoid calling setenv
546 * more than necessary since it can leak.
547 * We only manipulate flags of vars if 'parent' is set.
550 Var_Export1(const char *name
, int parent
)
558 return 0; /* skip internals */
562 * If it is one of the vars that should only appear in
563 * local context, skip it, else we can get Var_Subst
574 v
= VarFind(name
, VAR_GLOBAL
, 0);
579 (v
->flags
& (VAR_EXPORTED
|VAR_REEXPORT
)) == VAR_EXPORTED
) {
580 return 0; /* nothing to do */
582 val
= Buf_GetAll(&v
->val
, NULL
);
583 if (strchr(val
, '$')) {
586 * Flag this as something we need to re-export.
587 * No point actually exporting it now though,
588 * the child can do it at the last minute.
590 v
->flags
|= (VAR_EXPORTED
|VAR_REEXPORT
);
593 n
= snprintf(tmp
, sizeof(tmp
), "${%s}", name
);
594 if (n
< (int)sizeof(tmp
)) {
595 val
= Var_Subst(NULL
, tmp
, VAR_GLOBAL
, 0);
596 setenv(name
, val
, 1);
601 v
->flags
&= ~VAR_REEXPORT
; /* once will do */
603 if (parent
|| !(v
->flags
& VAR_EXPORTED
)) {
604 setenv(name
, val
, 1);
608 * This is so Var_Set knows to call Var_Export again...
611 v
->flags
|= VAR_EXPORTED
;
617 * This gets called from our children.
629 if (VAR_EXPORTED_NONE
== var_exportedVars
)
632 if (VAR_EXPORTED_ALL
== var_exportedVars
) {
634 * Ouch! This is crazy...
636 for (var
= Hash_EnumFirst(&VAR_GLOBAL
->context
, &state
);
638 var
= Hash_EnumNext(&state
)) {
639 v
= (Var
*)Hash_GetValue(var
);
640 Var_Export1(v
->name
, 0);
645 * We have a number of exported vars,
647 n
= snprintf(tmp
, sizeof(tmp
), "${" MAKE_EXPORTED
":O:u}");
648 if (n
< (int)sizeof(tmp
)) {
654 val
= Var_Subst(NULL
, tmp
, VAR_GLOBAL
, 0);
655 av
= brk_string(val
, &ac
, FALSE
, &as
);
656 for (i
= 0; i
< ac
; i
++) {
657 Var_Export1(av
[i
], 0);
666 * This is called when .export is seen or
667 * .MAKE.EXPORTED is modified.
668 * It is also called when any exported var is modified.
671 Var_Export(char *str
, int isExport
)
680 if (isExport
&& (!str
|| !str
[0])) {
681 var_exportedVars
= VAR_EXPORTED_ALL
; /* use with caution! */
685 val
= Var_Subst(NULL
, str
, VAR_GLOBAL
, 0);
686 av
= brk_string(val
, &ac
, FALSE
, &as
);
687 for (i
= 0; i
< ac
; i
++) {
692 * If it is one of the vars that should only appear in
693 * local context, skip it, else we can get Var_Subst
704 if (Var_Export1(name
, VAR_EXPORT_PARENT
)) {
705 if (VAR_EXPORTED_ALL
!= var_exportedVars
)
706 var_exportedVars
= VAR_EXPORTED_YES
;
708 Var_Append(MAKE_EXPORTED
, name
, VAR_GLOBAL
);
719 * This is called when .unexport[-env] is seen.
722 Var_UnExport(char *str
)
727 Boolean unexport_env
;
730 if (!str
|| !str
[0]) {
731 return; /* assert? */
737 unexport_env
= (strncmp(str
, "-env", 4) == 0);
739 extern char **environ
;
740 static char **savenv
;
743 cp
= getenv(MAKE_LEVEL
); /* we should preserve this */
744 if (environ
== savenv
) {
745 /* we have been here before! */
746 newenv
= bmake_realloc(environ
, 2 * sizeof(char *));
752 newenv
= bmake_malloc(2 * sizeof(char *));
756 /* Note: we cannot safely free() the original environ. */
757 environ
= savenv
= newenv
;
760 setenv(MAKE_LEVEL
, cp
, 1);
762 for (; *str
!= '\n' && isspace((unsigned char) *str
); str
++)
764 if (str
[0] && str
[0] != '\n') {
770 /* Using .MAKE.EXPORTED */
771 n
= snprintf(tmp
, sizeof(tmp
), "${" MAKE_EXPORTED
":O:u}");
772 if (n
< (int)sizeof(tmp
)) {
773 vlist
= Var_Subst(NULL
, tmp
, VAR_GLOBAL
, 0);
783 av
= brk_string(vlist
, &ac
, FALSE
, &as
);
784 for (i
= 0; i
< ac
; i
++) {
785 v
= VarFind(av
[i
], VAR_GLOBAL
, 0);
789 (v
->flags
& (VAR_EXPORTED
|VAR_REEXPORT
)) == VAR_EXPORTED
) {
792 v
->flags
&= ~(VAR_EXPORTED
|VAR_REEXPORT
);
794 * If we are unexporting a list,
795 * remove each one from .MAKE.EXPORTED.
796 * If we are removing them all,
797 * just delete .MAKE.EXPORTED below.
800 n
= snprintf(tmp
, sizeof(tmp
),
801 "${" MAKE_EXPORTED
":N%s}", v
->name
);
802 if (n
< (int)sizeof(tmp
)) {
803 cp
= Var_Subst(NULL
, tmp
, VAR_GLOBAL
, 0);
804 Var_Set(MAKE_EXPORTED
, cp
, VAR_GLOBAL
, 0);
812 Var_Delete(MAKE_EXPORTED
, VAR_GLOBAL
);
819 *-----------------------------------------------------------------------
821 * Set the variable name to the value val in the given context.
824 * name name of variable to set
825 * val value to give to the variable
826 * ctxt context in which to set it
832 * If the variable doesn't yet exist, a new record is created for it.
833 * Else the old value is freed and the new one stuck in its place
836 * The variable is searched for only in its context before being
837 * created in that context. I.e. if the context is VAR_GLOBAL,
838 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
839 * VAR_CMD->context is searched. This is done to avoid the literally
840 * thousands of unnecessary strcmp's that used to be done to
841 * set, say, $(@) or $(<).
842 * If the context is VAR_GLOBAL though, we check if the variable
843 * was set in VAR_CMD from the command line and skip it if so.
844 *-----------------------------------------------------------------------
847 Var_Set(const char *name
, const char *val
, GNode
*ctxt
, int flags
)
850 char *expanded_name
= NULL
;
853 * We only look for a variable in the given context since anything set
854 * here will override anything in a lower context, so there's not much
855 * point in searching them all just to save a bit of memory...
857 if (strchr(name
, '$') != NULL
) {
858 expanded_name
= Var_Subst(NULL
, name
, ctxt
, 0);
859 if (expanded_name
[0] == 0) {
861 fprintf(debug_file
, "Var_Set(\"%s\", \"%s\", ...) "
862 "name expands to empty string - ignored\n",
868 name
= expanded_name
;
870 if (ctxt
== VAR_GLOBAL
) {
871 v
= VarFind(name
, VAR_CMD
, 0);
873 if ((v
->flags
& VAR_FROM_CMD
)) {
875 fprintf(debug_file
, "%s:%s = %s ignored!\n", ctxt
->name
, name
, val
);
882 v
= VarFind(name
, ctxt
, 0);
884 VarAdd(name
, val
, ctxt
);
887 Buf_AddBytes(&v
->val
, strlen(val
), val
);
890 fprintf(debug_file
, "%s:%s = %s\n", ctxt
->name
, name
, val
);
892 if ((v
->flags
& VAR_EXPORTED
)) {
893 Var_Export1(name
, VAR_EXPORT_PARENT
);
897 * Any variables given on the command line are automatically exported
898 * to the environment (as per POSIX standard)
900 if (ctxt
== VAR_CMD
&& (flags
& VAR_NO_EXPORT
) == 0) {
902 /* we just added it */
903 v
= VarFind(name
, ctxt
, 0);
906 v
->flags
|= VAR_FROM_CMD
;
908 * If requested, don't export these in the environment
909 * individually. We still put them in MAKEOVERRIDES so
910 * that the command-line settings continue to override
913 if (varNoExportEnv
!= TRUE
)
914 setenv(name
, val
, 1);
916 Var_Append(MAKEOVERRIDES
, name
, VAR_GLOBAL
);
919 * Another special case.
920 * Several make's support this sort of mechanism for tracking
921 * recursion - but each uses a different name.
922 * We allow the makefiles to update .MAKE.LEVEL and ensure
923 * children see a correctly incremented value.
925 if (ctxt
== VAR_GLOBAL
&& strcmp(MAKE_LEVEL
, name
) == 0) {
930 snprintf(tmp
, sizeof(tmp
), "%u", level
+ 1);
931 setenv(MAKE_LEVEL
, tmp
, 1);
936 if (expanded_name
!= NULL
)
943 *-----------------------------------------------------------------------
945 * The variable of the given name has the given value appended to it in
949 * name name of variable to modify
950 * val String to append to it
951 * ctxt Context in which this should occur
957 * If the variable doesn't exist, it is created. Else the strings
958 * are concatenated (with a space in between).
961 * Only if the variable is being sought in the global context is the
962 * environment searched.
963 * XXX: Knows its calling circumstances in that if called with ctxt
964 * an actual target, it will only search that context since only
965 * a local variable could be being appended to. This is actually
966 * a big win and must be tolerated.
967 *-----------------------------------------------------------------------
970 Var_Append(const char *name
, const char *val
, GNode
*ctxt
)
974 char *expanded_name
= NULL
;
976 if (strchr(name
, '$') != NULL
) {
977 expanded_name
= Var_Subst(NULL
, name
, ctxt
, 0);
978 if (expanded_name
[0] == 0) {
980 fprintf(debug_file
, "Var_Append(\"%s\", \"%s\", ...) "
981 "name expands to empty string - ignored\n",
987 name
= expanded_name
;
990 v
= VarFind(name
, ctxt
, (ctxt
== VAR_GLOBAL
) ? FIND_ENV
: 0);
993 VarAdd(name
, val
, ctxt
);
995 Buf_AddByte(&v
->val
, ' ');
996 Buf_AddBytes(&v
->val
, strlen(val
), val
);
999 fprintf(debug_file
, "%s:%s = %s\n", ctxt
->name
, name
,
1000 Buf_GetAll(&v
->val
, NULL
));
1003 if (v
->flags
& VAR_FROM_ENV
) {
1005 * If the original variable came from the environment, we
1006 * have to install it in the global context (we could place
1007 * it in the environment, but then we should provide a way to
1008 * export other variables...)
1010 v
->flags
&= ~VAR_FROM_ENV
;
1011 h
= Hash_CreateEntry(&ctxt
->context
, name
, NULL
);
1012 Hash_SetValue(h
, v
);
1015 if (expanded_name
!= NULL
)
1016 free(expanded_name
);
1020 *-----------------------------------------------------------------------
1022 * See if the given variable exists.
1025 * name Variable to find
1026 * ctxt Context in which to start search
1029 * TRUE if it does, FALSE if it doesn't
1034 *-----------------------------------------------------------------------
1037 Var_Exists(const char *name
, GNode
*ctxt
)
1042 if ((cp
= strchr(name
, '$')) != NULL
) {
1043 cp
= Var_Subst(NULL
, name
, ctxt
, FALSE
);
1045 v
= VarFind(cp
? cp
: name
, ctxt
, FIND_CMD
|FIND_GLOBAL
|FIND_ENV
);
1052 (void)VarFreeEnv(v
, TRUE
);
1058 *-----------------------------------------------------------------------
1060 * Return the value of the named variable in the given context
1064 * ctxt context in which to search for it
1067 * The value if the variable exists, NULL if it doesn't
1071 *-----------------------------------------------------------------------
1074 Var_Value(const char *name
, GNode
*ctxt
, char **frp
)
1078 v
= VarFind(name
, ctxt
, FIND_ENV
| FIND_GLOBAL
| FIND_CMD
);
1081 char *p
= (Buf_GetAll(&v
->val
, NULL
));
1082 if (VarFreeEnv(v
, FALSE
))
1091 *-----------------------------------------------------------------------
1093 * Remove the tail of the given word and place the result in the given
1098 * addSpace True if need to add a space to the buffer
1099 * before sticking in the head
1100 * buf Buffer in which to store it
1103 * TRUE if characters were added to the buffer (a space needs to be
1104 * added to the buffer before the next word).
1107 * The trimmed word is added to the buffer.
1109 *-----------------------------------------------------------------------
1112 VarHead(GNode
*ctx __unused
, Var_Parse_State
*vpstate
,
1113 char *word
, Boolean addSpace
, Buffer
*buf
,
1118 slash
= strrchr(word
, '/');
1119 if (slash
!= NULL
) {
1120 if (addSpace
&& vpstate
->varSpace
) {
1121 Buf_AddByte(buf
, vpstate
->varSpace
);
1124 Buf_AddBytes(buf
, strlen(word
), word
);
1129 * If no directory part, give . (q.v. the POSIX standard)
1131 if (addSpace
&& vpstate
->varSpace
)
1132 Buf_AddByte(buf
, vpstate
->varSpace
);
1133 Buf_AddByte(buf
, '.');
1135 return(dummy
? TRUE
: TRUE
);
1139 *-----------------------------------------------------------------------
1141 * Remove the head of the given word and place the result in the given
1146 * addSpace True if need to add a space to the buffer
1147 * before adding the tail
1148 * buf Buffer in which to store it
1151 * TRUE if characters were added to the buffer (a space needs to be
1152 * added to the buffer before the next word).
1155 * The trimmed word is added to the buffer.
1157 *-----------------------------------------------------------------------
1160 VarTail(GNode
*ctx __unused
, Var_Parse_State
*vpstate
,
1161 char *word
, Boolean addSpace
, Buffer
*buf
,
1166 if (addSpace
&& vpstate
->varSpace
) {
1167 Buf_AddByte(buf
, vpstate
->varSpace
);
1170 slash
= strrchr(word
, '/');
1171 if (slash
!= NULL
) {
1173 Buf_AddBytes(buf
, strlen(slash
), slash
);
1176 Buf_AddBytes(buf
, strlen(word
), word
);
1178 return (dummy
? TRUE
: TRUE
);
1182 *-----------------------------------------------------------------------
1184 * Place the suffix of the given word in the given buffer.
1188 * addSpace TRUE if need to add a space before placing the
1189 * suffix in the buffer
1190 * buf Buffer in which to store it
1193 * TRUE if characters were added to the buffer (a space needs to be
1194 * added to the buffer before the next word).
1197 * The suffix from the word is placed in the buffer.
1199 *-----------------------------------------------------------------------
1202 VarSuffix(GNode
*ctx __unused
, Var_Parse_State
*vpstate
,
1203 char *word
, Boolean addSpace
, Buffer
*buf
,
1208 dot
= strrchr(word
, '.');
1210 if (addSpace
&& vpstate
->varSpace
) {
1211 Buf_AddByte(buf
, vpstate
->varSpace
);
1214 Buf_AddBytes(buf
, strlen(dot
), dot
);
1218 return (dummy
? addSpace
: addSpace
);
1222 *-----------------------------------------------------------------------
1224 * Remove the suffix of the given word and place the result in the
1229 * addSpace TRUE if need to add a space to the buffer
1230 * before placing the root in it
1231 * buf Buffer in which to store it
1234 * TRUE if characters were added to the buffer (a space needs to be
1235 * added to the buffer before the next word).
1238 * The trimmed word is added to the buffer.
1240 *-----------------------------------------------------------------------
1243 VarRoot(GNode
*ctx __unused
, Var_Parse_State
*vpstate
,
1244 char *word
, Boolean addSpace
, Buffer
*buf
,
1249 if (addSpace
&& vpstate
->varSpace
) {
1250 Buf_AddByte(buf
, vpstate
->varSpace
);
1253 dot
= strrchr(word
, '.');
1256 Buf_AddBytes(buf
, strlen(word
), word
);
1259 Buf_AddBytes(buf
, strlen(word
), word
);
1261 return (dummy
? TRUE
: TRUE
);
1265 *-----------------------------------------------------------------------
1267 * Place the word in the buffer if it matches the given pattern.
1268 * Callback function for VarModify to implement the :M modifier.
1271 * word Word to examine
1272 * addSpace TRUE if need to add a space to the buffer
1273 * before adding the word, if it matches
1274 * buf Buffer in which to store it
1275 * pattern Pattern the word must match
1278 * TRUE if a space should be placed in the buffer before the next
1282 * The word may be copied to the buffer.
1284 *-----------------------------------------------------------------------
1287 VarMatch(GNode
*ctx __unused
, Var_Parse_State
*vpstate
,
1288 char *word
, Boolean addSpace
, Buffer
*buf
,
1292 fprintf(debug_file
, "VarMatch [%s] [%s]\n", word
, (char *)pattern
);
1293 if (Str_Match(word
, (char *)pattern
)) {
1294 if (addSpace
&& vpstate
->varSpace
) {
1295 Buf_AddByte(buf
, vpstate
->varSpace
);
1298 Buf_AddBytes(buf
, strlen(word
), word
);
1305 *-----------------------------------------------------------------------
1307 * Place the word in the buffer if it matches the given pattern.
1308 * Callback function for VarModify to implement the System V %
1312 * word Word to examine
1313 * addSpace TRUE if need to add a space to the buffer
1314 * before adding the word, if it matches
1315 * buf Buffer in which to store it
1316 * patp Pattern the word must match
1319 * TRUE if a space should be placed in the buffer before the next
1323 * The word may be copied to the buffer.
1325 *-----------------------------------------------------------------------
1328 VarSYSVMatch(GNode
*ctx
, Var_Parse_State
*vpstate
,
1329 char *word
, Boolean addSpace
, Buffer
*buf
,
1334 VarPattern
*pat
= (VarPattern
*)patp
;
1337 if (addSpace
&& vpstate
->varSpace
)
1338 Buf_AddByte(buf
, vpstate
->varSpace
);
1342 if ((ptr
= Str_SYSVMatch(word
, pat
->lhs
, &len
)) != NULL
) {
1343 varexp
= Var_Subst(NULL
, pat
->rhs
, ctx
, 0);
1344 Str_SYSVSubst(buf
, varexp
, ptr
, len
);
1347 Buf_AddBytes(buf
, strlen(word
), word
);
1356 *-----------------------------------------------------------------------
1358 * Place the word in the buffer if it doesn't match the given pattern.
1359 * Callback function for VarModify to implement the :N modifier.
1362 * word Word to examine
1363 * addSpace TRUE if need to add a space to the buffer
1364 * before adding the word, if it matches
1365 * buf Buffer in which to store it
1366 * pattern Pattern the word must match
1369 * TRUE if a space should be placed in the buffer before the next
1373 * The word may be copied to the buffer.
1375 *-----------------------------------------------------------------------
1378 VarNoMatch(GNode
*ctx __unused
, Var_Parse_State
*vpstate
,
1379 char *word
, Boolean addSpace
, Buffer
*buf
,
1382 if (!Str_Match(word
, (char *)pattern
)) {
1383 if (addSpace
&& vpstate
->varSpace
) {
1384 Buf_AddByte(buf
, vpstate
->varSpace
);
1387 Buf_AddBytes(buf
, strlen(word
), word
);
1394 *-----------------------------------------------------------------------
1396 * Perform a string-substitution on the given word, placing the
1397 * result in the passed buffer.
1400 * word Word to modify
1401 * addSpace True if space should be added before
1403 * buf Buffer for result
1404 * patternp Pattern for substitution
1407 * TRUE if a space is needed before more characters are added.
1412 *-----------------------------------------------------------------------
1415 VarSubstitute(GNode
*ctx __unused
, Var_Parse_State
*vpstate
,
1416 char *word
, Boolean addSpace
, Buffer
*buf
,
1419 int wordLen
; /* Length of word */
1420 char *cp
; /* General pointer */
1421 VarPattern
*pattern
= (VarPattern
*)patternp
;
1423 wordLen
= strlen(word
);
1424 if ((pattern
->flags
& (VAR_SUB_ONE
|VAR_SUB_MATCHED
)) !=
1425 (VAR_SUB_ONE
|VAR_SUB_MATCHED
)) {
1427 * Still substituting -- break it down into simple anchored cases
1428 * and if none of them fits, perform the general substitution case.
1430 if ((pattern
->flags
& VAR_MATCH_START
) &&
1431 (strncmp(word
, pattern
->lhs
, pattern
->leftLen
) == 0)) {
1433 * Anchored at start and beginning of word matches pattern
1435 if ((pattern
->flags
& VAR_MATCH_END
) &&
1436 (wordLen
== pattern
->leftLen
)) {
1438 * Also anchored at end and matches to the end (word
1439 * is same length as pattern) add space and rhs only
1440 * if rhs is non-null.
1442 if (pattern
->rightLen
!= 0) {
1443 if (addSpace
&& vpstate
->varSpace
) {
1444 Buf_AddByte(buf
, vpstate
->varSpace
);
1447 Buf_AddBytes(buf
, pattern
->rightLen
, pattern
->rhs
);
1449 pattern
->flags
|= VAR_SUB_MATCHED
;
1450 } else if (pattern
->flags
& VAR_MATCH_END
) {
1452 * Doesn't match to end -- copy word wholesale
1457 * Matches at start but need to copy in trailing characters
1459 if ((pattern
->rightLen
+ wordLen
- pattern
->leftLen
) != 0){
1460 if (addSpace
&& vpstate
->varSpace
) {
1461 Buf_AddByte(buf
, vpstate
->varSpace
);
1465 Buf_AddBytes(buf
, pattern
->rightLen
, pattern
->rhs
);
1466 Buf_AddBytes(buf
, wordLen
- pattern
->leftLen
,
1467 (word
+ pattern
->leftLen
));
1468 pattern
->flags
|= VAR_SUB_MATCHED
;
1470 } else if (pattern
->flags
& VAR_MATCH_START
) {
1472 * Had to match at start of word and didn't -- copy whole word.
1475 } else if (pattern
->flags
& VAR_MATCH_END
) {
1477 * Anchored at end, Find only place match could occur (leftLen
1478 * characters from the end of the word) and see if it does. Note
1479 * that because the $ will be left at the end of the lhs, we have
1482 cp
= word
+ (wordLen
- pattern
->leftLen
);
1484 (strncmp(cp
, pattern
->lhs
, pattern
->leftLen
) == 0)) {
1486 * Match found. If we will place characters in the buffer,
1487 * add a space before hand as indicated by addSpace, then
1488 * stuff in the initial, unmatched part of the word followed
1489 * by the right-hand-side.
1491 if (((cp
- word
) + pattern
->rightLen
) != 0) {
1492 if (addSpace
&& vpstate
->varSpace
) {
1493 Buf_AddByte(buf
, vpstate
->varSpace
);
1497 Buf_AddBytes(buf
, cp
- word
, word
);
1498 Buf_AddBytes(buf
, pattern
->rightLen
, pattern
->rhs
);
1499 pattern
->flags
|= VAR_SUB_MATCHED
;
1502 * Had to match at end and didn't. Copy entire word.
1508 * Pattern is unanchored: search for the pattern in the word using
1509 * String_FindSubstring, copying unmatched portions and the
1510 * right-hand-side for each match found, handling non-global
1511 * substitutions correctly, etc. When the loop is done, any
1512 * remaining part of the word (word and wordLen are adjusted
1513 * accordingly through the loop) is copied straight into the
1515 * addSpace is set FALSE as soon as a space is added to the
1522 origSize
= Buf_Size(buf
);
1524 cp
= Str_FindSubstring(word
, pattern
->lhs
);
1526 if (addSpace
&& (((cp
- word
) + pattern
->rightLen
) != 0)){
1527 Buf_AddByte(buf
, vpstate
->varSpace
);
1530 Buf_AddBytes(buf
, cp
-word
, word
);
1531 Buf_AddBytes(buf
, pattern
->rightLen
, pattern
->rhs
);
1532 wordLen
-= (cp
- word
) + pattern
->leftLen
;
1533 word
= cp
+ pattern
->leftLen
;
1537 if ((pattern
->flags
& VAR_SUB_GLOBAL
) == 0) {
1540 pattern
->flags
|= VAR_SUB_MATCHED
;
1546 if (addSpace
&& vpstate
->varSpace
) {
1547 Buf_AddByte(buf
, vpstate
->varSpace
);
1549 Buf_AddBytes(buf
, wordLen
, word
);
1552 * If added characters to the buffer, need to add a space
1553 * before we add any more. If we didn't add any, just return
1554 * the previous value of addSpace.
1556 return ((Buf_Size(buf
) != origSize
) || addSpace
);
1561 if (addSpace
&& vpstate
->varSpace
) {
1562 Buf_AddByte(buf
, vpstate
->varSpace
);
1564 Buf_AddBytes(buf
, wordLen
, word
);
1570 *-----------------------------------------------------------------------
1572 * Print the error caused by a regcomp or regexec call.
1578 * An error gets printed.
1580 *-----------------------------------------------------------------------
1583 VarREError(int errnum
, regex_t
*pat
, const char *str
)
1588 errlen
= regerror(errnum
, pat
, 0, 0);
1589 errbuf
= bmake_malloc(errlen
);
1590 regerror(errnum
, pat
, errbuf
, errlen
);
1591 Error("%s: %s", str
, errbuf
);
1597 *-----------------------------------------------------------------------
1598 * VarRESubstitute --
1599 * Perform a regex substitution on the given word, placing the
1600 * result in the passed buffer.
1603 * TRUE if a space is needed before more characters are added.
1608 *-----------------------------------------------------------------------
1611 VarRESubstitute(GNode
*ctx __unused
, Var_Parse_State
*vpstate __unused
,
1612 char *word
, Boolean addSpace
, Buffer
*buf
,
1622 #define MAYBE_ADD_SPACE() \
1623 if (addSpace && !added) \
1624 Buf_AddByte(buf, ' '); \
1631 if ((pat
->flags
& (VAR_SUB_ONE
|VAR_SUB_MATCHED
)) ==
1632 (VAR_SUB_ONE
|VAR_SUB_MATCHED
))
1636 xrv
= regexec(&pat
->re
, wp
, pat
->nsub
, pat
->matches
, flags
);
1641 pat
->flags
|= VAR_SUB_MATCHED
;
1642 if (pat
->matches
[0].rm_so
> 0) {
1644 Buf_AddBytes(buf
, pat
->matches
[0].rm_so
, wp
);
1647 for (rp
= pat
->replace
; *rp
; rp
++) {
1648 if ((*rp
== '\\') && ((rp
[1] == '&') || (rp
[1] == '\\'))) {
1650 Buf_AddByte(buf
,rp
[1]);
1653 else if ((*rp
== '&') ||
1654 ((*rp
== '\\') && isdigit((unsigned char)rp
[1]))) {
1672 if (n
> pat
->nsub
) {
1673 Error("No subexpression %s", &errstr
[0]);
1676 } else if ((pat
->matches
[n
].rm_so
== -1) &&
1677 (pat
->matches
[n
].rm_eo
== -1)) {
1678 Error("No match for subexpression %s", &errstr
[0]);
1682 subbuf
= wp
+ pat
->matches
[n
].rm_so
;
1683 sublen
= pat
->matches
[n
].rm_eo
- pat
->matches
[n
].rm_so
;
1688 Buf_AddBytes(buf
, sublen
, subbuf
);
1692 Buf_AddByte(buf
, *rp
);
1695 wp
+= pat
->matches
[0].rm_eo
;
1696 if (pat
->flags
& VAR_SUB_GLOBAL
) {
1697 flags
|= REG_NOTBOL
;
1698 if (pat
->matches
[0].rm_so
== 0 && pat
->matches
[0].rm_eo
== 0) {
1700 Buf_AddByte(buf
, *wp
);
1709 Buf_AddBytes(buf
, strlen(wp
), wp
);
1713 VarREError(xrv
, &pat
->re
, "Unexpected regex error");
1718 Buf_AddBytes(buf
,strlen(wp
),wp
);
1722 return(addSpace
||added
);
1729 *-----------------------------------------------------------------------
1731 * Implements the :@<temp>@<string>@ modifier of ODE make.
1732 * We set the temp variable named in pattern.lhs to word and expand
1733 * pattern.rhs storing the result in the passed buffer.
1736 * word Word to modify
1737 * addSpace True if space should be added before
1739 * buf Buffer for result
1740 * pattern Datafor substitution
1743 * TRUE if a space is needed before more characters are added.
1748 *-----------------------------------------------------------------------
1751 VarLoopExpand(GNode
*ctx __unused
, Var_Parse_State
*vpstate __unused
,
1752 char *word
, Boolean addSpace
, Buffer
*buf
,
1755 VarLoop_t
*loop
= (VarLoop_t
*)loopp
;
1759 if (word
&& *word
) {
1760 Var_Set(loop
->tvar
, word
, loop
->ctxt
, VAR_NO_EXPORT
);
1761 s
= Var_Subst(NULL
, loop
->str
, loop
->ctxt
, loop
->errnum
);
1762 if (s
!= NULL
&& *s
!= '\0') {
1763 if (addSpace
&& *s
!= '\n')
1764 Buf_AddByte(buf
, ' ');
1765 Buf_AddBytes(buf
, (slen
= strlen(s
)), s
);
1766 addSpace
= (slen
> 0 && s
[slen
- 1] != '\n');
1775 *-----------------------------------------------------------------------
1777 * Implements the :[start..end] modifier.
1778 * This is a special case of VarModify since we want to be able
1779 * to scan the list backwards if start > end.
1782 * str String whose words should be trimmed
1783 * seldata words to select
1786 * A string of all the words selected.
1791 *-----------------------------------------------------------------------
1794 VarSelectWords(GNode
*ctx __unused
, Var_Parse_State
*vpstate
,
1795 const char *str
, VarSelectWords_t
*seldata
)
1797 Buffer buf
; /* Buffer for the new string */
1798 Boolean addSpace
; /* TRUE if need to add a space to the
1799 * buffer before adding the trimmed
1801 char **av
; /* word list */
1802 char *as
; /* word list memory */
1804 int start
, end
, step
;
1809 if (vpstate
->oneBigWord
) {
1810 /* fake what brk_string() would do if there were only one word */
1812 av
= bmake_malloc((ac
+ 1) * sizeof(char *));
1813 as
= bmake_strdup(str
);
1817 av
= brk_string(str
, &ac
, FALSE
, &as
);
1821 * Now sanitize seldata.
1822 * If seldata->start or seldata->end are negative, convert them to
1823 * the positive equivalents (-1 gets converted to argc, -2 gets
1824 * converted to (argc-1), etc.).
1826 if (seldata
->start
< 0)
1827 seldata
->start
= ac
+ seldata
->start
+ 1;
1828 if (seldata
->end
< 0)
1829 seldata
->end
= ac
+ seldata
->end
+ 1;
1832 * We avoid scanning more of the list than we need to.
1834 if (seldata
->start
> seldata
->end
) {
1835 start
= MIN(ac
, seldata
->start
) - 1;
1836 end
= MAX(0, seldata
->end
- 1);
1839 start
= MAX(0, seldata
->start
- 1);
1840 end
= MIN(ac
, seldata
->end
);
1845 (step
< 0 && i
>= end
) || (step
> 0 && i
< end
);
1847 if (av
[i
] && *av
[i
]) {
1848 if (addSpace
&& vpstate
->varSpace
) {
1849 Buf_AddByte(&buf
, vpstate
->varSpace
);
1851 Buf_AddBytes(&buf
, strlen(av
[i
]), av
[i
]);
1859 return Buf_Destroy(&buf
, FALSE
);
1863 *-----------------------------------------------------------------------
1865 * Modify each of the words of the passed string using the given
1866 * function. Used to implement all modifiers.
1869 * str String whose words should be trimmed
1870 * modProc Function to use to modify them
1871 * datum Datum to pass it
1874 * A string of all the words modified appropriately.
1879 *-----------------------------------------------------------------------
1882 VarModify(GNode
*ctx
, Var_Parse_State
*vpstate
,
1884 Boolean (*modProc
)(GNode
*, Var_Parse_State
*, char *,
1885 Boolean
, Buffer
*, void *),
1888 Buffer buf
; /* Buffer for the new string */
1889 Boolean addSpace
; /* TRUE if need to add a space to the
1890 * buffer before adding the trimmed
1892 char **av
; /* word list */
1893 char *as
; /* word list memory */
1899 if (vpstate
->oneBigWord
) {
1900 /* fake what brk_string() would do if there were only one word */
1902 av
= bmake_malloc((ac
+ 1) * sizeof(char *));
1903 as
= bmake_strdup(str
);
1907 av
= brk_string(str
, &ac
, FALSE
, &as
);
1910 for (i
= 0; i
< ac
; i
++) {
1911 addSpace
= (*modProc
)(ctx
, vpstate
, av
[i
], addSpace
, &buf
, datum
);
1917 return Buf_Destroy(&buf
, FALSE
);
1922 VarWordCompare(const void *a
, const void *b
)
1924 int r
= strcmp(*(const char * const *)a
, *(const char * const *)b
);
1929 *-----------------------------------------------------------------------
1931 * Order the words in the string.
1934 * str String whose words should be sorted.
1935 * otype How to order: s - sort, x - random.
1938 * A string containing the words ordered.
1943 *-----------------------------------------------------------------------
1946 VarOrder(const char *str
, const char otype
)
1948 Buffer buf
; /* Buffer for the new string */
1949 char **av
; /* word list [first word does not count] */
1950 char *as
; /* word list memory */
1955 av
= brk_string(str
, &ac
, FALSE
, &as
);
1959 case 's': /* sort alphabetically */
1960 qsort(av
, ac
, sizeof(char *), VarWordCompare
);
1962 case 'x': /* randomize */
1968 * We will use [ac..2] range for mod factors. This will produce
1969 * random numbers in [(ac-1)..0] interval, and minimal
1970 * reasonable value for mod factor is 2 (the mod 1 will produce
1971 * 0 with probability 1).
1973 for (i
= ac
-1; i
> 0; i
--) {
1974 rndidx
= random() % (i
+ 1);
1982 } /* end of switch */
1984 for (i
= 0; i
< ac
; i
++) {
1985 Buf_AddBytes(&buf
, strlen(av
[i
]), av
[i
]);
1987 Buf_AddByte(&buf
, ' ');
1993 return Buf_Destroy(&buf
, FALSE
);
1998 *-----------------------------------------------------------------------
2000 * Remove adjacent duplicate words.
2003 * str String whose words should be sorted
2006 * A string containing the resulting words.
2011 *-----------------------------------------------------------------------
2014 VarUniq(const char *str
)
2016 Buffer buf
; /* Buffer for new string */
2017 char **av
; /* List of words to affect */
2018 char *as
; /* Word list memory */
2022 av
= brk_string(str
, &ac
, FALSE
, &as
);
2025 for (j
= 0, i
= 1; i
< ac
; i
++)
2026 if (strcmp(av
[i
], av
[j
]) != 0 && (++j
!= i
))
2031 for (i
= 0; i
< ac
; i
++) {
2032 Buf_AddBytes(&buf
, strlen(av
[i
]), av
[i
]);
2034 Buf_AddByte(&buf
, ' ');
2040 return Buf_Destroy(&buf
, FALSE
);
2045 *-----------------------------------------------------------------------
2047 * Pass through the tstr looking for 1) escaped delimiters,
2048 * '$'s and backslashes (place the escaped character in
2049 * uninterpreted) and 2) unescaped $'s that aren't before
2050 * the delimiter (expand the variable substitution unless flags
2051 * has VAR_NOSUBST set).
2052 * Return the expanded string or NULL if the delimiter was missing
2053 * If pattern is specified, handle escaped ampersands, and replace
2054 * unescaped ampersands with the lhs of the pattern.
2057 * A string of all the words modified appropriately.
2058 * If length is specified, return the string length of the buffer
2059 * If flags is specified and the last character of the pattern is a
2060 * $ set the VAR_MATCH_END bit of flags.
2064 *-----------------------------------------------------------------------
2067 VarGetPattern(GNode
*ctxt
, Var_Parse_State
*vpstate __unused
,
2068 int errnum
, const char **tstr
, int delim
, int *flags
,
2069 int *length
, VarPattern
*pattern
)
2080 #define IS_A_MATCH(cp, delim) \
2081 ((cp[0] == '\\') && ((cp[1] == delim) || \
2082 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
2085 * Skim through until the matching delimiter is found;
2086 * pick up variable substitutions on the way. Also allow
2087 * backslashes to quote the delimiter, $, and \, but don't
2088 * touch other backslashes.
2090 for (cp
= *tstr
; *cp
&& (*cp
!= delim
); cp
++) {
2091 if (IS_A_MATCH(cp
, delim
)) {
2092 Buf_AddByte(&buf
, cp
[1]);
2094 } else if (*cp
== '$') {
2095 if (cp
[1] == delim
) {
2097 Buf_AddByte(&buf
, *cp
);
2100 * Unescaped $ at end of pattern => anchor
2103 *flags
|= VAR_MATCH_END
;
2105 if (flags
== NULL
|| (*flags
& VAR_NOSUBST
) == 0) {
2111 * If unescaped dollar sign not before the
2112 * delimiter, assume it's a variable
2113 * substitution and recurse.
2115 cp2
= Var_Parse(cp
, ctxt
, errnum
, &len
, &freeIt
);
2116 Buf_AddBytes(&buf
, strlen(cp2
), cp2
);
2121 const char *cp2
= &cp
[1];
2123 if (*cp2
== PROPEN
|| *cp2
== BROPEN
) {
2125 * Find the end of this variable reference
2126 * and suck it in without further ado.
2127 * It will be interperated later.
2130 int want
= (*cp2
== PROPEN
) ? PRCLOSE
: BRCLOSE
;
2133 for (++cp2
; *cp2
!= '\0' && depth
> 0; ++cp2
) {
2134 if (cp2
[-1] != '\\') {
2141 Buf_AddBytes(&buf
, cp2
- cp
, cp
);
2144 Buf_AddByte(&buf
, *cp
);
2148 else if (pattern
&& *cp
== '&')
2149 Buf_AddBytes(&buf
, pattern
->leftLen
, pattern
->lhs
);
2151 Buf_AddByte(&buf
, *cp
);
2161 *length
= Buf_Size(&buf
);
2162 rstr
= Buf_Destroy(&buf
, FALSE
);
2164 fprintf(debug_file
, "Modifier pattern: \"%s\"\n", rstr
);
2169 *-----------------------------------------------------------------------
2171 * Quote shell meta-characters in the string
2179 *-----------------------------------------------------------------------
2186 /* This should cover most shells :-( */
2187 static const char meta
[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
2188 const char *newline
;
2191 if ((newline
= Shell_GetNewline()) == NULL
)
2193 nlen
= strlen(newline
);
2196 while (*str
!= '\0') {
2197 if ((len
= strcspn(str
, meta
)) != 0) {
2198 Buf_AddBytes(&buf
, len
, str
);
2200 } else if (*str
== '\n') {
2201 Buf_AddBytes(&buf
, nlen
, newline
);
2204 Buf_AddByte(&buf
, '\\');
2205 Buf_AddByte(&buf
, *str
);
2209 str
= Buf_Destroy(&buf
, FALSE
);
2211 fprintf(debug_file
, "QuoteMeta: [%s]\n", str
);
2216 *-----------------------------------------------------------------------
2218 * Change the string to all uppercase or all lowercase
2221 * str String to modify
2222 * upper TRUE -> uppercase, else lowercase
2225 * The string with case changed
2230 *-----------------------------------------------------------------------
2233 VarChangeCase(char *str
, int upper
)
2236 int (*modProc
)(int);
2238 modProc
= (upper
? toupper
: tolower
);
2240 for (; *str
; str
++) {
2241 Buf_AddByte(&buf
, modProc(*str
));
2243 return Buf_Destroy(&buf
, FALSE
);
2247 * Now we need to apply any modifiers the user wants applied.
2249 * :M<pattern> words which match the given <pattern>.
2250 * <pattern> is of the standard file
2252 * :N<pattern> words which do not match the given <pattern>.
2253 * :S<d><pat1><d><pat2><d>[1gW]
2254 * Substitute <pat2> for <pat1> in the value
2255 * :C<d><pat1><d><pat2><d>[1gW]
2256 * Substitute <pat2> for regex <pat1> in the value
2257 * :H Substitute the head of each word
2258 * :T Substitute the tail of each word
2259 * :E Substitute the extension (minus '.') of
2261 * :R Substitute the root of each word
2262 * (pathname minus the suffix).
2263 * :O ("Order") Alphabeticaly sort words in variable.
2264 * :Ox ("intermiX") Randomize words in variable.
2265 * :u ("uniq") Remove adjacent duplicate words.
2266 * :tu Converts the variable contents to uppercase.
2267 * :tl Converts the variable contents to lowercase.
2268 * :ts[c] Sets varSpace - the char used to
2269 * separate words to 'c'. If 'c' is
2270 * omitted then no separation is used.
2271 * :tW Treat the variable contents as a single
2272 * word, even if it contains spaces.
2273 * (Mnemonic: one big 'W'ord.)
2274 * :tw Treat the variable contents as multiple
2275 * space-separated words.
2276 * (Mnemonic: many small 'w'ords.)
2277 * :[index] Select a single word from the value.
2278 * :[start..end] Select multiple words from the value.
2279 * :[*] or :[0] Select the entire value, as a single
2280 * word. Equivalent to :tW.
2281 * :[@] Select the entire value, as multiple
2282 * words. Undoes the effect of :[*].
2283 * Equivalent to :tw.
2284 * :[#] Returns the number of words in the value.
2286 * :?<true-value>:<false-value>
2287 * If the variable evaluates to true, return
2288 * true value, else return the second value.
2289 * :lhs=rhs Like :S, but the rhs goes to the end of
2291 * :sh Treat the current value as a command
2292 * to be run, new value is its output.
2293 * The following added so we can handle ODE makefiles.
2294 * :@<tmpvar>@<newval>@
2295 * Assign a temporary local variable <tmpvar>
2296 * to the current value of each word in turn
2297 * and replace each word with the result of
2298 * evaluating <newval>
2299 * :D<newval> Use <newval> as value if variable defined
2300 * :U<newval> Use <newval> as value if variable undefined
2301 * :L Use the name of the variable as the value.
2302 * :P Use the path of the node that has the same
2303 * name as the variable as the value. This
2304 * basically includes an implied :L so that
2305 * the common method of refering to the path
2306 * of your dependent 'x' in a rule is to use
2307 * the form '${x:P}'.
2308 * :!<cmd>! Run cmd much the same as :sh run's the
2309 * current value of the variable.
2310 * The ::= modifiers, actually assign a value to the variable.
2311 * Their main purpose is in supporting modifiers of .for loop
2312 * iterators and other obscure uses. They always expand to
2313 * nothing. In a target rule that would otherwise expand to an
2314 * empty line they can be preceded with @: to keep make happy.
2318 * .for i in ${.TARGET} ${.TARGET:R}.gz
2323 * ::=<str> Assigns <str> as the new value of variable.
2324 * ::?=<str> Assigns <str> as value of variable if
2325 * it was not already set.
2326 * ::+=<str> Appends <str> to variable.
2327 * ::!=<cmd> Assigns output of <cmd> as the new value of
2332 ApplyModifiers(char *nstr
, const char *tstr
,
2333 int startc
, int endc
,
2334 Var
*v
, GNode
*ctxt
, Boolean errnum
,
2335 int *lengthPtr
, void **freePtr
)
2338 const char *cp
; /* Secondary pointer into str (place marker
2340 char *newStr
; /* New value to return */
2341 char termc
; /* Character which terminated scan */
2342 int cnt
; /* Used to count brace pairs when variable in
2343 * in parens or braces */
2345 int modifier
; /* that we are processing */
2346 Var_Parse_State parsestate
; /* Flags passed to helper functions */
2349 parsestate
.oneBigWord
= FALSE
;
2350 parsestate
.varSpace
= ' '; /* word separator */
2354 while (*tstr
&& *tstr
!= endc
) {
2358 * We have some complex modifiers in a variable.
2364 rval
= Var_Parse(tstr
, ctxt
, errnum
, &rlen
, &freeIt
);
2367 fprintf(debug_file
, "Got '%s' from '%.*s'%.*s\n",
2368 rval
, rlen
, tstr
, rlen
, tstr
+ rlen
);
2373 if (rval
!= NULL
&& *rval
) {
2376 nstr
= ApplyModifiers(nstr
, rval
,
2378 v
, ctxt
, errnum
, &used
, freePtr
);
2379 if (nstr
== var_Error
2380 || (nstr
== varNoError
&& errnum
== 0)
2381 || strlen(rval
) != (size_t) used
) {
2384 goto out
; /* error already reported */
2391 else if (!*tstr
&& endc
) {
2392 Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc
, v
->name
);
2398 fprintf(debug_file
, "Applying :%c to \"%s\"\n", *tstr
, nstr
);
2401 switch ((modifier
= *tstr
)) {
2404 if (tstr
[1] == '=' ||
2406 (tstr
[1] == '!' || tstr
[1] == '+' || tstr
[1] == '?'))) {
2408 * "::=", "::!=", "::+=", or "::?="
2410 GNode
*v_ctxt
; /* context where v belongs */
2416 if (v
->name
[0] == 0)
2422 if (v
->flags
& VAR_JUNK
) {
2424 * We need to bmake_strdup() it incase
2425 * VarGetPattern() recurses.
2428 v
->name
= bmake_strdup(v
->name
);
2429 } else if (ctxt
!= VAR_GLOBAL
) {
2430 Var
*gv
= VarFind(v
->name
, ctxt
, 0);
2432 v_ctxt
= VAR_GLOBAL
;
2434 VarFreeEnv(gv
, TRUE
);
2437 switch ((how
= *tstr
)) {
2450 pattern
.rhs
= VarGetPattern(ctxt
, &parsestate
, errnum
,
2454 if (v
->flags
& VAR_JUNK
) {
2455 /* restore original name */
2459 if (pattern
.rhs
== NULL
)
2467 Var_Append(v
->name
, pattern
.rhs
, v_ctxt
);
2470 newStr
= Cmd_Exec(pattern
.rhs
, &emsg
);
2474 Var_Set(v
->name
, newStr
, v_ctxt
, 0);
2479 if ((v
->flags
& VAR_JUNK
) == 0)
2483 Var_Set(v
->name
, pattern
.rhs
, v_ctxt
, 0);
2486 free(UNCONST(pattern
.rhs
));
2490 goto default_case
; /* "::<unrecognised>" */
2495 int flags
= VAR_NOSUBST
;
2499 if ((loop
.tvar
= VarGetPattern(ctxt
, &parsestate
, errnum
,
2501 &flags
, &loop
.tvarLen
,
2505 if ((loop
.str
= VarGetPattern(ctxt
, &parsestate
, errnum
,
2507 &flags
, &loop
.strLen
,
2514 loop
.errnum
= errnum
;
2516 newStr
= VarModify(ctxt
, &parsestate
, nstr
, VarLoopExpand
,
2525 Buffer buf
; /* Buffer for patterns */
2526 int wantit
; /* want data in buffer */
2529 * Pass through tstr looking for 1) escaped delimiters,
2530 * '$'s and backslashes (place the escaped character in
2531 * uninterpreted) and 2) unescaped $'s that aren't before
2532 * the delimiter (expand the variable substitution).
2533 * The result is left in the Buffer buf.
2537 *cp
!= endc
&& *cp
!= ':' && *cp
!= '\0';
2539 if ((*cp
== '\\') &&
2545 Buf_AddByte(&buf
, cp
[1]);
2547 } else if (*cp
== '$') {
2549 * If unescaped dollar sign, assume it's a
2550 * variable substitution and recurse.
2556 cp2
= Var_Parse(cp
, ctxt
, errnum
, &len
, &freeIt
);
2557 Buf_AddBytes(&buf
, strlen(cp2
), cp2
);
2562 Buf_AddByte(&buf
, *cp
);
2569 wantit
= ((v
->flags
& VAR_JUNK
) != 0);
2571 wantit
= ((v
->flags
& VAR_JUNK
) == 0);
2572 if ((v
->flags
& VAR_JUNK
) != 0)
2573 v
->flags
|= VAR_KEEP
;
2575 newStr
= Buf_Destroy(&buf
, FALSE
);
2578 Buf_Destroy(&buf
, TRUE
);
2584 if ((v
->flags
& VAR_JUNK
) != 0)
2585 v
->flags
|= VAR_KEEP
;
2586 newStr
= bmake_strdup(v
->name
);
2595 if ((v
->flags
& VAR_JUNK
) != 0)
2596 v
->flags
|= VAR_KEEP
;
2597 gn
= Targ_FindNode(v
->name
, TARG_NOCREATE
);
2598 if (gn
== NULL
|| gn
->type
& OP_NOPATH
) {
2600 } else if (gn
->path
) {
2601 newStr
= bmake_strdup(gn
->path
);
2603 newStr
= Dir_FindFile(v
->name
, Suff_FindPath(gn
));
2606 newStr
= bmake_strdup(v
->name
);
2621 if ((pattern
.rhs
= VarGetPattern(ctxt
, &parsestate
, errnum
,
2623 NULL
, &pattern
.rightLen
,
2626 newStr
= Cmd_Exec(pattern
.rhs
, &emsg
);
2627 free(UNCONST(pattern
.rhs
));
2632 if (v
->flags
& VAR_JUNK
) {
2633 v
->flags
|= VAR_KEEP
;
2640 * Look for the closing ']', recursively
2641 * expanding any embedded variables.
2643 * estr is a pointer to the expanded result,
2644 * which we must free().
2648 cp
= tstr
+1; /* point to char after '[' */
2649 delim
= ']'; /* look for closing ']' */
2650 estr
= VarGetPattern(ctxt
, &parsestate
,
2654 goto cleanup
; /* report missing ']' */
2655 /* now cp points just after the closing ']' */
2657 if (cp
[0] != ':' && cp
[0] != endc
) {
2658 /* Found junk after ']' */
2662 if (estr
[0] == '\0') {
2663 /* Found empty square brackets in ":[]". */
2666 } else if (estr
[0] == '#' && estr
[1] == '\0') {
2670 * We will need enough space for the decimal
2671 * representation of an int. We calculate the
2672 * space needed for the octal representation,
2673 * and add enough slop to cope with a '-' sign
2674 * (which should never be needed) and a '\0'
2675 * string terminator.
2678 (sizeof(int) * CHAR_BIT
+ 2) / 3 + 2;
2680 newStr
= bmake_malloc(newStrSize
);
2681 if (parsestate
.oneBigWord
) {
2682 strncpy(newStr
, "1", newStrSize
);
2684 /* XXX: brk_string() is a rather expensive
2685 * way of counting words. */
2690 av
= brk_string(nstr
, &ac
, FALSE
, &as
);
2691 snprintf(newStr
, newStrSize
, "%d", ac
);
2698 } else if (estr
[0] == '*' && estr
[1] == '\0') {
2700 parsestate
.oneBigWord
= TRUE
;
2705 } else if (estr
[0] == '@' && estr
[1] == '\0') {
2707 parsestate
.oneBigWord
= FALSE
;
2714 * We expect estr to contain a single
2715 * integer for :[N], or two integers
2716 * separated by ".." for :[start..end].
2720 VarSelectWords_t seldata
= { 0, 0 };
2722 seldata
.start
= strtol(estr
, &ep
, 0);
2724 /* Found junk instead of a number */
2727 } else if (ep
[0] == '\0') {
2728 /* Found only one integer in :[N] */
2729 seldata
.end
= seldata
.start
;
2730 } else if (ep
[0] == '.' && ep
[1] == '.' &&
2732 /* Expecting another integer after ".." */
2734 seldata
.end
= strtol(ep
, &ep
, 0);
2735 if (ep
[0] != '\0') {
2736 /* Found junk after ".." */
2741 /* Found junk instead of ".." */
2746 * Now seldata is properly filled in,
2747 * but we still have to check for 0 as
2750 if (seldata
.start
== 0 && seldata
.end
== 0) {
2751 /* ":[0]" or perhaps ":[0..0]" */
2752 parsestate
.oneBigWord
= TRUE
;
2757 } else if (seldata
.start
== 0 ||
2759 /* ":[0..N]" or ":[N..0]" */
2764 * Normal case: select the words
2765 * described by seldata.
2767 newStr
= VarSelectWords(ctxt
, &parsestate
,
2778 cp
= tstr
+ 1; /* make sure it is set */
2779 if (tstr
[1] != endc
&& tstr
[1] != ':') {
2780 if (tstr
[1] == 's') {
2782 * Use the char (if any) at tstr[2]
2783 * as the word separator.
2787 if (tstr
[2] != endc
&&
2788 (tstr
[3] == endc
|| tstr
[3] == ':')) {
2789 /* ":ts<unrecognised><endc>" or
2790 * ":ts<unrecognised>:" */
2791 parsestate
.varSpace
= tstr
[2];
2793 } else if (tstr
[2] == endc
|| tstr
[2] == ':') {
2794 /* ":ts<endc>" or ":ts:" */
2795 parsestate
.varSpace
= 0; /* no separator */
2797 } else if (tstr
[2] == '\\') {
2800 parsestate
.varSpace
= '\n';
2804 parsestate
.varSpace
= '\t';
2808 if (isdigit((unsigned char)tstr
[3])) {
2811 parsestate
.varSpace
=
2812 strtoul(&tstr
[3], &ep
, 0);
2813 if (*ep
!= ':' && *ep
!= endc
)
2818 * ":ts<backslash><unrecognised>".
2826 * Found ":ts<unrecognised><unrecognised>".
2834 * We cannot be certain that VarModify
2835 * will be used - even if there is a
2836 * subsequent modifier, so do a no-op
2837 * VarSubstitute now to for str to be
2838 * re-expanded without the spaces.
2840 pattern
.flags
= VAR_SUB_ONE
;
2841 pattern
.lhs
= pattern
.rhs
= "\032";
2842 pattern
.leftLen
= pattern
.rightLen
= 1;
2844 newStr
= VarModify(ctxt
, &parsestate
, nstr
,
2847 } else if (tstr
[2] == endc
|| tstr
[2] == ':') {
2849 * Check for two-character options:
2852 if (tstr
[1] == 'u' || tstr
[1] == 'l') {
2853 newStr
= VarChangeCase(nstr
, (tstr
[1] == 'u'));
2856 } else if (tstr
[1] == 'W' || tstr
[1] == 'w') {
2857 parsestate
.oneBigWord
= (tstr
[1] == 'W');
2862 /* Found ":t<unrecognised>:" or
2863 * ":t<unrecognised><endc>". */
2868 * Found ":t<unrecognised><unrecognised>".
2874 * Found ":t<endc>" or ":t:".
2884 const char *endpat
; /* points just after end of pattern */
2886 Boolean copy
; /* pattern should be, or has been, copied */
2894 * In the loop below, ignore ':' unless we are at
2895 * (or back to) the original brace level.
2896 * XXX This will likely not work right if $() and ${}
2900 *cp
!= '\0' && !(*cp
== ':' && nest
== 1);
2905 cp
[1] == endc
|| cp
[1] == startc
)) {
2915 if (*cp
== '(' || *cp
== '{')
2917 if (*cp
== ')' || *cp
== '}') {
2927 * Need to compress the \:'s out of the pattern, so
2928 * allocate enough room to hold the uncompressed
2929 * pattern (note that cp started at tstr+1, so
2930 * cp - tstr takes the null byte into account) and
2931 * compress the pattern into the space.
2933 pattern
= bmake_malloc(cp
- tstr
);
2934 for (cp2
= pattern
, cp
= tstr
+ 1;
2938 if ((*cp
== '\\') && (cp
+1 < endpat
) &&
2939 (cp
[1] == ':' || cp
[1] == endc
)) {
2948 * Either Var_Subst or VarModify will need a
2949 * nul-terminated string soon, so construct one now.
2951 pattern
= bmake_strndup(tstr
+1, endpat
- (tstr
+ 1));
2955 * pattern contains embedded '$', so use Var_Subst to
2959 pattern
= Var_Subst(NULL
, cp2
, ctxt
, errnum
);
2963 fprintf(debug_file
, "Pattern for [%s] is [%s]\n", nstr
,
2966 newStr
= VarModify(ctxt
, &parsestate
, nstr
, VarMatch
,
2969 newStr
= VarModify(ctxt
, &parsestate
, nstr
, VarNoMatch
,
2978 Var_Parse_State tmpparsestate
;
2981 tmpparsestate
= parsestate
;
2986 * If pattern begins with '^', it is anchored to the
2987 * start of the word -- skip over it and flag pattern.
2990 pattern
.flags
|= VAR_MATCH_START
;
2995 if ((pattern
.lhs
= VarGetPattern(ctxt
, &parsestate
, errnum
,
3002 if ((pattern
.rhs
= VarGetPattern(ctxt
, &parsestate
, errnum
,
3009 * Check for global substitution. If 'g' after the final
3010 * delimiter, substitution is global and is marked that
3016 pattern
.flags
|= VAR_SUB_GLOBAL
;
3019 pattern
.flags
|= VAR_SUB_ONE
;
3022 tmpparsestate
.oneBigWord
= TRUE
;
3029 newStr
= VarModify(ctxt
, &tmpparsestate
, nstr
,
3034 * Free the two strings.
3036 free(UNCONST(pattern
.lhs
));
3037 free(UNCONST(pattern
.rhs
));
3046 /* find ':', and then substitute accordingly */
3052 if ((pattern
.lhs
= VarGetPattern(ctxt
, &parsestate
, errnum
,
3058 /* BROPEN or PROPEN */
3060 if ((pattern
.rhs
= VarGetPattern(ctxt
, &parsestate
, errnum
,
3068 if (Cond_EvalExpression(NULL
, v
->name
, &value
, 0)
3070 Error("Bad conditional expression `%s' in %s?%s:%s",
3071 v
->name
, v
->name
, pattern
.lhs
, pattern
.rhs
);
3076 newStr
= UNCONST(pattern
.lhs
);
3077 free(UNCONST(pattern
.rhs
));
3079 newStr
= UNCONST(pattern
.rhs
);
3080 free(UNCONST(pattern
.lhs
));
3082 if (v
->flags
& VAR_JUNK
) {
3083 v
->flags
|= VAR_KEEP
;
3090 VarREPattern pattern
;
3093 Var_Parse_State tmpparsestate
;
3096 tmpparsestate
= parsestate
;
3102 if ((re
= VarGetPattern(ctxt
, &parsestate
, errnum
, &cp
, delim
,
3103 NULL
, NULL
, NULL
)) == NULL
)
3106 if ((pattern
.replace
= VarGetPattern(ctxt
, &parsestate
,
3107 errnum
, &cp
, delim
, NULL
,
3108 NULL
, NULL
)) == NULL
){
3116 pattern
.flags
|= VAR_SUB_GLOBAL
;
3119 pattern
.flags
|= VAR_SUB_ONE
;
3122 tmpparsestate
.oneBigWord
= TRUE
;
3130 error
= regcomp(&pattern
.re
, re
, REG_EXTENDED
);
3133 *lengthPtr
= cp
- start
+ 1;
3134 VarREError(error
, &pattern
.re
, "RE substitution error");
3135 free(pattern
.replace
);
3139 pattern
.nsub
= pattern
.re
.re_nsub
+ 1;
3140 if (pattern
.nsub
< 1)
3142 if (pattern
.nsub
> 10)
3144 pattern
.matches
= bmake_malloc(pattern
.nsub
*
3145 sizeof(regmatch_t
));
3146 newStr
= VarModify(ctxt
, &tmpparsestate
, nstr
,
3149 regfree(&pattern
.re
);
3150 free(pattern
.replace
);
3151 free(pattern
.matches
);
3157 if (tstr
[1] == endc
|| tstr
[1] == ':') {
3158 newStr
= VarQuote(nstr
);
3165 if (tstr
[1] == endc
|| tstr
[1] == ':') {
3166 newStr
= VarModify(ctxt
, &parsestate
, nstr
, VarTail
,
3174 if (tstr
[1] == endc
|| tstr
[1] == ':') {
3175 newStr
= VarModify(ctxt
, &parsestate
, nstr
, VarHead
,
3183 if (tstr
[1] == endc
|| tstr
[1] == ':') {
3184 newStr
= VarModify(ctxt
, &parsestate
, nstr
, VarSuffix
,
3192 if (tstr
[1] == endc
|| tstr
[1] == ':') {
3193 newStr
= VarModify(ctxt
, &parsestate
, nstr
, VarRoot
,
3204 cp
= tstr
+ 1; /* skip to the rest in any case */
3205 if (tstr
[1] == endc
|| tstr
[1] == ':') {
3208 } else if ( (tstr
[1] == 'x') &&
3209 (tstr
[2] == endc
|| tstr
[2] == ':') ) {
3216 newStr
= VarOrder(nstr
, otype
);
3220 if (tstr
[1] == endc
|| tstr
[1] == ':') {
3221 newStr
= VarUniq(nstr
);
3229 if (tstr
[1] == 'h' && (tstr
[2] == endc
|| tstr
[2] == ':')) {
3231 newStr
= Cmd_Exec(nstr
, &emsg
);
3245 * This can either be a bogus modifier or a System-V
3246 * substitution command.
3254 * First we make a pass through the string trying
3255 * to verify it is a SYSV-make-style translation:
3256 * it must be: <string1>=<string2>)
3260 while (*cp
!= '\0' && cnt
) {
3263 /* continue looking for endc */
3265 else if (*cp
== endc
)
3267 else if (*cp
== startc
)
3272 if (*cp
== endc
&& eqFound
) {
3275 * Now we break this sucker into the lhs and
3276 * rhs. We must null terminate them of course.
3280 if ((pattern
.lhs
= VarGetPattern(ctxt
, &parsestate
,
3281 errnum
, &cp
, delim
, &pattern
.flags
,
3282 &pattern
.leftLen
, NULL
)) == NULL
)
3285 if ((pattern
.rhs
= VarGetPattern(ctxt
, &parsestate
,
3286 errnum
, &cp
, delim
, NULL
, &pattern
.rightLen
,
3291 * SYSV modifications happen through the whole
3292 * string. Note the pattern is anchored at the end.
3296 newStr
= VarModify(ctxt
, &parsestate
, nstr
,
3299 free(UNCONST(pattern
.lhs
));
3300 free(UNCONST(pattern
.rhs
));
3304 Error("Unknown modifier '%c'", *tstr
);
3306 *cp
!= ':' && *cp
!= endc
&& *cp
!= '\0';
3315 fprintf(debug_file
, "Result of :%c is \"%s\"\n", modifier
, newStr
);
3318 if (newStr
!= nstr
) {
3324 if (nstr
!= var_Error
&& nstr
!= varNoError
) {
3328 if (termc
== '\0' && endc
!= '\0') {
3329 Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc
, v
->name
, nstr
, modifier
);
3330 } else if (termc
== ':') {
3336 *lengthPtr
= tstr
- start
;
3341 Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr
, ":)}"), tstr
,
3345 *lengthPtr
= cp
- start
;
3347 Error("Unclosed substitution for %s (%c missing)",
3357 *-----------------------------------------------------------------------
3359 * Given the start of a variable invocation, extract the variable
3360 * name and find its value, then modify it according to the
3364 * str The string to parse
3365 * ctxt The context for the variable
3366 * errnum TRUE if undefined variables are an error
3367 * lengthPtr OUT: The length of the specification
3368 * freePtr OUT: Non-NULL if caller should free *freePtr
3371 * The (possibly-modified) value of the variable or var_Error if the
3372 * specification is invalid. The length of the specification is
3373 * placed in *lengthPtr (for invalid specifications, this is just
3375 * If *freePtr is non-NULL then it's a pointer that the caller
3376 * should pass to free() to free memory used by the result.
3381 *-----------------------------------------------------------------------
3383 /* coverity[+alloc : arg-*4] */
3385 Var_Parse(const char *str
, GNode
*ctxt
, Boolean errnum
, int *lengthPtr
,
3388 const char *tstr
; /* Pointer into str */
3389 Var
*v
; /* Variable in invocation */
3390 Boolean haveModifier
;/* TRUE if have modifiers for the variable */
3391 char endc
; /* Ending character when variable in parens
3393 char startc
; /* Starting character when variable in parens
3395 int vlen
; /* Length of variable name */
3396 const char *start
; /* Points to original start of str */
3397 char *nstr
; /* New string, used during expansion */
3398 Boolean dynamic
; /* TRUE if the variable is local and we're
3399 * expanding it in a non-local context. This
3400 * is done to support dynamic sources. The
3401 * result is just the invocation, unaltered */
3402 Var_Parse_State parsestate
; /* Flags passed to helper functions */
3408 parsestate
.oneBigWord
= FALSE
;
3409 parsestate
.varSpace
= ' '; /* word separator */
3412 if (startc
!= PROPEN
&& startc
!= BROPEN
) {
3414 * If it's not bounded by braces of some sort, life is much simpler.
3415 * We just need to check for the first character and return the
3416 * value if it exists.
3419 /* Error out some really stupid names */
3420 if (startc
== '\0' || strchr(")}:$", startc
)) {
3427 v
= VarFind(name
, ctxt
, FIND_ENV
| FIND_GLOBAL
| FIND_CMD
);
3431 if ((ctxt
== VAR_CMD
) || (ctxt
== VAR_GLOBAL
)) {
3433 * If substituting a local variable in a non-local context,
3434 * assume it's for dynamic source stuff. We have to handle
3435 * this specially and return the longhand for the variable
3436 * with the dollar sign escaped so it makes it back to the
3437 * caller. Only four of the local variables are treated
3438 * specially as they are the only four that will be set
3439 * when dynamic sources are expanded.
3443 return UNCONST("$(.TARGET)");
3445 return UNCONST("$(.ARCHIVE)");
3447 return UNCONST("$(.PREFIX)");
3449 return UNCONST("$(.MEMBER)");
3455 return (errnum
? var_Error
: varNoError
);
3457 haveModifier
= FALSE
;
3462 Buffer buf
; /* Holds the variable name */
3464 endc
= startc
== PROPEN
? PRCLOSE
: BRCLOSE
;
3468 * Skip to the end character or a colon, whichever comes first.
3470 for (tstr
= str
+ 2;
3471 *tstr
!= '\0' && *tstr
!= endc
&& *tstr
!= ':';
3475 * A variable inside a variable, expand
3480 char *rval
= Var_Parse(tstr
, ctxt
, errnum
, &rlen
, &freeIt
);
3482 Buf_AddBytes(&buf
, strlen(rval
), rval
);
3489 Buf_AddByte(&buf
, *tstr
);
3492 haveModifier
= TRUE
;
3493 } else if (*tstr
!= '\0') {
3494 haveModifier
= FALSE
;
3497 * If we never did find the end character, return NULL
3498 * right now, setting the length to be the distance to
3499 * the end of the string, since that's what make does.
3501 *lengthPtr
= tstr
- str
;
3502 Buf_Destroy(&buf
, TRUE
);
3505 str
= Buf_GetAll(&buf
, &vlen
);
3508 * At this point, str points into newly allocated memory from
3509 * buf, containing only the name of the variable.
3511 * start and tstr point into the const string that was pointed
3512 * to by the original value of the str parameter. start points
3513 * to the '$' at the beginning of the string, while tstr points
3514 * to the char just after the end of the variable name -- this
3515 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3518 v
= VarFind(str
, ctxt
, FIND_ENV
| FIND_GLOBAL
| FIND_CMD
);
3520 * Check also for bogus D and F forms of local variables since we're
3521 * in a local context and the name is the right length.
3523 if ((v
== NULL
) && (ctxt
!= VAR_CMD
) && (ctxt
!= VAR_GLOBAL
) &&
3524 (vlen
== 2) && (str
[1] == 'F' || str
[1] == 'D') &&
3525 strchr("@%*!<>", str
[0]) != NULL
) {
3527 * Well, it's local -- go look for it.
3531 v
= VarFind(name
, ctxt
, 0);
3535 * No need for nested expansion or anything, as we're
3536 * the only one who sets these things and we sure don't
3537 * but nested invocations in them...
3539 nstr
= Buf_GetAll(&v
->val
, NULL
);
3541 if (str
[1] == 'D') {
3542 nstr
= VarModify(ctxt
, &parsestate
, nstr
, VarHead
,
3545 nstr
= VarModify(ctxt
, &parsestate
, nstr
, VarTail
,
3549 * Resulting string is dynamically allocated, so
3550 * tell caller to free it.
3553 *lengthPtr
= tstr
-start
+1;
3554 Buf_Destroy(&buf
, TRUE
);
3555 VarFreeEnv(v
, TRUE
);
3562 (((vlen
== 2) && (str
[1] == 'F' || str
[1] == 'D')))) &&
3563 ((ctxt
== VAR_CMD
) || (ctxt
== VAR_GLOBAL
)))
3566 * If substituting a local variable in a non-local context,
3567 * assume it's for dynamic source stuff. We have to handle
3568 * this specially and return the longhand for the variable
3569 * with the dollar sign escaped so it makes it back to the
3570 * caller. Only four of the local variables are treated
3571 * specially as they are the only four that will be set
3572 * when dynamic sources are expanded.
3582 } else if ((vlen
> 2) && (*str
== '.') &&
3583 isupper((unsigned char) str
[1]) &&
3584 ((ctxt
== VAR_CMD
) || (ctxt
== VAR_GLOBAL
)))
3589 if ((strncmp(str
, ".TARGET", len
) == 0) ||
3590 (strncmp(str
, ".ARCHIVE", len
) == 0) ||
3591 (strncmp(str
, ".PREFIX", len
) == 0) ||
3592 (strncmp(str
, ".MEMBER", len
) == 0))
3598 if (!haveModifier
) {
3600 * No modifiers -- have specification length so we can return
3603 *lengthPtr
= tstr
- start
+ 1;
3605 char *pstr
= bmake_strndup(start
, *lengthPtr
);
3607 Buf_Destroy(&buf
, TRUE
);
3610 Buf_Destroy(&buf
, TRUE
);
3611 return (errnum
? var_Error
: varNoError
);
3615 * Still need to get to the end of the variable specification,
3616 * so kludge up a Var structure for the modifications
3618 v
= bmake_malloc(sizeof(Var
));
3619 v
->name
= UNCONST(str
);
3620 Buf_Init(&v
->val
, 1);
3621 v
->flags
= VAR_JUNK
;
3622 Buf_Destroy(&buf
, FALSE
);
3625 Buf_Destroy(&buf
, TRUE
);
3628 if (v
->flags
& VAR_IN_USE
) {
3629 Fatal("Variable %s is recursive.", v
->name
);
3632 v
->flags
|= VAR_IN_USE
;
3635 * Before doing any modification, we have to make sure the value
3636 * has been fully expanded. If it looks like recursion might be
3637 * necessary (there's a dollar sign somewhere in the variable's value)
3638 * we just call Var_Subst to do any other substitutions that are
3639 * necessary. Note that the value returned by Var_Subst will have
3640 * been dynamically-allocated, so it will need freeing when we
3643 nstr
= Buf_GetAll(&v
->val
, NULL
);
3644 if (strchr(nstr
, '$') != NULL
) {
3645 nstr
= Var_Subst(NULL
, nstr
, ctxt
, errnum
);
3649 v
->flags
&= ~VAR_IN_USE
;
3651 if ((nstr
!= NULL
) && haveModifier
) {
3654 * Skip initial colon.
3658 nstr
= ApplyModifiers(nstr
, tstr
, startc
, endc
,
3659 v
, ctxt
, errnum
, &used
, freePtr
);
3663 *lengthPtr
= tstr
- start
+ 1;
3665 *lengthPtr
= tstr
- start
;
3668 if (v
->flags
& VAR_FROM_ENV
) {
3669 Boolean destroy
= FALSE
;
3671 if (nstr
!= Buf_GetAll(&v
->val
, NULL
)) {
3675 * Returning the value unmodified, so tell the caller to free
3680 VarFreeEnv(v
, destroy
);
3681 } else if (v
->flags
& VAR_JUNK
) {
3683 * Perform any free'ing needed and set *freePtr to NULL so the caller
3684 * doesn't try to free a static pointer.
3685 * If VAR_KEEP is also set then we want to keep str as is.
3687 if (!(v
->flags
& VAR_KEEP
)) {
3693 nstr
= bmake_strndup(start
, *lengthPtr
);
3699 if (nstr
!= Buf_GetAll(&v
->val
, NULL
))
3700 Buf_Destroy(&v
->val
, TRUE
);
3708 *-----------------------------------------------------------------------
3710 * Substitute for all variables in the given string in the given context
3711 * If undefErr is TRUE, Parse_Error will be called when an undefined
3712 * variable is encountered.
3715 * var Named variable || NULL for all
3716 * str the string which to substitute
3717 * ctxt the context wherein to find variables
3718 * undefErr TRUE if undefineds are an error
3721 * The resulting string.
3724 * None. The old string must be freed by the caller
3725 *-----------------------------------------------------------------------
3728 Var_Subst(const char *var
, const char *str
, GNode
*ctxt
, Boolean undefErr
)
3730 Buffer buf
; /* Buffer for forming things */
3731 char *val
; /* Value to substitute for a variable */
3732 int length
; /* Length of the variable invocation */
3733 Boolean trailingBslash
; /* variable ends in \ */
3734 void *freeIt
= NULL
; /* Set if it should be freed */
3735 static Boolean errorReported
; /* Set true if an error has already
3736 * been reported to prevent a plethora
3737 * of messages when recursing */
3740 errorReported
= FALSE
;
3741 trailingBslash
= FALSE
;
3744 if (*str
== '\n' && trailingBslash
)
3745 Buf_AddByte(&buf
, ' ');
3746 if (var
== NULL
&& (*str
== '$') && (str
[1] == '$')) {
3748 * A dollar sign may be escaped either with another dollar sign.
3749 * In such a case, we skip over the escape character and store the
3750 * dollar sign into the buffer directly.
3753 Buf_AddByte(&buf
, *str
);
3755 } else if (*str
!= '$') {
3757 * Skip as many characters as possible -- either to the end of
3758 * the string or to the next dollar sign (variable invocation).
3762 for (cp
= str
++; *str
!= '$' && *str
!= '\0'; str
++)
3764 Buf_AddBytes(&buf
, str
- cp
, cp
);
3769 if (str
[1] == '\0') {
3770 /* A trailing $ is kind of a special case */
3771 Buf_AddByte(&buf
, str
[0]);
3774 } else if (str
[1] != PROPEN
&& str
[1] != BROPEN
) {
3775 if (str
[1] != *var
|| strlen(var
) > 1) {
3776 Buf_AddBytes(&buf
, 2, str
);
3788 * Scan up to the end of the variable name.
3790 for (p
= &str
[2]; *p
&&
3791 *p
!= ':' && *p
!= PRCLOSE
&& *p
!= BRCLOSE
; p
++)
3795 * A variable inside the variable. We cannot expand
3796 * the external variable yet, so we try again with
3800 Buf_AddBytes(&buf
, p
- str
, str
);
3805 if (strncmp(var
, str
+ 2, p
- str
- 2) != 0 ||
3806 var
[p
- str
- 2] != '\0') {
3808 * Not the variable we want to expand, scan
3809 * until the next variable
3811 for (;*p
!= '$' && *p
!= '\0'; p
++)
3813 Buf_AddBytes(&buf
, p
- str
, str
);
3826 val
= Var_Parse(str
, ctxt
, undefErr
, &length
, &freeIt
);
3829 * When we come down here, val should either point to the
3830 * value of this variable, suitably modified, or be NULL.
3831 * Length should be the total length of the potential
3832 * variable invocation (from $ to end character...)
3834 if (val
== var_Error
|| val
== varNoError
) {
3836 * If performing old-time variable substitution, skip over
3837 * the variable and continue with the substitution. Otherwise,
3838 * store the dollar sign and advance str so we continue with
3843 } else if (undefErr
) {
3845 * If variable is undefined, complain and skip the
3846 * variable. The complaint will stop us from doing anything
3847 * when the file is parsed.
3849 if (!errorReported
) {
3850 Parse_Error(PARSE_FATAL
,
3851 "Undefined variable \"%.*s\"",length
,str
);
3854 errorReported
= TRUE
;
3856 Buf_AddByte(&buf
, *str
);
3861 * We've now got a variable structure to store in. But first,
3862 * advance the string pointer.
3867 * Copy all the characters from the variable value straight
3868 * into the new string.
3870 length
= strlen(val
);
3871 Buf_AddBytes(&buf
, length
, val
);
3872 trailingBslash
= length
> 0 && val
[length
- 1] == '\\';
3881 return Buf_Destroy(&buf
, FALSE
);
3885 *-----------------------------------------------------------------------
3887 * Return the tail from each of a list of words. Used to set the
3888 * System V local variables.
3891 * file Filename to modify
3894 * The resulting string.
3899 *-----------------------------------------------------------------------
3903 Var_GetTail(char *file
)
3905 return(VarModify(file
, VarTail
, NULL
));
3909 *-----------------------------------------------------------------------
3911 * Find the leading components of a (list of) filename(s).
3912 * XXX: VarHead does not replace foo by ., as (sun) System V make
3916 * file Filename to manipulate
3919 * The leading components.
3924 *-----------------------------------------------------------------------
3927 Var_GetHead(char *file
)
3929 return(VarModify(file
, VarHead
, NULL
));
3934 *-----------------------------------------------------------------------
3936 * Initialize the module
3942 * The VAR_CMD and VAR_GLOBAL contexts are created
3943 *-----------------------------------------------------------------------
3948 VAR_GLOBAL
= Targ_NewGN("Global");
3949 VAR_CMD
= Targ_NewGN("Command");
3960 /****************** PRINT DEBUGGING INFO *****************/
3962 VarPrintVar(void *vp
)
3965 fprintf(debug_file
, "%-16s = %s\n", v
->name
, Buf_GetAll(&v
->val
, NULL
));
3969 *-----------------------------------------------------------------------
3971 * print all variables in a context
3972 *-----------------------------------------------------------------------
3975 Var_Dump(GNode
*ctxt
)
3980 for (h
= Hash_EnumFirst(&ctxt
->context
, &search
);
3982 h
= Hash_EnumNext(&search
)) {
3983 VarPrintVar(Hash_GetValue(h
));