1 /* $NetBSD: var.c,v 1.184 2013/09/04 15:38:26 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.184 2013/09/04 15:38:26 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.184 2013/09/04 15:38:26 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>
142 extern int makelevel;
144 * XXX transition hack for FreeBSD ports.
145 * bsd.port.mk can set .MAKE.FreeBSD_UL=yes
146 * to cause us to treat :[LU] as aliases for :t[lu]
147 * To be reverted when ports converts to :t[lu] (when 8.3 is EOL)
149 #define MAKE_FREEBSD_UL ".MAKE.FreeBSD_UL"
150 #ifdef MAKE_FREEBSD_UL
151 static int FreeBSD_UL = FALSE;
155 * This lets us tell if we have replaced the original environ
156 * (which we cannot free).
158 char **savedEnv = NULL;
161 * This is a harmless return value for Var_Parse that can be used by Var_Subst
162 * to determine if there was an error in parsing -- easier than returning
163 * a flag, as things outside this module don't give a hoot.
165 char var_Error[] = "";
168 * Similar to var_Error, but returned when the 'errnum' flag for Var_Parse is
169 * set false. Why not just use a constant? Well, gcc likes to condense
170 * identical string instances...
172 static char varNoError[] = "";
175 * Internally, variables are contained in four different contexts.
176 * 1) the environment. They may not be changed. If an environment
177 * variable is appended-to, the result is placed in the global
179 * 2) the global context. Variables set in the Makefile are located in
180 * the global context. It is the penultimate context searched when
182 * 3) the command-line context. All variables set on the command line
183 * are placed in this context. They are UNALTERABLE once placed here.
184 * 4) the local context. Each target has associated with it a context
185 * list. On this list are located the structures describing such
186 * local variables as $(@) and $(*)
187 * The four contexts are searched in the reverse order from which they are
190 GNode *VAR_INTERNAL; /* variables from make itself */
191 GNode *VAR_GLOBAL; /* variables from the makefile */
192 GNode *VAR_CMD; /* variables defined on the command-line */
194 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
195 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
196 #define FIND_ENV 0x4 /* look in the environment also */
199 char *name; /* the variable's name */
200 Buffer val; /* its value */
201 int flags; /* miscellaneous status flags */
202 #define VAR_IN_USE 1 /* Variable's value currently being used.
203 * Used to avoid recursion */
204 #define VAR_FROM_ENV 2 /* Variable comes from the environment */
205 #define VAR_JUNK 4 /* Variable is a junk variable that
206 * should be destroyed when done with
207 * it. Used by Var_Parse for undefined,
208 * modified variables */
209 #define VAR_KEEP 8 /* Variable is VAR_JUNK, but we found
210 * a use for it in some modifier and
211 * the value is therefore valid */
212 #define VAR_EXPORTED 16 /* Variable is exported */
213 #define VAR_REEXPORT 32 /* Indicate if var needs re-export.
214 * This would be true if it contains $'s
216 #define VAR_FROM_CMD 64 /* Variable came from command line */
220 * Exporting vars is expensive so skip it if we can
222 #define VAR_EXPORTED_NONE 0
223 #define VAR_EXPORTED_YES 1
224 #define VAR_EXPORTED_ALL 2
225 static int var_exportedVars = VAR_EXPORTED_NONE;
227 * We pass this to Var_Export when doing the initial export
228 * or after updating an exported var.
230 #define VAR_EXPORT_PARENT 1
232 /* Var*Pattern flags */
233 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
234 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
235 #define VAR_SUB_MATCHED 0x04 /* There was a match */
236 #define VAR_MATCH_START 0x08 /* Match at start of word */
237 #define VAR_MATCH_END 0x10 /* Match at end of word */
238 #define VAR_NOSUBST 0x20 /* don't expand vars in VarGetPattern */
241 #define VAR_NO_EXPORT 0x01 /* do not export */
245 * The following fields are set by Var_Parse() when it
246 * encounters modifiers that need to keep state for use by
247 * subsequent modifiers within the same variable expansion.
249 Byte varSpace; /* Word separator in expansions */
250 Boolean oneBigWord; /* TRUE if we will treat the variable as a
251 * single big word, even if it contains
252 * embedded spaces (as opposed to the
253 * usual behaviour of treating it as
254 * several space-separated words). */
257 /* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/",
258 * to VarSYSVMatch() for ":lhs=rhs". */
260 const char *lhs; /* String to match */
261 int leftLen; /* Length of string */
262 const char *rhs; /* Replacement string (w/ &'s removed) */
263 int rightLen; /* Length of replacement */
267 /* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */
269 GNode *ctxt; /* variable context */
270 char *tvar; /* name of temp var */
272 char *str; /* string to expand */
274 int errnum; /* errnum for not defined */
278 /* struct passed as 'void *' to VarRESubstitute() for ":C///" */
288 /* struct passed to VarSelectWords() for ":[start..end]" */
290 int start; /* first word to select */
291 int end; /* last word to select */
294 static Var *VarFind(const char *, GNode *, int);
295 static void VarAdd(const char *, const char *, GNode *);
296 static Boolean VarHead(GNode *, Var_Parse_State *,
297 char *, Boolean, Buffer *, void *);
298 static Boolean VarTail(GNode *, Var_Parse_State *,
299 char *, Boolean, Buffer *, void *);
300 static Boolean VarSuffix(GNode *, Var_Parse_State *,
301 char *, Boolean, Buffer *, void *);
302 static Boolean VarRoot(GNode *, Var_Parse_State *,
303 char *, Boolean, Buffer *, void *);
304 static Boolean VarMatch(GNode *, Var_Parse_State *,
305 char *, Boolean, Buffer *, void *);
307 static Boolean VarSYSVMatch(GNode *, Var_Parse_State *,
308 char *, Boolean, Buffer *, void *);
310 static Boolean VarNoMatch(GNode *, Var_Parse_State *,
311 char *, Boolean, Buffer *, void *);
313 static void VarREError(int, regex_t *, const char *);
314 static Boolean VarRESubstitute(GNode *, Var_Parse_State *,
315 char *, Boolean, Buffer *, void *);
317 static Boolean VarSubstitute(GNode *, Var_Parse_State *,
318 char *, Boolean, Buffer *, void *);
319 static Boolean VarLoopExpand(GNode *, Var_Parse_State *,
320 char *, Boolean, Buffer *, void *);
321 static char *VarGetPattern(GNode *, Var_Parse_State *,
322 int, const char **, int, int *, int *,
324 static char *VarQuote(char *);
325 static char *VarHash(char *);
326 static char *VarModify(GNode *, Var_Parse_State *,
328 Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *),
330 static char *VarOrder(const char *, const char);
331 static char *VarUniq(const char *);
332 static int VarWordCompare(const void *, const void *);
333 static void VarPrintVar(void *);
341 *-----------------------------------------------------------------------
343 * Find the given variable in the given context and any other contexts
348 * ctxt context in which to find it
349 * flags FIND_GLOBAL set means to look in the
350 * VAR_GLOBAL context as well. FIND_CMD set means
351 * to look in the VAR_CMD context also. FIND_ENV
352 * set means to look in the environment
355 * A pointer to the structure describing the desired variable or
356 * NULL if the variable does not exist.
360 *-----------------------------------------------------------------------
363 VarFind(const char *name, GNode *ctxt, int flags)
369 * If the variable name begins with a '.', it could very well be one of
370 * the local ones. We check the name against all the local variables
371 * and substitute the short version in for 'name' if it matches one of
374 if (*name == '.' && isupper((unsigned char) name[1]))
377 if (!strcmp(name, ".ALLSRC"))
379 if (!strcmp(name, ".ARCHIVE"))
383 if (!strcmp(name, ".IMPSRC"))
387 if (!strcmp(name, ".MEMBER"))
391 if (!strcmp(name, ".OODATE"))
395 if (!strcmp(name, ".PREFIX"))
399 if (!strcmp(name, ".TARGET"))
404 /* for compatibility with gmake */
405 if (name[0] == '^' && name[1] == '\0')
410 * First look for the variable in the given context. If it's not there,
411 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
412 * depending on the FIND_* flags in 'flags'
414 var = Hash_FindEntry(&ctxt->context, name);
416 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
417 var = Hash_FindEntry(&VAR_CMD->context, name);
419 if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
420 (ctxt != VAR_GLOBAL))
422 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
423 if ((var == NULL) && (ctxt != VAR_INTERNAL)) {
424 /* VAR_INTERNAL is subordinate to VAR_GLOBAL */
425 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
428 if ((var == NULL) && (flags & FIND_ENV)) {
431 if ((env = getenv(name)) != NULL) {
434 v = bmake_malloc(sizeof(Var));
435 v->name = bmake_strdup(name);
439 Buf_Init(&v->val, len + 1);
440 Buf_AddBytes(&v->val, len, env);
442 v->flags = VAR_FROM_ENV;
444 } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
445 (ctxt != VAR_GLOBAL))
447 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
448 if ((var == NULL) && (ctxt != VAR_INTERNAL)) {
449 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
454 return ((Var *)Hash_GetValue(var));
459 } else if (var == NULL) {
462 return ((Var *)Hash_GetValue(var));
467 *-----------------------------------------------------------------------
469 * If the variable is an environment variable, free it
473 * destroy true if the value buffer should be destroyed.
476 * 1 if it is an environment variable 0 ow.
479 * The variable is free'ed if it is an environent variable.
480 *-----------------------------------------------------------------------
483 VarFreeEnv(Var *v, Boolean destroy)
485 if ((v->flags & VAR_FROM_ENV) == 0)
488 Buf_Destroy(&v->val, destroy);
494 *-----------------------------------------------------------------------
496 * Add a new variable of name name and value val to the given context
499 * name name of variable to add
500 * val value to set it to
501 * ctxt context in which to set it
507 * The new variable is placed at the front of the given context
508 * The name and val arguments are duplicated so they may
510 *-----------------------------------------------------------------------
513 VarAdd(const char *name, const char *val, GNode *ctxt)
519 v = bmake_malloc(sizeof(Var));
521 len = val ? strlen(val) : 0;
522 Buf_Init(&v->val, len+1);
523 Buf_AddBytes(&v->val, len, val);
527 h = Hash_CreateEntry(&ctxt->context, name, NULL);
531 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
536 *-----------------------------------------------------------------------
538 * Remove a variable from a context.
544 * The Var structure is removed and freed.
546 *-----------------------------------------------------------------------
549 Var_Delete(const char *name, GNode *ctxt)
554 if (strchr(name, '$')) {
555 cp = Var_Subst(NULL, name, VAR_GLOBAL, 0);
559 ln = Hash_FindEntry(&ctxt->context, cp);
561 fprintf(debug_file, "%s:delete %s%s\n",
562 ctxt->name, cp, ln ? "" : " (not found)");
570 v = (Var *)Hash_GetValue(ln);
571 if ((v->flags & VAR_EXPORTED)) {
574 if (strcmp(MAKE_EXPORTED, v->name) == 0) {
575 var_exportedVars = VAR_EXPORTED_NONE;
577 if (v->name != ln->name)
579 Hash_DeleteEntry(&ctxt->context, ln);
580 Buf_Destroy(&v->val, TRUE);
588 * We ignore make internal variables (those which start with '.')
589 * Also we jump through some hoops to avoid calling setenv
590 * more than necessary since it can leak.
591 * We only manipulate flags of vars if 'parent' is set.
594 Var_Export1(const char *name, int parent)
602 return 0; /* skip internals */
606 * If it is one of the vars that should only appear in
607 * local context, skip it, else we can get Var_Subst
618 v = VarFind(name, VAR_GLOBAL, 0);
623 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
624 return 0; /* nothing to do */
626 val = Buf_GetAll(&v->val, NULL);
627 if (strchr(val, '$')) {
630 * Flag this as something we need to re-export.
631 * No point actually exporting it now though,
632 * the child can do it at the last minute.
634 v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
637 if (v->flags & VAR_IN_USE) {
639 * We recursed while exporting in a child.
640 * This isn't going to end well, just skip it.
644 n = snprintf(tmp, sizeof(tmp), "${%s}", name);
645 if (n < (int)sizeof(tmp)) {
646 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
647 setenv(name, val, 1);
652 v->flags &= ~VAR_REEXPORT; /* once will do */
654 if (parent || !(v->flags & VAR_EXPORTED)) {
655 setenv(name, val, 1);
659 * This is so Var_Set knows to call Var_Export again...
662 v->flags |= VAR_EXPORTED;
668 * This gets called from our children.
681 * Several make's support this sort of mechanism for tracking
682 * recursion - but each uses a different name.
683 * We allow the makefiles to update MAKELEVEL and ensure
684 * children see a correctly incremented value.
686 snprintf(tmp, sizeof(tmp), "%d", makelevel + 1);
687 setenv(MAKE_LEVEL_ENV, tmp, 1);
689 if (VAR_EXPORTED_NONE == var_exportedVars)
692 if (VAR_EXPORTED_ALL == var_exportedVars) {
694 * Ouch! This is crazy...
696 for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
698 var = Hash_EnumNext(&state)) {
699 v = (Var *)Hash_GetValue(var);
700 Var_Export1(v->name, 0);
705 * We have a number of exported vars,
707 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
708 if (n < (int)sizeof(tmp)) {
714 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
715 av = brk_string(val, &ac, FALSE, &as);
716 for (i = 0; i < ac; i++) {
717 Var_Export1(av[i], 0);
726 * This is called when .export is seen or
727 * .MAKE.EXPORTED is modified.
728 * It is also called when any exported var is modified.
731 Var_Export(char *str, int isExport)
741 if (isExport && (!str || !str[0])) {
742 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
746 if (strncmp(str, "-env", 4) == 0) {
750 track = VAR_EXPORT_PARENT;
752 val = Var_Subst(NULL, str, VAR_GLOBAL, 0);
753 av = brk_string(val, &ac, FALSE, &as);
754 for (i = 0; i < ac; i++) {
759 * If it is one of the vars that should only appear in
760 * local context, skip it, else we can get Var_Subst
771 if (Var_Export1(name, track)) {
772 if (VAR_EXPORTED_ALL != var_exportedVars)
773 var_exportedVars = VAR_EXPORTED_YES;
774 if (isExport && track) {
775 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
786 * This is called when .unexport[-env] is seen.
788 extern char **environ;
791 Var_UnExport(char *str)
796 Boolean unexport_env;
799 if (!str || !str[0]) {
800 return; /* assert? */
806 unexport_env = (strncmp(str, "-env", 4) == 0);
810 cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */
811 if (environ == savedEnv) {
812 /* we have been here before! */
813 newenv = bmake_realloc(environ, 2 * sizeof(char *));
819 newenv = bmake_malloc(2 * sizeof(char *));
823 /* Note: we cannot safely free() the original environ. */
824 environ = savedEnv = newenv;
827 setenv(MAKE_LEVEL_ENV, cp, 1);
829 for (; *str != '\n' && isspace((unsigned char) *str); str++)
831 if (str[0] && str[0] != '\n') {
837 /* Using .MAKE.EXPORTED */
838 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
839 if (n < (int)sizeof(tmp)) {
840 vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
850 av = brk_string(vlist, &ac, FALSE, &as);
851 for (i = 0; i < ac; i++) {
852 v = VarFind(av[i], VAR_GLOBAL, 0);
856 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
859 v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT);
861 * If we are unexporting a list,
862 * remove each one from .MAKE.EXPORTED.
863 * If we are removing them all,
864 * just delete .MAKE.EXPORTED below.
867 n = snprintf(tmp, sizeof(tmp),
868 "${" MAKE_EXPORTED ":N%s}", v->name);
869 if (n < (int)sizeof(tmp)) {
870 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
871 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0);
879 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
886 *-----------------------------------------------------------------------
888 * Set the variable name to the value val in the given context.
891 * name name of variable to set
892 * val value to give to the variable
893 * ctxt context in which to set it
899 * If the variable doesn't yet exist, a new record is created for it.
900 * Else the old value is freed and the new one stuck in its place
903 * The variable is searched for only in its context before being
904 * created in that context. I.e. if the context is VAR_GLOBAL,
905 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
906 * VAR_CMD->context is searched. This is done to avoid the literally
907 * thousands of unnecessary strcmp's that used to be done to
908 * set, say, $(@) or $(<).
909 * If the context is VAR_GLOBAL though, we check if the variable
910 * was set in VAR_CMD from the command line and skip it if so.
911 *-----------------------------------------------------------------------
914 Var_Set(const char *name, const char *val, GNode *ctxt, int flags)
917 char *expanded_name = NULL;
920 * We only look for a variable in the given context since anything set
921 * here will override anything in a lower context, so there's not much
922 * point in searching them all just to save a bit of memory...
924 if (strchr(name, '$') != NULL) {
925 expanded_name = Var_Subst(NULL, name, ctxt, 0);
926 if (expanded_name[0] == 0) {
928 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
929 "name expands to empty string - ignored\n",
935 name = expanded_name;
937 if (ctxt == VAR_GLOBAL) {
938 v = VarFind(name, VAR_CMD, 0);
940 if ((v->flags & VAR_FROM_CMD)) {
942 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
949 v = VarFind(name, ctxt, 0);
951 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
953 * This var would normally prevent the same name being added
954 * to VAR_GLOBAL, so delete it from there if needed.
955 * Otherwise -V name may show the wrong value.
957 Var_Delete(name, VAR_GLOBAL);
959 VarAdd(name, val, ctxt);
962 Buf_AddBytes(&v->val, strlen(val), val);
965 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
967 if ((v->flags & VAR_EXPORTED)) {
968 Var_Export1(name, VAR_EXPORT_PARENT);
972 * Any variables given on the command line are automatically exported
973 * to the environment (as per POSIX standard)
975 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
977 /* we just added it */
978 v = VarFind(name, ctxt, 0);
981 v->flags |= VAR_FROM_CMD;
983 * If requested, don't export these in the environment
984 * individually. We still put them in MAKEOVERRIDES so
985 * that the command-line settings continue to override
988 if (varNoExportEnv != TRUE)
989 setenv(name, val, 1);
991 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
994 #ifdef MAKE_FREEBSD_UL
995 if (strcmp(MAKE_FREEBSD_UL, name) == 0) {
996 FreeBSD_UL = getBoolean(MAKE_FREEBSD_UL, FALSE);
1002 if (expanded_name != NULL)
1003 free(expanded_name);
1005 VarFreeEnv(v, TRUE);
1009 *-----------------------------------------------------------------------
1011 * The variable of the given name has the given value appended to it in
1012 * the given context.
1015 * name name of variable to modify
1016 * val String to append to it
1017 * ctxt Context in which this should occur
1023 * If the variable doesn't exist, it is created. Else the strings
1024 * are concatenated (with a space in between).
1027 * Only if the variable is being sought in the global context is the
1028 * environment searched.
1029 * XXX: Knows its calling circumstances in that if called with ctxt
1030 * an actual target, it will only search that context since only
1031 * a local variable could be being appended to. This is actually
1032 * a big win and must be tolerated.
1033 *-----------------------------------------------------------------------
1036 Var_Append(const char *name, const char *val, GNode *ctxt)
1040 char *expanded_name = NULL;
1042 if (strchr(name, '$') != NULL) {
1043 expanded_name = Var_Subst(NULL, name, ctxt, 0);
1044 if (expanded_name[0] == 0) {
1046 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
1047 "name expands to empty string - ignored\n",
1050 free(expanded_name);
1053 name = expanded_name;
1056 v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
1059 VarAdd(name, val, ctxt);
1061 Buf_AddByte(&v->val, ' ');
1062 Buf_AddBytes(&v->val, strlen(val), val);
1065 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
1066 Buf_GetAll(&v->val, NULL));
1069 if (v->flags & VAR_FROM_ENV) {
1071 * If the original variable came from the environment, we
1072 * have to install it in the global context (we could place
1073 * it in the environment, but then we should provide a way to
1074 * export other variables...)
1076 v->flags &= ~VAR_FROM_ENV;
1077 h = Hash_CreateEntry(&ctxt->context, name, NULL);
1078 Hash_SetValue(h, v);
1081 if (expanded_name != NULL)
1082 free(expanded_name);
1086 *-----------------------------------------------------------------------
1088 * See if the given variable exists.
1091 * name Variable to find
1092 * ctxt Context in which to start search
1095 * TRUE if it does, FALSE if it doesn't
1100 *-----------------------------------------------------------------------
1103 Var_Exists(const char *name, GNode *ctxt)
1108 if ((cp = strchr(name, '$')) != NULL) {
1109 cp = Var_Subst(NULL, name, ctxt, FALSE);
1111 v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
1118 (void)VarFreeEnv(v, TRUE);
1124 *-----------------------------------------------------------------------
1126 * Return the value of the named variable in the given context
1130 * ctxt context in which to search for it
1133 * The value if the variable exists, NULL if it doesn't
1137 *-----------------------------------------------------------------------
1140 Var_Value(const char *name, GNode *ctxt, char **frp)
1144 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1147 char *p = (Buf_GetAll(&v->val, NULL));
1148 if (VarFreeEnv(v, FALSE))
1157 *-----------------------------------------------------------------------
1159 * Remove the tail of the given word and place the result in the given
1164 * addSpace True if need to add a space to the buffer
1165 * before sticking in the head
1166 * buf Buffer in which to store it
1169 * TRUE if characters were added to the buffer (a space needs to be
1170 * added to the buffer before the next word).
1173 * The trimmed word is added to the buffer.
1175 *-----------------------------------------------------------------------
1178 VarHead(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1179 char *word, Boolean addSpace, Buffer *buf,
1184 slash = strrchr(word, '/');
1185 if (slash != NULL) {
1186 if (addSpace && vpstate->varSpace) {
1187 Buf_AddByte(buf, vpstate->varSpace);
1190 Buf_AddBytes(buf, strlen(word), word);
1195 * If no directory part, give . (q.v. the POSIX standard)
1197 if (addSpace && vpstate->varSpace)
1198 Buf_AddByte(buf, vpstate->varSpace);
1199 Buf_AddByte(buf, '.');
1201 return(dummy ? TRUE : TRUE);
1205 *-----------------------------------------------------------------------
1207 * Remove the head of the given word and place the result in the given
1212 * addSpace True if need to add a space to the buffer
1213 * before adding the tail
1214 * buf Buffer in which to store it
1217 * TRUE if characters were added to the buffer (a space needs to be
1218 * added to the buffer before the next word).
1221 * The trimmed word is added to the buffer.
1223 *-----------------------------------------------------------------------
1226 VarTail(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1227 char *word, Boolean addSpace, Buffer *buf,
1232 if (addSpace && vpstate->varSpace) {
1233 Buf_AddByte(buf, vpstate->varSpace);
1236 slash = strrchr(word, '/');
1237 if (slash != NULL) {
1239 Buf_AddBytes(buf, strlen(slash), slash);
1242 Buf_AddBytes(buf, strlen(word), word);
1244 return (dummy ? TRUE : TRUE);
1248 *-----------------------------------------------------------------------
1250 * Place the suffix of the given word in the given buffer.
1254 * addSpace TRUE if need to add a space before placing the
1255 * suffix in the buffer
1256 * buf Buffer in which to store it
1259 * TRUE if characters were added to the buffer (a space needs to be
1260 * added to the buffer before the next word).
1263 * The suffix from the word is placed in the buffer.
1265 *-----------------------------------------------------------------------
1268 VarSuffix(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1269 char *word, Boolean addSpace, Buffer *buf,
1274 dot = strrchr(word, '.');
1276 if (addSpace && vpstate->varSpace) {
1277 Buf_AddByte(buf, vpstate->varSpace);
1280 Buf_AddBytes(buf, strlen(dot), dot);
1284 return (dummy ? addSpace : addSpace);
1288 *-----------------------------------------------------------------------
1290 * Remove the suffix of the given word and place the result in the
1295 * addSpace TRUE if need to add a space to the buffer
1296 * before placing the root in it
1297 * buf Buffer in which to store it
1300 * TRUE if characters were added to the buffer (a space needs to be
1301 * added to the buffer before the next word).
1304 * The trimmed word is added to the buffer.
1306 *-----------------------------------------------------------------------
1309 VarRoot(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1310 char *word, Boolean addSpace, Buffer *buf,
1315 if (addSpace && vpstate->varSpace) {
1316 Buf_AddByte(buf, vpstate->varSpace);
1319 dot = strrchr(word, '.');
1322 Buf_AddBytes(buf, strlen(word), word);
1325 Buf_AddBytes(buf, strlen(word), word);
1327 return (dummy ? TRUE : TRUE);
1331 *-----------------------------------------------------------------------
1333 * Place the word in the buffer if it matches the given pattern.
1334 * Callback function for VarModify to implement the :M modifier.
1337 * word Word to examine
1338 * addSpace TRUE if need to add a space to the buffer
1339 * before adding the word, if it matches
1340 * buf Buffer in which to store it
1341 * pattern Pattern the word must match
1344 * TRUE if a space should be placed in the buffer before the next
1348 * The word may be copied to the buffer.
1350 *-----------------------------------------------------------------------
1353 VarMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1354 char *word, Boolean addSpace, Buffer *buf,
1358 fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
1359 if (Str_Match(word, (char *)pattern)) {
1360 if (addSpace && vpstate->varSpace) {
1361 Buf_AddByte(buf, vpstate->varSpace);
1364 Buf_AddBytes(buf, strlen(word), word);
1371 *-----------------------------------------------------------------------
1373 * Place the word in the buffer if it matches the given pattern.
1374 * Callback function for VarModify to implement the System V %
1378 * word Word to examine
1379 * addSpace TRUE if need to add a space to the buffer
1380 * before adding the word, if it matches
1381 * buf Buffer in which to store it
1382 * patp Pattern the word must match
1385 * TRUE if a space should be placed in the buffer before the next
1389 * The word may be copied to the buffer.
1391 *-----------------------------------------------------------------------
1394 VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
1395 char *word, Boolean addSpace, Buffer *buf,
1400 VarPattern *pat = (VarPattern *)patp;
1403 if (addSpace && vpstate->varSpace)
1404 Buf_AddByte(buf, vpstate->varSpace);
1408 if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
1409 varexp = Var_Subst(NULL, pat->rhs, ctx, 0);
1410 Str_SYSVSubst(buf, varexp, ptr, len);
1413 Buf_AddBytes(buf, strlen(word), word);
1422 *-----------------------------------------------------------------------
1424 * Place the word in the buffer if it doesn't match the given pattern.
1425 * Callback function for VarModify to implement the :N modifier.
1428 * word Word to examine
1429 * addSpace TRUE if need to add a space to the buffer
1430 * before adding the word, if it matches
1431 * buf Buffer in which to store it
1432 * pattern Pattern the word must match
1435 * TRUE if a space should be placed in the buffer before the next
1439 * The word may be copied to the buffer.
1441 *-----------------------------------------------------------------------
1444 VarNoMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1445 char *word, Boolean addSpace, Buffer *buf,
1448 if (!Str_Match(word, (char *)pattern)) {
1449 if (addSpace && vpstate->varSpace) {
1450 Buf_AddByte(buf, vpstate->varSpace);
1453 Buf_AddBytes(buf, strlen(word), word);
1460 *-----------------------------------------------------------------------
1462 * Perform a string-substitution on the given word, placing the
1463 * result in the passed buffer.
1466 * word Word to modify
1467 * addSpace True if space should be added before
1469 * buf Buffer for result
1470 * patternp Pattern for substitution
1473 * TRUE if a space is needed before more characters are added.
1478 *-----------------------------------------------------------------------
1481 VarSubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1482 char *word, Boolean addSpace, Buffer *buf,
1485 int wordLen; /* Length of word */
1486 char *cp; /* General pointer */
1487 VarPattern *pattern = (VarPattern *)patternp;
1489 wordLen = strlen(word);
1490 if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
1491 (VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1493 * Still substituting -- break it down into simple anchored cases
1494 * and if none of them fits, perform the general substitution case.
1496 if ((pattern->flags & VAR_MATCH_START) &&
1497 (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
1499 * Anchored at start and beginning of word matches pattern
1501 if ((pattern->flags & VAR_MATCH_END) &&
1502 (wordLen == pattern->leftLen)) {
1504 * Also anchored at end and matches to the end (word
1505 * is same length as pattern) add space and rhs only
1506 * if rhs is non-null.
1508 if (pattern->rightLen != 0) {
1509 if (addSpace && vpstate->varSpace) {
1510 Buf_AddByte(buf, vpstate->varSpace);
1513 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1515 pattern->flags |= VAR_SUB_MATCHED;
1516 } else if (pattern->flags & VAR_MATCH_END) {
1518 * Doesn't match to end -- copy word wholesale
1523 * Matches at start but need to copy in trailing characters
1525 if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1526 if (addSpace && vpstate->varSpace) {
1527 Buf_AddByte(buf, vpstate->varSpace);
1531 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1532 Buf_AddBytes(buf, wordLen - pattern->leftLen,
1533 (word + pattern->leftLen));
1534 pattern->flags |= VAR_SUB_MATCHED;
1536 } else if (pattern->flags & VAR_MATCH_START) {
1538 * Had to match at start of word and didn't -- copy whole word.
1541 } else if (pattern->flags & VAR_MATCH_END) {
1543 * Anchored at end, Find only place match could occur (leftLen
1544 * characters from the end of the word) and see if it does. Note
1545 * that because the $ will be left at the end of the lhs, we have
1548 cp = word + (wordLen - pattern->leftLen);
1550 (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
1552 * Match found. If we will place characters in the buffer,
1553 * add a space before hand as indicated by addSpace, then
1554 * stuff in the initial, unmatched part of the word followed
1555 * by the right-hand-side.
1557 if (((cp - word) + pattern->rightLen) != 0) {
1558 if (addSpace && vpstate->varSpace) {
1559 Buf_AddByte(buf, vpstate->varSpace);
1563 Buf_AddBytes(buf, cp - word, word);
1564 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1565 pattern->flags |= VAR_SUB_MATCHED;
1568 * Had to match at end and didn't. Copy entire word.
1574 * Pattern is unanchored: search for the pattern in the word using
1575 * String_FindSubstring, copying unmatched portions and the
1576 * right-hand-side for each match found, handling non-global
1577 * substitutions correctly, etc. When the loop is done, any
1578 * remaining part of the word (word and wordLen are adjusted
1579 * accordingly through the loop) is copied straight into the
1581 * addSpace is set FALSE as soon as a space is added to the
1588 origSize = Buf_Size(buf);
1590 cp = Str_FindSubstring(word, pattern->lhs);
1592 if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1593 Buf_AddByte(buf, vpstate->varSpace);
1596 Buf_AddBytes(buf, cp-word, word);
1597 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1598 wordLen -= (cp - word) + pattern->leftLen;
1599 word = cp + pattern->leftLen;
1603 if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
1606 pattern->flags |= VAR_SUB_MATCHED;
1612 if (addSpace && vpstate->varSpace) {
1613 Buf_AddByte(buf, vpstate->varSpace);
1615 Buf_AddBytes(buf, wordLen, word);
1618 * If added characters to the buffer, need to add a space
1619 * before we add any more. If we didn't add any, just return
1620 * the previous value of addSpace.
1622 return ((Buf_Size(buf) != origSize) || addSpace);
1627 if (addSpace && vpstate->varSpace) {
1628 Buf_AddByte(buf, vpstate->varSpace);
1630 Buf_AddBytes(buf, wordLen, word);
1636 *-----------------------------------------------------------------------
1638 * Print the error caused by a regcomp or regexec call.
1644 * An error gets printed.
1646 *-----------------------------------------------------------------------
1649 VarREError(int errnum, regex_t *pat, const char *str)
1654 errlen = regerror(errnum, pat, 0, 0);
1655 errbuf = bmake_malloc(errlen);
1656 regerror(errnum, pat, errbuf, errlen);
1657 Error("%s: %s", str, errbuf);
1663 *-----------------------------------------------------------------------
1664 * VarRESubstitute --
1665 * Perform a regex substitution on the given word, placing the
1666 * result in the passed buffer.
1669 * TRUE if a space is needed before more characters are added.
1674 *-----------------------------------------------------------------------
1677 VarRESubstitute(GNode *ctx MAKE_ATTR_UNUSED,
1678 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1679 char *word, Boolean addSpace, Buffer *buf,
1689 #define MAYBE_ADD_SPACE() \
1690 if (addSpace && !added) \
1691 Buf_AddByte(buf, ' '); \
1698 if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1699 (VAR_SUB_ONE|VAR_SUB_MATCHED))
1703 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1708 pat->flags |= VAR_SUB_MATCHED;
1709 if (pat->matches[0].rm_so > 0) {
1711 Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1714 for (rp = pat->replace; *rp; rp++) {
1715 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1717 Buf_AddByte(buf,rp[1]);
1720 else if ((*rp == '&') ||
1721 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1739 if (n > pat->nsub) {
1740 Error("No subexpression %s", &errstr[0]);
1743 } else if ((pat->matches[n].rm_so == -1) &&
1744 (pat->matches[n].rm_eo == -1)) {
1745 Error("No match for subexpression %s", &errstr[0]);
1749 subbuf = wp + pat->matches[n].rm_so;
1750 sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1755 Buf_AddBytes(buf, sublen, subbuf);
1759 Buf_AddByte(buf, *rp);
1762 wp += pat->matches[0].rm_eo;
1763 if (pat->flags & VAR_SUB_GLOBAL) {
1764 flags |= REG_NOTBOL;
1765 if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1767 Buf_AddByte(buf, *wp);
1776 Buf_AddBytes(buf, strlen(wp), wp);
1780 VarREError(xrv, &pat->re, "Unexpected regex error");
1785 Buf_AddBytes(buf,strlen(wp),wp);
1789 return(addSpace||added);
1796 *-----------------------------------------------------------------------
1798 * Implements the :@<temp>@<string>@ modifier of ODE make.
1799 * We set the temp variable named in pattern.lhs to word and expand
1800 * pattern.rhs storing the result in the passed buffer.
1803 * word Word to modify
1804 * addSpace True if space should be added before
1806 * buf Buffer for result
1807 * pattern Datafor substitution
1810 * TRUE if a space is needed before more characters are added.
1815 *-----------------------------------------------------------------------
1818 VarLoopExpand(GNode *ctx MAKE_ATTR_UNUSED,
1819 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1820 char *word, Boolean addSpace, Buffer *buf,
1823 VarLoop_t *loop = (VarLoop_t *)loopp;
1827 if (word && *word) {
1828 Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
1829 s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum);
1830 if (s != NULL && *s != '\0') {
1831 if (addSpace && *s != '\n')
1832 Buf_AddByte(buf, ' ');
1833 Buf_AddBytes(buf, (slen = strlen(s)), s);
1834 addSpace = (slen > 0 && s[slen - 1] != '\n');
1843 *-----------------------------------------------------------------------
1845 * Implements the :[start..end] modifier.
1846 * This is a special case of VarModify since we want to be able
1847 * to scan the list backwards if start > end.
1850 * str String whose words should be trimmed
1851 * seldata words to select
1854 * A string of all the words selected.
1859 *-----------------------------------------------------------------------
1862 VarSelectWords(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1863 const char *str, VarSelectWords_t *seldata)
1865 Buffer buf; /* Buffer for the new string */
1866 Boolean addSpace; /* TRUE if need to add a space to the
1867 * buffer before adding the trimmed
1869 char **av; /* word list */
1870 char *as; /* word list memory */
1872 int start, end, step;
1877 if (vpstate->oneBigWord) {
1878 /* fake what brk_string() would do if there were only one word */
1880 av = bmake_malloc((ac + 1) * sizeof(char *));
1881 as = bmake_strdup(str);
1885 av = brk_string(str, &ac, FALSE, &as);
1889 * Now sanitize seldata.
1890 * If seldata->start or seldata->end are negative, convert them to
1891 * the positive equivalents (-1 gets converted to argc, -2 gets
1892 * converted to (argc-1), etc.).
1894 if (seldata->start < 0)
1895 seldata->start = ac + seldata->start + 1;
1896 if (seldata->end < 0)
1897 seldata->end = ac + seldata->end + 1;
1900 * We avoid scanning more of the list than we need to.
1902 if (seldata->start > seldata->end) {
1903 start = MIN(ac, seldata->start) - 1;
1904 end = MAX(0, seldata->end - 1);
1907 start = MAX(0, seldata->start - 1);
1908 end = MIN(ac, seldata->end);
1913 (step < 0 && i >= end) || (step > 0 && i < end);
1915 if (av[i] && *av[i]) {
1916 if (addSpace && vpstate->varSpace) {
1917 Buf_AddByte(&buf, vpstate->varSpace);
1919 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
1927 return Buf_Destroy(&buf, FALSE);
1933 * Replace each word with the result of realpath()
1937 VarRealpath(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1938 char *word, Boolean addSpace, Buffer *buf,
1939 void *patternp MAKE_ATTR_UNUSED)
1942 char rbuf[MAXPATHLEN];
1945 if (addSpace && vpstate->varSpace) {
1946 Buf_AddByte(buf, vpstate->varSpace);
1949 rp = realpath(word, rbuf);
1950 if (rp && *rp == '/' && stat(rp, &st) == 0)
1953 Buf_AddBytes(buf, strlen(word), word);
1958 *-----------------------------------------------------------------------
1960 * Modify each of the words of the passed string using the given
1961 * function. Used to implement all modifiers.
1964 * str String whose words should be trimmed
1965 * modProc Function to use to modify them
1966 * datum Datum to pass it
1969 * A string of all the words modified appropriately.
1974 *-----------------------------------------------------------------------
1977 VarModify(GNode *ctx, Var_Parse_State *vpstate,
1979 Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
1980 Boolean, Buffer *, void *),
1983 Buffer buf; /* Buffer for the new string */
1984 Boolean addSpace; /* TRUE if need to add a space to the
1985 * buffer before adding the trimmed
1987 char **av; /* word list */
1988 char *as; /* word list memory */
1994 if (vpstate->oneBigWord) {
1995 /* fake what brk_string() would do if there were only one word */
1997 av = bmake_malloc((ac + 1) * sizeof(char *));
1998 as = bmake_strdup(str);
2002 av = brk_string(str, &ac, FALSE, &as);
2005 for (i = 0; i < ac; i++) {
2006 addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum);
2012 return Buf_Destroy(&buf, FALSE);
2017 VarWordCompare(const void *a, const void *b)
2019 int r = strcmp(*(const char * const *)a, *(const char * const *)b);
2024 *-----------------------------------------------------------------------
2026 * Order the words in the string.
2029 * str String whose words should be sorted.
2030 * otype How to order: s - sort, x - random.
2033 * A string containing the words ordered.
2038 *-----------------------------------------------------------------------
2041 VarOrder(const char *str, const char otype)
2043 Buffer buf; /* Buffer for the new string */
2044 char **av; /* word list [first word does not count] */
2045 char *as; /* word list memory */
2050 av = brk_string(str, &ac, FALSE, &as);
2054 case 's': /* sort alphabetically */
2055 qsort(av, ac, sizeof(char *), VarWordCompare);
2057 case 'x': /* randomize */
2063 * We will use [ac..2] range for mod factors. This will produce
2064 * random numbers in [(ac-1)..0] interval, and minimal
2065 * reasonable value for mod factor is 2 (the mod 1 will produce
2066 * 0 with probability 1).
2068 for (i = ac-1; i > 0; i--) {
2069 rndidx = random() % (i + 1);
2077 } /* end of switch */
2079 for (i = 0; i < ac; i++) {
2080 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2082 Buf_AddByte(&buf, ' ');
2088 return Buf_Destroy(&buf, FALSE);
2093 *-----------------------------------------------------------------------
2095 * Remove adjacent duplicate words.
2098 * str String whose words should be sorted
2101 * A string containing the resulting words.
2106 *-----------------------------------------------------------------------
2109 VarUniq(const char *str)
2111 Buffer buf; /* Buffer for new string */
2112 char **av; /* List of words to affect */
2113 char *as; /* Word list memory */
2117 av = brk_string(str, &ac, FALSE, &as);
2120 for (j = 0, i = 1; i < ac; i++)
2121 if (strcmp(av[i], av[j]) != 0 && (++j != i))
2126 for (i = 0; i < ac; i++) {
2127 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2129 Buf_AddByte(&buf, ' ');
2135 return Buf_Destroy(&buf, FALSE);
2140 *-----------------------------------------------------------------------
2142 * Pass through the tstr looking for 1) escaped delimiters,
2143 * '$'s and backslashes (place the escaped character in
2144 * uninterpreted) and 2) unescaped $'s that aren't before
2145 * the delimiter (expand the variable substitution unless flags
2146 * has VAR_NOSUBST set).
2147 * Return the expanded string or NULL if the delimiter was missing
2148 * If pattern is specified, handle escaped ampersands, and replace
2149 * unescaped ampersands with the lhs of the pattern.
2152 * A string of all the words modified appropriately.
2153 * If length is specified, return the string length of the buffer
2154 * If flags is specified and the last character of the pattern is a
2155 * $ set the VAR_MATCH_END bit of flags.
2159 *-----------------------------------------------------------------------
2162 VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
2163 int errnum, const char **tstr, int delim, int *flags,
2164 int *length, VarPattern *pattern)
2175 #define IS_A_MATCH(cp, delim) \
2176 ((cp[0] == '\\') && ((cp[1] == delim) || \
2177 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
2180 * Skim through until the matching delimiter is found;
2181 * pick up variable substitutions on the way. Also allow
2182 * backslashes to quote the delimiter, $, and \, but don't
2183 * touch other backslashes.
2185 for (cp = *tstr; *cp && (*cp != delim); cp++) {
2186 if (IS_A_MATCH(cp, delim)) {
2187 Buf_AddByte(&buf, cp[1]);
2189 } else if (*cp == '$') {
2190 if (cp[1] == delim) {
2192 Buf_AddByte(&buf, *cp);
2195 * Unescaped $ at end of pattern => anchor
2198 *flags |= VAR_MATCH_END;
2200 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
2206 * If unescaped dollar sign not before the
2207 * delimiter, assume it's a variable
2208 * substitution and recurse.
2210 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2211 Buf_AddBytes(&buf, strlen(cp2), cp2);
2216 const char *cp2 = &cp[1];
2218 if (*cp2 == PROPEN || *cp2 == BROPEN) {
2220 * Find the end of this variable reference
2221 * and suck it in without further ado.
2222 * It will be interperated later.
2225 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
2228 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
2229 if (cp2[-1] != '\\') {
2236 Buf_AddBytes(&buf, cp2 - cp, cp);
2239 Buf_AddByte(&buf, *cp);
2243 else if (pattern && *cp == '&')
2244 Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
2246 Buf_AddByte(&buf, *cp);
2256 *length = Buf_Size(&buf);
2257 rstr = Buf_Destroy(&buf, FALSE);
2259 fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
2264 *-----------------------------------------------------------------------
2266 * Quote shell meta-characters in the string
2274 *-----------------------------------------------------------------------
2281 /* This should cover most shells :-( */
2282 static const char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
2283 const char *newline;
2286 if ((newline = Shell_GetNewline()) == NULL)
2288 nlen = strlen(newline);
2291 while (*str != '\0') {
2292 if ((len = strcspn(str, meta)) != 0) {
2293 Buf_AddBytes(&buf, len, str);
2295 } else if (*str == '\n') {
2296 Buf_AddBytes(&buf, nlen, newline);
2299 Buf_AddByte(&buf, '\\');
2300 Buf_AddByte(&buf, *str);
2304 str = Buf_Destroy(&buf, FALSE);
2306 fprintf(debug_file, "QuoteMeta: [%s]\n", str);
2311 *-----------------------------------------------------------------------
2313 * Hash the string using the MurmurHash3 algorithm.
2314 * Output is computed using 32bit Little Endian arithmetic.
2317 * str String to modify
2320 * Hash value of str, encoded as 8 hex digits.
2325 *-----------------------------------------------------------------------
2330 static const char hexdigits[16] = "0123456789abcdef";
2333 unsigned char *ustr = (unsigned char *)str;
2334 uint32_t h, k, c1, c2;
2341 for (len = len2; len; ) {
2345 k = (ustr[3] << 24) | (ustr[2] << 16) | (ustr[1] << 8) | ustr[0];
2350 k |= (ustr[2] << 16);
2352 k |= (ustr[1] << 8);
2357 c1 = c1 * 5 + 0x7b7d159cU;
2358 c2 = c2 * 5 + 0x6bce6396U;
2360 k = (k << 11) ^ (k >> 21);
2362 h = (h << 13) ^ (h >> 19);
2363 h = h * 5 + 0x52dce729U;
2373 for (len = 0; len < 8; ++len) {
2374 Buf_AddByte(&buf, hexdigits[h & 15]);
2378 return Buf_Destroy(&buf, FALSE);
2382 VarStrftime(const char *fmt, int zulu)
2390 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2392 buf[sizeof(buf) - 1] = '\0';
2393 return bmake_strdup(buf);
2397 * Now we need to apply any modifiers the user wants applied.
2399 * :M<pattern> words which match the given <pattern>.
2400 * <pattern> is of the standard file
2402 * :N<pattern> words which do not match the given <pattern>.
2403 * :S<d><pat1><d><pat2><d>[1gW]
2404 * Substitute <pat2> for <pat1> in the value
2405 * :C<d><pat1><d><pat2><d>[1gW]
2406 * Substitute <pat2> for regex <pat1> in the value
2407 * :H Substitute the head of each word
2408 * :T Substitute the tail of each word
2409 * :E Substitute the extension (minus '.') of
2411 * :R Substitute the root of each word
2412 * (pathname minus the suffix).
2413 * :O ("Order") Alphabeticaly sort words in variable.
2414 * :Ox ("intermiX") Randomize words in variable.
2415 * :u ("uniq") Remove adjacent duplicate words.
2416 * :tu Converts the variable contents to uppercase.
2417 * :tl Converts the variable contents to lowercase.
2418 * :ts[c] Sets varSpace - the char used to
2419 * separate words to 'c'. If 'c' is
2420 * omitted then no separation is used.
2421 * :tW Treat the variable contents as a single
2422 * word, even if it contains spaces.
2423 * (Mnemonic: one big 'W'ord.)
2424 * :tw Treat the variable contents as multiple
2425 * space-separated words.
2426 * (Mnemonic: many small 'w'ords.)
2427 * :[index] Select a single word from the value.
2428 * :[start..end] Select multiple words from the value.
2429 * :[*] or :[0] Select the entire value, as a single
2430 * word. Equivalent to :tW.
2431 * :[@] Select the entire value, as multiple
2432 * words. Undoes the effect of :[*].
2433 * Equivalent to :tw.
2434 * :[#] Returns the number of words in the value.
2436 * :?<true-value>:<false-value>
2437 * If the variable evaluates to true, return
2438 * true value, else return the second value.
2439 * :lhs=rhs Like :S, but the rhs goes to the end of
2441 * :sh Treat the current value as a command
2442 * to be run, new value is its output.
2443 * The following added so we can handle ODE makefiles.
2444 * :@<tmpvar>@<newval>@
2445 * Assign a temporary local variable <tmpvar>
2446 * to the current value of each word in turn
2447 * and replace each word with the result of
2448 * evaluating <newval>
2449 * :D<newval> Use <newval> as value if variable defined
2450 * :U<newval> Use <newval> as value if variable undefined
2451 * :L Use the name of the variable as the value.
2452 * :P Use the path of the node that has the same
2453 * name as the variable as the value. This
2454 * basically includes an implied :L so that
2455 * the common method of refering to the path
2456 * of your dependent 'x' in a rule is to use
2457 * the form '${x:P}'.
2458 * :!<cmd>! Run cmd much the same as :sh run's the
2459 * current value of the variable.
2460 * The ::= modifiers, actually assign a value to the variable.
2461 * Their main purpose is in supporting modifiers of .for loop
2462 * iterators and other obscure uses. They always expand to
2463 * nothing. In a target rule that would otherwise expand to an
2464 * empty line they can be preceded with @: to keep make happy.
2468 * .for i in ${.TARGET} ${.TARGET:R}.gz
2473 * ::=<str> Assigns <str> as the new value of variable.
2474 * ::?=<str> Assigns <str> as value of variable if
2475 * it was not already set.
2476 * ::+=<str> Appends <str> to variable.
2477 * ::!=<cmd> Assigns output of <cmd> as the new value of
2481 /* we now have some modifiers with long names */
2482 #define STRMOD_MATCH(s, want, n) \
2483 (strncmp(s, want, n) == 0 && (s[n] == endc || s[n] == ':'))
2486 ApplyModifiers(char *nstr, const char *tstr,
2487 int startc, int endc,
2488 Var *v, GNode *ctxt, Boolean errnum,
2489 int *lengthPtr, void **freePtr)
2492 const char *cp; /* Secondary pointer into str (place marker
2494 char *newStr; /* New value to return */
2495 char termc; /* Character which terminated scan */
2496 int cnt; /* Used to count brace pairs when variable in
2497 * in parens or braces */
2499 int modifier; /* that we are processing */
2500 Var_Parse_State parsestate; /* Flags passed to helper functions */
2503 parsestate.oneBigWord = FALSE;
2504 parsestate.varSpace = ' '; /* word separator */
2508 while (*tstr && *tstr != endc) {
2512 * We may have some complex modifiers in a variable.
2519 rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
2522 * If we have not parsed up to endc or ':',
2523 * we are not interested.
2525 if (rval != NULL && *rval &&
2526 (c = tstr[rlen]) != '\0' &&
2535 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
2536 rval, rlen, tstr, rlen, tstr + rlen);
2541 if (rval != NULL && *rval) {
2544 nstr = ApplyModifiers(nstr, rval,
2546 v, ctxt, errnum, &used, freePtr);
2547 if (nstr == var_Error
2548 || (nstr == varNoError && errnum == 0)
2549 || strlen(rval) != (size_t) used) {
2552 goto out; /* error already reported */
2559 else if (!*tstr && endc) {
2560 Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name);
2567 fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", v->name,
2571 switch ((modifier = *tstr)) {
2574 if (tstr[1] == '=' ||
2576 (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
2578 * "::=", "::!=", "::+=", or "::?="
2580 GNode *v_ctxt; /* context where v belongs */
2586 if (v->name[0] == 0)
2592 if (v->flags & VAR_JUNK) {
2594 * We need to bmake_strdup() it incase
2595 * VarGetPattern() recurses.
2598 v->name = bmake_strdup(v->name);
2599 } else if (ctxt != VAR_GLOBAL) {
2600 Var *gv = VarFind(v->name, ctxt, 0);
2602 v_ctxt = VAR_GLOBAL;
2604 VarFreeEnv(gv, TRUE);
2607 switch ((how = *tstr)) {
2617 delim = startc == PROPEN ? PRCLOSE : BRCLOSE;
2620 pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2624 if (v->flags & VAR_JUNK) {
2625 /* restore original name */
2629 if (pattern.rhs == NULL)
2637 Var_Append(v->name, pattern.rhs, v_ctxt);
2640 newStr = Cmd_Exec(pattern.rhs, &emsg);
2644 Var_Set(v->name, newStr, v_ctxt, 0);
2649 if ((v->flags & VAR_JUNK) == 0)
2653 Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2656 free(UNCONST(pattern.rhs));
2660 goto default_case; /* "::<unrecognised>" */
2665 int flags = VAR_NOSUBST;
2669 if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum,
2671 &flags, &loop.tvarLen,
2675 if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum,
2677 &flags, &loop.strLen,
2684 loop.errnum = errnum;
2686 newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
2693 #ifdef MAKE_FREEBSD_UL
2697 /* we have to be careful, since :U is used internally */
2698 if (nc == ':' || nc == endc) {
2699 char *dp = bmake_strdup(nstr);
2700 for (newStr = dp; *dp; dp++)
2701 *dp = toupper((unsigned char)*dp);
2704 break; /* yes inside the conditional */
2711 Buffer buf; /* Buffer for patterns */
2712 int wantit; /* want data in buffer */
2715 * Pass through tstr looking for 1) escaped delimiters,
2716 * '$'s and backslashes (place the escaped character in
2717 * uninterpreted) and 2) unescaped $'s that aren't before
2718 * the delimiter (expand the variable substitution).
2719 * The result is left in the Buffer buf.
2723 *cp != endc && *cp != ':' && *cp != '\0';
2725 if ((*cp == '\\') &&
2731 Buf_AddByte(&buf, cp[1]);
2733 } else if (*cp == '$') {
2735 * If unescaped dollar sign, assume it's a
2736 * variable substitution and recurse.
2742 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2743 Buf_AddBytes(&buf, strlen(cp2), cp2);
2748 Buf_AddByte(&buf, *cp);
2755 wantit = ((v->flags & VAR_JUNK) != 0);
2757 wantit = ((v->flags & VAR_JUNK) == 0);
2758 if ((v->flags & VAR_JUNK) != 0)
2759 v->flags |= VAR_KEEP;
2761 newStr = Buf_Destroy(&buf, FALSE);
2764 Buf_Destroy(&buf, TRUE);
2769 #ifdef MAKE_FREEBSD_UL
2771 char *dp = bmake_strdup(nstr);
2772 for (newStr = dp; *dp; dp++)
2773 *dp = tolower((unsigned char)*dp);
2781 if ((v->flags & VAR_JUNK) != 0)
2782 v->flags |= VAR_KEEP;
2783 newStr = bmake_strdup(v->name);
2792 if ((v->flags & VAR_JUNK) != 0)
2793 v->flags |= VAR_KEEP;
2794 gn = Targ_FindNode(v->name, TARG_NOCREATE);
2795 if (gn == NULL || gn->type & OP_NOPATH) {
2797 } else if (gn->path) {
2798 newStr = bmake_strdup(gn->path);
2800 newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
2803 newStr = bmake_strdup(v->name);
2818 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2820 NULL, &pattern.rightLen,
2823 newStr = Cmd_Exec(pattern.rhs, &emsg);
2824 free(UNCONST(pattern.rhs));
2829 if (v->flags & VAR_JUNK) {
2830 v->flags |= VAR_KEEP;
2837 * Look for the closing ']', recursively
2838 * expanding any embedded variables.
2840 * estr is a pointer to the expanded result,
2841 * which we must free().
2845 cp = tstr+1; /* point to char after '[' */
2846 delim = ']'; /* look for closing ']' */
2847 estr = VarGetPattern(ctxt, &parsestate,
2851 goto cleanup; /* report missing ']' */
2852 /* now cp points just after the closing ']' */
2854 if (cp[0] != ':' && cp[0] != endc) {
2855 /* Found junk after ']' */
2859 if (estr[0] == '\0') {
2860 /* Found empty square brackets in ":[]". */
2863 } else if (estr[0] == '#' && estr[1] == '\0') {
2867 * We will need enough space for the decimal
2868 * representation of an int. We calculate the
2869 * space needed for the octal representation,
2870 * and add enough slop to cope with a '-' sign
2871 * (which should never be needed) and a '\0'
2872 * string terminator.
2875 (sizeof(int) * CHAR_BIT + 2) / 3 + 2;
2877 newStr = bmake_malloc(newStrSize);
2878 if (parsestate.oneBigWord) {
2879 strncpy(newStr, "1", newStrSize);
2881 /* XXX: brk_string() is a rather expensive
2882 * way of counting words. */
2887 av = brk_string(nstr, &ac, FALSE, &as);
2888 snprintf(newStr, newStrSize, "%d", ac);
2895 } else if (estr[0] == '*' && estr[1] == '\0') {
2897 parsestate.oneBigWord = TRUE;
2902 } else if (estr[0] == '@' && estr[1] == '\0') {
2904 parsestate.oneBigWord = FALSE;
2911 * We expect estr to contain a single
2912 * integer for :[N], or two integers
2913 * separated by ".." for :[start..end].
2917 VarSelectWords_t seldata = { 0, 0 };
2919 seldata.start = strtol(estr, &ep, 0);
2921 /* Found junk instead of a number */
2924 } else if (ep[0] == '\0') {
2925 /* Found only one integer in :[N] */
2926 seldata.end = seldata.start;
2927 } else if (ep[0] == '.' && ep[1] == '.' &&
2929 /* Expecting another integer after ".." */
2931 seldata.end = strtol(ep, &ep, 0);
2932 if (ep[0] != '\0') {
2933 /* Found junk after ".." */
2938 /* Found junk instead of ".." */
2943 * Now seldata is properly filled in,
2944 * but we still have to check for 0 as
2947 if (seldata.start == 0 && seldata.end == 0) {
2948 /* ":[0]" or perhaps ":[0..0]" */
2949 parsestate.oneBigWord = TRUE;
2954 } else if (seldata.start == 0 ||
2956 /* ":[0..N]" or ":[N..0]" */
2961 * Normal case: select the words
2962 * described by seldata.
2964 newStr = VarSelectWords(ctxt, &parsestate,
2974 cp = tstr + 1; /* make sure it is set */
2975 if (STRMOD_MATCH(tstr, "gmtime", 6)) {
2976 newStr = VarStrftime(nstr, 1);
2984 cp = tstr + 1; /* make sure it is set */
2985 if (STRMOD_MATCH(tstr, "hash", 4)) {
2986 newStr = VarHash(nstr);
2994 cp = tstr + 1; /* make sure it is set */
2995 if (STRMOD_MATCH(tstr, "localtime", 9)) {
2996 newStr = VarStrftime(nstr, 0);
3005 cp = tstr + 1; /* make sure it is set */
3006 if (tstr[1] != endc && tstr[1] != ':') {
3007 if (tstr[1] == 's') {
3009 * Use the char (if any) at tstr[2]
3010 * as the word separator.
3014 if (tstr[2] != endc &&
3015 (tstr[3] == endc || tstr[3] == ':')) {
3016 /* ":ts<unrecognised><endc>" or
3017 * ":ts<unrecognised>:" */
3018 parsestate.varSpace = tstr[2];
3020 } else if (tstr[2] == endc || tstr[2] == ':') {
3021 /* ":ts<endc>" or ":ts:" */
3022 parsestate.varSpace = 0; /* no separator */
3024 } else if (tstr[2] == '\\') {
3027 parsestate.varSpace = '\n';
3031 parsestate.varSpace = '\t';
3035 if (isdigit((unsigned char)tstr[3])) {
3038 parsestate.varSpace =
3039 strtoul(&tstr[3], &ep, 0);
3040 if (*ep != ':' && *ep != endc)
3045 * ":ts<backslash><unrecognised>".
3053 * Found ":ts<unrecognised><unrecognised>".
3061 * We cannot be certain that VarModify
3062 * will be used - even if there is a
3063 * subsequent modifier, so do a no-op
3064 * VarSubstitute now to for str to be
3065 * re-expanded without the spaces.
3067 pattern.flags = VAR_SUB_ONE;
3068 pattern.lhs = pattern.rhs = "\032";
3069 pattern.leftLen = pattern.rightLen = 1;
3071 newStr = VarModify(ctxt, &parsestate, nstr,
3074 } else if (tstr[2] == endc || tstr[2] == ':') {
3076 * Check for two-character options:
3079 if (tstr[1] == 'A') { /* absolute path */
3080 newStr = VarModify(ctxt, &parsestate, nstr,
3084 } else if (tstr[1] == 'u') {
3085 char *dp = bmake_strdup(nstr);
3086 for (newStr = dp; *dp; dp++)
3087 *dp = toupper((unsigned char)*dp);
3090 } else if (tstr[1] == 'l') {
3091 char *dp = bmake_strdup(nstr);
3092 for (newStr = dp; *dp; dp++)
3093 *dp = tolower((unsigned char)*dp);
3096 } else if (tstr[1] == 'W' || tstr[1] == 'w') {
3097 parsestate.oneBigWord = (tstr[1] == 'W');
3102 /* Found ":t<unrecognised>:" or
3103 * ":t<unrecognised><endc>". */
3108 * Found ":t<unrecognised><unrecognised>".
3114 * Found ":t<endc>" or ":t:".
3124 const char *endpat; /* points just after end of pattern */
3126 Boolean copy; /* pattern should be, or has been, copied */
3134 * In the loop below, ignore ':' unless we are at
3135 * (or back to) the original brace level.
3136 * XXX This will likely not work right if $() and ${}
3140 *cp != '\0' && !(*cp == ':' && nest == 1);
3145 cp[1] == endc || cp[1] == startc)) {
3155 if (*cp == '(' || *cp == '{')
3157 if (*cp == ')' || *cp == '}') {
3167 * Need to compress the \:'s out of the pattern, so
3168 * allocate enough room to hold the uncompressed
3169 * pattern (note that cp started at tstr+1, so
3170 * cp - tstr takes the null byte into account) and
3171 * compress the pattern into the space.
3173 pattern = bmake_malloc(cp - tstr);
3174 for (cp2 = pattern, cp = tstr + 1;
3178 if ((*cp == '\\') && (cp+1 < endpat) &&
3179 (cp[1] == ':' || cp[1] == endc)) {
3188 * Either Var_Subst or VarModify will need a
3189 * nul-terminated string soon, so construct one now.
3191 pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
3195 * pattern contains embedded '$', so use Var_Subst to
3199 pattern = Var_Subst(NULL, cp2, ctxt, errnum);
3203 fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
3204 v->name, nstr, pattern);
3206 newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
3209 newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
3218 Var_Parse_State tmpparsestate;
3221 tmpparsestate = parsestate;
3226 * If pattern begins with '^', it is anchored to the
3227 * start of the word -- skip over it and flag pattern.
3230 pattern.flags |= VAR_MATCH_START;
3235 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3242 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3249 * Check for global substitution. If 'g' after the final
3250 * delimiter, substitution is global and is marked that
3256 pattern.flags |= VAR_SUB_GLOBAL;
3259 pattern.flags |= VAR_SUB_ONE;
3262 tmpparsestate.oneBigWord = TRUE;
3269 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3274 * Free the two strings.
3276 free(UNCONST(pattern.lhs));
3277 free(UNCONST(pattern.rhs));
3286 /* find ':', and then substitute accordingly */
3292 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3298 /* BROPEN or PROPEN */
3300 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3308 if (Cond_EvalExpression(NULL, v->name, &value, 0)
3310 Error("Bad conditional expression `%s' in %s?%s:%s",
3311 v->name, v->name, pattern.lhs, pattern.rhs);
3316 newStr = UNCONST(pattern.lhs);
3317 free(UNCONST(pattern.rhs));
3319 newStr = UNCONST(pattern.rhs);
3320 free(UNCONST(pattern.lhs));
3322 if (v->flags & VAR_JUNK) {
3323 v->flags |= VAR_KEEP;
3330 VarREPattern pattern;
3333 Var_Parse_State tmpparsestate;
3336 tmpparsestate = parsestate;
3342 if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim,
3343 NULL, NULL, NULL)) == NULL)
3346 if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
3347 errnum, &cp, delim, NULL,
3348 NULL, NULL)) == NULL){
3356 pattern.flags |= VAR_SUB_GLOBAL;
3359 pattern.flags |= VAR_SUB_ONE;
3362 tmpparsestate.oneBigWord = TRUE;
3370 error = regcomp(&pattern.re, re, REG_EXTENDED);
3373 *lengthPtr = cp - start + 1;
3374 VarREError(error, &pattern.re, "RE substitution error");
3375 free(pattern.replace);
3379 pattern.nsub = pattern.re.re_nsub + 1;
3380 if (pattern.nsub < 1)
3382 if (pattern.nsub > 10)
3384 pattern.matches = bmake_malloc(pattern.nsub *
3385 sizeof(regmatch_t));
3386 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3389 regfree(&pattern.re);
3390 free(pattern.replace);
3391 free(pattern.matches);
3397 if (tstr[1] == endc || tstr[1] == ':') {
3398 newStr = VarQuote(nstr);
3405 if (tstr[1] == endc || tstr[1] == ':') {
3406 newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
3414 if (tstr[1] == endc || tstr[1] == ':') {
3415 newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
3423 if (tstr[1] == endc || tstr[1] == ':') {
3424 newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
3432 if (tstr[1] == endc || tstr[1] == ':') {
3433 newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
3444 cp = tstr + 1; /* skip to the rest in any case */
3445 if (tstr[1] == endc || tstr[1] == ':') {
3448 } else if ( (tstr[1] == 'x') &&
3449 (tstr[2] == endc || tstr[2] == ':') ) {
3456 newStr = VarOrder(nstr, otype);
3460 if (tstr[1] == endc || tstr[1] == ':') {
3461 newStr = VarUniq(nstr);
3469 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
3471 newStr = Cmd_Exec(nstr, &emsg);
3485 * This can either be a bogus modifier or a System-V
3486 * substitution command.
3494 * First we make a pass through the string trying
3495 * to verify it is a SYSV-make-style translation:
3496 * it must be: <string1>=<string2>)
3500 while (*cp != '\0' && cnt) {
3503 /* continue looking for endc */
3505 else if (*cp == endc)
3507 else if (*cp == startc)
3512 if (*cp == endc && eqFound) {
3515 * Now we break this sucker into the lhs and
3516 * rhs. We must null terminate them of course.
3520 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
3521 errnum, &cp, delim, &pattern.flags,
3522 &pattern.leftLen, NULL)) == NULL)
3525 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
3526 errnum, &cp, delim, NULL, &pattern.rightLen,
3531 * SYSV modifications happen through the whole
3532 * string. Note the pattern is anchored at the end.
3536 if (pattern.leftLen == 0 && *nstr == '\0') {
3537 newStr = nstr; /* special case */
3539 newStr = VarModify(ctxt, &parsestate, nstr,
3543 free(UNCONST(pattern.lhs));
3544 free(UNCONST(pattern.rhs));
3548 Error("Unknown modifier '%c'", *tstr);
3550 *cp != ':' && *cp != endc && *cp != '\0';
3559 fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
3560 v->name, modifier, newStr);
3563 if (newStr != nstr) {
3569 if (nstr != var_Error && nstr != varNoError) {
3573 if (termc == '\0' && endc != '\0') {
3574 Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier);
3575 } else if (termc == ':') {
3581 *lengthPtr = tstr - start;
3586 Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
3590 *lengthPtr = cp - start;
3592 Error("Unclosed substitution for %s (%c missing)",
3602 *-----------------------------------------------------------------------
3604 * Given the start of a variable invocation, extract the variable
3605 * name and find its value, then modify it according to the
3609 * str The string to parse
3610 * ctxt The context for the variable
3611 * errnum TRUE if undefined variables are an error
3612 * lengthPtr OUT: The length of the specification
3613 * freePtr OUT: Non-NULL if caller should free *freePtr
3616 * The (possibly-modified) value of the variable or var_Error if the
3617 * specification is invalid. The length of the specification is
3618 * placed in *lengthPtr (for invalid specifications, this is just
3620 * If *freePtr is non-NULL then it's a pointer that the caller
3621 * should pass to free() to free memory used by the result.
3626 *-----------------------------------------------------------------------
3628 /* coverity[+alloc : arg-*4] */
3630 Var_Parse(const char *str, GNode *ctxt, Boolean errnum, int *lengthPtr,
3633 const char *tstr; /* Pointer into str */
3634 Var *v; /* Variable in invocation */
3635 Boolean haveModifier;/* TRUE if have modifiers for the variable */
3636 char endc; /* Ending character when variable in parens
3638 char startc; /* Starting character when variable in parens
3640 int vlen; /* Length of variable name */
3641 const char *start; /* Points to original start of str */
3642 char *nstr; /* New string, used during expansion */
3643 Boolean dynamic; /* TRUE if the variable is local and we're
3644 * expanding it in a non-local context. This
3645 * is done to support dynamic sources. The
3646 * result is just the invocation, unaltered */
3647 Var_Parse_State parsestate; /* Flags passed to helper functions */
3653 parsestate.oneBigWord = FALSE;
3654 parsestate.varSpace = ' '; /* word separator */
3657 if (startc != PROPEN && startc != BROPEN) {
3659 * If it's not bounded by braces of some sort, life is much simpler.
3660 * We just need to check for the first character and return the
3661 * value if it exists.
3664 /* Error out some really stupid names */
3665 if (startc == '\0' || strchr(")}:$", startc)) {
3672 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3676 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
3678 * If substituting a local variable in a non-local context,
3679 * assume it's for dynamic source stuff. We have to handle
3680 * this specially and return the longhand for the variable
3681 * with the dollar sign escaped so it makes it back to the
3682 * caller. Only four of the local variables are treated
3683 * specially as they are the only four that will be set
3684 * when dynamic sources are expanded.
3688 return UNCONST("$(.TARGET)");
3690 return UNCONST("$(.ARCHIVE)");
3692 return UNCONST("$(.PREFIX)");
3694 return UNCONST("$(.MEMBER)");
3700 return (errnum ? var_Error : varNoError);
3702 haveModifier = FALSE;
3707 Buffer buf; /* Holds the variable name */
3709 endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3713 * Skip to the end character or a colon, whichever comes first.
3715 for (tstr = str + 2;
3716 *tstr != '\0' && *tstr != endc && *tstr != ':';
3720 * A variable inside a variable, expand
3725 char *rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
3727 Buf_AddBytes(&buf, strlen(rval), rval);
3734 Buf_AddByte(&buf, *tstr);
3737 haveModifier = TRUE;
3738 } else if (*tstr != '\0') {
3739 haveModifier = FALSE;
3742 * If we never did find the end character, return NULL
3743 * right now, setting the length to be the distance to
3744 * the end of the string, since that's what make does.
3746 *lengthPtr = tstr - str;
3747 Buf_Destroy(&buf, TRUE);
3750 str = Buf_GetAll(&buf, &vlen);
3753 * At this point, str points into newly allocated memory from
3754 * buf, containing only the name of the variable.
3756 * start and tstr point into the const string that was pointed
3757 * to by the original value of the str parameter. start points
3758 * to the '$' at the beginning of the string, while tstr points
3759 * to the char just after the end of the variable name -- this
3760 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3763 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3765 * Check also for bogus D and F forms of local variables since we're
3766 * in a local context and the name is the right length.
3768 if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
3769 (vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
3770 strchr("@%*!<>", str[0]) != NULL) {
3772 * Well, it's local -- go look for it.
3776 v = VarFind(name, ctxt, 0);
3780 * No need for nested expansion or anything, as we're
3781 * the only one who sets these things and we sure don't
3782 * but nested invocations in them...
3784 nstr = Buf_GetAll(&v->val, NULL);
3786 if (str[1] == 'D') {
3787 nstr = VarModify(ctxt, &parsestate, nstr, VarHead,
3790 nstr = VarModify(ctxt, &parsestate, nstr, VarTail,
3794 * Resulting string is dynamically allocated, so
3795 * tell caller to free it.
3798 *lengthPtr = tstr-start+1;
3799 Buf_Destroy(&buf, TRUE);
3800 VarFreeEnv(v, TRUE);
3807 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
3808 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3811 * If substituting a local variable in a non-local context,
3812 * assume it's for dynamic source stuff. We have to handle
3813 * this specially and return the longhand for the variable
3814 * with the dollar sign escaped so it makes it back to the
3815 * caller. Only four of the local variables are treated
3816 * specially as they are the only four that will be set
3817 * when dynamic sources are expanded.
3827 } else if ((vlen > 2) && (*str == '.') &&
3828 isupper((unsigned char) str[1]) &&
3829 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3834 if ((strncmp(str, ".TARGET", len) == 0) ||
3835 (strncmp(str, ".ARCHIVE", len) == 0) ||
3836 (strncmp(str, ".PREFIX", len) == 0) ||
3837 (strncmp(str, ".MEMBER", len) == 0))
3843 if (!haveModifier) {
3845 * No modifiers -- have specification length so we can return
3848 *lengthPtr = tstr - start + 1;
3850 char *pstr = bmake_strndup(start, *lengthPtr);
3852 Buf_Destroy(&buf, TRUE);
3855 Buf_Destroy(&buf, TRUE);
3856 return (errnum ? var_Error : varNoError);
3860 * Still need to get to the end of the variable specification,
3861 * so kludge up a Var structure for the modifications
3863 v = bmake_malloc(sizeof(Var));
3864 v->name = UNCONST(str);
3865 Buf_Init(&v->val, 1);
3866 v->flags = VAR_JUNK;
3867 Buf_Destroy(&buf, FALSE);
3870 Buf_Destroy(&buf, TRUE);
3873 if (v->flags & VAR_IN_USE) {
3874 Fatal("Variable %s is recursive.", v->name);
3877 v->flags |= VAR_IN_USE;
3880 * Before doing any modification, we have to make sure the value
3881 * has been fully expanded. If it looks like recursion might be
3882 * necessary (there's a dollar sign somewhere in the variable's value)
3883 * we just call Var_Subst to do any other substitutions that are
3884 * necessary. Note that the value returned by Var_Subst will have
3885 * been dynamically-allocated, so it will need freeing when we
3888 nstr = Buf_GetAll(&v->val, NULL);
3889 if (strchr(nstr, '$') != NULL) {
3890 nstr = Var_Subst(NULL, nstr, ctxt, errnum);
3894 v->flags &= ~VAR_IN_USE;
3896 if ((nstr != NULL) && haveModifier) {
3899 * Skip initial colon.
3903 nstr = ApplyModifiers(nstr, tstr, startc, endc,
3904 v, ctxt, errnum, &used, freePtr);
3908 *lengthPtr = tstr - start + 1;
3910 *lengthPtr = tstr - start;
3913 if (v->flags & VAR_FROM_ENV) {
3914 Boolean destroy = FALSE;
3916 if (nstr != Buf_GetAll(&v->val, NULL)) {
3920 * Returning the value unmodified, so tell the caller to free
3925 VarFreeEnv(v, destroy);
3926 } else if (v->flags & VAR_JUNK) {
3928 * Perform any free'ing needed and set *freePtr to NULL so the caller
3929 * doesn't try to free a static pointer.
3930 * If VAR_KEEP is also set then we want to keep str as is.
3932 if (!(v->flags & VAR_KEEP)) {
3938 nstr = bmake_strndup(start, *lengthPtr);
3941 nstr = errnum ? var_Error : varNoError;
3944 if (nstr != Buf_GetAll(&v->val, NULL))
3945 Buf_Destroy(&v->val, TRUE);
3953 *-----------------------------------------------------------------------
3955 * Substitute for all variables in the given string in the given context
3956 * If undefErr is TRUE, Parse_Error will be called when an undefined
3957 * variable is encountered.
3960 * var Named variable || NULL for all
3961 * str the string which to substitute
3962 * ctxt the context wherein to find variables
3963 * undefErr TRUE if undefineds are an error
3966 * The resulting string.
3969 * None. The old string must be freed by the caller
3970 *-----------------------------------------------------------------------
3973 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
3975 Buffer buf; /* Buffer for forming things */
3976 char *val; /* Value to substitute for a variable */
3977 int length; /* Length of the variable invocation */
3978 Boolean trailingBslash; /* variable ends in \ */
3979 void *freeIt = NULL; /* Set if it should be freed */
3980 static Boolean errorReported; /* Set true if an error has already
3981 * been reported to prevent a plethora
3982 * of messages when recursing */
3985 errorReported = FALSE;
3986 trailingBslash = FALSE;
3989 if (*str == '\n' && trailingBslash)
3990 Buf_AddByte(&buf, ' ');
3991 if (var == NULL && (*str == '$') && (str[1] == '$')) {
3993 * A dollar sign may be escaped either with another dollar sign.
3994 * In such a case, we skip over the escape character and store the
3995 * dollar sign into the buffer directly.
3998 Buf_AddByte(&buf, *str);
4000 } else if (*str != '$') {
4002 * Skip as many characters as possible -- either to the end of
4003 * the string or to the next dollar sign (variable invocation).
4007 for (cp = str++; *str != '$' && *str != '\0'; str++)
4009 Buf_AddBytes(&buf, str - cp, cp);
4014 if (str[1] == '\0') {
4015 /* A trailing $ is kind of a special case */
4016 Buf_AddByte(&buf, str[0]);
4019 } else if (str[1] != PROPEN && str[1] != BROPEN) {
4020 if (str[1] != *var || strlen(var) > 1) {
4021 Buf_AddBytes(&buf, 2, str);
4033 * Scan up to the end of the variable name.
4035 for (p = &str[2]; *p &&
4036 *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
4040 * A variable inside the variable. We cannot expand
4041 * the external variable yet, so we try again with
4045 Buf_AddBytes(&buf, p - str, str);
4050 if (strncmp(var, str + 2, p - str - 2) != 0 ||
4051 var[p - str - 2] != '\0') {
4053 * Not the variable we want to expand, scan
4054 * until the next variable
4056 for (;*p != '$' && *p != '\0'; p++)
4058 Buf_AddBytes(&buf, p - str, str);
4071 val = Var_Parse(str, ctxt, undefErr, &length, &freeIt);
4074 * When we come down here, val should either point to the
4075 * value of this variable, suitably modified, or be NULL.
4076 * Length should be the total length of the potential
4077 * variable invocation (from $ to end character...)
4079 if (val == var_Error || val == varNoError) {
4081 * If performing old-time variable substitution, skip over
4082 * the variable and continue with the substitution. Otherwise,
4083 * store the dollar sign and advance str so we continue with
4088 } else if (undefErr) {
4090 * If variable is undefined, complain and skip the
4091 * variable. The complaint will stop us from doing anything
4092 * when the file is parsed.
4094 if (!errorReported) {
4095 Parse_Error(PARSE_FATAL,
4096 "Undefined variable \"%.*s\"",length,str);
4099 errorReported = TRUE;
4101 Buf_AddByte(&buf, *str);
4106 * We've now got a variable structure to store in. But first,
4107 * advance the string pointer.
4112 * Copy all the characters from the variable value straight
4113 * into the new string.
4115 length = strlen(val);
4116 Buf_AddBytes(&buf, length, val);
4117 trailingBslash = length > 0 && val[length - 1] == '\\';
4126 return Buf_DestroyCompact(&buf);
4130 *-----------------------------------------------------------------------
4132 * Return the tail from each of a list of words. Used to set the
4133 * System V local variables.
4136 * file Filename to modify
4139 * The resulting string.
4144 *-----------------------------------------------------------------------
4148 Var_GetTail(char *file)
4150 return(VarModify(file, VarTail, NULL));
4154 *-----------------------------------------------------------------------
4156 * Find the leading components of a (list of) filename(s).
4157 * XXX: VarHead does not replace foo by ., as (sun) System V make
4161 * file Filename to manipulate
4164 * The leading components.
4169 *-----------------------------------------------------------------------
4172 Var_GetHead(char *file)
4174 return(VarModify(file, VarHead, NULL));
4179 *-----------------------------------------------------------------------
4181 * Initialize the module
4187 * The VAR_CMD and VAR_GLOBAL contexts are created
4188 *-----------------------------------------------------------------------
4193 VAR_INTERNAL = Targ_NewGN("Internal");
4194 VAR_GLOBAL = Targ_NewGN("Global");
4195 VAR_CMD = Targ_NewGN("Command");
4206 /****************** PRINT DEBUGGING INFO *****************/
4208 VarPrintVar(void *vp)
4211 fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
4215 *-----------------------------------------------------------------------
4217 * print all variables in a context
4218 *-----------------------------------------------------------------------
4221 Var_Dump(GNode *ctxt)
4226 for (h = Hash_EnumFirst(&ctxt->context, &search);
4228 h = Hash_EnumNext(&search)) {
4229 VarPrintVar(Hash_GetValue(h));