1 /* $NetBSD: var.c,v 1.174 2013/05/18 13:12:45 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.174 2013/05/18 13:12:45 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.174 2013/05/18 13:12:45 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.
126 #include <sys/stat.h>
128 #include <sys/types.h>
132 #include <inttypes.h>
143 * This lets us tell if we have replaced the original environ
144 * (which we cannot free).
146 char **savedEnv = NULL;
149 * This is a harmless return value for Var_Parse that can be used by Var_Subst
150 * to determine if there was an error in parsing -- easier than returning
151 * a flag, as things outside this module don't give a hoot.
153 char var_Error[] = "";
156 * Similar to var_Error, but returned when the 'errnum' flag for Var_Parse is
157 * set false. Why not just use a constant? Well, gcc likes to condense
158 * identical string instances...
160 static char varNoError[] = "";
163 * Internally, variables are contained in four different contexts.
164 * 1) the environment. They may not be changed. If an environment
165 * variable is appended-to, the result is placed in the global
167 * 2) the global context. Variables set in the Makefile are located in
168 * the global context. It is the penultimate context searched when
170 * 3) the command-line context. All variables set on the command line
171 * are placed in this context. They are UNALTERABLE once placed here.
172 * 4) the local context. Each target has associated with it a context
173 * list. On this list are located the structures describing such
174 * local variables as $(@) and $(*)
175 * The four contexts are searched in the reverse order from which they are
178 GNode *VAR_GLOBAL; /* variables from the makefile */
179 GNode *VAR_CMD; /* variables defined on the command-line */
181 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
182 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
183 #define FIND_ENV 0x4 /* look in the environment also */
186 char *name; /* the variable's name */
187 Buffer val; /* its value */
188 int flags; /* miscellaneous status flags */
189 #define VAR_IN_USE 1 /* Variable's value currently being used.
190 * Used to avoid recursion */
191 #define VAR_FROM_ENV 2 /* Variable comes from the environment */
192 #define VAR_JUNK 4 /* Variable is a junk variable that
193 * should be destroyed when done with
194 * it. Used by Var_Parse for undefined,
195 * modified variables */
196 #define VAR_KEEP 8 /* Variable is VAR_JUNK, but we found
197 * a use for it in some modifier and
198 * the value is therefore valid */
199 #define VAR_EXPORTED 16 /* Variable is exported */
200 #define VAR_REEXPORT 32 /* Indicate if var needs re-export.
201 * This would be true if it contains $'s
203 #define VAR_FROM_CMD 64 /* Variable came from command line */
207 * Exporting vars is expensive so skip it if we can
209 #define VAR_EXPORTED_NONE 0
210 #define VAR_EXPORTED_YES 1
211 #define VAR_EXPORTED_ALL 2
212 static int var_exportedVars = VAR_EXPORTED_NONE;
214 * We pass this to Var_Export when doing the initial export
215 * or after updating an exported var.
217 #define VAR_EXPORT_PARENT 1
219 /* Var*Pattern flags */
220 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
221 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
222 #define VAR_SUB_MATCHED 0x04 /* There was a match */
223 #define VAR_MATCH_START 0x08 /* Match at start of word */
224 #define VAR_MATCH_END 0x10 /* Match at end of word */
225 #define VAR_NOSUBST 0x20 /* don't expand vars in VarGetPattern */
228 #define VAR_NO_EXPORT 0x01 /* do not export */
232 * The following fields are set by Var_Parse() when it
233 * encounters modifiers that need to keep state for use by
234 * subsequent modifiers within the same variable expansion.
236 Byte varSpace; /* Word separator in expansions */
237 Boolean oneBigWord; /* TRUE if we will treat the variable as a
238 * single big word, even if it contains
239 * embedded spaces (as opposed to the
240 * usual behaviour of treating it as
241 * several space-separated words). */
244 /* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/",
245 * to VarSYSVMatch() for ":lhs=rhs". */
247 const char *lhs; /* String to match */
248 int leftLen; /* Length of string */
249 const char *rhs; /* Replacement string (w/ &'s removed) */
250 int rightLen; /* Length of replacement */
254 /* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */
256 GNode *ctxt; /* variable context */
257 char *tvar; /* name of temp var */
259 char *str; /* string to expand */
261 int errnum; /* errnum for not defined */
265 /* struct passed as 'void *' to VarRESubstitute() for ":C///" */
275 /* struct passed to VarSelectWords() for ":[start..end]" */
277 int start; /* first word to select */
278 int end; /* last word to select */
281 static Var *VarFind(const char *, GNode *, int);
282 static void VarAdd(const char *, const char *, GNode *);
283 static Boolean VarHead(GNode *, Var_Parse_State *,
284 char *, Boolean, Buffer *, void *);
285 static Boolean VarTail(GNode *, Var_Parse_State *,
286 char *, Boolean, Buffer *, void *);
287 static Boolean VarSuffix(GNode *, Var_Parse_State *,
288 char *, Boolean, Buffer *, void *);
289 static Boolean VarRoot(GNode *, Var_Parse_State *,
290 char *, Boolean, Buffer *, void *);
291 static Boolean VarMatch(GNode *, Var_Parse_State *,
292 char *, Boolean, Buffer *, void *);
294 static Boolean VarSYSVMatch(GNode *, Var_Parse_State *,
295 char *, Boolean, Buffer *, void *);
297 static Boolean VarNoMatch(GNode *, Var_Parse_State *,
298 char *, Boolean, Buffer *, void *);
300 static void VarREError(int, regex_t *, const char *);
301 static Boolean VarRESubstitute(GNode *, Var_Parse_State *,
302 char *, Boolean, Buffer *, void *);
304 static Boolean VarSubstitute(GNode *, Var_Parse_State *,
305 char *, Boolean, Buffer *, void *);
306 static Boolean VarLoopExpand(GNode *, Var_Parse_State *,
307 char *, Boolean, Buffer *, void *);
308 static char *VarGetPattern(GNode *, Var_Parse_State *,
309 int, const char **, int, int *, int *,
311 static char *VarQuote(char *);
312 static char *VarHash(char *);
313 static char *VarModify(GNode *, Var_Parse_State *,
315 Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *),
317 static char *VarOrder(const char *, const char);
318 static char *VarUniq(const char *);
319 static int VarWordCompare(const void *, const void *);
320 static void VarPrintVar(void *);
328 *-----------------------------------------------------------------------
330 * Find the given variable in the given context and any other contexts
335 * ctxt context in which to find it
336 * flags FIND_GLOBAL set means to look in the
337 * VAR_GLOBAL context as well. FIND_CMD set means
338 * to look in the VAR_CMD context also. FIND_ENV
339 * set means to look in the environment
342 * A pointer to the structure describing the desired variable or
343 * NULL if the variable does not exist.
347 *-----------------------------------------------------------------------
350 VarFind(const char *name, GNode *ctxt, int flags)
356 * If the variable name begins with a '.', it could very well be one of
357 * the local ones. We check the name against all the local variables
358 * and substitute the short version in for 'name' if it matches one of
361 if (*name == '.' && isupper((unsigned char) name[1]))
364 if (!strcmp(name, ".ALLSRC"))
366 if (!strcmp(name, ".ARCHIVE"))
370 if (!strcmp(name, ".IMPSRC"))
374 if (!strcmp(name, ".MEMBER"))
378 if (!strcmp(name, ".OODATE"))
382 if (!strcmp(name, ".PREFIX"))
386 if (!strcmp(name, ".TARGET"))
391 /* for compatibility with gmake */
392 if (name[0] == '^' && name[1] == '\0')
397 * First look for the variable in the given context. If it's not there,
398 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
399 * depending on the FIND_* flags in 'flags'
401 var = Hash_FindEntry(&ctxt->context, name);
403 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
404 var = Hash_FindEntry(&VAR_CMD->context, name);
406 if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
407 (ctxt != VAR_GLOBAL))
409 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
411 if ((var == NULL) && (flags & FIND_ENV)) {
414 if ((env = getenv(name)) != NULL) {
417 v = bmake_malloc(sizeof(Var));
418 v->name = bmake_strdup(name);
422 Buf_Init(&v->val, len + 1);
423 Buf_AddBytes(&v->val, len, env);
425 v->flags = VAR_FROM_ENV;
427 } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
428 (ctxt != VAR_GLOBAL))
430 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
434 return ((Var *)Hash_GetValue(var));
439 } else if (var == NULL) {
442 return ((Var *)Hash_GetValue(var));
447 *-----------------------------------------------------------------------
449 * If the variable is an environment variable, free it
453 * destroy true if the value buffer should be destroyed.
456 * 1 if it is an environment variable 0 ow.
459 * The variable is free'ed if it is an environent variable.
460 *-----------------------------------------------------------------------
463 VarFreeEnv(Var *v, Boolean destroy)
465 if ((v->flags & VAR_FROM_ENV) == 0)
468 Buf_Destroy(&v->val, destroy);
474 *-----------------------------------------------------------------------
476 * Add a new variable of name name and value val to the given context
479 * name name of variable to add
480 * val value to set it to
481 * ctxt context in which to set it
487 * The new variable is placed at the front of the given context
488 * The name and val arguments are duplicated so they may
490 *-----------------------------------------------------------------------
493 VarAdd(const char *name, const char *val, GNode *ctxt)
499 v = bmake_malloc(sizeof(Var));
501 len = val ? strlen(val) : 0;
502 Buf_Init(&v->val, len+1);
503 Buf_AddBytes(&v->val, len, val);
507 h = Hash_CreateEntry(&ctxt->context, name, NULL);
511 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
516 *-----------------------------------------------------------------------
518 * Remove a variable from a context.
524 * The Var structure is removed and freed.
526 *-----------------------------------------------------------------------
529 Var_Delete(const char *name, GNode *ctxt)
534 if (strchr(name, '$')) {
535 cp = Var_Subst(NULL, name, VAR_GLOBAL, 0);
539 ln = Hash_FindEntry(&ctxt->context, cp);
541 fprintf(debug_file, "%s:delete %s%s\n",
542 ctxt->name, cp, ln ? "" : " (not found)");
550 v = (Var *)Hash_GetValue(ln);
551 if ((v->flags & VAR_EXPORTED)) {
554 if (strcmp(MAKE_EXPORTED, v->name) == 0) {
555 var_exportedVars = VAR_EXPORTED_NONE;
557 if (v->name != ln->name)
559 Hash_DeleteEntry(&ctxt->context, ln);
560 Buf_Destroy(&v->val, TRUE);
568 * We ignore make internal variables (those which start with '.')
569 * Also we jump through some hoops to avoid calling setenv
570 * more than necessary since it can leak.
571 * We only manipulate flags of vars if 'parent' is set.
574 Var_Export1(const char *name, int parent)
582 return 0; /* skip internals */
586 * If it is one of the vars that should only appear in
587 * local context, skip it, else we can get Var_Subst
598 v = VarFind(name, VAR_GLOBAL, 0);
603 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
604 return 0; /* nothing to do */
606 val = Buf_GetAll(&v->val, NULL);
607 if (strchr(val, '$')) {
610 * Flag this as something we need to re-export.
611 * No point actually exporting it now though,
612 * the child can do it at the last minute.
614 v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
617 if (v->flags & VAR_IN_USE) {
619 * We recursed while exporting in a child.
620 * This isn't going to end well, just skip it.
624 n = snprintf(tmp, sizeof(tmp), "${%s}", name);
625 if (n < (int)sizeof(tmp)) {
626 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
627 setenv(name, val, 1);
632 v->flags &= ~VAR_REEXPORT; /* once will do */
634 if (parent || !(v->flags & VAR_EXPORTED)) {
635 setenv(name, val, 1);
639 * This is so Var_Set knows to call Var_Export again...
642 v->flags |= VAR_EXPORTED;
648 * This gets called from our children.
660 if (VAR_EXPORTED_NONE == var_exportedVars)
663 if (VAR_EXPORTED_ALL == var_exportedVars) {
665 * Ouch! This is crazy...
667 for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
669 var = Hash_EnumNext(&state)) {
670 v = (Var *)Hash_GetValue(var);
671 Var_Export1(v->name, 0);
676 * We have a number of exported vars,
678 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
679 if (n < (int)sizeof(tmp)) {
685 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
686 av = brk_string(val, &ac, FALSE, &as);
687 for (i = 0; i < ac; i++) {
688 Var_Export1(av[i], 0);
697 * This is called when .export is seen or
698 * .MAKE.EXPORTED is modified.
699 * It is also called when any exported var is modified.
702 Var_Export(char *str, int isExport)
712 if (isExport && (!str || !str[0])) {
713 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
717 if (strncmp(str, "-env", 4) == 0) {
721 track = VAR_EXPORT_PARENT;
723 val = Var_Subst(NULL, str, VAR_GLOBAL, 0);
724 av = brk_string(val, &ac, FALSE, &as);
725 for (i = 0; i < ac; i++) {
730 * If it is one of the vars that should only appear in
731 * local context, skip it, else we can get Var_Subst
742 if (Var_Export1(name, track)) {
743 if (VAR_EXPORTED_ALL != var_exportedVars)
744 var_exportedVars = VAR_EXPORTED_YES;
745 if (isExport && track) {
746 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
757 * This is called when .unexport[-env] is seen.
759 extern char **environ;
762 Var_UnExport(char *str)
767 Boolean unexport_env;
770 if (!str || !str[0]) {
771 return; /* assert? */
777 unexport_env = (strncmp(str, "-env", 4) == 0);
781 cp = getenv(MAKE_LEVEL); /* we should preserve this */
782 if (environ == savedEnv) {
783 /* we have been here before! */
784 newenv = bmake_realloc(environ, 2 * sizeof(char *));
790 newenv = bmake_malloc(2 * sizeof(char *));
794 /* Note: we cannot safely free() the original environ. */
795 environ = savedEnv = newenv;
798 setenv(MAKE_LEVEL, cp, 1);
799 #ifdef MAKE_LEVEL_SAFE
800 setenv(MAKE_LEVEL_SAFE, cp, 1);
803 for (; *str != '\n' && isspace((unsigned char) *str); str++)
805 if (str[0] && str[0] != '\n') {
811 /* Using .MAKE.EXPORTED */
812 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
813 if (n < (int)sizeof(tmp)) {
814 vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
824 av = brk_string(vlist, &ac, FALSE, &as);
825 for (i = 0; i < ac; i++) {
826 v = VarFind(av[i], VAR_GLOBAL, 0);
830 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
833 v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT);
835 * If we are unexporting a list,
836 * remove each one from .MAKE.EXPORTED.
837 * If we are removing them all,
838 * just delete .MAKE.EXPORTED below.
841 n = snprintf(tmp, sizeof(tmp),
842 "${" MAKE_EXPORTED ":N%s}", v->name);
843 if (n < (int)sizeof(tmp)) {
844 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
845 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0);
853 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
860 *-----------------------------------------------------------------------
862 * Set the variable name to the value val in the given context.
865 * name name of variable to set
866 * val value to give to the variable
867 * ctxt context in which to set it
873 * If the variable doesn't yet exist, a new record is created for it.
874 * Else the old value is freed and the new one stuck in its place
877 * The variable is searched for only in its context before being
878 * created in that context. I.e. if the context is VAR_GLOBAL,
879 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
880 * VAR_CMD->context is searched. This is done to avoid the literally
881 * thousands of unnecessary strcmp's that used to be done to
882 * set, say, $(@) or $(<).
883 * If the context is VAR_GLOBAL though, we check if the variable
884 * was set in VAR_CMD from the command line and skip it if so.
885 *-----------------------------------------------------------------------
888 Var_Set(const char *name, const char *val, GNode *ctxt, int flags)
891 char *expanded_name = NULL;
894 * We only look for a variable in the given context since anything set
895 * here will override anything in a lower context, so there's not much
896 * point in searching them all just to save a bit of memory...
898 if (strchr(name, '$') != NULL) {
899 expanded_name = Var_Subst(NULL, name, ctxt, 0);
900 if (expanded_name[0] == 0) {
902 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
903 "name expands to empty string - ignored\n",
909 name = expanded_name;
911 if (ctxt == VAR_GLOBAL) {
912 v = VarFind(name, VAR_CMD, 0);
914 if ((v->flags & VAR_FROM_CMD)) {
916 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
923 v = VarFind(name, ctxt, 0);
925 VarAdd(name, val, ctxt);
928 Buf_AddBytes(&v->val, strlen(val), val);
931 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
933 if ((v->flags & VAR_EXPORTED)) {
934 Var_Export1(name, VAR_EXPORT_PARENT);
938 * Any variables given on the command line are automatically exported
939 * to the environment (as per POSIX standard)
941 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
943 /* we just added it */
944 v = VarFind(name, ctxt, 0);
947 v->flags |= VAR_FROM_CMD;
949 * If requested, don't export these in the environment
950 * individually. We still put them in MAKEOVERRIDES so
951 * that the command-line settings continue to override
954 if (varNoExportEnv != TRUE)
955 setenv(name, val, 1);
957 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
960 * Another special case.
961 * Several make's support this sort of mechanism for tracking
962 * recursion - but each uses a different name.
963 * We allow the makefiles to update .MAKE.LEVEL and ensure
964 * children see a correctly incremented value.
966 if (ctxt == VAR_GLOBAL && strcmp(MAKE_LEVEL, name) == 0) {
971 snprintf(tmp, sizeof(tmp), "%u", level + 1);
972 setenv(MAKE_LEVEL, tmp, 1);
973 #ifdef MAKE_LEVEL_SAFE
974 setenv(MAKE_LEVEL_SAFE, tmp, 1);
980 if (expanded_name != NULL)
987 *-----------------------------------------------------------------------
989 * The variable of the given name has the given value appended to it in
993 * name name of variable to modify
994 * val String to append to it
995 * ctxt Context in which this should occur
1001 * If the variable doesn't exist, it is created. Else the strings
1002 * are concatenated (with a space in between).
1005 * Only if the variable is being sought in the global context is the
1006 * environment searched.
1007 * XXX: Knows its calling circumstances in that if called with ctxt
1008 * an actual target, it will only search that context since only
1009 * a local variable could be being appended to. This is actually
1010 * a big win and must be tolerated.
1011 *-----------------------------------------------------------------------
1014 Var_Append(const char *name, const char *val, GNode *ctxt)
1018 char *expanded_name = NULL;
1020 if (strchr(name, '$') != NULL) {
1021 expanded_name = Var_Subst(NULL, name, ctxt, 0);
1022 if (expanded_name[0] == 0) {
1024 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
1025 "name expands to empty string - ignored\n",
1028 free(expanded_name);
1031 name = expanded_name;
1034 v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
1037 VarAdd(name, val, ctxt);
1039 Buf_AddByte(&v->val, ' ');
1040 Buf_AddBytes(&v->val, strlen(val), val);
1043 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
1044 Buf_GetAll(&v->val, NULL));
1047 if (v->flags & VAR_FROM_ENV) {
1049 * If the original variable came from the environment, we
1050 * have to install it in the global context (we could place
1051 * it in the environment, but then we should provide a way to
1052 * export other variables...)
1054 v->flags &= ~VAR_FROM_ENV;
1055 h = Hash_CreateEntry(&ctxt->context, name, NULL);
1056 Hash_SetValue(h, v);
1059 if (expanded_name != NULL)
1060 free(expanded_name);
1064 *-----------------------------------------------------------------------
1066 * See if the given variable exists.
1069 * name Variable to find
1070 * ctxt Context in which to start search
1073 * TRUE if it does, FALSE if it doesn't
1078 *-----------------------------------------------------------------------
1081 Var_Exists(const char *name, GNode *ctxt)
1086 if ((cp = strchr(name, '$')) != NULL) {
1087 cp = Var_Subst(NULL, name, ctxt, FALSE);
1089 v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
1096 (void)VarFreeEnv(v, TRUE);
1102 *-----------------------------------------------------------------------
1104 * Return the value of the named variable in the given context
1108 * ctxt context in which to search for it
1111 * The value if the variable exists, NULL if it doesn't
1115 *-----------------------------------------------------------------------
1118 Var_Value(const char *name, GNode *ctxt, char **frp)
1122 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1125 char *p = (Buf_GetAll(&v->val, NULL));
1126 if (VarFreeEnv(v, FALSE))
1135 *-----------------------------------------------------------------------
1137 * Remove the tail of the given word and place the result in the given
1142 * addSpace True if need to add a space to the buffer
1143 * before sticking in the head
1144 * buf Buffer in which to store it
1147 * TRUE if characters were added to the buffer (a space needs to be
1148 * added to the buffer before the next word).
1151 * The trimmed word is added to the buffer.
1153 *-----------------------------------------------------------------------
1156 VarHead(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1157 char *word, Boolean addSpace, Buffer *buf,
1162 slash = strrchr(word, '/');
1163 if (slash != NULL) {
1164 if (addSpace && vpstate->varSpace) {
1165 Buf_AddByte(buf, vpstate->varSpace);
1168 Buf_AddBytes(buf, strlen(word), word);
1173 * If no directory part, give . (q.v. the POSIX standard)
1175 if (addSpace && vpstate->varSpace)
1176 Buf_AddByte(buf, vpstate->varSpace);
1177 Buf_AddByte(buf, '.');
1179 return(dummy ? TRUE : TRUE);
1183 *-----------------------------------------------------------------------
1185 * Remove the head of the given word and place the result in the given
1190 * addSpace True if need to add a space to the buffer
1191 * before adding the tail
1192 * buf Buffer in which to store it
1195 * TRUE if characters were added to the buffer (a space needs to be
1196 * added to the buffer before the next word).
1199 * The trimmed word is added to the buffer.
1201 *-----------------------------------------------------------------------
1204 VarTail(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1205 char *word, Boolean addSpace, Buffer *buf,
1210 if (addSpace && vpstate->varSpace) {
1211 Buf_AddByte(buf, vpstate->varSpace);
1214 slash = strrchr(word, '/');
1215 if (slash != NULL) {
1217 Buf_AddBytes(buf, strlen(slash), slash);
1220 Buf_AddBytes(buf, strlen(word), word);
1222 return (dummy ? TRUE : TRUE);
1226 *-----------------------------------------------------------------------
1228 * Place the suffix of the given word in the given buffer.
1232 * addSpace TRUE if need to add a space before placing the
1233 * suffix in the buffer
1234 * buf Buffer in which to store it
1237 * TRUE if characters were added to the buffer (a space needs to be
1238 * added to the buffer before the next word).
1241 * The suffix from the word is placed in the buffer.
1243 *-----------------------------------------------------------------------
1246 VarSuffix(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1247 char *word, Boolean addSpace, Buffer *buf,
1252 dot = strrchr(word, '.');
1254 if (addSpace && vpstate->varSpace) {
1255 Buf_AddByte(buf, vpstate->varSpace);
1258 Buf_AddBytes(buf, strlen(dot), dot);
1262 return (dummy ? addSpace : addSpace);
1266 *-----------------------------------------------------------------------
1268 * Remove the suffix of the given word and place the result in the
1273 * addSpace TRUE if need to add a space to the buffer
1274 * before placing the root in it
1275 * buf Buffer in which to store it
1278 * TRUE if characters were added to the buffer (a space needs to be
1279 * added to the buffer before the next word).
1282 * The trimmed word is added to the buffer.
1284 *-----------------------------------------------------------------------
1287 VarRoot(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1288 char *word, Boolean addSpace, Buffer *buf,
1293 if (addSpace && vpstate->varSpace) {
1294 Buf_AddByte(buf, vpstate->varSpace);
1297 dot = strrchr(word, '.');
1300 Buf_AddBytes(buf, strlen(word), word);
1303 Buf_AddBytes(buf, strlen(word), word);
1305 return (dummy ? TRUE : TRUE);
1309 *-----------------------------------------------------------------------
1311 * Place the word in the buffer if it matches the given pattern.
1312 * Callback function for VarModify to implement the :M modifier.
1315 * word Word to examine
1316 * addSpace TRUE if need to add a space to the buffer
1317 * before adding the word, if it matches
1318 * buf Buffer in which to store it
1319 * pattern Pattern the word must match
1322 * TRUE if a space should be placed in the buffer before the next
1326 * The word may be copied to the buffer.
1328 *-----------------------------------------------------------------------
1331 VarMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1332 char *word, Boolean addSpace, Buffer *buf,
1336 fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
1337 if (Str_Match(word, (char *)pattern)) {
1338 if (addSpace && vpstate->varSpace) {
1339 Buf_AddByte(buf, vpstate->varSpace);
1342 Buf_AddBytes(buf, strlen(word), word);
1349 *-----------------------------------------------------------------------
1351 * Place the word in the buffer if it matches the given pattern.
1352 * Callback function for VarModify to implement the System V %
1356 * word Word to examine
1357 * addSpace TRUE if need to add a space to the buffer
1358 * before adding the word, if it matches
1359 * buf Buffer in which to store it
1360 * patp Pattern the word must match
1363 * TRUE if a space should be placed in the buffer before the next
1367 * The word may be copied to the buffer.
1369 *-----------------------------------------------------------------------
1372 VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
1373 char *word, Boolean addSpace, Buffer *buf,
1378 VarPattern *pat = (VarPattern *)patp;
1381 if (addSpace && vpstate->varSpace)
1382 Buf_AddByte(buf, vpstate->varSpace);
1386 if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
1387 varexp = Var_Subst(NULL, pat->rhs, ctx, 0);
1388 Str_SYSVSubst(buf, varexp, ptr, len);
1391 Buf_AddBytes(buf, strlen(word), word);
1400 *-----------------------------------------------------------------------
1402 * Place the word in the buffer if it doesn't match the given pattern.
1403 * Callback function for VarModify to implement the :N modifier.
1406 * word Word to examine
1407 * addSpace TRUE if need to add a space to the buffer
1408 * before adding the word, if it matches
1409 * buf Buffer in which to store it
1410 * pattern Pattern the word must match
1413 * TRUE if a space should be placed in the buffer before the next
1417 * The word may be copied to the buffer.
1419 *-----------------------------------------------------------------------
1422 VarNoMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1423 char *word, Boolean addSpace, Buffer *buf,
1426 if (!Str_Match(word, (char *)pattern)) {
1427 if (addSpace && vpstate->varSpace) {
1428 Buf_AddByte(buf, vpstate->varSpace);
1431 Buf_AddBytes(buf, strlen(word), word);
1438 *-----------------------------------------------------------------------
1440 * Perform a string-substitution on the given word, placing the
1441 * result in the passed buffer.
1444 * word Word to modify
1445 * addSpace True if space should be added before
1447 * buf Buffer for result
1448 * patternp Pattern for substitution
1451 * TRUE if a space is needed before more characters are added.
1456 *-----------------------------------------------------------------------
1459 VarSubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1460 char *word, Boolean addSpace, Buffer *buf,
1463 int wordLen; /* Length of word */
1464 char *cp; /* General pointer */
1465 VarPattern *pattern = (VarPattern *)patternp;
1467 wordLen = strlen(word);
1468 if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
1469 (VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1471 * Still substituting -- break it down into simple anchored cases
1472 * and if none of them fits, perform the general substitution case.
1474 if ((pattern->flags & VAR_MATCH_START) &&
1475 (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
1477 * Anchored at start and beginning of word matches pattern
1479 if ((pattern->flags & VAR_MATCH_END) &&
1480 (wordLen == pattern->leftLen)) {
1482 * Also anchored at end and matches to the end (word
1483 * is same length as pattern) add space and rhs only
1484 * if rhs is non-null.
1486 if (pattern->rightLen != 0) {
1487 if (addSpace && vpstate->varSpace) {
1488 Buf_AddByte(buf, vpstate->varSpace);
1491 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1493 pattern->flags |= VAR_SUB_MATCHED;
1494 } else if (pattern->flags & VAR_MATCH_END) {
1496 * Doesn't match to end -- copy word wholesale
1501 * Matches at start but need to copy in trailing characters
1503 if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1504 if (addSpace && vpstate->varSpace) {
1505 Buf_AddByte(buf, vpstate->varSpace);
1509 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1510 Buf_AddBytes(buf, wordLen - pattern->leftLen,
1511 (word + pattern->leftLen));
1512 pattern->flags |= VAR_SUB_MATCHED;
1514 } else if (pattern->flags & VAR_MATCH_START) {
1516 * Had to match at start of word and didn't -- copy whole word.
1519 } else if (pattern->flags & VAR_MATCH_END) {
1521 * Anchored at end, Find only place match could occur (leftLen
1522 * characters from the end of the word) and see if it does. Note
1523 * that because the $ will be left at the end of the lhs, we have
1526 cp = word + (wordLen - pattern->leftLen);
1528 (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
1530 * Match found. If we will place characters in the buffer,
1531 * add a space before hand as indicated by addSpace, then
1532 * stuff in the initial, unmatched part of the word followed
1533 * by the right-hand-side.
1535 if (((cp - word) + pattern->rightLen) != 0) {
1536 if (addSpace && vpstate->varSpace) {
1537 Buf_AddByte(buf, vpstate->varSpace);
1541 Buf_AddBytes(buf, cp - word, word);
1542 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1543 pattern->flags |= VAR_SUB_MATCHED;
1546 * Had to match at end and didn't. Copy entire word.
1552 * Pattern is unanchored: search for the pattern in the word using
1553 * String_FindSubstring, copying unmatched portions and the
1554 * right-hand-side for each match found, handling non-global
1555 * substitutions correctly, etc. When the loop is done, any
1556 * remaining part of the word (word and wordLen are adjusted
1557 * accordingly through the loop) is copied straight into the
1559 * addSpace is set FALSE as soon as a space is added to the
1566 origSize = Buf_Size(buf);
1568 cp = Str_FindSubstring(word, pattern->lhs);
1570 if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1571 Buf_AddByte(buf, vpstate->varSpace);
1574 Buf_AddBytes(buf, cp-word, word);
1575 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1576 wordLen -= (cp - word) + pattern->leftLen;
1577 word = cp + pattern->leftLen;
1581 if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
1584 pattern->flags |= VAR_SUB_MATCHED;
1590 if (addSpace && vpstate->varSpace) {
1591 Buf_AddByte(buf, vpstate->varSpace);
1593 Buf_AddBytes(buf, wordLen, word);
1596 * If added characters to the buffer, need to add a space
1597 * before we add any more. If we didn't add any, just return
1598 * the previous value of addSpace.
1600 return ((Buf_Size(buf) != origSize) || addSpace);
1605 if (addSpace && vpstate->varSpace) {
1606 Buf_AddByte(buf, vpstate->varSpace);
1608 Buf_AddBytes(buf, wordLen, word);
1614 *-----------------------------------------------------------------------
1616 * Print the error caused by a regcomp or regexec call.
1622 * An error gets printed.
1624 *-----------------------------------------------------------------------
1627 VarREError(int errnum, regex_t *pat, const char *str)
1632 errlen = regerror(errnum, pat, 0, 0);
1633 errbuf = bmake_malloc(errlen);
1634 regerror(errnum, pat, errbuf, errlen);
1635 Error("%s: %s", str, errbuf);
1641 *-----------------------------------------------------------------------
1642 * VarRESubstitute --
1643 * Perform a regex substitution on the given word, placing the
1644 * result in the passed buffer.
1647 * TRUE if a space is needed before more characters are added.
1652 *-----------------------------------------------------------------------
1655 VarRESubstitute(GNode *ctx MAKE_ATTR_UNUSED,
1656 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1657 char *word, Boolean addSpace, Buffer *buf,
1667 #define MAYBE_ADD_SPACE() \
1668 if (addSpace && !added) \
1669 Buf_AddByte(buf, ' '); \
1676 if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1677 (VAR_SUB_ONE|VAR_SUB_MATCHED))
1681 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1686 pat->flags |= VAR_SUB_MATCHED;
1687 if (pat->matches[0].rm_so > 0) {
1689 Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1692 for (rp = pat->replace; *rp; rp++) {
1693 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1695 Buf_AddByte(buf,rp[1]);
1698 else if ((*rp == '&') ||
1699 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1717 if (n > pat->nsub) {
1718 Error("No subexpression %s", &errstr[0]);
1721 } else if ((pat->matches[n].rm_so == -1) &&
1722 (pat->matches[n].rm_eo == -1)) {
1723 Error("No match for subexpression %s", &errstr[0]);
1727 subbuf = wp + pat->matches[n].rm_so;
1728 sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1733 Buf_AddBytes(buf, sublen, subbuf);
1737 Buf_AddByte(buf, *rp);
1740 wp += pat->matches[0].rm_eo;
1741 if (pat->flags & VAR_SUB_GLOBAL) {
1742 flags |= REG_NOTBOL;
1743 if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1745 Buf_AddByte(buf, *wp);
1754 Buf_AddBytes(buf, strlen(wp), wp);
1758 VarREError(xrv, &pat->re, "Unexpected regex error");
1763 Buf_AddBytes(buf,strlen(wp),wp);
1767 return(addSpace||added);
1774 *-----------------------------------------------------------------------
1776 * Implements the :@<temp>@<string>@ modifier of ODE make.
1777 * We set the temp variable named in pattern.lhs to word and expand
1778 * pattern.rhs storing the result in the passed buffer.
1781 * word Word to modify
1782 * addSpace True if space should be added before
1784 * buf Buffer for result
1785 * pattern Datafor substitution
1788 * TRUE if a space is needed before more characters are added.
1793 *-----------------------------------------------------------------------
1796 VarLoopExpand(GNode *ctx MAKE_ATTR_UNUSED,
1797 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1798 char *word, Boolean addSpace, Buffer *buf,
1801 VarLoop_t *loop = (VarLoop_t *)loopp;
1805 if (word && *word) {
1806 Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
1807 s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum);
1808 if (s != NULL && *s != '\0') {
1809 if (addSpace && *s != '\n')
1810 Buf_AddByte(buf, ' ');
1811 Buf_AddBytes(buf, (slen = strlen(s)), s);
1812 addSpace = (slen > 0 && s[slen - 1] != '\n');
1821 *-----------------------------------------------------------------------
1823 * Implements the :[start..end] modifier.
1824 * This is a special case of VarModify since we want to be able
1825 * to scan the list backwards if start > end.
1828 * str String whose words should be trimmed
1829 * seldata words to select
1832 * A string of all the words selected.
1837 *-----------------------------------------------------------------------
1840 VarSelectWords(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1841 const char *str, VarSelectWords_t *seldata)
1843 Buffer buf; /* Buffer for the new string */
1844 Boolean addSpace; /* TRUE if need to add a space to the
1845 * buffer before adding the trimmed
1847 char **av; /* word list */
1848 char *as; /* word list memory */
1850 int start, end, step;
1855 if (vpstate->oneBigWord) {
1856 /* fake what brk_string() would do if there were only one word */
1858 av = bmake_malloc((ac + 1) * sizeof(char *));
1859 as = bmake_strdup(str);
1863 av = brk_string(str, &ac, FALSE, &as);
1867 * Now sanitize seldata.
1868 * If seldata->start or seldata->end are negative, convert them to
1869 * the positive equivalents (-1 gets converted to argc, -2 gets
1870 * converted to (argc-1), etc.).
1872 if (seldata->start < 0)
1873 seldata->start = ac + seldata->start + 1;
1874 if (seldata->end < 0)
1875 seldata->end = ac + seldata->end + 1;
1878 * We avoid scanning more of the list than we need to.
1880 if (seldata->start > seldata->end) {
1881 start = MIN(ac, seldata->start) - 1;
1882 end = MAX(0, seldata->end - 1);
1885 start = MAX(0, seldata->start - 1);
1886 end = MIN(ac, seldata->end);
1891 (step < 0 && i >= end) || (step > 0 && i < end);
1893 if (av[i] && *av[i]) {
1894 if (addSpace && vpstate->varSpace) {
1895 Buf_AddByte(&buf, vpstate->varSpace);
1897 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
1905 return Buf_Destroy(&buf, FALSE);
1911 * Replace each word with the result of realpath()
1915 VarRealpath(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1916 char *word, Boolean addSpace, Buffer *buf,
1917 void *patternp MAKE_ATTR_UNUSED)
1920 char rbuf[MAXPATHLEN];
1923 if (addSpace && vpstate->varSpace) {
1924 Buf_AddByte(buf, vpstate->varSpace);
1927 rp = realpath(word, rbuf);
1928 if (rp && *rp == '/' && stat(rp, &st) == 0)
1931 Buf_AddBytes(buf, strlen(word), word);
1936 *-----------------------------------------------------------------------
1938 * Modify each of the words of the passed string using the given
1939 * function. Used to implement all modifiers.
1942 * str String whose words should be trimmed
1943 * modProc Function to use to modify them
1944 * datum Datum to pass it
1947 * A string of all the words modified appropriately.
1952 *-----------------------------------------------------------------------
1955 VarModify(GNode *ctx, Var_Parse_State *vpstate,
1957 Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
1958 Boolean, Buffer *, void *),
1961 Buffer buf; /* Buffer for the new string */
1962 Boolean addSpace; /* TRUE if need to add a space to the
1963 * buffer before adding the trimmed
1965 char **av; /* word list */
1966 char *as; /* word list memory */
1972 if (vpstate->oneBigWord) {
1973 /* fake what brk_string() would do if there were only one word */
1975 av = bmake_malloc((ac + 1) * sizeof(char *));
1976 as = bmake_strdup(str);
1980 av = brk_string(str, &ac, FALSE, &as);
1983 for (i = 0; i < ac; i++) {
1984 addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum);
1990 return Buf_Destroy(&buf, FALSE);
1995 VarWordCompare(const void *a, const void *b)
1997 int r = strcmp(*(const char * const *)a, *(const char * const *)b);
2002 *-----------------------------------------------------------------------
2004 * Order the words in the string.
2007 * str String whose words should be sorted.
2008 * otype How to order: s - sort, x - random.
2011 * A string containing the words ordered.
2016 *-----------------------------------------------------------------------
2019 VarOrder(const char *str, const char otype)
2021 Buffer buf; /* Buffer for the new string */
2022 char **av; /* word list [first word does not count] */
2023 char *as; /* word list memory */
2028 av = brk_string(str, &ac, FALSE, &as);
2032 case 's': /* sort alphabetically */
2033 qsort(av, ac, sizeof(char *), VarWordCompare);
2035 case 'x': /* randomize */
2041 * We will use [ac..2] range for mod factors. This will produce
2042 * random numbers in [(ac-1)..0] interval, and minimal
2043 * reasonable value for mod factor is 2 (the mod 1 will produce
2044 * 0 with probability 1).
2046 for (i = ac-1; i > 0; i--) {
2047 rndidx = random() % (i + 1);
2055 } /* end of switch */
2057 for (i = 0; i < ac; i++) {
2058 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2060 Buf_AddByte(&buf, ' ');
2066 return Buf_Destroy(&buf, FALSE);
2071 *-----------------------------------------------------------------------
2073 * Remove adjacent duplicate words.
2076 * str String whose words should be sorted
2079 * A string containing the resulting words.
2084 *-----------------------------------------------------------------------
2087 VarUniq(const char *str)
2089 Buffer buf; /* Buffer for new string */
2090 char **av; /* List of words to affect */
2091 char *as; /* Word list memory */
2095 av = brk_string(str, &ac, FALSE, &as);
2098 for (j = 0, i = 1; i < ac; i++)
2099 if (strcmp(av[i], av[j]) != 0 && (++j != i))
2104 for (i = 0; i < ac; i++) {
2105 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2107 Buf_AddByte(&buf, ' ');
2113 return Buf_Destroy(&buf, FALSE);
2118 *-----------------------------------------------------------------------
2120 * Pass through the tstr looking for 1) escaped delimiters,
2121 * '$'s and backslashes (place the escaped character in
2122 * uninterpreted) and 2) unescaped $'s that aren't before
2123 * the delimiter (expand the variable substitution unless flags
2124 * has VAR_NOSUBST set).
2125 * Return the expanded string or NULL if the delimiter was missing
2126 * If pattern is specified, handle escaped ampersands, and replace
2127 * unescaped ampersands with the lhs of the pattern.
2130 * A string of all the words modified appropriately.
2131 * If length is specified, return the string length of the buffer
2132 * If flags is specified and the last character of the pattern is a
2133 * $ set the VAR_MATCH_END bit of flags.
2137 *-----------------------------------------------------------------------
2140 VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
2141 int errnum, const char **tstr, int delim, int *flags,
2142 int *length, VarPattern *pattern)
2153 #define IS_A_MATCH(cp, delim) \
2154 ((cp[0] == '\\') && ((cp[1] == delim) || \
2155 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
2158 * Skim through until the matching delimiter is found;
2159 * pick up variable substitutions on the way. Also allow
2160 * backslashes to quote the delimiter, $, and \, but don't
2161 * touch other backslashes.
2163 for (cp = *tstr; *cp && (*cp != delim); cp++) {
2164 if (IS_A_MATCH(cp, delim)) {
2165 Buf_AddByte(&buf, cp[1]);
2167 } else if (*cp == '$') {
2168 if (cp[1] == delim) {
2170 Buf_AddByte(&buf, *cp);
2173 * Unescaped $ at end of pattern => anchor
2176 *flags |= VAR_MATCH_END;
2178 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
2184 * If unescaped dollar sign not before the
2185 * delimiter, assume it's a variable
2186 * substitution and recurse.
2188 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2189 Buf_AddBytes(&buf, strlen(cp2), cp2);
2194 const char *cp2 = &cp[1];
2196 if (*cp2 == PROPEN || *cp2 == BROPEN) {
2198 * Find the end of this variable reference
2199 * and suck it in without further ado.
2200 * It will be interperated later.
2203 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
2206 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
2207 if (cp2[-1] != '\\') {
2214 Buf_AddBytes(&buf, cp2 - cp, cp);
2217 Buf_AddByte(&buf, *cp);
2221 else if (pattern && *cp == '&')
2222 Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
2224 Buf_AddByte(&buf, *cp);
2234 *length = Buf_Size(&buf);
2235 rstr = Buf_Destroy(&buf, FALSE);
2237 fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
2242 *-----------------------------------------------------------------------
2244 * Quote shell meta-characters in the string
2252 *-----------------------------------------------------------------------
2259 /* This should cover most shells :-( */
2260 static const char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
2261 const char *newline;
2264 if ((newline = Shell_GetNewline()) == NULL)
2266 nlen = strlen(newline);
2269 while (*str != '\0') {
2270 if ((len = strcspn(str, meta)) != 0) {
2271 Buf_AddBytes(&buf, len, str);
2273 } else if (*str == '\n') {
2274 Buf_AddBytes(&buf, nlen, newline);
2277 Buf_AddByte(&buf, '\\');
2278 Buf_AddByte(&buf, *str);
2282 str = Buf_Destroy(&buf, FALSE);
2284 fprintf(debug_file, "QuoteMeta: [%s]\n", str);
2289 *-----------------------------------------------------------------------
2291 * Hash the string using the MurmurHash3 algorithm.
2292 * Output is computed using 32bit Little Endian arithmetic.
2295 * str String to modify
2298 * Hash value of str, encoded as 8 hex digits.
2303 *-----------------------------------------------------------------------
2308 static const char hexdigits[16] = "0123456789abcdef";
2311 unsigned char *ustr = (unsigned char *)str;
2312 uint32_t h, k, c1, c2;
2321 for (len = len2; len; ) {
2325 k = (ustr[3] << 24) | (ustr[2] << 16) | (ustr[1] << 8) | ustr[0];
2330 k |= (ustr[2] << 16);
2332 k |= (ustr[1] << 8);
2337 c1 = c1 * 5 + 0x7b7d159cU;
2338 c2 = c2 * 5 + 0x6bce6396U;
2340 k = (k << 11) ^ (k >> 21);
2342 h = (h << 13) ^ (h >> 19);
2343 h = h * 5 + 0x52dce729U;
2353 for (len = 0; len < 8; ++len) {
2354 Buf_AddByte(&buf, hexdigits[h & 15]);
2358 return Buf_Destroy(&buf, FALSE);
2362 VarStrftime(const char *fmt, int zulu)
2370 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2372 buf[sizeof(buf) - 1] = '\0';
2373 return bmake_strdup(buf);
2377 * Now we need to apply any modifiers the user wants applied.
2379 * :M<pattern> words which match the given <pattern>.
2380 * <pattern> is of the standard file
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
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.
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
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.
2448 * .for i in ${.TARGET} ${.TARGET:R}.gz
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
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] == ':'))
2466 ApplyModifiers(char *nstr, const char *tstr,
2467 int startc, int endc,
2468 Var *v, GNode *ctxt, Boolean errnum,
2469 int *lengthPtr, void **freePtr)
2472 const char *cp; /* Secondary pointer into str (place marker
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 */
2479 int modifier; /* that we are processing */
2480 Var_Parse_State parsestate; /* Flags passed to helper functions */
2483 parsestate.oneBigWord = FALSE;
2484 parsestate.varSpace = ' '; /* word separator */
2488 while (*tstr && *tstr != endc) {
2492 * We may have some complex modifiers in a variable.
2499 rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
2502 * If we have not parsed up to endc or ':',
2503 * we are not interested.
2505 if (rval != NULL && *rval &&
2506 (c = tstr[rlen]) != '\0' &&
2515 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
2516 rval, rlen, tstr, rlen, tstr + rlen);
2521 if (rval != NULL && *rval) {
2524 nstr = ApplyModifiers(nstr, rval,
2526 v, ctxt, errnum, &used, freePtr);
2527 if (nstr == var_Error
2528 || (nstr == varNoError && errnum == 0)
2529 || strlen(rval) != (size_t) used) {
2532 goto out; /* error already reported */
2539 else if (!*tstr && endc) {
2540 Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name);
2547 fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", v->name,
2551 switch ((modifier = *tstr)) {
2554 if (tstr[1] == '=' ||
2556 (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
2558 * "::=", "::!=", "::+=", or "::?="
2560 GNode *v_ctxt; /* context where v belongs */
2566 if (v->name[0] == 0)
2572 if (v->flags & VAR_JUNK) {
2574 * We need to bmake_strdup() it incase
2575 * VarGetPattern() recurses.
2578 v->name = bmake_strdup(v->name);
2579 } else if (ctxt != VAR_GLOBAL) {
2580 Var *gv = VarFind(v->name, ctxt, 0);
2582 v_ctxt = VAR_GLOBAL;
2584 VarFreeEnv(gv, TRUE);
2587 switch ((how = *tstr)) {
2597 delim = startc == PROPEN ? PRCLOSE : BRCLOSE;
2600 pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2604 if (v->flags & VAR_JUNK) {
2605 /* restore original name */
2609 if (pattern.rhs == NULL)
2617 Var_Append(v->name, pattern.rhs, v_ctxt);
2620 newStr = Cmd_Exec(pattern.rhs, &emsg);
2624 Var_Set(v->name, newStr, v_ctxt, 0);
2629 if ((v->flags & VAR_JUNK) == 0)
2633 Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2636 free(UNCONST(pattern.rhs));
2640 goto default_case; /* "::<unrecognised>" */
2645 int flags = VAR_NOSUBST;
2649 if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum,
2651 &flags, &loop.tvarLen,
2655 if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum,
2657 &flags, &loop.strLen,
2664 loop.errnum = errnum;
2666 newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
2675 Buffer buf; /* Buffer for patterns */
2676 int wantit; /* want data in buffer */
2679 * Pass through tstr looking for 1) escaped delimiters,
2680 * '$'s and backslashes (place the escaped character in
2681 * uninterpreted) and 2) unescaped $'s that aren't before
2682 * the delimiter (expand the variable substitution).
2683 * The result is left in the Buffer buf.
2687 *cp != endc && *cp != ':' && *cp != '\0';
2689 if ((*cp == '\\') &&
2695 Buf_AddByte(&buf, cp[1]);
2697 } else if (*cp == '$') {
2699 * If unescaped dollar sign, assume it's a
2700 * variable substitution and recurse.
2706 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2707 Buf_AddBytes(&buf, strlen(cp2), cp2);
2712 Buf_AddByte(&buf, *cp);
2719 wantit = ((v->flags & VAR_JUNK) != 0);
2721 wantit = ((v->flags & VAR_JUNK) == 0);
2722 if ((v->flags & VAR_JUNK) != 0)
2723 v->flags |= VAR_KEEP;
2725 newStr = Buf_Destroy(&buf, FALSE);
2728 Buf_Destroy(&buf, TRUE);
2734 if ((v->flags & VAR_JUNK) != 0)
2735 v->flags |= VAR_KEEP;
2736 newStr = bmake_strdup(v->name);
2745 if ((v->flags & VAR_JUNK) != 0)
2746 v->flags |= VAR_KEEP;
2747 gn = Targ_FindNode(v->name, TARG_NOCREATE);
2748 if (gn == NULL || gn->type & OP_NOPATH) {
2750 } else if (gn->path) {
2751 newStr = bmake_strdup(gn->path);
2753 newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
2756 newStr = bmake_strdup(v->name);
2771 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2773 NULL, &pattern.rightLen,
2776 newStr = Cmd_Exec(pattern.rhs, &emsg);
2777 free(UNCONST(pattern.rhs));
2782 if (v->flags & VAR_JUNK) {
2783 v->flags |= VAR_KEEP;
2790 * Look for the closing ']', recursively
2791 * expanding any embedded variables.
2793 * estr is a pointer to the expanded result,
2794 * which we must free().
2798 cp = tstr+1; /* point to char after '[' */
2799 delim = ']'; /* look for closing ']' */
2800 estr = VarGetPattern(ctxt, &parsestate,
2804 goto cleanup; /* report missing ']' */
2805 /* now cp points just after the closing ']' */
2807 if (cp[0] != ':' && cp[0] != endc) {
2808 /* Found junk after ']' */
2812 if (estr[0] == '\0') {
2813 /* Found empty square brackets in ":[]". */
2816 } else if (estr[0] == '#' && estr[1] == '\0') {
2820 * We will need enough space for the decimal
2821 * representation of an int. We calculate the
2822 * space needed for the octal representation,
2823 * and add enough slop to cope with a '-' sign
2824 * (which should never be needed) and a '\0'
2825 * string terminator.
2828 (sizeof(int) * CHAR_BIT + 2) / 3 + 2;
2830 newStr = bmake_malloc(newStrSize);
2831 if (parsestate.oneBigWord) {
2832 strncpy(newStr, "1", newStrSize);
2834 /* XXX: brk_string() is a rather expensive
2835 * way of counting words. */
2840 av = brk_string(nstr, &ac, FALSE, &as);
2841 snprintf(newStr, newStrSize, "%d", ac);
2848 } else if (estr[0] == '*' && estr[1] == '\0') {
2850 parsestate.oneBigWord = TRUE;
2855 } else if (estr[0] == '@' && estr[1] == '\0') {
2857 parsestate.oneBigWord = FALSE;
2864 * We expect estr to contain a single
2865 * integer for :[N], or two integers
2866 * separated by ".." for :[start..end].
2870 VarSelectWords_t seldata = { 0, 0 };
2872 seldata.start = strtol(estr, &ep, 0);
2874 /* Found junk instead of a number */
2877 } else if (ep[0] == '\0') {
2878 /* Found only one integer in :[N] */
2879 seldata.end = seldata.start;
2880 } else if (ep[0] == '.' && ep[1] == '.' &&
2882 /* Expecting another integer after ".." */
2884 seldata.end = strtol(ep, &ep, 0);
2885 if (ep[0] != '\0') {
2886 /* Found junk after ".." */
2891 /* Found junk instead of ".." */
2896 * Now seldata is properly filled in,
2897 * but we still have to check for 0 as
2900 if (seldata.start == 0 && seldata.end == 0) {
2901 /* ":[0]" or perhaps ":[0..0]" */
2902 parsestate.oneBigWord = TRUE;
2907 } else if (seldata.start == 0 ||
2909 /* ":[0..N]" or ":[N..0]" */
2914 * Normal case: select the words
2915 * described by seldata.
2917 newStr = VarSelectWords(ctxt, &parsestate,
2927 cp = tstr + 1; /* make sure it is set */
2928 if (STRMOD_MATCH(tstr, "gmtime", 6)) {
2929 newStr = VarStrftime(nstr, 1);
2937 cp = tstr + 1; /* make sure it is set */
2938 if (STRMOD_MATCH(tstr, "hash", 4)) {
2939 newStr = VarHash(nstr);
2947 cp = tstr + 1; /* make sure it is set */
2948 if (STRMOD_MATCH(tstr, "localtime", 9)) {
2949 newStr = VarStrftime(nstr, 0);
2958 cp = tstr + 1; /* make sure it is set */
2959 if (tstr[1] != endc && tstr[1] != ':') {
2960 if (tstr[1] == 's') {
2962 * Use the char (if any) at tstr[2]
2963 * as the word separator.
2967 if (tstr[2] != endc &&
2968 (tstr[3] == endc || tstr[3] == ':')) {
2969 /* ":ts<unrecognised><endc>" or
2970 * ":ts<unrecognised>:" */
2971 parsestate.varSpace = tstr[2];
2973 } else if (tstr[2] == endc || tstr[2] == ':') {
2974 /* ":ts<endc>" or ":ts:" */
2975 parsestate.varSpace = 0; /* no separator */
2977 } else if (tstr[2] == '\\') {
2980 parsestate.varSpace = '\n';
2984 parsestate.varSpace = '\t';
2988 if (isdigit((unsigned char)tstr[3])) {
2991 parsestate.varSpace =
2992 strtoul(&tstr[3], &ep, 0);
2993 if (*ep != ':' && *ep != endc)
2998 * ":ts<backslash><unrecognised>".
3006 * Found ":ts<unrecognised><unrecognised>".
3014 * We cannot be certain that VarModify
3015 * will be used - even if there is a
3016 * subsequent modifier, so do a no-op
3017 * VarSubstitute now to for str to be
3018 * re-expanded without the spaces.
3020 pattern.flags = VAR_SUB_ONE;
3021 pattern.lhs = pattern.rhs = "\032";
3022 pattern.leftLen = pattern.rightLen = 1;
3024 newStr = VarModify(ctxt, &parsestate, nstr,
3027 } else if (tstr[2] == endc || tstr[2] == ':') {
3029 * Check for two-character options:
3032 if (tstr[1] == 'A') { /* absolute path */
3033 newStr = VarModify(ctxt, &parsestate, nstr,
3037 } else if (tstr[1] == 'u') {
3038 char *dp = bmake_strdup(nstr);
3039 for (newStr = dp; *dp; dp++)
3040 *dp = toupper((unsigned char)*dp);
3043 } else if (tstr[1] == 'l') {
3044 char *dp = bmake_strdup(nstr);
3045 for (newStr = dp; *dp; dp++)
3046 *dp = tolower((unsigned char)*dp);
3049 } else if (tstr[1] == 'W' || tstr[1] == 'w') {
3050 parsestate.oneBigWord = (tstr[1] == 'W');
3055 /* Found ":t<unrecognised>:" or
3056 * ":t<unrecognised><endc>". */
3061 * Found ":t<unrecognised><unrecognised>".
3067 * Found ":t<endc>" or ":t:".
3077 const char *endpat; /* points just after end of pattern */
3079 Boolean copy; /* pattern should be, or has been, copied */
3087 * In the loop below, ignore ':' unless we are at
3088 * (or back to) the original brace level.
3089 * XXX This will likely not work right if $() and ${}
3093 *cp != '\0' && !(*cp == ':' && nest == 1);
3098 cp[1] == endc || cp[1] == startc)) {
3108 if (*cp == '(' || *cp == '{')
3110 if (*cp == ')' || *cp == '}') {
3120 * Need to compress the \:'s out of the pattern, so
3121 * allocate enough room to hold the uncompressed
3122 * pattern (note that cp started at tstr+1, so
3123 * cp - tstr takes the null byte into account) and
3124 * compress the pattern into the space.
3126 pattern = bmake_malloc(cp - tstr);
3127 for (cp2 = pattern, cp = tstr + 1;
3131 if ((*cp == '\\') && (cp+1 < endpat) &&
3132 (cp[1] == ':' || cp[1] == endc)) {
3141 * Either Var_Subst or VarModify will need a
3142 * nul-terminated string soon, so construct one now.
3144 pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
3148 * pattern contains embedded '$', so use Var_Subst to
3152 pattern = Var_Subst(NULL, cp2, ctxt, errnum);
3156 fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
3157 v->name, nstr, pattern);
3159 newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
3162 newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
3171 Var_Parse_State tmpparsestate;
3174 tmpparsestate = parsestate;
3179 * If pattern begins with '^', it is anchored to the
3180 * start of the word -- skip over it and flag pattern.
3183 pattern.flags |= VAR_MATCH_START;
3188 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3195 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3202 * Check for global substitution. If 'g' after the final
3203 * delimiter, substitution is global and is marked that
3209 pattern.flags |= VAR_SUB_GLOBAL;
3212 pattern.flags |= VAR_SUB_ONE;
3215 tmpparsestate.oneBigWord = TRUE;
3222 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3227 * Free the two strings.
3229 free(UNCONST(pattern.lhs));
3230 free(UNCONST(pattern.rhs));
3239 /* find ':', and then substitute accordingly */
3245 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3251 /* BROPEN or PROPEN */
3253 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3261 if (Cond_EvalExpression(NULL, v->name, &value, 0)
3263 Error("Bad conditional expression `%s' in %s?%s:%s",
3264 v->name, v->name, pattern.lhs, pattern.rhs);
3269 newStr = UNCONST(pattern.lhs);
3270 free(UNCONST(pattern.rhs));
3272 newStr = UNCONST(pattern.rhs);
3273 free(UNCONST(pattern.lhs));
3275 if (v->flags & VAR_JUNK) {
3276 v->flags |= VAR_KEEP;
3283 VarREPattern pattern;
3286 Var_Parse_State tmpparsestate;
3289 tmpparsestate = parsestate;
3295 if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim,
3296 NULL, NULL, NULL)) == NULL)
3299 if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
3300 errnum, &cp, delim, NULL,
3301 NULL, NULL)) == NULL){
3309 pattern.flags |= VAR_SUB_GLOBAL;
3312 pattern.flags |= VAR_SUB_ONE;
3315 tmpparsestate.oneBigWord = TRUE;
3323 error = regcomp(&pattern.re, re, REG_EXTENDED);
3326 *lengthPtr = cp - start + 1;
3327 VarREError(error, &pattern.re, "RE substitution error");
3328 free(pattern.replace);
3332 pattern.nsub = pattern.re.re_nsub + 1;
3333 if (pattern.nsub < 1)
3335 if (pattern.nsub > 10)
3337 pattern.matches = bmake_malloc(pattern.nsub *
3338 sizeof(regmatch_t));
3339 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3342 regfree(&pattern.re);
3343 free(pattern.replace);
3344 free(pattern.matches);
3350 if (tstr[1] == endc || tstr[1] == ':') {
3351 newStr = VarQuote(nstr);
3358 if (tstr[1] == endc || tstr[1] == ':') {
3359 newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
3367 if (tstr[1] == endc || tstr[1] == ':') {
3368 newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
3376 if (tstr[1] == endc || tstr[1] == ':') {
3377 newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
3385 if (tstr[1] == endc || tstr[1] == ':') {
3386 newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
3397 cp = tstr + 1; /* skip to the rest in any case */
3398 if (tstr[1] == endc || tstr[1] == ':') {
3401 } else if ( (tstr[1] == 'x') &&
3402 (tstr[2] == endc || tstr[2] == ':') ) {
3409 newStr = VarOrder(nstr, otype);
3413 if (tstr[1] == endc || tstr[1] == ':') {
3414 newStr = VarUniq(nstr);
3422 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
3424 newStr = Cmd_Exec(nstr, &emsg);
3438 * This can either be a bogus modifier or a System-V
3439 * substitution command.
3447 * First we make a pass through the string trying
3448 * to verify it is a SYSV-make-style translation:
3449 * it must be: <string1>=<string2>)
3453 while (*cp != '\0' && cnt) {
3456 /* continue looking for endc */
3458 else if (*cp == endc)
3460 else if (*cp == startc)
3465 if (*cp == endc && eqFound) {
3468 * Now we break this sucker into the lhs and
3469 * rhs. We must null terminate them of course.
3473 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
3474 errnum, &cp, delim, &pattern.flags,
3475 &pattern.leftLen, NULL)) == NULL)
3478 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
3479 errnum, &cp, delim, NULL, &pattern.rightLen,
3484 * SYSV modifications happen through the whole
3485 * string. Note the pattern is anchored at the end.
3489 if (pattern.leftLen == 0 && *nstr == '\0') {
3490 newStr = nstr; /* special case */
3492 newStr = VarModify(ctxt, &parsestate, nstr,
3496 free(UNCONST(pattern.lhs));
3497 free(UNCONST(pattern.rhs));
3501 Error("Unknown modifier '%c'", *tstr);
3503 *cp != ':' && *cp != endc && *cp != '\0';
3512 fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
3513 v->name, modifier, newStr);
3516 if (newStr != nstr) {
3522 if (nstr != var_Error && nstr != varNoError) {
3526 if (termc == '\0' && endc != '\0') {
3527 Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier);
3528 } else if (termc == ':') {
3534 *lengthPtr = tstr - start;
3539 Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
3543 *lengthPtr = cp - start;
3545 Error("Unclosed substitution for %s (%c missing)",
3555 *-----------------------------------------------------------------------
3557 * Given the start of a variable invocation, extract the variable
3558 * name and find its value, then modify it according to the
3562 * str The string to parse
3563 * ctxt The context for the variable
3564 * errnum TRUE if undefined variables are an error
3565 * lengthPtr OUT: The length of the specification
3566 * freePtr OUT: Non-NULL if caller should free *freePtr
3569 * The (possibly-modified) value of the variable or var_Error if the
3570 * specification is invalid. The length of the specification is
3571 * placed in *lengthPtr (for invalid specifications, this is just
3573 * If *freePtr is non-NULL then it's a pointer that the caller
3574 * should pass to free() to free memory used by the result.
3579 *-----------------------------------------------------------------------
3581 /* coverity[+alloc : arg-*4] */
3583 Var_Parse(const char *str, GNode *ctxt, Boolean errnum, int *lengthPtr,
3586 const char *tstr; /* Pointer into str */
3587 Var *v; /* Variable in invocation */
3588 Boolean haveModifier;/* TRUE if have modifiers for the variable */
3589 char endc; /* Ending character when variable in parens
3591 char startc; /* Starting character when variable in parens
3593 int vlen; /* Length of variable name */
3594 const char *start; /* Points to original start of str */
3595 char *nstr; /* New string, used during expansion */
3596 Boolean dynamic; /* TRUE if the variable is local and we're
3597 * expanding it in a non-local context. This
3598 * is done to support dynamic sources. The
3599 * result is just the invocation, unaltered */
3600 Var_Parse_State parsestate; /* Flags passed to helper functions */
3606 parsestate.oneBigWord = FALSE;
3607 parsestate.varSpace = ' '; /* word separator */
3610 if (startc != PROPEN && startc != BROPEN) {
3612 * If it's not bounded by braces of some sort, life is much simpler.
3613 * We just need to check for the first character and return the
3614 * value if it exists.
3617 /* Error out some really stupid names */
3618 if (startc == '\0' || strchr(")}:$", startc)) {
3625 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3629 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
3631 * If substituting a local variable in a non-local context,
3632 * assume it's for dynamic source stuff. We have to handle
3633 * this specially and return the longhand for the variable
3634 * with the dollar sign escaped so it makes it back to the
3635 * caller. Only four of the local variables are treated
3636 * specially as they are the only four that will be set
3637 * when dynamic sources are expanded.
3641 return UNCONST("$(.TARGET)");
3643 return UNCONST("$(.ARCHIVE)");
3645 return UNCONST("$(.PREFIX)");
3647 return UNCONST("$(.MEMBER)");
3653 return (errnum ? var_Error : varNoError);
3655 haveModifier = FALSE;
3660 Buffer buf; /* Holds the variable name */
3662 endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3666 * Skip to the end character or a colon, whichever comes first.
3668 for (tstr = str + 2;
3669 *tstr != '\0' && *tstr != endc && *tstr != ':';
3673 * A variable inside a variable, expand
3678 char *rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
3680 Buf_AddBytes(&buf, strlen(rval), rval);
3687 Buf_AddByte(&buf, *tstr);
3690 haveModifier = TRUE;
3691 } else if (*tstr != '\0') {
3692 haveModifier = FALSE;
3695 * If we never did find the end character, return NULL
3696 * right now, setting the length to be the distance to
3697 * the end of the string, since that's what make does.
3699 *lengthPtr = tstr - str;
3700 Buf_Destroy(&buf, TRUE);
3703 str = Buf_GetAll(&buf, &vlen);
3706 * At this point, str points into newly allocated memory from
3707 * buf, containing only the name of the variable.
3709 * start and tstr point into the const string that was pointed
3710 * to by the original value of the str parameter. start points
3711 * to the '$' at the beginning of the string, while tstr points
3712 * to the char just after the end of the variable name -- this
3713 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3716 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3718 * Check also for bogus D and F forms of local variables since we're
3719 * in a local context and the name is the right length.
3721 if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
3722 (vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
3723 strchr("@%*!<>", str[0]) != NULL) {
3725 * Well, it's local -- go look for it.
3729 v = VarFind(name, ctxt, 0);
3733 * No need for nested expansion or anything, as we're
3734 * the only one who sets these things and we sure don't
3735 * but nested invocations in them...
3737 nstr = Buf_GetAll(&v->val, NULL);
3739 if (str[1] == 'D') {
3740 nstr = VarModify(ctxt, &parsestate, nstr, VarHead,
3743 nstr = VarModify(ctxt, &parsestate, nstr, VarTail,
3747 * Resulting string is dynamically allocated, so
3748 * tell caller to free it.
3751 *lengthPtr = tstr-start+1;
3752 Buf_Destroy(&buf, TRUE);
3753 VarFreeEnv(v, TRUE);
3760 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
3761 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3764 * If substituting a local variable in a non-local context,
3765 * assume it's for dynamic source stuff. We have to handle
3766 * this specially and return the longhand for the variable
3767 * with the dollar sign escaped so it makes it back to the
3768 * caller. Only four of the local variables are treated
3769 * specially as they are the only four that will be set
3770 * when dynamic sources are expanded.
3780 } else if ((vlen > 2) && (*str == '.') &&
3781 isupper((unsigned char) str[1]) &&
3782 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3787 if ((strncmp(str, ".TARGET", len) == 0) ||
3788 (strncmp(str, ".ARCHIVE", len) == 0) ||
3789 (strncmp(str, ".PREFIX", len) == 0) ||
3790 (strncmp(str, ".MEMBER", len) == 0))
3796 if (!haveModifier) {
3798 * No modifiers -- have specification length so we can return
3801 *lengthPtr = tstr - start + 1;
3803 char *pstr = bmake_strndup(start, *lengthPtr);
3805 Buf_Destroy(&buf, TRUE);
3808 Buf_Destroy(&buf, TRUE);
3809 return (errnum ? var_Error : varNoError);
3813 * Still need to get to the end of the variable specification,
3814 * so kludge up a Var structure for the modifications
3816 v = bmake_malloc(sizeof(Var));
3817 v->name = UNCONST(str);
3818 Buf_Init(&v->val, 1);
3819 v->flags = VAR_JUNK;
3820 Buf_Destroy(&buf, FALSE);
3823 Buf_Destroy(&buf, TRUE);
3826 if (v->flags & VAR_IN_USE) {
3827 Fatal("Variable %s is recursive.", v->name);
3830 v->flags |= VAR_IN_USE;
3833 * Before doing any modification, we have to make sure the value
3834 * has been fully expanded. If it looks like recursion might be
3835 * necessary (there's a dollar sign somewhere in the variable's value)
3836 * we just call Var_Subst to do any other substitutions that are
3837 * necessary. Note that the value returned by Var_Subst will have
3838 * been dynamically-allocated, so it will need freeing when we
3841 nstr = Buf_GetAll(&v->val, NULL);
3842 if (strchr(nstr, '$') != NULL) {
3843 nstr = Var_Subst(NULL, nstr, ctxt, errnum);
3847 v->flags &= ~VAR_IN_USE;
3849 if ((nstr != NULL) && haveModifier) {
3852 * Skip initial colon.
3856 nstr = ApplyModifiers(nstr, tstr, startc, endc,
3857 v, ctxt, errnum, &used, freePtr);
3861 *lengthPtr = tstr - start + 1;
3863 *lengthPtr = tstr - start;
3866 if (v->flags & VAR_FROM_ENV) {
3867 Boolean destroy = FALSE;
3869 if (nstr != Buf_GetAll(&v->val, NULL)) {
3873 * Returning the value unmodified, so tell the caller to free
3878 VarFreeEnv(v, destroy);
3879 } else if (v->flags & VAR_JUNK) {
3881 * Perform any free'ing needed and set *freePtr to NULL so the caller
3882 * doesn't try to free a static pointer.
3883 * If VAR_KEEP is also set then we want to keep str as is.
3885 if (!(v->flags & VAR_KEEP)) {
3891 nstr = bmake_strndup(start, *lengthPtr);
3894 nstr = errnum ? var_Error : varNoError;
3897 if (nstr != Buf_GetAll(&v->val, NULL))
3898 Buf_Destroy(&v->val, TRUE);
3906 *-----------------------------------------------------------------------
3908 * Substitute for all variables in the given string in the given context
3909 * If undefErr is TRUE, Parse_Error will be called when an undefined
3910 * variable is encountered.
3913 * var Named variable || NULL for all
3914 * str the string which to substitute
3915 * ctxt the context wherein to find variables
3916 * undefErr TRUE if undefineds are an error
3919 * The resulting string.
3922 * None. The old string must be freed by the caller
3923 *-----------------------------------------------------------------------
3926 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
3928 Buffer buf; /* Buffer for forming things */
3929 char *val; /* Value to substitute for a variable */
3930 int length; /* Length of the variable invocation */
3931 Boolean trailingBslash; /* variable ends in \ */
3932 void *freeIt = NULL; /* Set if it should be freed */
3933 static Boolean errorReported; /* Set true if an error has already
3934 * been reported to prevent a plethora
3935 * of messages when recursing */
3938 errorReported = FALSE;
3939 trailingBslash = FALSE;
3942 if (*str == '\n' && trailingBslash)
3943 Buf_AddByte(&buf, ' ');
3944 if (var == NULL && (*str == '$') && (str[1] == '$')) {
3946 * A dollar sign may be escaped either with another dollar sign.
3947 * In such a case, we skip over the escape character and store the
3948 * dollar sign into the buffer directly.
3951 Buf_AddByte(&buf, *str);
3953 } else if (*str != '$') {
3955 * Skip as many characters as possible -- either to the end of
3956 * the string or to the next dollar sign (variable invocation).
3960 for (cp = str++; *str != '$' && *str != '\0'; str++)
3962 Buf_AddBytes(&buf, str - cp, cp);
3967 if (str[1] == '\0') {
3968 /* A trailing $ is kind of a special case */
3969 Buf_AddByte(&buf, str[0]);
3972 } else if (str[1] != PROPEN && str[1] != BROPEN) {
3973 if (str[1] != *var || strlen(var) > 1) {
3974 Buf_AddBytes(&buf, 2, str);
3986 * Scan up to the end of the variable name.
3988 for (p = &str[2]; *p &&
3989 *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
3993 * A variable inside the variable. We cannot expand
3994 * the external variable yet, so we try again with
3998 Buf_AddBytes(&buf, p - str, str);
4003 if (strncmp(var, str + 2, p - str - 2) != 0 ||
4004 var[p - str - 2] != '\0') {
4006 * Not the variable we want to expand, scan
4007 * until the next variable
4009 for (;*p != '$' && *p != '\0'; p++)
4011 Buf_AddBytes(&buf, p - str, str);
4024 val = Var_Parse(str, ctxt, undefErr, &length, &freeIt);
4027 * When we come down here, val should either point to the
4028 * value of this variable, suitably modified, or be NULL.
4029 * Length should be the total length of the potential
4030 * variable invocation (from $ to end character...)
4032 if (val == var_Error || val == varNoError) {
4034 * If performing old-time variable substitution, skip over
4035 * the variable and continue with the substitution. Otherwise,
4036 * store the dollar sign and advance str so we continue with
4041 } else if (undefErr) {
4043 * If variable is undefined, complain and skip the
4044 * variable. The complaint will stop us from doing anything
4045 * when the file is parsed.
4047 if (!errorReported) {
4048 Parse_Error(PARSE_FATAL,
4049 "Undefined variable \"%.*s\"",length,str);
4052 errorReported = TRUE;
4054 Buf_AddByte(&buf, *str);
4059 * We've now got a variable structure to store in. But first,
4060 * advance the string pointer.
4065 * Copy all the characters from the variable value straight
4066 * into the new string.
4068 length = strlen(val);
4069 Buf_AddBytes(&buf, length, val);
4070 trailingBslash = length > 0 && val[length - 1] == '\\';
4079 return Buf_DestroyCompact(&buf);
4083 *-----------------------------------------------------------------------
4085 * Return the tail from each of a list of words. Used to set the
4086 * System V local variables.
4089 * file Filename to modify
4092 * The resulting string.
4097 *-----------------------------------------------------------------------
4101 Var_GetTail(char *file)
4103 return(VarModify(file, VarTail, NULL));
4107 *-----------------------------------------------------------------------
4109 * Find the leading components of a (list of) filename(s).
4110 * XXX: VarHead does not replace foo by ., as (sun) System V make
4114 * file Filename to manipulate
4117 * The leading components.
4122 *-----------------------------------------------------------------------
4125 Var_GetHead(char *file)
4127 return(VarModify(file, VarHead, NULL));
4132 *-----------------------------------------------------------------------
4134 * Initialize the module
4140 * The VAR_CMD and VAR_GLOBAL contexts are created
4141 *-----------------------------------------------------------------------
4146 VAR_GLOBAL = Targ_NewGN("Global");
4147 VAR_CMD = Targ_NewGN("Command");
4158 /****************** PRINT DEBUGGING INFO *****************/
4160 VarPrintVar(void *vp)
4163 fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
4167 *-----------------------------------------------------------------------
4169 * print all variables in a context
4170 *-----------------------------------------------------------------------
4173 Var_Dump(GNode *ctxt)
4178 for (h = Hash_EnumFirst(&ctxt->context, &search);
4180 h = Hash_EnumNext(&search)) {
4181 VarPrintVar(Hash_GetValue(h));