1 /* $NetBSD: var.c,v 1.171 2012/06/12 19:21:51 joerg 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.171 2012/06/12 19:21:51 joerg 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.171 2012/06/12 19:21:51 joerg 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 *VarChangeCase(char *, int);
313 static char *VarHash(char *);
314 static char *VarModify(GNode *, Var_Parse_State *,
316 Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *),
318 static char *VarOrder(const char *, const char);
319 static char *VarUniq(const char *);
320 static int VarWordCompare(const void *, const void *);
321 static void VarPrintVar(void *);
329 *-----------------------------------------------------------------------
331 * Find the given variable in the given context and any other contexts
336 * ctxt context in which to find it
337 * flags FIND_GLOBAL set means to look in the
338 * VAR_GLOBAL context as well. FIND_CMD set means
339 * to look in the VAR_CMD context also. FIND_ENV
340 * set means to look in the environment
343 * A pointer to the structure describing the desired variable or
344 * NULL if the variable does not exist.
348 *-----------------------------------------------------------------------
351 VarFind(const char *name, GNode *ctxt, int flags)
357 * If the variable name begins with a '.', it could very well be one of
358 * the local ones. We check the name against all the local variables
359 * and substitute the short version in for 'name' if it matches one of
362 if (*name == '.' && isupper((unsigned char) name[1]))
365 if (!strcmp(name, ".ALLSRC"))
367 if (!strcmp(name, ".ARCHIVE"))
371 if (!strcmp(name, ".IMPSRC"))
375 if (!strcmp(name, ".MEMBER"))
379 if (!strcmp(name, ".OODATE"))
383 if (!strcmp(name, ".PREFIX"))
387 if (!strcmp(name, ".TARGET"))
392 /* for compatibility with gmake */
393 if (name[0] == '^' && name[1] == '\0')
398 * First look for the variable in the given context. If it's not there,
399 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
400 * depending on the FIND_* flags in 'flags'
402 var = Hash_FindEntry(&ctxt->context, name);
404 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
405 var = Hash_FindEntry(&VAR_CMD->context, name);
407 if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
408 (ctxt != VAR_GLOBAL))
410 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
412 if ((var == NULL) && (flags & FIND_ENV)) {
415 if ((env = getenv(name)) != NULL) {
418 v = bmake_malloc(sizeof(Var));
419 v->name = bmake_strdup(name);
423 Buf_Init(&v->val, len + 1);
424 Buf_AddBytes(&v->val, len, env);
426 v->flags = VAR_FROM_ENV;
428 } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
429 (ctxt != VAR_GLOBAL))
431 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
435 return ((Var *)Hash_GetValue(var));
440 } else if (var == NULL) {
443 return ((Var *)Hash_GetValue(var));
448 *-----------------------------------------------------------------------
450 * If the variable is an environment variable, free it
454 * destroy true if the value buffer should be destroyed.
457 * 1 if it is an environment variable 0 ow.
460 * The variable is free'ed if it is an environent variable.
461 *-----------------------------------------------------------------------
464 VarFreeEnv(Var *v, Boolean destroy)
466 if ((v->flags & VAR_FROM_ENV) == 0)
469 Buf_Destroy(&v->val, destroy);
475 *-----------------------------------------------------------------------
477 * Add a new variable of name name and value val to the given context
480 * name name of variable to add
481 * val value to set it to
482 * ctxt context in which to set it
488 * The new variable is placed at the front of the given context
489 * The name and val arguments are duplicated so they may
491 *-----------------------------------------------------------------------
494 VarAdd(const char *name, const char *val, GNode *ctxt)
500 v = bmake_malloc(sizeof(Var));
502 len = val ? strlen(val) : 0;
503 Buf_Init(&v->val, len+1);
504 Buf_AddBytes(&v->val, len, val);
508 h = Hash_CreateEntry(&ctxt->context, name, NULL);
512 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
517 *-----------------------------------------------------------------------
519 * Remove a variable from a context.
525 * The Var structure is removed and freed.
527 *-----------------------------------------------------------------------
530 Var_Delete(const char *name, GNode *ctxt)
534 ln = Hash_FindEntry(&ctxt->context, name);
536 fprintf(debug_file, "%s:delete %s%s\n",
537 ctxt->name, name, ln ? "" : " (not found)");
542 v = (Var *)Hash_GetValue(ln);
543 if ((v->flags & VAR_EXPORTED)) {
546 if (strcmp(MAKE_EXPORTED, v->name) == 0) {
547 var_exportedVars = VAR_EXPORTED_NONE;
549 if (v->name != ln->name)
551 Hash_DeleteEntry(&ctxt->context, ln);
552 Buf_Destroy(&v->val, TRUE);
560 * We ignore make internal variables (those which start with '.')
561 * Also we jump through some hoops to avoid calling setenv
562 * more than necessary since it can leak.
563 * We only manipulate flags of vars if 'parent' is set.
566 Var_Export1(const char *name, int parent)
574 return 0; /* skip internals */
578 * If it is one of the vars that should only appear in
579 * local context, skip it, else we can get Var_Subst
590 v = VarFind(name, VAR_GLOBAL, 0);
595 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
596 return 0; /* nothing to do */
598 val = Buf_GetAll(&v->val, NULL);
599 if (strchr(val, '$')) {
602 * Flag this as something we need to re-export.
603 * No point actually exporting it now though,
604 * the child can do it at the last minute.
606 v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
609 if (v->flags & VAR_IN_USE) {
611 * We recursed while exporting in a child.
612 * This isn't going to end well, just skip it.
616 n = snprintf(tmp, sizeof(tmp), "${%s}", name);
617 if (n < (int)sizeof(tmp)) {
618 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
619 setenv(name, val, 1);
624 v->flags &= ~VAR_REEXPORT; /* once will do */
626 if (parent || !(v->flags & VAR_EXPORTED)) {
627 setenv(name, val, 1);
631 * This is so Var_Set knows to call Var_Export again...
634 v->flags |= VAR_EXPORTED;
640 * This gets called from our children.
652 if (VAR_EXPORTED_NONE == var_exportedVars)
655 if (VAR_EXPORTED_ALL == var_exportedVars) {
657 * Ouch! This is crazy...
659 for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
661 var = Hash_EnumNext(&state)) {
662 v = (Var *)Hash_GetValue(var);
663 Var_Export1(v->name, 0);
668 * We have a number of exported vars,
670 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
671 if (n < (int)sizeof(tmp)) {
677 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
678 av = brk_string(val, &ac, FALSE, &as);
679 for (i = 0; i < ac; i++) {
680 Var_Export1(av[i], 0);
689 * This is called when .export is seen or
690 * .MAKE.EXPORTED is modified.
691 * It is also called when any exported var is modified.
694 Var_Export(char *str, int isExport)
704 if (isExport && (!str || !str[0])) {
705 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
709 if (strncmp(str, "-env", 4) == 0) {
713 track = VAR_EXPORT_PARENT;
715 val = Var_Subst(NULL, str, VAR_GLOBAL, 0);
716 av = brk_string(val, &ac, FALSE, &as);
717 for (i = 0; i < ac; i++) {
722 * If it is one of the vars that should only appear in
723 * local context, skip it, else we can get Var_Subst
734 if (Var_Export1(name, track)) {
735 if (VAR_EXPORTED_ALL != var_exportedVars)
736 var_exportedVars = VAR_EXPORTED_YES;
737 if (isExport && track) {
738 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
749 * This is called when .unexport[-env] is seen.
751 extern char **environ;
754 Var_UnExport(char *str)
759 Boolean unexport_env;
762 if (!str || !str[0]) {
763 return; /* assert? */
769 unexport_env = (strncmp(str, "-env", 4) == 0);
773 cp = getenv(MAKE_LEVEL); /* we should preserve this */
774 if (environ == savedEnv) {
775 /* we have been here before! */
776 newenv = bmake_realloc(environ, 2 * sizeof(char *));
782 newenv = bmake_malloc(2 * sizeof(char *));
786 /* Note: we cannot safely free() the original environ. */
787 environ = savedEnv = newenv;
790 setenv(MAKE_LEVEL, cp, 1);
791 #ifdef MAKE_LEVEL_SAFE
792 setenv(MAKE_LEVEL_SAFE, cp, 1);
795 for (; *str != '\n' && isspace((unsigned char) *str); str++)
797 if (str[0] && str[0] != '\n') {
803 /* Using .MAKE.EXPORTED */
804 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
805 if (n < (int)sizeof(tmp)) {
806 vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
816 av = brk_string(vlist, &ac, FALSE, &as);
817 for (i = 0; i < ac; i++) {
818 v = VarFind(av[i], VAR_GLOBAL, 0);
822 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
825 v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT);
827 * If we are unexporting a list,
828 * remove each one from .MAKE.EXPORTED.
829 * If we are removing them all,
830 * just delete .MAKE.EXPORTED below.
833 n = snprintf(tmp, sizeof(tmp),
834 "${" MAKE_EXPORTED ":N%s}", v->name);
835 if (n < (int)sizeof(tmp)) {
836 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
837 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0);
845 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
852 *-----------------------------------------------------------------------
854 * Set the variable name to the value val in the given context.
857 * name name of variable to set
858 * val value to give to the variable
859 * ctxt context in which to set it
865 * If the variable doesn't yet exist, a new record is created for it.
866 * Else the old value is freed and the new one stuck in its place
869 * The variable is searched for only in its context before being
870 * created in that context. I.e. if the context is VAR_GLOBAL,
871 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
872 * VAR_CMD->context is searched. This is done to avoid the literally
873 * thousands of unnecessary strcmp's that used to be done to
874 * set, say, $(@) or $(<).
875 * If the context is VAR_GLOBAL though, we check if the variable
876 * was set in VAR_CMD from the command line and skip it if so.
877 *-----------------------------------------------------------------------
880 Var_Set(const char *name, const char *val, GNode *ctxt, int flags)
883 char *expanded_name = NULL;
886 * We only look for a variable in the given context since anything set
887 * here will override anything in a lower context, so there's not much
888 * point in searching them all just to save a bit of memory...
890 if (strchr(name, '$') != NULL) {
891 expanded_name = Var_Subst(NULL, name, ctxt, 0);
892 if (expanded_name[0] == 0) {
894 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
895 "name expands to empty string - ignored\n",
901 name = expanded_name;
903 if (ctxt == VAR_GLOBAL) {
904 v = VarFind(name, VAR_CMD, 0);
906 if ((v->flags & VAR_FROM_CMD)) {
908 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
915 v = VarFind(name, ctxt, 0);
917 VarAdd(name, val, ctxt);
920 Buf_AddBytes(&v->val, strlen(val), val);
923 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
925 if ((v->flags & VAR_EXPORTED)) {
926 Var_Export1(name, VAR_EXPORT_PARENT);
930 * Any variables given on the command line are automatically exported
931 * to the environment (as per POSIX standard)
933 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
935 /* we just added it */
936 v = VarFind(name, ctxt, 0);
939 v->flags |= VAR_FROM_CMD;
941 * If requested, don't export these in the environment
942 * individually. We still put them in MAKEOVERRIDES so
943 * that the command-line settings continue to override
946 if (varNoExportEnv != TRUE)
947 setenv(name, val, 1);
949 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
952 * Another special case.
953 * Several make's support this sort of mechanism for tracking
954 * recursion - but each uses a different name.
955 * We allow the makefiles to update .MAKE.LEVEL and ensure
956 * children see a correctly incremented value.
958 if (ctxt == VAR_GLOBAL && strcmp(MAKE_LEVEL, name) == 0) {
963 snprintf(tmp, sizeof(tmp), "%u", level + 1);
964 setenv(MAKE_LEVEL, tmp, 1);
965 #ifdef MAKE_LEVEL_SAFE
966 setenv(MAKE_LEVEL_SAFE, tmp, 1);
972 if (expanded_name != NULL)
979 *-----------------------------------------------------------------------
981 * The variable of the given name has the given value appended to it in
985 * name name of variable to modify
986 * val String to append to it
987 * ctxt Context in which this should occur
993 * If the variable doesn't exist, it is created. Else the strings
994 * are concatenated (with a space in between).
997 * Only if the variable is being sought in the global context is the
998 * environment searched.
999 * XXX: Knows its calling circumstances in that if called with ctxt
1000 * an actual target, it will only search that context since only
1001 * a local variable could be being appended to. This is actually
1002 * a big win and must be tolerated.
1003 *-----------------------------------------------------------------------
1006 Var_Append(const char *name, const char *val, GNode *ctxt)
1010 char *expanded_name = NULL;
1012 if (strchr(name, '$') != NULL) {
1013 expanded_name = Var_Subst(NULL, name, ctxt, 0);
1014 if (expanded_name[0] == 0) {
1016 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
1017 "name expands to empty string - ignored\n",
1020 free(expanded_name);
1023 name = expanded_name;
1026 v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
1029 VarAdd(name, val, ctxt);
1031 Buf_AddByte(&v->val, ' ');
1032 Buf_AddBytes(&v->val, strlen(val), val);
1035 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
1036 Buf_GetAll(&v->val, NULL));
1039 if (v->flags & VAR_FROM_ENV) {
1041 * If the original variable came from the environment, we
1042 * have to install it in the global context (we could place
1043 * it in the environment, but then we should provide a way to
1044 * export other variables...)
1046 v->flags &= ~VAR_FROM_ENV;
1047 h = Hash_CreateEntry(&ctxt->context, name, NULL);
1048 Hash_SetValue(h, v);
1051 if (expanded_name != NULL)
1052 free(expanded_name);
1056 *-----------------------------------------------------------------------
1058 * See if the given variable exists.
1061 * name Variable to find
1062 * ctxt Context in which to start search
1065 * TRUE if it does, FALSE if it doesn't
1070 *-----------------------------------------------------------------------
1073 Var_Exists(const char *name, GNode *ctxt)
1078 if ((cp = strchr(name, '$')) != NULL) {
1079 cp = Var_Subst(NULL, name, ctxt, FALSE);
1081 v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
1088 (void)VarFreeEnv(v, TRUE);
1094 *-----------------------------------------------------------------------
1096 * Return the value of the named variable in the given context
1100 * ctxt context in which to search for it
1103 * The value if the variable exists, NULL if it doesn't
1107 *-----------------------------------------------------------------------
1110 Var_Value(const char *name, GNode *ctxt, char **frp)
1114 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1117 char *p = (Buf_GetAll(&v->val, NULL));
1118 if (VarFreeEnv(v, FALSE))
1127 *-----------------------------------------------------------------------
1129 * Remove the tail of the given word and place the result in the given
1134 * addSpace True if need to add a space to the buffer
1135 * before sticking in the head
1136 * buf Buffer in which to store it
1139 * TRUE if characters were added to the buffer (a space needs to be
1140 * added to the buffer before the next word).
1143 * The trimmed word is added to the buffer.
1145 *-----------------------------------------------------------------------
1148 VarHead(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1149 char *word, Boolean addSpace, Buffer *buf,
1154 slash = strrchr(word, '/');
1155 if (slash != NULL) {
1156 if (addSpace && vpstate->varSpace) {
1157 Buf_AddByte(buf, vpstate->varSpace);
1160 Buf_AddBytes(buf, strlen(word), word);
1165 * If no directory part, give . (q.v. the POSIX standard)
1167 if (addSpace && vpstate->varSpace)
1168 Buf_AddByte(buf, vpstate->varSpace);
1169 Buf_AddByte(buf, '.');
1171 return(dummy ? TRUE : TRUE);
1175 *-----------------------------------------------------------------------
1177 * Remove the head of the given word and place the result in the given
1182 * addSpace True if need to add a space to the buffer
1183 * before adding the tail
1184 * buf Buffer in which to store it
1187 * TRUE if characters were added to the buffer (a space needs to be
1188 * added to the buffer before the next word).
1191 * The trimmed word is added to the buffer.
1193 *-----------------------------------------------------------------------
1196 VarTail(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1197 char *word, Boolean addSpace, Buffer *buf,
1202 if (addSpace && vpstate->varSpace) {
1203 Buf_AddByte(buf, vpstate->varSpace);
1206 slash = strrchr(word, '/');
1207 if (slash != NULL) {
1209 Buf_AddBytes(buf, strlen(slash), slash);
1212 Buf_AddBytes(buf, strlen(word), word);
1214 return (dummy ? TRUE : TRUE);
1218 *-----------------------------------------------------------------------
1220 * Place the suffix of the given word in the given buffer.
1224 * addSpace TRUE if need to add a space before placing the
1225 * suffix in the buffer
1226 * buf Buffer in which to store it
1229 * TRUE if characters were added to the buffer (a space needs to be
1230 * added to the buffer before the next word).
1233 * The suffix from the word is placed in the buffer.
1235 *-----------------------------------------------------------------------
1238 VarSuffix(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1239 char *word, Boolean addSpace, Buffer *buf,
1244 dot = strrchr(word, '.');
1246 if (addSpace && vpstate->varSpace) {
1247 Buf_AddByte(buf, vpstate->varSpace);
1250 Buf_AddBytes(buf, strlen(dot), dot);
1254 return (dummy ? addSpace : addSpace);
1258 *-----------------------------------------------------------------------
1260 * Remove the suffix of the given word and place the result in the
1265 * addSpace TRUE if need to add a space to the buffer
1266 * before placing the root in it
1267 * buf Buffer in which to store it
1270 * TRUE if characters were added to the buffer (a space needs to be
1271 * added to the buffer before the next word).
1274 * The trimmed word is added to the buffer.
1276 *-----------------------------------------------------------------------
1279 VarRoot(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1280 char *word, Boolean addSpace, Buffer *buf,
1285 if (addSpace && vpstate->varSpace) {
1286 Buf_AddByte(buf, vpstate->varSpace);
1289 dot = strrchr(word, '.');
1292 Buf_AddBytes(buf, strlen(word), word);
1295 Buf_AddBytes(buf, strlen(word), word);
1297 return (dummy ? TRUE : TRUE);
1301 *-----------------------------------------------------------------------
1303 * Place the word in the buffer if it matches the given pattern.
1304 * Callback function for VarModify to implement the :M modifier.
1307 * word Word to examine
1308 * addSpace TRUE if need to add a space to the buffer
1309 * before adding the word, if it matches
1310 * buf Buffer in which to store it
1311 * pattern Pattern the word must match
1314 * TRUE if a space should be placed in the buffer before the next
1318 * The word may be copied to the buffer.
1320 *-----------------------------------------------------------------------
1323 VarMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1324 char *word, Boolean addSpace, Buffer *buf,
1328 fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
1329 if (Str_Match(word, (char *)pattern)) {
1330 if (addSpace && vpstate->varSpace) {
1331 Buf_AddByte(buf, vpstate->varSpace);
1334 Buf_AddBytes(buf, strlen(word), word);
1341 *-----------------------------------------------------------------------
1343 * Place the word in the buffer if it matches the given pattern.
1344 * Callback function for VarModify to implement the System V %
1348 * word Word to examine
1349 * addSpace TRUE if need to add a space to the buffer
1350 * before adding the word, if it matches
1351 * buf Buffer in which to store it
1352 * patp Pattern the word must match
1355 * TRUE if a space should be placed in the buffer before the next
1359 * The word may be copied to the buffer.
1361 *-----------------------------------------------------------------------
1364 VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
1365 char *word, Boolean addSpace, Buffer *buf,
1370 VarPattern *pat = (VarPattern *)patp;
1373 if (addSpace && vpstate->varSpace)
1374 Buf_AddByte(buf, vpstate->varSpace);
1378 if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
1379 varexp = Var_Subst(NULL, pat->rhs, ctx, 0);
1380 Str_SYSVSubst(buf, varexp, ptr, len);
1383 Buf_AddBytes(buf, strlen(word), word);
1392 *-----------------------------------------------------------------------
1394 * Place the word in the buffer if it doesn't match the given pattern.
1395 * Callback function for VarModify to implement the :N modifier.
1398 * word Word to examine
1399 * addSpace TRUE if need to add a space to the buffer
1400 * before adding the word, if it matches
1401 * buf Buffer in which to store it
1402 * pattern Pattern the word must match
1405 * TRUE if a space should be placed in the buffer before the next
1409 * The word may be copied to the buffer.
1411 *-----------------------------------------------------------------------
1414 VarNoMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1415 char *word, Boolean addSpace, Buffer *buf,
1418 if (!Str_Match(word, (char *)pattern)) {
1419 if (addSpace && vpstate->varSpace) {
1420 Buf_AddByte(buf, vpstate->varSpace);
1423 Buf_AddBytes(buf, strlen(word), word);
1430 *-----------------------------------------------------------------------
1432 * Perform a string-substitution on the given word, placing the
1433 * result in the passed buffer.
1436 * word Word to modify
1437 * addSpace True if space should be added before
1439 * buf Buffer for result
1440 * patternp Pattern for substitution
1443 * TRUE if a space is needed before more characters are added.
1448 *-----------------------------------------------------------------------
1451 VarSubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1452 char *word, Boolean addSpace, Buffer *buf,
1455 int wordLen; /* Length of word */
1456 char *cp; /* General pointer */
1457 VarPattern *pattern = (VarPattern *)patternp;
1459 wordLen = strlen(word);
1460 if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
1461 (VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1463 * Still substituting -- break it down into simple anchored cases
1464 * and if none of them fits, perform the general substitution case.
1466 if ((pattern->flags & VAR_MATCH_START) &&
1467 (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
1469 * Anchored at start and beginning of word matches pattern
1471 if ((pattern->flags & VAR_MATCH_END) &&
1472 (wordLen == pattern->leftLen)) {
1474 * Also anchored at end and matches to the end (word
1475 * is same length as pattern) add space and rhs only
1476 * if rhs is non-null.
1478 if (pattern->rightLen != 0) {
1479 if (addSpace && vpstate->varSpace) {
1480 Buf_AddByte(buf, vpstate->varSpace);
1483 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1485 pattern->flags |= VAR_SUB_MATCHED;
1486 } else if (pattern->flags & VAR_MATCH_END) {
1488 * Doesn't match to end -- copy word wholesale
1493 * Matches at start but need to copy in trailing characters
1495 if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1496 if (addSpace && vpstate->varSpace) {
1497 Buf_AddByte(buf, vpstate->varSpace);
1501 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1502 Buf_AddBytes(buf, wordLen - pattern->leftLen,
1503 (word + pattern->leftLen));
1504 pattern->flags |= VAR_SUB_MATCHED;
1506 } else if (pattern->flags & VAR_MATCH_START) {
1508 * Had to match at start of word and didn't -- copy whole word.
1511 } else if (pattern->flags & VAR_MATCH_END) {
1513 * Anchored at end, Find only place match could occur (leftLen
1514 * characters from the end of the word) and see if it does. Note
1515 * that because the $ will be left at the end of the lhs, we have
1518 cp = word + (wordLen - pattern->leftLen);
1520 (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
1522 * Match found. If we will place characters in the buffer,
1523 * add a space before hand as indicated by addSpace, then
1524 * stuff in the initial, unmatched part of the word followed
1525 * by the right-hand-side.
1527 if (((cp - word) + pattern->rightLen) != 0) {
1528 if (addSpace && vpstate->varSpace) {
1529 Buf_AddByte(buf, vpstate->varSpace);
1533 Buf_AddBytes(buf, cp - word, word);
1534 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1535 pattern->flags |= VAR_SUB_MATCHED;
1538 * Had to match at end and didn't. Copy entire word.
1544 * Pattern is unanchored: search for the pattern in the word using
1545 * String_FindSubstring, copying unmatched portions and the
1546 * right-hand-side for each match found, handling non-global
1547 * substitutions correctly, etc. When the loop is done, any
1548 * remaining part of the word (word and wordLen are adjusted
1549 * accordingly through the loop) is copied straight into the
1551 * addSpace is set FALSE as soon as a space is added to the
1558 origSize = Buf_Size(buf);
1560 cp = Str_FindSubstring(word, pattern->lhs);
1562 if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1563 Buf_AddByte(buf, vpstate->varSpace);
1566 Buf_AddBytes(buf, cp-word, word);
1567 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1568 wordLen -= (cp - word) + pattern->leftLen;
1569 word = cp + pattern->leftLen;
1573 if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
1576 pattern->flags |= VAR_SUB_MATCHED;
1582 if (addSpace && vpstate->varSpace) {
1583 Buf_AddByte(buf, vpstate->varSpace);
1585 Buf_AddBytes(buf, wordLen, word);
1588 * If added characters to the buffer, need to add a space
1589 * before we add any more. If we didn't add any, just return
1590 * the previous value of addSpace.
1592 return ((Buf_Size(buf) != origSize) || addSpace);
1597 if (addSpace && vpstate->varSpace) {
1598 Buf_AddByte(buf, vpstate->varSpace);
1600 Buf_AddBytes(buf, wordLen, word);
1606 *-----------------------------------------------------------------------
1608 * Print the error caused by a regcomp or regexec call.
1614 * An error gets printed.
1616 *-----------------------------------------------------------------------
1619 VarREError(int errnum, regex_t *pat, const char *str)
1624 errlen = regerror(errnum, pat, 0, 0);
1625 errbuf = bmake_malloc(errlen);
1626 regerror(errnum, pat, errbuf, errlen);
1627 Error("%s: %s", str, errbuf);
1633 *-----------------------------------------------------------------------
1634 * VarRESubstitute --
1635 * Perform a regex substitution on the given word, placing the
1636 * result in the passed buffer.
1639 * TRUE if a space is needed before more characters are added.
1644 *-----------------------------------------------------------------------
1647 VarRESubstitute(GNode *ctx MAKE_ATTR_UNUSED,
1648 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1649 char *word, Boolean addSpace, Buffer *buf,
1659 #define MAYBE_ADD_SPACE() \
1660 if (addSpace && !added) \
1661 Buf_AddByte(buf, ' '); \
1668 if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1669 (VAR_SUB_ONE|VAR_SUB_MATCHED))
1673 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1678 pat->flags |= VAR_SUB_MATCHED;
1679 if (pat->matches[0].rm_so > 0) {
1681 Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1684 for (rp = pat->replace; *rp; rp++) {
1685 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1687 Buf_AddByte(buf,rp[1]);
1690 else if ((*rp == '&') ||
1691 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1709 if (n > pat->nsub) {
1710 Error("No subexpression %s", &errstr[0]);
1713 } else if ((pat->matches[n].rm_so == -1) &&
1714 (pat->matches[n].rm_eo == -1)) {
1715 Error("No match for subexpression %s", &errstr[0]);
1719 subbuf = wp + pat->matches[n].rm_so;
1720 sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1725 Buf_AddBytes(buf, sublen, subbuf);
1729 Buf_AddByte(buf, *rp);
1732 wp += pat->matches[0].rm_eo;
1733 if (pat->flags & VAR_SUB_GLOBAL) {
1734 flags |= REG_NOTBOL;
1735 if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1737 Buf_AddByte(buf, *wp);
1746 Buf_AddBytes(buf, strlen(wp), wp);
1750 VarREError(xrv, &pat->re, "Unexpected regex error");
1755 Buf_AddBytes(buf,strlen(wp),wp);
1759 return(addSpace||added);
1766 *-----------------------------------------------------------------------
1768 * Implements the :@<temp>@<string>@ modifier of ODE make.
1769 * We set the temp variable named in pattern.lhs to word and expand
1770 * pattern.rhs storing the result in the passed buffer.
1773 * word Word to modify
1774 * addSpace True if space should be added before
1776 * buf Buffer for result
1777 * pattern Datafor substitution
1780 * TRUE if a space is needed before more characters are added.
1785 *-----------------------------------------------------------------------
1788 VarLoopExpand(GNode *ctx MAKE_ATTR_UNUSED,
1789 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1790 char *word, Boolean addSpace, Buffer *buf,
1793 VarLoop_t *loop = (VarLoop_t *)loopp;
1797 if (word && *word) {
1798 Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
1799 s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum);
1800 if (s != NULL && *s != '\0') {
1801 if (addSpace && *s != '\n')
1802 Buf_AddByte(buf, ' ');
1803 Buf_AddBytes(buf, (slen = strlen(s)), s);
1804 addSpace = (slen > 0 && s[slen - 1] != '\n');
1813 *-----------------------------------------------------------------------
1815 * Implements the :[start..end] modifier.
1816 * This is a special case of VarModify since we want to be able
1817 * to scan the list backwards if start > end.
1820 * str String whose words should be trimmed
1821 * seldata words to select
1824 * A string of all the words selected.
1829 *-----------------------------------------------------------------------
1832 VarSelectWords(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1833 const char *str, VarSelectWords_t *seldata)
1835 Buffer buf; /* Buffer for the new string */
1836 Boolean addSpace; /* TRUE if need to add a space to the
1837 * buffer before adding the trimmed
1839 char **av; /* word list */
1840 char *as; /* word list memory */
1842 int start, end, step;
1847 if (vpstate->oneBigWord) {
1848 /* fake what brk_string() would do if there were only one word */
1850 av = bmake_malloc((ac + 1) * sizeof(char *));
1851 as = bmake_strdup(str);
1855 av = brk_string(str, &ac, FALSE, &as);
1859 * Now sanitize seldata.
1860 * If seldata->start or seldata->end are negative, convert them to
1861 * the positive equivalents (-1 gets converted to argc, -2 gets
1862 * converted to (argc-1), etc.).
1864 if (seldata->start < 0)
1865 seldata->start = ac + seldata->start + 1;
1866 if (seldata->end < 0)
1867 seldata->end = ac + seldata->end + 1;
1870 * We avoid scanning more of the list than we need to.
1872 if (seldata->start > seldata->end) {
1873 start = MIN(ac, seldata->start) - 1;
1874 end = MAX(0, seldata->end - 1);
1877 start = MAX(0, seldata->start - 1);
1878 end = MIN(ac, seldata->end);
1883 (step < 0 && i >= end) || (step > 0 && i < end);
1885 if (av[i] && *av[i]) {
1886 if (addSpace && vpstate->varSpace) {
1887 Buf_AddByte(&buf, vpstate->varSpace);
1889 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
1897 return Buf_Destroy(&buf, FALSE);
1903 * Replace each word with the result of realpath()
1907 VarRealpath(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1908 char *word, Boolean addSpace, Buffer *buf,
1909 void *patternp MAKE_ATTR_UNUSED)
1912 char rbuf[MAXPATHLEN];
1915 if (addSpace && vpstate->varSpace) {
1916 Buf_AddByte(buf, vpstate->varSpace);
1919 rp = realpath(word, rbuf);
1920 if (rp && *rp == '/' && stat(rp, &st) == 0)
1923 Buf_AddBytes(buf, strlen(word), word);
1928 *-----------------------------------------------------------------------
1930 * Modify each of the words of the passed string using the given
1931 * function. Used to implement all modifiers.
1934 * str String whose words should be trimmed
1935 * modProc Function to use to modify them
1936 * datum Datum to pass it
1939 * A string of all the words modified appropriately.
1944 *-----------------------------------------------------------------------
1947 VarModify(GNode *ctx, Var_Parse_State *vpstate,
1949 Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
1950 Boolean, Buffer *, void *),
1953 Buffer buf; /* Buffer for the new string */
1954 Boolean addSpace; /* TRUE if need to add a space to the
1955 * buffer before adding the trimmed
1957 char **av; /* word list */
1958 char *as; /* word list memory */
1964 if (vpstate->oneBigWord) {
1965 /* fake what brk_string() would do if there were only one word */
1967 av = bmake_malloc((ac + 1) * sizeof(char *));
1968 as = bmake_strdup(str);
1972 av = brk_string(str, &ac, FALSE, &as);
1975 for (i = 0; i < ac; i++) {
1976 addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum);
1982 return Buf_Destroy(&buf, FALSE);
1987 VarWordCompare(const void *a, const void *b)
1989 int r = strcmp(*(const char * const *)a, *(const char * const *)b);
1994 *-----------------------------------------------------------------------
1996 * Order the words in the string.
1999 * str String whose words should be sorted.
2000 * otype How to order: s - sort, x - random.
2003 * A string containing the words ordered.
2008 *-----------------------------------------------------------------------
2011 VarOrder(const char *str, const char otype)
2013 Buffer buf; /* Buffer for the new string */
2014 char **av; /* word list [first word does not count] */
2015 char *as; /* word list memory */
2020 av = brk_string(str, &ac, FALSE, &as);
2024 case 's': /* sort alphabetically */
2025 qsort(av, ac, sizeof(char *), VarWordCompare);
2027 case 'x': /* randomize */
2033 * We will use [ac..2] range for mod factors. This will produce
2034 * random numbers in [(ac-1)..0] interval, and minimal
2035 * reasonable value for mod factor is 2 (the mod 1 will produce
2036 * 0 with probability 1).
2038 for (i = ac-1; i > 0; i--) {
2039 rndidx = random() % (i + 1);
2047 } /* end of switch */
2049 for (i = 0; i < ac; i++) {
2050 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2052 Buf_AddByte(&buf, ' ');
2058 return Buf_Destroy(&buf, FALSE);
2063 *-----------------------------------------------------------------------
2065 * Remove adjacent duplicate words.
2068 * str String whose words should be sorted
2071 * A string containing the resulting words.
2076 *-----------------------------------------------------------------------
2079 VarUniq(const char *str)
2081 Buffer buf; /* Buffer for new string */
2082 char **av; /* List of words to affect */
2083 char *as; /* Word list memory */
2087 av = brk_string(str, &ac, FALSE, &as);
2090 for (j = 0, i = 1; i < ac; i++)
2091 if (strcmp(av[i], av[j]) != 0 && (++j != i))
2096 for (i = 0; i < ac; i++) {
2097 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2099 Buf_AddByte(&buf, ' ');
2105 return Buf_Destroy(&buf, FALSE);
2110 *-----------------------------------------------------------------------
2112 * Pass through the tstr looking for 1) escaped delimiters,
2113 * '$'s and backslashes (place the escaped character in
2114 * uninterpreted) and 2) unescaped $'s that aren't before
2115 * the delimiter (expand the variable substitution unless flags
2116 * has VAR_NOSUBST set).
2117 * Return the expanded string or NULL if the delimiter was missing
2118 * If pattern is specified, handle escaped ampersands, and replace
2119 * unescaped ampersands with the lhs of the pattern.
2122 * A string of all the words modified appropriately.
2123 * If length is specified, return the string length of the buffer
2124 * If flags is specified and the last character of the pattern is a
2125 * $ set the VAR_MATCH_END bit of flags.
2129 *-----------------------------------------------------------------------
2132 VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
2133 int errnum, const char **tstr, int delim, int *flags,
2134 int *length, VarPattern *pattern)
2145 #define IS_A_MATCH(cp, delim) \
2146 ((cp[0] == '\\') && ((cp[1] == delim) || \
2147 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
2150 * Skim through until the matching delimiter is found;
2151 * pick up variable substitutions on the way. Also allow
2152 * backslashes to quote the delimiter, $, and \, but don't
2153 * touch other backslashes.
2155 for (cp = *tstr; *cp && (*cp != delim); cp++) {
2156 if (IS_A_MATCH(cp, delim)) {
2157 Buf_AddByte(&buf, cp[1]);
2159 } else if (*cp == '$') {
2160 if (cp[1] == delim) {
2162 Buf_AddByte(&buf, *cp);
2165 * Unescaped $ at end of pattern => anchor
2168 *flags |= VAR_MATCH_END;
2170 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
2176 * If unescaped dollar sign not before the
2177 * delimiter, assume it's a variable
2178 * substitution and recurse.
2180 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2181 Buf_AddBytes(&buf, strlen(cp2), cp2);
2186 const char *cp2 = &cp[1];
2188 if (*cp2 == PROPEN || *cp2 == BROPEN) {
2190 * Find the end of this variable reference
2191 * and suck it in without further ado.
2192 * It will be interperated later.
2195 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
2198 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
2199 if (cp2[-1] != '\\') {
2206 Buf_AddBytes(&buf, cp2 - cp, cp);
2209 Buf_AddByte(&buf, *cp);
2213 else if (pattern && *cp == '&')
2214 Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
2216 Buf_AddByte(&buf, *cp);
2226 *length = Buf_Size(&buf);
2227 rstr = Buf_Destroy(&buf, FALSE);
2229 fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
2234 *-----------------------------------------------------------------------
2236 * Quote shell meta-characters in the string
2244 *-----------------------------------------------------------------------
2251 /* This should cover most shells :-( */
2252 static const char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
2253 const char *newline;
2256 if ((newline = Shell_GetNewline()) == NULL)
2258 nlen = strlen(newline);
2261 while (*str != '\0') {
2262 if ((len = strcspn(str, meta)) != 0) {
2263 Buf_AddBytes(&buf, len, str);
2265 } else if (*str == '\n') {
2266 Buf_AddBytes(&buf, nlen, newline);
2269 Buf_AddByte(&buf, '\\');
2270 Buf_AddByte(&buf, *str);
2274 str = Buf_Destroy(&buf, FALSE);
2276 fprintf(debug_file, "QuoteMeta: [%s]\n", str);
2281 *-----------------------------------------------------------------------
2283 * Hash the string using the MurmurHash3 algorithm.
2284 * Output is computed using 32bit Little Endian arithmetic.
2287 * str String to modify
2290 * Hash value of str, encoded as 8 hex digits.
2295 *-----------------------------------------------------------------------
2300 static const char hexdigits[16] = "0123456789abcdef";
2303 unsigned char *ustr = (unsigned char *)str;
2304 uint32_t h, k, c1, c2;
2313 for (len = len2; len; ) {
2317 k = (ustr[3] << 24) | (ustr[2] << 16) | (ustr[1] << 8) | ustr[0];
2322 k |= (ustr[2] << 16);
2324 k |= (ustr[1] << 8);
2329 c1 = c1 * 5 + 0x7b7d159cU;
2330 c2 = c2 * 5 + 0x6bce6396U;
2332 k = (k << 11) ^ (k >> 21);
2334 h = (h << 13) ^ (h >> 19);
2335 h = h * 5 + 0x52dce729U;
2345 for (len = 0; len < 8; ++len) {
2346 Buf_AddByte(&buf, hexdigits[h & 15]);
2350 return Buf_Destroy(&buf, FALSE);
2354 *-----------------------------------------------------------------------
2356 * Change the string to all uppercase or all lowercase
2359 * str String to modify
2360 * upper TRUE -> uppercase, else lowercase
2363 * The string with case changed
2368 *-----------------------------------------------------------------------
2371 VarChangeCase(char *str, int upper)
2374 int (*modProc)(int);
2376 modProc = (upper ? toupper : tolower);
2378 for (; *str ; str++) {
2379 Buf_AddByte(&buf, modProc(*str));
2381 return Buf_Destroy(&buf, FALSE);
2385 VarStrftime(const char *fmt, int zulu)
2393 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2395 buf[sizeof(buf) - 1] = '\0';
2396 return bmake_strdup(buf);
2400 * Now we need to apply any modifiers the user wants applied.
2402 * :M<pattern> words which match the given <pattern>.
2403 * <pattern> is of the standard file
2405 * :N<pattern> words which do not match the given <pattern>.
2406 * :S<d><pat1><d><pat2><d>[1gW]
2407 * Substitute <pat2> for <pat1> in the value
2408 * :C<d><pat1><d><pat2><d>[1gW]
2409 * Substitute <pat2> for regex <pat1> in the value
2410 * :H Substitute the head of each word
2411 * :T Substitute the tail of each word
2412 * :E Substitute the extension (minus '.') of
2414 * :R Substitute the root of each word
2415 * (pathname minus the suffix).
2416 * :O ("Order") Alphabeticaly sort words in variable.
2417 * :Ox ("intermiX") Randomize words in variable.
2418 * :u ("uniq") Remove adjacent duplicate words.
2419 * :tu Converts the variable contents to uppercase.
2420 * :tl Converts the variable contents to lowercase.
2421 * :ts[c] Sets varSpace - the char used to
2422 * separate words to 'c'. If 'c' is
2423 * omitted then no separation is used.
2424 * :tW Treat the variable contents as a single
2425 * word, even if it contains spaces.
2426 * (Mnemonic: one big 'W'ord.)
2427 * :tw Treat the variable contents as multiple
2428 * space-separated words.
2429 * (Mnemonic: many small 'w'ords.)
2430 * :[index] Select a single word from the value.
2431 * :[start..end] Select multiple words from the value.
2432 * :[*] or :[0] Select the entire value, as a single
2433 * word. Equivalent to :tW.
2434 * :[@] Select the entire value, as multiple
2435 * words. Undoes the effect of :[*].
2436 * Equivalent to :tw.
2437 * :[#] Returns the number of words in the value.
2439 * :?<true-value>:<false-value>
2440 * If the variable evaluates to true, return
2441 * true value, else return the second value.
2442 * :lhs=rhs Like :S, but the rhs goes to the end of
2444 * :sh Treat the current value as a command
2445 * to be run, new value is its output.
2446 * The following added so we can handle ODE makefiles.
2447 * :@<tmpvar>@<newval>@
2448 * Assign a temporary local variable <tmpvar>
2449 * to the current value of each word in turn
2450 * and replace each word with the result of
2451 * evaluating <newval>
2452 * :D<newval> Use <newval> as value if variable defined
2453 * :U<newval> Use <newval> as value if variable undefined
2454 * :L Use the name of the variable as the value.
2455 * :P Use the path of the node that has the same
2456 * name as the variable as the value. This
2457 * basically includes an implied :L so that
2458 * the common method of refering to the path
2459 * of your dependent 'x' in a rule is to use
2460 * the form '${x:P}'.
2461 * :!<cmd>! Run cmd much the same as :sh run's the
2462 * current value of the variable.
2463 * The ::= modifiers, actually assign a value to the variable.
2464 * Their main purpose is in supporting modifiers of .for loop
2465 * iterators and other obscure uses. They always expand to
2466 * nothing. In a target rule that would otherwise expand to an
2467 * empty line they can be preceded with @: to keep make happy.
2471 * .for i in ${.TARGET} ${.TARGET:R}.gz
2476 * ::=<str> Assigns <str> as the new value of variable.
2477 * ::?=<str> Assigns <str> as value of variable if
2478 * it was not already set.
2479 * ::+=<str> Appends <str> to variable.
2480 * ::!=<cmd> Assigns output of <cmd> as the new value of
2484 /* we now have some modifiers with long names */
2485 #define STRMOD_MATCH(s, want, n) \
2486 (strncmp(s, want, n) == 0 && (s[n] == endc || s[n] == ':'))
2489 ApplyModifiers(char *nstr, const char *tstr,
2490 int startc, int endc,
2491 Var *v, GNode *ctxt, Boolean errnum,
2492 int *lengthPtr, void **freePtr)
2495 const char *cp; /* Secondary pointer into str (place marker
2497 char *newStr; /* New value to return */
2498 char termc; /* Character which terminated scan */
2499 int cnt; /* Used to count brace pairs when variable in
2500 * in parens or braces */
2502 int modifier; /* that we are processing */
2503 Var_Parse_State parsestate; /* Flags passed to helper functions */
2506 parsestate.oneBigWord = FALSE;
2507 parsestate.varSpace = ' '; /* word separator */
2511 while (*tstr && *tstr != endc) {
2515 * We may have some complex modifiers in a variable.
2522 rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
2525 * If we have not parsed up to endc or ':',
2526 * we are not interested.
2528 if (rval != NULL && *rval &&
2529 (c = tstr[rlen]) != '\0' &&
2538 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
2539 rval, rlen, tstr, rlen, tstr + rlen);
2544 if (rval != NULL && *rval) {
2547 nstr = ApplyModifiers(nstr, rval,
2549 v, ctxt, errnum, &used, freePtr);
2550 if (nstr == var_Error
2551 || (nstr == varNoError && errnum == 0)
2552 || strlen(rval) != (size_t) used) {
2555 goto out; /* error already reported */
2562 else if (!*tstr && endc) {
2563 Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name);
2570 fprintf(debug_file, "Applying :%c to \"%s\"\n", *tstr, nstr);
2573 switch ((modifier = *tstr)) {
2576 if (tstr[1] == '=' ||
2578 (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
2580 * "::=", "::!=", "::+=", or "::?="
2582 GNode *v_ctxt; /* context where v belongs */
2588 if (v->name[0] == 0)
2594 if (v->flags & VAR_JUNK) {
2596 * We need to bmake_strdup() it incase
2597 * VarGetPattern() recurses.
2600 v->name = bmake_strdup(v->name);
2601 } else if (ctxt != VAR_GLOBAL) {
2602 Var *gv = VarFind(v->name, ctxt, 0);
2604 v_ctxt = VAR_GLOBAL;
2606 VarFreeEnv(gv, TRUE);
2609 switch ((how = *tstr)) {
2619 delim = startc == PROPEN ? PRCLOSE : BRCLOSE;
2622 pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2626 if (v->flags & VAR_JUNK) {
2627 /* restore original name */
2631 if (pattern.rhs == NULL)
2639 Var_Append(v->name, pattern.rhs, v_ctxt);
2642 newStr = Cmd_Exec(pattern.rhs, &emsg);
2646 Var_Set(v->name, newStr, v_ctxt, 0);
2651 if ((v->flags & VAR_JUNK) == 0)
2655 Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2658 free(UNCONST(pattern.rhs));
2662 goto default_case; /* "::<unrecognised>" */
2667 int flags = VAR_NOSUBST;
2671 if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum,
2673 &flags, &loop.tvarLen,
2677 if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum,
2679 &flags, &loop.strLen,
2686 loop.errnum = errnum;
2688 newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
2697 Buffer buf; /* Buffer for patterns */
2698 int wantit; /* want data in buffer */
2701 * Pass through tstr looking for 1) escaped delimiters,
2702 * '$'s and backslashes (place the escaped character in
2703 * uninterpreted) and 2) unescaped $'s that aren't before
2704 * the delimiter (expand the variable substitution).
2705 * The result is left in the Buffer buf.
2709 *cp != endc && *cp != ':' && *cp != '\0';
2711 if ((*cp == '\\') &&
2717 Buf_AddByte(&buf, cp[1]);
2719 } else if (*cp == '$') {
2721 * If unescaped dollar sign, assume it's a
2722 * variable substitution and recurse.
2728 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2729 Buf_AddBytes(&buf, strlen(cp2), cp2);
2734 Buf_AddByte(&buf, *cp);
2741 wantit = ((v->flags & VAR_JUNK) != 0);
2743 wantit = ((v->flags & VAR_JUNK) == 0);
2744 if ((v->flags & VAR_JUNK) != 0)
2745 v->flags |= VAR_KEEP;
2747 newStr = Buf_Destroy(&buf, FALSE);
2750 Buf_Destroy(&buf, TRUE);
2756 if ((v->flags & VAR_JUNK) != 0)
2757 v->flags |= VAR_KEEP;
2758 newStr = bmake_strdup(v->name);
2767 if ((v->flags & VAR_JUNK) != 0)
2768 v->flags |= VAR_KEEP;
2769 gn = Targ_FindNode(v->name, TARG_NOCREATE);
2770 if (gn == NULL || gn->type & OP_NOPATH) {
2772 } else if (gn->path) {
2773 newStr = bmake_strdup(gn->path);
2775 newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
2778 newStr = bmake_strdup(v->name);
2793 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2795 NULL, &pattern.rightLen,
2798 newStr = Cmd_Exec(pattern.rhs, &emsg);
2799 free(UNCONST(pattern.rhs));
2804 if (v->flags & VAR_JUNK) {
2805 v->flags |= VAR_KEEP;
2812 * Look for the closing ']', recursively
2813 * expanding any embedded variables.
2815 * estr is a pointer to the expanded result,
2816 * which we must free().
2820 cp = tstr+1; /* point to char after '[' */
2821 delim = ']'; /* look for closing ']' */
2822 estr = VarGetPattern(ctxt, &parsestate,
2826 goto cleanup; /* report missing ']' */
2827 /* now cp points just after the closing ']' */
2829 if (cp[0] != ':' && cp[0] != endc) {
2830 /* Found junk after ']' */
2834 if (estr[0] == '\0') {
2835 /* Found empty square brackets in ":[]". */
2838 } else if (estr[0] == '#' && estr[1] == '\0') {
2842 * We will need enough space for the decimal
2843 * representation of an int. We calculate the
2844 * space needed for the octal representation,
2845 * and add enough slop to cope with a '-' sign
2846 * (which should never be needed) and a '\0'
2847 * string terminator.
2850 (sizeof(int) * CHAR_BIT + 2) / 3 + 2;
2852 newStr = bmake_malloc(newStrSize);
2853 if (parsestate.oneBigWord) {
2854 strncpy(newStr, "1", newStrSize);
2856 /* XXX: brk_string() is a rather expensive
2857 * way of counting words. */
2862 av = brk_string(nstr, &ac, FALSE, &as);
2863 snprintf(newStr, newStrSize, "%d", ac);
2870 } else if (estr[0] == '*' && estr[1] == '\0') {
2872 parsestate.oneBigWord = TRUE;
2877 } else if (estr[0] == '@' && estr[1] == '\0') {
2879 parsestate.oneBigWord = FALSE;
2886 * We expect estr to contain a single
2887 * integer for :[N], or two integers
2888 * separated by ".." for :[start..end].
2892 VarSelectWords_t seldata = { 0, 0 };
2894 seldata.start = strtol(estr, &ep, 0);
2896 /* Found junk instead of a number */
2899 } else if (ep[0] == '\0') {
2900 /* Found only one integer in :[N] */
2901 seldata.end = seldata.start;
2902 } else if (ep[0] == '.' && ep[1] == '.' &&
2904 /* Expecting another integer after ".." */
2906 seldata.end = strtol(ep, &ep, 0);
2907 if (ep[0] != '\0') {
2908 /* Found junk after ".." */
2913 /* Found junk instead of ".." */
2918 * Now seldata is properly filled in,
2919 * but we still have to check for 0 as
2922 if (seldata.start == 0 && seldata.end == 0) {
2923 /* ":[0]" or perhaps ":[0..0]" */
2924 parsestate.oneBigWord = TRUE;
2929 } else if (seldata.start == 0 ||
2931 /* ":[0..N]" or ":[N..0]" */
2936 * Normal case: select the words
2937 * described by seldata.
2939 newStr = VarSelectWords(ctxt, &parsestate,
2949 cp = tstr + 1; /* make sure it is set */
2950 if (STRMOD_MATCH(tstr, "gmtime", 6)) {
2951 newStr = VarStrftime(nstr, 1);
2959 cp = tstr + 1; /* make sure it is set */
2960 if (STRMOD_MATCH(tstr, "hash", 4)) {
2961 newStr = VarHash(nstr);
2969 cp = tstr + 1; /* make sure it is set */
2970 if (STRMOD_MATCH(tstr, "localtime", 9)) {
2971 newStr = VarStrftime(nstr, 0);
2980 cp = tstr + 1; /* make sure it is set */
2981 if (tstr[1] != endc && tstr[1] != ':') {
2982 if (tstr[1] == 's') {
2984 * Use the char (if any) at tstr[2]
2985 * as the word separator.
2989 if (tstr[2] != endc &&
2990 (tstr[3] == endc || tstr[3] == ':')) {
2991 /* ":ts<unrecognised><endc>" or
2992 * ":ts<unrecognised>:" */
2993 parsestate.varSpace = tstr[2];
2995 } else if (tstr[2] == endc || tstr[2] == ':') {
2996 /* ":ts<endc>" or ":ts:" */
2997 parsestate.varSpace = 0; /* no separator */
2999 } else if (tstr[2] == '\\') {
3002 parsestate.varSpace = '\n';
3006 parsestate.varSpace = '\t';
3010 if (isdigit((unsigned char)tstr[3])) {
3013 parsestate.varSpace =
3014 strtoul(&tstr[3], &ep, 0);
3015 if (*ep != ':' && *ep != endc)
3020 * ":ts<backslash><unrecognised>".
3028 * Found ":ts<unrecognised><unrecognised>".
3036 * We cannot be certain that VarModify
3037 * will be used - even if there is a
3038 * subsequent modifier, so do a no-op
3039 * VarSubstitute now to for str to be
3040 * re-expanded without the spaces.
3042 pattern.flags = VAR_SUB_ONE;
3043 pattern.lhs = pattern.rhs = "\032";
3044 pattern.leftLen = pattern.rightLen = 1;
3046 newStr = VarModify(ctxt, &parsestate, nstr,
3049 } else if (tstr[2] == endc || tstr[2] == ':') {
3051 * Check for two-character options:
3054 if (tstr[1] == 'A') { /* absolute path */
3055 newStr = VarModify(ctxt, &parsestate, nstr,
3059 } else if (tstr[1] == 'u' || tstr[1] == 'l') {
3060 newStr = VarChangeCase(nstr, (tstr[1] == 'u'));
3063 } else if (tstr[1] == 'W' || tstr[1] == 'w') {
3064 parsestate.oneBigWord = (tstr[1] == 'W');
3069 /* Found ":t<unrecognised>:" or
3070 * ":t<unrecognised><endc>". */
3075 * Found ":t<unrecognised><unrecognised>".
3081 * Found ":t<endc>" or ":t:".
3091 const char *endpat; /* points just after end of pattern */
3093 Boolean copy; /* pattern should be, or has been, copied */
3101 * In the loop below, ignore ':' unless we are at
3102 * (or back to) the original brace level.
3103 * XXX This will likely not work right if $() and ${}
3107 *cp != '\0' && !(*cp == ':' && nest == 1);
3112 cp[1] == endc || cp[1] == startc)) {
3122 if (*cp == '(' || *cp == '{')
3124 if (*cp == ')' || *cp == '}') {
3134 * Need to compress the \:'s out of the pattern, so
3135 * allocate enough room to hold the uncompressed
3136 * pattern (note that cp started at tstr+1, so
3137 * cp - tstr takes the null byte into account) and
3138 * compress the pattern into the space.
3140 pattern = bmake_malloc(cp - tstr);
3141 for (cp2 = pattern, cp = tstr + 1;
3145 if ((*cp == '\\') && (cp+1 < endpat) &&
3146 (cp[1] == ':' || cp[1] == endc)) {
3155 * Either Var_Subst or VarModify will need a
3156 * nul-terminated string soon, so construct one now.
3158 pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
3162 * pattern contains embedded '$', so use Var_Subst to
3166 pattern = Var_Subst(NULL, cp2, ctxt, errnum);
3170 fprintf(debug_file, "Pattern for [%s] is [%s]\n", nstr,
3173 newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
3176 newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
3185 Var_Parse_State tmpparsestate;
3188 tmpparsestate = parsestate;
3193 * If pattern begins with '^', it is anchored to the
3194 * start of the word -- skip over it and flag pattern.
3197 pattern.flags |= VAR_MATCH_START;
3202 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3209 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3216 * Check for global substitution. If 'g' after the final
3217 * delimiter, substitution is global and is marked that
3223 pattern.flags |= VAR_SUB_GLOBAL;
3226 pattern.flags |= VAR_SUB_ONE;
3229 tmpparsestate.oneBigWord = TRUE;
3236 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3241 * Free the two strings.
3243 free(UNCONST(pattern.lhs));
3244 free(UNCONST(pattern.rhs));
3253 /* find ':', and then substitute accordingly */
3259 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3265 /* BROPEN or PROPEN */
3267 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3275 if (Cond_EvalExpression(NULL, v->name, &value, 0)
3277 Error("Bad conditional expression `%s' in %s?%s:%s",
3278 v->name, v->name, pattern.lhs, pattern.rhs);
3283 newStr = UNCONST(pattern.lhs);
3284 free(UNCONST(pattern.rhs));
3286 newStr = UNCONST(pattern.rhs);
3287 free(UNCONST(pattern.lhs));
3289 if (v->flags & VAR_JUNK) {
3290 v->flags |= VAR_KEEP;
3297 VarREPattern pattern;
3300 Var_Parse_State tmpparsestate;
3303 tmpparsestate = parsestate;
3309 if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim,
3310 NULL, NULL, NULL)) == NULL)
3313 if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
3314 errnum, &cp, delim, NULL,
3315 NULL, NULL)) == NULL){
3323 pattern.flags |= VAR_SUB_GLOBAL;
3326 pattern.flags |= VAR_SUB_ONE;
3329 tmpparsestate.oneBigWord = TRUE;
3337 error = regcomp(&pattern.re, re, REG_EXTENDED);
3340 *lengthPtr = cp - start + 1;
3341 VarREError(error, &pattern.re, "RE substitution error");
3342 free(pattern.replace);
3346 pattern.nsub = pattern.re.re_nsub + 1;
3347 if (pattern.nsub < 1)
3349 if (pattern.nsub > 10)
3351 pattern.matches = bmake_malloc(pattern.nsub *
3352 sizeof(regmatch_t));
3353 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3356 regfree(&pattern.re);
3357 free(pattern.replace);
3358 free(pattern.matches);
3364 if (tstr[1] == endc || tstr[1] == ':') {
3365 newStr = VarQuote(nstr);
3372 if (tstr[1] == endc || tstr[1] == ':') {
3373 newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
3381 if (tstr[1] == endc || tstr[1] == ':') {
3382 newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
3390 if (tstr[1] == endc || tstr[1] == ':') {
3391 newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
3399 if (tstr[1] == endc || tstr[1] == ':') {
3400 newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
3411 cp = tstr + 1; /* skip to the rest in any case */
3412 if (tstr[1] == endc || tstr[1] == ':') {
3415 } else if ( (tstr[1] == 'x') &&
3416 (tstr[2] == endc || tstr[2] == ':') ) {
3423 newStr = VarOrder(nstr, otype);
3427 if (tstr[1] == endc || tstr[1] == ':') {
3428 newStr = VarUniq(nstr);
3436 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
3438 newStr = Cmd_Exec(nstr, &emsg);
3452 * This can either be a bogus modifier or a System-V
3453 * substitution command.
3461 * First we make a pass through the string trying
3462 * to verify it is a SYSV-make-style translation:
3463 * it must be: <string1>=<string2>)
3467 while (*cp != '\0' && cnt) {
3470 /* continue looking for endc */
3472 else if (*cp == endc)
3474 else if (*cp == startc)
3479 if (*cp == endc && eqFound) {
3482 * Now we break this sucker into the lhs and
3483 * rhs. We must null terminate them of course.
3487 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
3488 errnum, &cp, delim, &pattern.flags,
3489 &pattern.leftLen, NULL)) == NULL)
3492 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
3493 errnum, &cp, delim, NULL, &pattern.rightLen,
3498 * SYSV modifications happen through the whole
3499 * string. Note the pattern is anchored at the end.
3503 if (pattern.leftLen == 0 && *nstr == '\0') {
3504 newStr = nstr; /* special case */
3506 newStr = VarModify(ctxt, &parsestate, nstr,
3510 free(UNCONST(pattern.lhs));
3511 free(UNCONST(pattern.rhs));
3515 Error("Unknown modifier '%c'", *tstr);
3517 *cp != ':' && *cp != endc && *cp != '\0';
3526 fprintf(debug_file, "Result of :%c is \"%s\"\n", modifier, newStr);
3529 if (newStr != nstr) {
3535 if (nstr != var_Error && nstr != varNoError) {
3539 if (termc == '\0' && endc != '\0') {
3540 Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier);
3541 } else if (termc == ':') {
3547 *lengthPtr = tstr - start;
3552 Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
3556 *lengthPtr = cp - start;
3558 Error("Unclosed substitution for %s (%c missing)",
3568 *-----------------------------------------------------------------------
3570 * Given the start of a variable invocation, extract the variable
3571 * name and find its value, then modify it according to the
3575 * str The string to parse
3576 * ctxt The context for the variable
3577 * errnum TRUE if undefined variables are an error
3578 * lengthPtr OUT: The length of the specification
3579 * freePtr OUT: Non-NULL if caller should free *freePtr
3582 * The (possibly-modified) value of the variable or var_Error if the
3583 * specification is invalid. The length of the specification is
3584 * placed in *lengthPtr (for invalid specifications, this is just
3586 * If *freePtr is non-NULL then it's a pointer that the caller
3587 * should pass to free() to free memory used by the result.
3592 *-----------------------------------------------------------------------
3594 /* coverity[+alloc : arg-*4] */
3596 Var_Parse(const char *str, GNode *ctxt, Boolean errnum, int *lengthPtr,
3599 const char *tstr; /* Pointer into str */
3600 Var *v; /* Variable in invocation */
3601 Boolean haveModifier;/* TRUE if have modifiers for the variable */
3602 char endc; /* Ending character when variable in parens
3604 char startc; /* Starting character when variable in parens
3606 int vlen; /* Length of variable name */
3607 const char *start; /* Points to original start of str */
3608 char *nstr; /* New string, used during expansion */
3609 Boolean dynamic; /* TRUE if the variable is local and we're
3610 * expanding it in a non-local context. This
3611 * is done to support dynamic sources. The
3612 * result is just the invocation, unaltered */
3613 Var_Parse_State parsestate; /* Flags passed to helper functions */
3619 parsestate.oneBigWord = FALSE;
3620 parsestate.varSpace = ' '; /* word separator */
3623 if (startc != PROPEN && startc != BROPEN) {
3625 * If it's not bounded by braces of some sort, life is much simpler.
3626 * We just need to check for the first character and return the
3627 * value if it exists.
3630 /* Error out some really stupid names */
3631 if (startc == '\0' || strchr(")}:$", startc)) {
3638 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3642 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
3644 * If substituting a local variable in a non-local context,
3645 * assume it's for dynamic source stuff. We have to handle
3646 * this specially and return the longhand for the variable
3647 * with the dollar sign escaped so it makes it back to the
3648 * caller. Only four of the local variables are treated
3649 * specially as they are the only four that will be set
3650 * when dynamic sources are expanded.
3654 return UNCONST("$(.TARGET)");
3656 return UNCONST("$(.ARCHIVE)");
3658 return UNCONST("$(.PREFIX)");
3660 return UNCONST("$(.MEMBER)");
3666 return (errnum ? var_Error : varNoError);
3668 haveModifier = FALSE;
3673 Buffer buf; /* Holds the variable name */
3675 endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3679 * Skip to the end character or a colon, whichever comes first.
3681 for (tstr = str + 2;
3682 *tstr != '\0' && *tstr != endc && *tstr != ':';
3686 * A variable inside a variable, expand
3691 char *rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
3693 Buf_AddBytes(&buf, strlen(rval), rval);
3700 Buf_AddByte(&buf, *tstr);
3703 haveModifier = TRUE;
3704 } else if (*tstr != '\0') {
3705 haveModifier = FALSE;
3708 * If we never did find the end character, return NULL
3709 * right now, setting the length to be the distance to
3710 * the end of the string, since that's what make does.
3712 *lengthPtr = tstr - str;
3713 Buf_Destroy(&buf, TRUE);
3716 str = Buf_GetAll(&buf, &vlen);
3719 * At this point, str points into newly allocated memory from
3720 * buf, containing only the name of the variable.
3722 * start and tstr point into the const string that was pointed
3723 * to by the original value of the str parameter. start points
3724 * to the '$' at the beginning of the string, while tstr points
3725 * to the char just after the end of the variable name -- this
3726 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3729 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3731 * Check also for bogus D and F forms of local variables since we're
3732 * in a local context and the name is the right length.
3734 if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
3735 (vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
3736 strchr("@%*!<>", str[0]) != NULL) {
3738 * Well, it's local -- go look for it.
3742 v = VarFind(name, ctxt, 0);
3746 * No need for nested expansion or anything, as we're
3747 * the only one who sets these things and we sure don't
3748 * but nested invocations in them...
3750 nstr = Buf_GetAll(&v->val, NULL);
3752 if (str[1] == 'D') {
3753 nstr = VarModify(ctxt, &parsestate, nstr, VarHead,
3756 nstr = VarModify(ctxt, &parsestate, nstr, VarTail,
3760 * Resulting string is dynamically allocated, so
3761 * tell caller to free it.
3764 *lengthPtr = tstr-start+1;
3765 Buf_Destroy(&buf, TRUE);
3766 VarFreeEnv(v, TRUE);
3773 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
3774 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3777 * If substituting a local variable in a non-local context,
3778 * assume it's for dynamic source stuff. We have to handle
3779 * this specially and return the longhand for the variable
3780 * with the dollar sign escaped so it makes it back to the
3781 * caller. Only four of the local variables are treated
3782 * specially as they are the only four that will be set
3783 * when dynamic sources are expanded.
3793 } else if ((vlen > 2) && (*str == '.') &&
3794 isupper((unsigned char) str[1]) &&
3795 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3800 if ((strncmp(str, ".TARGET", len) == 0) ||
3801 (strncmp(str, ".ARCHIVE", len) == 0) ||
3802 (strncmp(str, ".PREFIX", len) == 0) ||
3803 (strncmp(str, ".MEMBER", len) == 0))
3809 if (!haveModifier) {
3811 * No modifiers -- have specification length so we can return
3814 *lengthPtr = tstr - start + 1;
3816 char *pstr = bmake_strndup(start, *lengthPtr);
3818 Buf_Destroy(&buf, TRUE);
3821 Buf_Destroy(&buf, TRUE);
3822 return (errnum ? var_Error : varNoError);
3826 * Still need to get to the end of the variable specification,
3827 * so kludge up a Var structure for the modifications
3829 v = bmake_malloc(sizeof(Var));
3830 v->name = UNCONST(str);
3831 Buf_Init(&v->val, 1);
3832 v->flags = VAR_JUNK;
3833 Buf_Destroy(&buf, FALSE);
3836 Buf_Destroy(&buf, TRUE);
3839 if (v->flags & VAR_IN_USE) {
3840 Fatal("Variable %s is recursive.", v->name);
3843 v->flags |= VAR_IN_USE;
3846 * Before doing any modification, we have to make sure the value
3847 * has been fully expanded. If it looks like recursion might be
3848 * necessary (there's a dollar sign somewhere in the variable's value)
3849 * we just call Var_Subst to do any other substitutions that are
3850 * necessary. Note that the value returned by Var_Subst will have
3851 * been dynamically-allocated, so it will need freeing when we
3854 nstr = Buf_GetAll(&v->val, NULL);
3855 if (strchr(nstr, '$') != NULL) {
3856 nstr = Var_Subst(NULL, nstr, ctxt, errnum);
3860 v->flags &= ~VAR_IN_USE;
3862 if ((nstr != NULL) && haveModifier) {
3865 * Skip initial colon.
3869 nstr = ApplyModifiers(nstr, tstr, startc, endc,
3870 v, ctxt, errnum, &used, freePtr);
3874 *lengthPtr = tstr - start + 1;
3876 *lengthPtr = tstr - start;
3879 if (v->flags & VAR_FROM_ENV) {
3880 Boolean destroy = FALSE;
3882 if (nstr != Buf_GetAll(&v->val, NULL)) {
3886 * Returning the value unmodified, so tell the caller to free
3891 VarFreeEnv(v, destroy);
3892 } else if (v->flags & VAR_JUNK) {
3894 * Perform any free'ing needed and set *freePtr to NULL so the caller
3895 * doesn't try to free a static pointer.
3896 * If VAR_KEEP is also set then we want to keep str as is.
3898 if (!(v->flags & VAR_KEEP)) {
3904 nstr = bmake_strndup(start, *lengthPtr);
3907 nstr = errnum ? var_Error : varNoError;
3910 if (nstr != Buf_GetAll(&v->val, NULL))
3911 Buf_Destroy(&v->val, TRUE);
3919 *-----------------------------------------------------------------------
3921 * Substitute for all variables in the given string in the given context
3922 * If undefErr is TRUE, Parse_Error will be called when an undefined
3923 * variable is encountered.
3926 * var Named variable || NULL for all
3927 * str the string which to substitute
3928 * ctxt the context wherein to find variables
3929 * undefErr TRUE if undefineds are an error
3932 * The resulting string.
3935 * None. The old string must be freed by the caller
3936 *-----------------------------------------------------------------------
3939 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
3941 Buffer buf; /* Buffer for forming things */
3942 char *val; /* Value to substitute for a variable */
3943 int length; /* Length of the variable invocation */
3944 Boolean trailingBslash; /* variable ends in \ */
3945 void *freeIt = NULL; /* Set if it should be freed */
3946 static Boolean errorReported; /* Set true if an error has already
3947 * been reported to prevent a plethora
3948 * of messages when recursing */
3951 errorReported = FALSE;
3952 trailingBslash = FALSE;
3955 if (*str == '\n' && trailingBslash)
3956 Buf_AddByte(&buf, ' ');
3957 if (var == NULL && (*str == '$') && (str[1] == '$')) {
3959 * A dollar sign may be escaped either with another dollar sign.
3960 * In such a case, we skip over the escape character and store the
3961 * dollar sign into the buffer directly.
3964 Buf_AddByte(&buf, *str);
3966 } else if (*str != '$') {
3968 * Skip as many characters as possible -- either to the end of
3969 * the string or to the next dollar sign (variable invocation).
3973 for (cp = str++; *str != '$' && *str != '\0'; str++)
3975 Buf_AddBytes(&buf, str - cp, cp);
3980 if (str[1] == '\0') {
3981 /* A trailing $ is kind of a special case */
3982 Buf_AddByte(&buf, str[0]);
3985 } else if (str[1] != PROPEN && str[1] != BROPEN) {
3986 if (str[1] != *var || strlen(var) > 1) {
3987 Buf_AddBytes(&buf, 2, str);
3999 * Scan up to the end of the variable name.
4001 for (p = &str[2]; *p &&
4002 *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
4006 * A variable inside the variable. We cannot expand
4007 * the external variable yet, so we try again with
4011 Buf_AddBytes(&buf, p - str, str);
4016 if (strncmp(var, str + 2, p - str - 2) != 0 ||
4017 var[p - str - 2] != '\0') {
4019 * Not the variable we want to expand, scan
4020 * until the next variable
4022 for (;*p != '$' && *p != '\0'; p++)
4024 Buf_AddBytes(&buf, p - str, str);
4037 val = Var_Parse(str, ctxt, undefErr, &length, &freeIt);
4040 * When we come down here, val should either point to the
4041 * value of this variable, suitably modified, or be NULL.
4042 * Length should be the total length of the potential
4043 * variable invocation (from $ to end character...)
4045 if (val == var_Error || val == varNoError) {
4047 * If performing old-time variable substitution, skip over
4048 * the variable and continue with the substitution. Otherwise,
4049 * store the dollar sign and advance str so we continue with
4054 } else if (undefErr) {
4056 * If variable is undefined, complain and skip the
4057 * variable. The complaint will stop us from doing anything
4058 * when the file is parsed.
4060 if (!errorReported) {
4061 Parse_Error(PARSE_FATAL,
4062 "Undefined variable \"%.*s\"",length,str);
4065 errorReported = TRUE;
4067 Buf_AddByte(&buf, *str);
4072 * We've now got a variable structure to store in. But first,
4073 * advance the string pointer.
4078 * Copy all the characters from the variable value straight
4079 * into the new string.
4081 length = strlen(val);
4082 Buf_AddBytes(&buf, length, val);
4083 trailingBslash = length > 0 && val[length - 1] == '\\';
4092 return Buf_DestroyCompact(&buf);
4096 *-----------------------------------------------------------------------
4098 * Return the tail from each of a list of words. Used to set the
4099 * System V local variables.
4102 * file Filename to modify
4105 * The resulting string.
4110 *-----------------------------------------------------------------------
4114 Var_GetTail(char *file)
4116 return(VarModify(file, VarTail, NULL));
4120 *-----------------------------------------------------------------------
4122 * Find the leading components of a (list of) filename(s).
4123 * XXX: VarHead does not replace foo by ., as (sun) System V make
4127 * file Filename to manipulate
4130 * The leading components.
4135 *-----------------------------------------------------------------------
4138 Var_GetHead(char *file)
4140 return(VarModify(file, VarHead, NULL));
4145 *-----------------------------------------------------------------------
4147 * Initialize the module
4153 * The VAR_CMD and VAR_GLOBAL contexts are created
4154 *-----------------------------------------------------------------------
4159 VAR_GLOBAL = Targ_NewGN("Global");
4160 VAR_CMD = Targ_NewGN("Command");
4171 /****************** PRINT DEBUGGING INFO *****************/
4173 VarPrintVar(void *vp)
4176 fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
4180 *-----------------------------------------------------------------------
4182 * print all variables in a context
4183 *-----------------------------------------------------------------------
4186 Var_Dump(GNode *ctxt)
4191 for (h = Hash_EnumFirst(&ctxt->context, &search);
4193 h = Hash_EnumNext(&search)) {
4194 VarPrintVar(Hash_GetValue(h));