1 /* $NetBSD: var.c,v 1.175 2013/05/29 00:23:31 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.175 2013/05/29 00:23:31 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.175 2013/05/29 00:23:31 sjg Exp $");
86 * Variable-handling functions
89 * Var_Set Set the value of a variable in the given
90 * context. The variable is created if it doesn't
91 * yet exist. The value and variable name need not
94 * Var_Append Append more characters to an existing variable
95 * in the given context. The variable needn't
96 * exist already -- it will be created if it doesn't.
97 * A space is placed between the old value and the
100 * Var_Exists See if a variable exists.
102 * Var_Value Return the value of a variable in a context or
103 * NULL if the variable is undefined.
105 * Var_Subst Substitute named variable, or all variables if
106 * NULL in a string using
107 * the given context as the top-most one. If the
108 * third argument is non-zero, Parse_Error is
109 * called if any variables are undefined.
111 * Var_Parse Parse a variable expansion from a string and
112 * return the result and the number of characters
115 * Var_Delete Delete a variable in a context.
117 * Var_Init Initialize this module.
120 * Var_Dump Print out all variables defined in the given
123 * XXX: There's a lot of duplication in these functions.
126 #include <sys/stat.h>
128 #include <sys/types.h>
132 #include <inttypes.h>
143 * XXX transition hack for FreeBSD ports.
144 * bsd.port.mk can set .MAKE.FreeBSD_UL=yes
145 * to cause us to treat :[LU] as aliases for :t[lu]
146 * To be reverted when ports converts to :t[lu] (when 8.3 is EOL)
148 #define MAKE_FREEBSD_UL ".MAKE.FreeBSD_UL"
149 #ifdef MAKE_FREEBSD_UL
150 static int FreeBSD_UL = FALSE;
154 * This lets us tell if we have replaced the original environ
155 * (which we cannot free).
157 char **savedEnv = NULL;
160 * This is a harmless return value for Var_Parse that can be used by Var_Subst
161 * to determine if there was an error in parsing -- easier than returning
162 * a flag, as things outside this module don't give a hoot.
164 char var_Error[] = "";
167 * Similar to var_Error, but returned when the 'errnum' flag for Var_Parse is
168 * set false. Why not just use a constant? Well, gcc likes to condense
169 * identical string instances...
171 static char varNoError[] = "";
174 * Internally, variables are contained in four different contexts.
175 * 1) the environment. They may not be changed. If an environment
176 * variable is appended-to, the result is placed in the global
178 * 2) the global context. Variables set in the Makefile are located in
179 * the global context. It is the penultimate context searched when
181 * 3) the command-line context. All variables set on the command line
182 * are placed in this context. They are UNALTERABLE once placed here.
183 * 4) the local context. Each target has associated with it a context
184 * list. On this list are located the structures describing such
185 * local variables as $(@) and $(*)
186 * The four contexts are searched in the reverse order from which they are
189 GNode *VAR_GLOBAL; /* variables from the makefile */
190 GNode *VAR_CMD; /* variables defined on the command-line */
192 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
193 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
194 #define FIND_ENV 0x4 /* look in the environment also */
197 char *name; /* the variable's name */
198 Buffer val; /* its value */
199 int flags; /* miscellaneous status flags */
200 #define VAR_IN_USE 1 /* Variable's value currently being used.
201 * Used to avoid recursion */
202 #define VAR_FROM_ENV 2 /* Variable comes from the environment */
203 #define VAR_JUNK 4 /* Variable is a junk variable that
204 * should be destroyed when done with
205 * it. Used by Var_Parse for undefined,
206 * modified variables */
207 #define VAR_KEEP 8 /* Variable is VAR_JUNK, but we found
208 * a use for it in some modifier and
209 * the value is therefore valid */
210 #define VAR_EXPORTED 16 /* Variable is exported */
211 #define VAR_REEXPORT 32 /* Indicate if var needs re-export.
212 * This would be true if it contains $'s
214 #define VAR_FROM_CMD 64 /* Variable came from command line */
218 * Exporting vars is expensive so skip it if we can
220 #define VAR_EXPORTED_NONE 0
221 #define VAR_EXPORTED_YES 1
222 #define VAR_EXPORTED_ALL 2
223 static int var_exportedVars = VAR_EXPORTED_NONE;
225 * We pass this to Var_Export when doing the initial export
226 * or after updating an exported var.
228 #define VAR_EXPORT_PARENT 1
230 /* Var*Pattern flags */
231 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
232 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
233 #define VAR_SUB_MATCHED 0x04 /* There was a match */
234 #define VAR_MATCH_START 0x08 /* Match at start of word */
235 #define VAR_MATCH_END 0x10 /* Match at end of word */
236 #define VAR_NOSUBST 0x20 /* don't expand vars in VarGetPattern */
239 #define VAR_NO_EXPORT 0x01 /* do not export */
243 * The following fields are set by Var_Parse() when it
244 * encounters modifiers that need to keep state for use by
245 * subsequent modifiers within the same variable expansion.
247 Byte varSpace; /* Word separator in expansions */
248 Boolean oneBigWord; /* TRUE if we will treat the variable as a
249 * single big word, even if it contains
250 * embedded spaces (as opposed to the
251 * usual behaviour of treating it as
252 * several space-separated words). */
255 /* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/",
256 * to VarSYSVMatch() for ":lhs=rhs". */
258 const char *lhs; /* String to match */
259 int leftLen; /* Length of string */
260 const char *rhs; /* Replacement string (w/ &'s removed) */
261 int rightLen; /* Length of replacement */
265 /* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */
267 GNode *ctxt; /* variable context */
268 char *tvar; /* name of temp var */
270 char *str; /* string to expand */
272 int errnum; /* errnum for not defined */
276 /* struct passed as 'void *' to VarRESubstitute() for ":C///" */
286 /* struct passed to VarSelectWords() for ":[start..end]" */
288 int start; /* first word to select */
289 int end; /* last word to select */
292 static Var *VarFind(const char *, GNode *, int);
293 static void VarAdd(const char *, const char *, GNode *);
294 static Boolean VarHead(GNode *, Var_Parse_State *,
295 char *, Boolean, Buffer *, void *);
296 static Boolean VarTail(GNode *, Var_Parse_State *,
297 char *, Boolean, Buffer *, void *);
298 static Boolean VarSuffix(GNode *, Var_Parse_State *,
299 char *, Boolean, Buffer *, void *);
300 static Boolean VarRoot(GNode *, Var_Parse_State *,
301 char *, Boolean, Buffer *, void *);
302 static Boolean VarMatch(GNode *, Var_Parse_State *,
303 char *, Boolean, Buffer *, void *);
305 static Boolean VarSYSVMatch(GNode *, Var_Parse_State *,
306 char *, Boolean, Buffer *, void *);
308 static Boolean VarNoMatch(GNode *, Var_Parse_State *,
309 char *, Boolean, Buffer *, void *);
311 static void VarREError(int, regex_t *, const char *);
312 static Boolean VarRESubstitute(GNode *, Var_Parse_State *,
313 char *, Boolean, Buffer *, void *);
315 static Boolean VarSubstitute(GNode *, Var_Parse_State *,
316 char *, Boolean, Buffer *, void *);
317 static Boolean VarLoopExpand(GNode *, Var_Parse_State *,
318 char *, Boolean, Buffer *, void *);
319 static char *VarGetPattern(GNode *, Var_Parse_State *,
320 int, const char **, int, int *, int *,
322 static char *VarQuote(char *);
323 static char *VarHash(char *);
324 static char *VarModify(GNode *, Var_Parse_State *,
326 Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *),
328 static char *VarOrder(const char *, const char);
329 static char *VarUniq(const char *);
330 static int VarWordCompare(const void *, const void *);
331 static void VarPrintVar(void *);
339 *-----------------------------------------------------------------------
341 * Find the given variable in the given context and any other contexts
346 * ctxt context in which to find it
347 * flags FIND_GLOBAL set means to look in the
348 * VAR_GLOBAL context as well. FIND_CMD set means
349 * to look in the VAR_CMD context also. FIND_ENV
350 * set means to look in the environment
353 * A pointer to the structure describing the desired variable or
354 * NULL if the variable does not exist.
358 *-----------------------------------------------------------------------
361 VarFind(const char *name, GNode *ctxt, int flags)
367 * If the variable name begins with a '.', it could very well be one of
368 * the local ones. We check the name against all the local variables
369 * and substitute the short version in for 'name' if it matches one of
372 if (*name == '.' && isupper((unsigned char) name[1]))
375 if (!strcmp(name, ".ALLSRC"))
377 if (!strcmp(name, ".ARCHIVE"))
381 if (!strcmp(name, ".IMPSRC"))
385 if (!strcmp(name, ".MEMBER"))
389 if (!strcmp(name, ".OODATE"))
393 if (!strcmp(name, ".PREFIX"))
397 if (!strcmp(name, ".TARGET"))
402 /* for compatibility with gmake */
403 if (name[0] == '^' && name[1] == '\0')
408 * First look for the variable in the given context. If it's not there,
409 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
410 * depending on the FIND_* flags in 'flags'
412 var = Hash_FindEntry(&ctxt->context, name);
414 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
415 var = Hash_FindEntry(&VAR_CMD->context, name);
417 if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
418 (ctxt != VAR_GLOBAL))
420 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
422 if ((var == NULL) && (flags & FIND_ENV)) {
425 if ((env = getenv(name)) != NULL) {
428 v = bmake_malloc(sizeof(Var));
429 v->name = bmake_strdup(name);
433 Buf_Init(&v->val, len + 1);
434 Buf_AddBytes(&v->val, len, env);
436 v->flags = VAR_FROM_ENV;
438 } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
439 (ctxt != VAR_GLOBAL))
441 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
445 return ((Var *)Hash_GetValue(var));
450 } else if (var == NULL) {
453 return ((Var *)Hash_GetValue(var));
458 *-----------------------------------------------------------------------
460 * If the variable is an environment variable, free it
464 * destroy true if the value buffer should be destroyed.
467 * 1 if it is an environment variable 0 ow.
470 * The variable is free'ed if it is an environent variable.
471 *-----------------------------------------------------------------------
474 VarFreeEnv(Var *v, Boolean destroy)
476 if ((v->flags & VAR_FROM_ENV) == 0)
479 Buf_Destroy(&v->val, destroy);
485 *-----------------------------------------------------------------------
487 * Add a new variable of name name and value val to the given context
490 * name name of variable to add
491 * val value to set it to
492 * ctxt context in which to set it
498 * The new variable is placed at the front of the given context
499 * The name and val arguments are duplicated so they may
501 *-----------------------------------------------------------------------
504 VarAdd(const char *name, const char *val, GNode *ctxt)
510 v = bmake_malloc(sizeof(Var));
512 len = val ? strlen(val) : 0;
513 Buf_Init(&v->val, len+1);
514 Buf_AddBytes(&v->val, len, val);
518 h = Hash_CreateEntry(&ctxt->context, name, NULL);
522 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
527 *-----------------------------------------------------------------------
529 * Remove a variable from a context.
535 * The Var structure is removed and freed.
537 *-----------------------------------------------------------------------
540 Var_Delete(const char *name, GNode *ctxt)
545 if (strchr(name, '$')) {
546 cp = Var_Subst(NULL, name, VAR_GLOBAL, 0);
550 ln = Hash_FindEntry(&ctxt->context, cp);
552 fprintf(debug_file, "%s:delete %s%s\n",
553 ctxt->name, cp, ln ? "" : " (not found)");
561 v = (Var *)Hash_GetValue(ln);
562 if ((v->flags & VAR_EXPORTED)) {
565 if (strcmp(MAKE_EXPORTED, v->name) == 0) {
566 var_exportedVars = VAR_EXPORTED_NONE;
568 if (v->name != ln->name)
570 Hash_DeleteEntry(&ctxt->context, ln);
571 Buf_Destroy(&v->val, TRUE);
579 * We ignore make internal variables (those which start with '.')
580 * Also we jump through some hoops to avoid calling setenv
581 * more than necessary since it can leak.
582 * We only manipulate flags of vars if 'parent' is set.
585 Var_Export1(const char *name, int parent)
593 return 0; /* skip internals */
597 * If it is one of the vars that should only appear in
598 * local context, skip it, else we can get Var_Subst
609 v = VarFind(name, VAR_GLOBAL, 0);
614 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
615 return 0; /* nothing to do */
617 val = Buf_GetAll(&v->val, NULL);
618 if (strchr(val, '$')) {
621 * Flag this as something we need to re-export.
622 * No point actually exporting it now though,
623 * the child can do it at the last minute.
625 v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
628 if (v->flags & VAR_IN_USE) {
630 * We recursed while exporting in a child.
631 * This isn't going to end well, just skip it.
635 n = snprintf(tmp, sizeof(tmp), "${%s}", name);
636 if (n < (int)sizeof(tmp)) {
637 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
638 setenv(name, val, 1);
643 v->flags &= ~VAR_REEXPORT; /* once will do */
645 if (parent || !(v->flags & VAR_EXPORTED)) {
646 setenv(name, val, 1);
650 * This is so Var_Set knows to call Var_Export again...
653 v->flags |= VAR_EXPORTED;
659 * This gets called from our children.
671 if (VAR_EXPORTED_NONE == var_exportedVars)
674 if (VAR_EXPORTED_ALL == var_exportedVars) {
676 * Ouch! This is crazy...
678 for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
680 var = Hash_EnumNext(&state)) {
681 v = (Var *)Hash_GetValue(var);
682 Var_Export1(v->name, 0);
687 * We have a number of exported vars,
689 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
690 if (n < (int)sizeof(tmp)) {
696 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
697 av = brk_string(val, &ac, FALSE, &as);
698 for (i = 0; i < ac; i++) {
699 Var_Export1(av[i], 0);
708 * This is called when .export is seen or
709 * .MAKE.EXPORTED is modified.
710 * It is also called when any exported var is modified.
713 Var_Export(char *str, int isExport)
723 if (isExport && (!str || !str[0])) {
724 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
728 if (strncmp(str, "-env", 4) == 0) {
732 track = VAR_EXPORT_PARENT;
734 val = Var_Subst(NULL, str, VAR_GLOBAL, 0);
735 av = brk_string(val, &ac, FALSE, &as);
736 for (i = 0; i < ac; i++) {
741 * If it is one of the vars that should only appear in
742 * local context, skip it, else we can get Var_Subst
753 if (Var_Export1(name, track)) {
754 if (VAR_EXPORTED_ALL != var_exportedVars)
755 var_exportedVars = VAR_EXPORTED_YES;
756 if (isExport && track) {
757 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
768 * This is called when .unexport[-env] is seen.
770 extern char **environ;
773 Var_UnExport(char *str)
778 Boolean unexport_env;
781 if (!str || !str[0]) {
782 return; /* assert? */
788 unexport_env = (strncmp(str, "-env", 4) == 0);
792 cp = getenv(MAKE_LEVEL); /* we should preserve this */
793 if (environ == savedEnv) {
794 /* we have been here before! */
795 newenv = bmake_realloc(environ, 2 * sizeof(char *));
801 newenv = bmake_malloc(2 * sizeof(char *));
805 /* Note: we cannot safely free() the original environ. */
806 environ = savedEnv = newenv;
809 setenv(MAKE_LEVEL, cp, 1);
810 #ifdef MAKE_LEVEL_SAFE
811 setenv(MAKE_LEVEL_SAFE, cp, 1);
814 for (; *str != '\n' && isspace((unsigned char) *str); str++)
816 if (str[0] && str[0] != '\n') {
822 /* Using .MAKE.EXPORTED */
823 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
824 if (n < (int)sizeof(tmp)) {
825 vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
835 av = brk_string(vlist, &ac, FALSE, &as);
836 for (i = 0; i < ac; i++) {
837 v = VarFind(av[i], VAR_GLOBAL, 0);
841 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
844 v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT);
846 * If we are unexporting a list,
847 * remove each one from .MAKE.EXPORTED.
848 * If we are removing them all,
849 * just delete .MAKE.EXPORTED below.
852 n = snprintf(tmp, sizeof(tmp),
853 "${" MAKE_EXPORTED ":N%s}", v->name);
854 if (n < (int)sizeof(tmp)) {
855 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
856 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0);
864 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
871 *-----------------------------------------------------------------------
873 * Set the variable name to the value val in the given context.
876 * name name of variable to set
877 * val value to give to the variable
878 * ctxt context in which to set it
884 * If the variable doesn't yet exist, a new record is created for it.
885 * Else the old value is freed and the new one stuck in its place
888 * The variable is searched for only in its context before being
889 * created in that context. I.e. if the context is VAR_GLOBAL,
890 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
891 * VAR_CMD->context is searched. This is done to avoid the literally
892 * thousands of unnecessary strcmp's that used to be done to
893 * set, say, $(@) or $(<).
894 * If the context is VAR_GLOBAL though, we check if the variable
895 * was set in VAR_CMD from the command line and skip it if so.
896 *-----------------------------------------------------------------------
899 Var_Set(const char *name, const char *val, GNode *ctxt, int flags)
902 char *expanded_name = NULL;
905 * We only look for a variable in the given context since anything set
906 * here will override anything in a lower context, so there's not much
907 * point in searching them all just to save a bit of memory...
909 if (strchr(name, '$') != NULL) {
910 expanded_name = Var_Subst(NULL, name, ctxt, 0);
911 if (expanded_name[0] == 0) {
913 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
914 "name expands to empty string - ignored\n",
920 name = expanded_name;
922 if (ctxt == VAR_GLOBAL) {
923 v = VarFind(name, VAR_CMD, 0);
925 if ((v->flags & VAR_FROM_CMD)) {
927 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
934 v = VarFind(name, ctxt, 0);
936 VarAdd(name, val, ctxt);
939 Buf_AddBytes(&v->val, strlen(val), val);
942 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
944 if ((v->flags & VAR_EXPORTED)) {
945 Var_Export1(name, VAR_EXPORT_PARENT);
949 * Any variables given on the command line are automatically exported
950 * to the environment (as per POSIX standard)
952 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
954 /* we just added it */
955 v = VarFind(name, ctxt, 0);
958 v->flags |= VAR_FROM_CMD;
960 * If requested, don't export these in the environment
961 * individually. We still put them in MAKEOVERRIDES so
962 * that the command-line settings continue to override
965 if (varNoExportEnv != TRUE)
966 setenv(name, val, 1);
968 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
971 * Another special case.
972 * Several make's support this sort of mechanism for tracking
973 * recursion - but each uses a different name.
974 * We allow the makefiles to update .MAKE.LEVEL and ensure
975 * children see a correctly incremented value.
977 if (ctxt == VAR_GLOBAL && strcmp(MAKE_LEVEL, name) == 0) {
982 snprintf(tmp, sizeof(tmp), "%u", level + 1);
983 setenv(MAKE_LEVEL, tmp, 1);
984 #ifdef MAKE_LEVEL_SAFE
985 setenv(MAKE_LEVEL_SAFE, tmp, 1);
988 #ifdef MAKE_FREEBSD_UL
989 if (strcmp(MAKE_FREEBSD_UL, name) == 0) {
990 FreeBSD_UL = getBoolean(MAKE_FREEBSD_UL, FALSE);
996 if (expanded_name != NULL)
1003 *-----------------------------------------------------------------------
1005 * The variable of the given name has the given value appended to it in
1006 * the given context.
1009 * name name of variable to modify
1010 * val String to append to it
1011 * ctxt Context in which this should occur
1017 * If the variable doesn't exist, it is created. Else the strings
1018 * are concatenated (with a space in between).
1021 * Only if the variable is being sought in the global context is the
1022 * environment searched.
1023 * XXX: Knows its calling circumstances in that if called with ctxt
1024 * an actual target, it will only search that context since only
1025 * a local variable could be being appended to. This is actually
1026 * a big win and must be tolerated.
1027 *-----------------------------------------------------------------------
1030 Var_Append(const char *name, const char *val, GNode *ctxt)
1034 char *expanded_name = NULL;
1036 if (strchr(name, '$') != NULL) {
1037 expanded_name = Var_Subst(NULL, name, ctxt, 0);
1038 if (expanded_name[0] == 0) {
1040 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
1041 "name expands to empty string - ignored\n",
1044 free(expanded_name);
1047 name = expanded_name;
1050 v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
1053 VarAdd(name, val, ctxt);
1055 Buf_AddByte(&v->val, ' ');
1056 Buf_AddBytes(&v->val, strlen(val), val);
1059 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
1060 Buf_GetAll(&v->val, NULL));
1063 if (v->flags & VAR_FROM_ENV) {
1065 * If the original variable came from the environment, we
1066 * have to install it in the global context (we could place
1067 * it in the environment, but then we should provide a way to
1068 * export other variables...)
1070 v->flags &= ~VAR_FROM_ENV;
1071 h = Hash_CreateEntry(&ctxt->context, name, NULL);
1072 Hash_SetValue(h, v);
1075 if (expanded_name != NULL)
1076 free(expanded_name);
1080 *-----------------------------------------------------------------------
1082 * See if the given variable exists.
1085 * name Variable to find
1086 * ctxt Context in which to start search
1089 * TRUE if it does, FALSE if it doesn't
1094 *-----------------------------------------------------------------------
1097 Var_Exists(const char *name, GNode *ctxt)
1102 if ((cp = strchr(name, '$')) != NULL) {
1103 cp = Var_Subst(NULL, name, ctxt, FALSE);
1105 v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
1112 (void)VarFreeEnv(v, TRUE);
1118 *-----------------------------------------------------------------------
1120 * Return the value of the named variable in the given context
1124 * ctxt context in which to search for it
1127 * The value if the variable exists, NULL if it doesn't
1131 *-----------------------------------------------------------------------
1134 Var_Value(const char *name, GNode *ctxt, char **frp)
1138 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1141 char *p = (Buf_GetAll(&v->val, NULL));
1142 if (VarFreeEnv(v, FALSE))
1151 *-----------------------------------------------------------------------
1153 * Remove the tail of the given word and place the result in the given
1158 * addSpace True if need to add a space to the buffer
1159 * before sticking in the head
1160 * buf Buffer in which to store it
1163 * TRUE if characters were added to the buffer (a space needs to be
1164 * added to the buffer before the next word).
1167 * The trimmed word is added to the buffer.
1169 *-----------------------------------------------------------------------
1172 VarHead(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1173 char *word, Boolean addSpace, Buffer *buf,
1178 slash = strrchr(word, '/');
1179 if (slash != NULL) {
1180 if (addSpace && vpstate->varSpace) {
1181 Buf_AddByte(buf, vpstate->varSpace);
1184 Buf_AddBytes(buf, strlen(word), word);
1189 * If no directory part, give . (q.v. the POSIX standard)
1191 if (addSpace && vpstate->varSpace)
1192 Buf_AddByte(buf, vpstate->varSpace);
1193 Buf_AddByte(buf, '.');
1195 return(dummy ? TRUE : TRUE);
1199 *-----------------------------------------------------------------------
1201 * Remove the head of the given word and place the result in the given
1206 * addSpace True if need to add a space to the buffer
1207 * before adding the tail
1208 * buf Buffer in which to store it
1211 * TRUE if characters were added to the buffer (a space needs to be
1212 * added to the buffer before the next word).
1215 * The trimmed word is added to the buffer.
1217 *-----------------------------------------------------------------------
1220 VarTail(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1221 char *word, Boolean addSpace, Buffer *buf,
1226 if (addSpace && vpstate->varSpace) {
1227 Buf_AddByte(buf, vpstate->varSpace);
1230 slash = strrchr(word, '/');
1231 if (slash != NULL) {
1233 Buf_AddBytes(buf, strlen(slash), slash);
1236 Buf_AddBytes(buf, strlen(word), word);
1238 return (dummy ? TRUE : TRUE);
1242 *-----------------------------------------------------------------------
1244 * Place the suffix of the given word in the given buffer.
1248 * addSpace TRUE if need to add a space before placing the
1249 * suffix in the buffer
1250 * buf Buffer in which to store it
1253 * TRUE if characters were added to the buffer (a space needs to be
1254 * added to the buffer before the next word).
1257 * The suffix from the word is placed in the buffer.
1259 *-----------------------------------------------------------------------
1262 VarSuffix(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1263 char *word, Boolean addSpace, Buffer *buf,
1268 dot = strrchr(word, '.');
1270 if (addSpace && vpstate->varSpace) {
1271 Buf_AddByte(buf, vpstate->varSpace);
1274 Buf_AddBytes(buf, strlen(dot), dot);
1278 return (dummy ? addSpace : addSpace);
1282 *-----------------------------------------------------------------------
1284 * Remove the suffix of the given word and place the result in the
1289 * addSpace TRUE if need to add a space to the buffer
1290 * before placing the root in it
1291 * buf Buffer in which to store it
1294 * TRUE if characters were added to the buffer (a space needs to be
1295 * added to the buffer before the next word).
1298 * The trimmed word is added to the buffer.
1300 *-----------------------------------------------------------------------
1303 VarRoot(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1304 char *word, Boolean addSpace, Buffer *buf,
1309 if (addSpace && vpstate->varSpace) {
1310 Buf_AddByte(buf, vpstate->varSpace);
1313 dot = strrchr(word, '.');
1316 Buf_AddBytes(buf, strlen(word), word);
1319 Buf_AddBytes(buf, strlen(word), word);
1321 return (dummy ? TRUE : TRUE);
1325 *-----------------------------------------------------------------------
1327 * Place the word in the buffer if it matches the given pattern.
1328 * Callback function for VarModify to implement the :M modifier.
1331 * word Word to examine
1332 * addSpace TRUE if need to add a space to the buffer
1333 * before adding the word, if it matches
1334 * buf Buffer in which to store it
1335 * pattern Pattern the word must match
1338 * TRUE if a space should be placed in the buffer before the next
1342 * The word may be copied to the buffer.
1344 *-----------------------------------------------------------------------
1347 VarMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1348 char *word, Boolean addSpace, Buffer *buf,
1352 fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
1353 if (Str_Match(word, (char *)pattern)) {
1354 if (addSpace && vpstate->varSpace) {
1355 Buf_AddByte(buf, vpstate->varSpace);
1358 Buf_AddBytes(buf, strlen(word), word);
1365 *-----------------------------------------------------------------------
1367 * Place the word in the buffer if it matches the given pattern.
1368 * Callback function for VarModify to implement the System V %
1372 * word Word to examine
1373 * addSpace TRUE if need to add a space to the buffer
1374 * before adding the word, if it matches
1375 * buf Buffer in which to store it
1376 * patp Pattern the word must match
1379 * TRUE if a space should be placed in the buffer before the next
1383 * The word may be copied to the buffer.
1385 *-----------------------------------------------------------------------
1388 VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
1389 char *word, Boolean addSpace, Buffer *buf,
1394 VarPattern *pat = (VarPattern *)patp;
1397 if (addSpace && vpstate->varSpace)
1398 Buf_AddByte(buf, vpstate->varSpace);
1402 if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
1403 varexp = Var_Subst(NULL, pat->rhs, ctx, 0);
1404 Str_SYSVSubst(buf, varexp, ptr, len);
1407 Buf_AddBytes(buf, strlen(word), word);
1416 *-----------------------------------------------------------------------
1418 * Place the word in the buffer if it doesn't match the given pattern.
1419 * Callback function for VarModify to implement the :N modifier.
1422 * word Word to examine
1423 * addSpace TRUE if need to add a space to the buffer
1424 * before adding the word, if it matches
1425 * buf Buffer in which to store it
1426 * pattern Pattern the word must match
1429 * TRUE if a space should be placed in the buffer before the next
1433 * The word may be copied to the buffer.
1435 *-----------------------------------------------------------------------
1438 VarNoMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1439 char *word, Boolean addSpace, Buffer *buf,
1442 if (!Str_Match(word, (char *)pattern)) {
1443 if (addSpace && vpstate->varSpace) {
1444 Buf_AddByte(buf, vpstate->varSpace);
1447 Buf_AddBytes(buf, strlen(word), word);
1454 *-----------------------------------------------------------------------
1456 * Perform a string-substitution on the given word, placing the
1457 * result in the passed buffer.
1460 * word Word to modify
1461 * addSpace True if space should be added before
1463 * buf Buffer for result
1464 * patternp Pattern for substitution
1467 * TRUE if a space is needed before more characters are added.
1472 *-----------------------------------------------------------------------
1475 VarSubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1476 char *word, Boolean addSpace, Buffer *buf,
1479 int wordLen; /* Length of word */
1480 char *cp; /* General pointer */
1481 VarPattern *pattern = (VarPattern *)patternp;
1483 wordLen = strlen(word);
1484 if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
1485 (VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1487 * Still substituting -- break it down into simple anchored cases
1488 * and if none of them fits, perform the general substitution case.
1490 if ((pattern->flags & VAR_MATCH_START) &&
1491 (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
1493 * Anchored at start and beginning of word matches pattern
1495 if ((pattern->flags & VAR_MATCH_END) &&
1496 (wordLen == pattern->leftLen)) {
1498 * Also anchored at end and matches to the end (word
1499 * is same length as pattern) add space and rhs only
1500 * if rhs is non-null.
1502 if (pattern->rightLen != 0) {
1503 if (addSpace && vpstate->varSpace) {
1504 Buf_AddByte(buf, vpstate->varSpace);
1507 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1509 pattern->flags |= VAR_SUB_MATCHED;
1510 } else if (pattern->flags & VAR_MATCH_END) {
1512 * Doesn't match to end -- copy word wholesale
1517 * Matches at start but need to copy in trailing characters
1519 if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1520 if (addSpace && vpstate->varSpace) {
1521 Buf_AddByte(buf, vpstate->varSpace);
1525 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1526 Buf_AddBytes(buf, wordLen - pattern->leftLen,
1527 (word + pattern->leftLen));
1528 pattern->flags |= VAR_SUB_MATCHED;
1530 } else if (pattern->flags & VAR_MATCH_START) {
1532 * Had to match at start of word and didn't -- copy whole word.
1535 } else if (pattern->flags & VAR_MATCH_END) {
1537 * Anchored at end, Find only place match could occur (leftLen
1538 * characters from the end of the word) and see if it does. Note
1539 * that because the $ will be left at the end of the lhs, we have
1542 cp = word + (wordLen - pattern->leftLen);
1544 (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
1546 * Match found. If we will place characters in the buffer,
1547 * add a space before hand as indicated by addSpace, then
1548 * stuff in the initial, unmatched part of the word followed
1549 * by the right-hand-side.
1551 if (((cp - word) + pattern->rightLen) != 0) {
1552 if (addSpace && vpstate->varSpace) {
1553 Buf_AddByte(buf, vpstate->varSpace);
1557 Buf_AddBytes(buf, cp - word, word);
1558 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1559 pattern->flags |= VAR_SUB_MATCHED;
1562 * Had to match at end and didn't. Copy entire word.
1568 * Pattern is unanchored: search for the pattern in the word using
1569 * String_FindSubstring, copying unmatched portions and the
1570 * right-hand-side for each match found, handling non-global
1571 * substitutions correctly, etc. When the loop is done, any
1572 * remaining part of the word (word and wordLen are adjusted
1573 * accordingly through the loop) is copied straight into the
1575 * addSpace is set FALSE as soon as a space is added to the
1582 origSize = Buf_Size(buf);
1584 cp = Str_FindSubstring(word, pattern->lhs);
1586 if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1587 Buf_AddByte(buf, vpstate->varSpace);
1590 Buf_AddBytes(buf, cp-word, word);
1591 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1592 wordLen -= (cp - word) + pattern->leftLen;
1593 word = cp + pattern->leftLen;
1597 if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
1600 pattern->flags |= VAR_SUB_MATCHED;
1606 if (addSpace && vpstate->varSpace) {
1607 Buf_AddByte(buf, vpstate->varSpace);
1609 Buf_AddBytes(buf, wordLen, word);
1612 * If added characters to the buffer, need to add a space
1613 * before we add any more. If we didn't add any, just return
1614 * the previous value of addSpace.
1616 return ((Buf_Size(buf) != origSize) || addSpace);
1621 if (addSpace && vpstate->varSpace) {
1622 Buf_AddByte(buf, vpstate->varSpace);
1624 Buf_AddBytes(buf, wordLen, word);
1630 *-----------------------------------------------------------------------
1632 * Print the error caused by a regcomp or regexec call.
1638 * An error gets printed.
1640 *-----------------------------------------------------------------------
1643 VarREError(int errnum, regex_t *pat, const char *str)
1648 errlen = regerror(errnum, pat, 0, 0);
1649 errbuf = bmake_malloc(errlen);
1650 regerror(errnum, pat, errbuf, errlen);
1651 Error("%s: %s", str, errbuf);
1657 *-----------------------------------------------------------------------
1658 * VarRESubstitute --
1659 * Perform a regex substitution on the given word, placing the
1660 * result in the passed buffer.
1663 * TRUE if a space is needed before more characters are added.
1668 *-----------------------------------------------------------------------
1671 VarRESubstitute(GNode *ctx MAKE_ATTR_UNUSED,
1672 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1673 char *word, Boolean addSpace, Buffer *buf,
1683 #define MAYBE_ADD_SPACE() \
1684 if (addSpace && !added) \
1685 Buf_AddByte(buf, ' '); \
1692 if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1693 (VAR_SUB_ONE|VAR_SUB_MATCHED))
1697 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1702 pat->flags |= VAR_SUB_MATCHED;
1703 if (pat->matches[0].rm_so > 0) {
1705 Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1708 for (rp = pat->replace; *rp; rp++) {
1709 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1711 Buf_AddByte(buf,rp[1]);
1714 else if ((*rp == '&') ||
1715 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1733 if (n > pat->nsub) {
1734 Error("No subexpression %s", &errstr[0]);
1737 } else if ((pat->matches[n].rm_so == -1) &&
1738 (pat->matches[n].rm_eo == -1)) {
1739 Error("No match for subexpression %s", &errstr[0]);
1743 subbuf = wp + pat->matches[n].rm_so;
1744 sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1749 Buf_AddBytes(buf, sublen, subbuf);
1753 Buf_AddByte(buf, *rp);
1756 wp += pat->matches[0].rm_eo;
1757 if (pat->flags & VAR_SUB_GLOBAL) {
1758 flags |= REG_NOTBOL;
1759 if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1761 Buf_AddByte(buf, *wp);
1770 Buf_AddBytes(buf, strlen(wp), wp);
1774 VarREError(xrv, &pat->re, "Unexpected regex error");
1779 Buf_AddBytes(buf,strlen(wp),wp);
1783 return(addSpace||added);
1790 *-----------------------------------------------------------------------
1792 * Implements the :@<temp>@<string>@ modifier of ODE make.
1793 * We set the temp variable named in pattern.lhs to word and expand
1794 * pattern.rhs storing the result in the passed buffer.
1797 * word Word to modify
1798 * addSpace True if space should be added before
1800 * buf Buffer for result
1801 * pattern Datafor substitution
1804 * TRUE if a space is needed before more characters are added.
1809 *-----------------------------------------------------------------------
1812 VarLoopExpand(GNode *ctx MAKE_ATTR_UNUSED,
1813 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1814 char *word, Boolean addSpace, Buffer *buf,
1817 VarLoop_t *loop = (VarLoop_t *)loopp;
1821 if (word && *word) {
1822 Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
1823 s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum);
1824 if (s != NULL && *s != '\0') {
1825 if (addSpace && *s != '\n')
1826 Buf_AddByte(buf, ' ');
1827 Buf_AddBytes(buf, (slen = strlen(s)), s);
1828 addSpace = (slen > 0 && s[slen - 1] != '\n');
1837 *-----------------------------------------------------------------------
1839 * Implements the :[start..end] modifier.
1840 * This is a special case of VarModify since we want to be able
1841 * to scan the list backwards if start > end.
1844 * str String whose words should be trimmed
1845 * seldata words to select
1848 * A string of all the words selected.
1853 *-----------------------------------------------------------------------
1856 VarSelectWords(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1857 const char *str, VarSelectWords_t *seldata)
1859 Buffer buf; /* Buffer for the new string */
1860 Boolean addSpace; /* TRUE if need to add a space to the
1861 * buffer before adding the trimmed
1863 char **av; /* word list */
1864 char *as; /* word list memory */
1866 int start, end, step;
1871 if (vpstate->oneBigWord) {
1872 /* fake what brk_string() would do if there were only one word */
1874 av = bmake_malloc((ac + 1) * sizeof(char *));
1875 as = bmake_strdup(str);
1879 av = brk_string(str, &ac, FALSE, &as);
1883 * Now sanitize seldata.
1884 * If seldata->start or seldata->end are negative, convert them to
1885 * the positive equivalents (-1 gets converted to argc, -2 gets
1886 * converted to (argc-1), etc.).
1888 if (seldata->start < 0)
1889 seldata->start = ac + seldata->start + 1;
1890 if (seldata->end < 0)
1891 seldata->end = ac + seldata->end + 1;
1894 * We avoid scanning more of the list than we need to.
1896 if (seldata->start > seldata->end) {
1897 start = MIN(ac, seldata->start) - 1;
1898 end = MAX(0, seldata->end - 1);
1901 start = MAX(0, seldata->start - 1);
1902 end = MIN(ac, seldata->end);
1907 (step < 0 && i >= end) || (step > 0 && i < end);
1909 if (av[i] && *av[i]) {
1910 if (addSpace && vpstate->varSpace) {
1911 Buf_AddByte(&buf, vpstate->varSpace);
1913 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
1921 return Buf_Destroy(&buf, FALSE);
1927 * Replace each word with the result of realpath()
1931 VarRealpath(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1932 char *word, Boolean addSpace, Buffer *buf,
1933 void *patternp MAKE_ATTR_UNUSED)
1936 char rbuf[MAXPATHLEN];
1939 if (addSpace && vpstate->varSpace) {
1940 Buf_AddByte(buf, vpstate->varSpace);
1943 rp = realpath(word, rbuf);
1944 if (rp && *rp == '/' && stat(rp, &st) == 0)
1947 Buf_AddBytes(buf, strlen(word), word);
1952 *-----------------------------------------------------------------------
1954 * Modify each of the words of the passed string using the given
1955 * function. Used to implement all modifiers.
1958 * str String whose words should be trimmed
1959 * modProc Function to use to modify them
1960 * datum Datum to pass it
1963 * A string of all the words modified appropriately.
1968 *-----------------------------------------------------------------------
1971 VarModify(GNode *ctx, Var_Parse_State *vpstate,
1973 Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
1974 Boolean, Buffer *, void *),
1977 Buffer buf; /* Buffer for the new string */
1978 Boolean addSpace; /* TRUE if need to add a space to the
1979 * buffer before adding the trimmed
1981 char **av; /* word list */
1982 char *as; /* word list memory */
1988 if (vpstate->oneBigWord) {
1989 /* fake what brk_string() would do if there were only one word */
1991 av = bmake_malloc((ac + 1) * sizeof(char *));
1992 as = bmake_strdup(str);
1996 av = brk_string(str, &ac, FALSE, &as);
1999 for (i = 0; i < ac; i++) {
2000 addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum);
2006 return Buf_Destroy(&buf, FALSE);
2011 VarWordCompare(const void *a, const void *b)
2013 int r = strcmp(*(const char * const *)a, *(const char * const *)b);
2018 *-----------------------------------------------------------------------
2020 * Order the words in the string.
2023 * str String whose words should be sorted.
2024 * otype How to order: s - sort, x - random.
2027 * A string containing the words ordered.
2032 *-----------------------------------------------------------------------
2035 VarOrder(const char *str, const char otype)
2037 Buffer buf; /* Buffer for the new string */
2038 char **av; /* word list [first word does not count] */
2039 char *as; /* word list memory */
2044 av = brk_string(str, &ac, FALSE, &as);
2048 case 's': /* sort alphabetically */
2049 qsort(av, ac, sizeof(char *), VarWordCompare);
2051 case 'x': /* randomize */
2057 * We will use [ac..2] range for mod factors. This will produce
2058 * random numbers in [(ac-1)..0] interval, and minimal
2059 * reasonable value for mod factor is 2 (the mod 1 will produce
2060 * 0 with probability 1).
2062 for (i = ac-1; i > 0; i--) {
2063 rndidx = random() % (i + 1);
2071 } /* end of switch */
2073 for (i = 0; i < ac; i++) {
2074 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2076 Buf_AddByte(&buf, ' ');
2082 return Buf_Destroy(&buf, FALSE);
2087 *-----------------------------------------------------------------------
2089 * Remove adjacent duplicate words.
2092 * str String whose words should be sorted
2095 * A string containing the resulting words.
2100 *-----------------------------------------------------------------------
2103 VarUniq(const char *str)
2105 Buffer buf; /* Buffer for new string */
2106 char **av; /* List of words to affect */
2107 char *as; /* Word list memory */
2111 av = brk_string(str, &ac, FALSE, &as);
2114 for (j = 0, i = 1; i < ac; i++)
2115 if (strcmp(av[i], av[j]) != 0 && (++j != i))
2120 for (i = 0; i < ac; i++) {
2121 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2123 Buf_AddByte(&buf, ' ');
2129 return Buf_Destroy(&buf, FALSE);
2134 *-----------------------------------------------------------------------
2136 * Pass through the tstr looking for 1) escaped delimiters,
2137 * '$'s and backslashes (place the escaped character in
2138 * uninterpreted) and 2) unescaped $'s that aren't before
2139 * the delimiter (expand the variable substitution unless flags
2140 * has VAR_NOSUBST set).
2141 * Return the expanded string or NULL if the delimiter was missing
2142 * If pattern is specified, handle escaped ampersands, and replace
2143 * unescaped ampersands with the lhs of the pattern.
2146 * A string of all the words modified appropriately.
2147 * If length is specified, return the string length of the buffer
2148 * If flags is specified and the last character of the pattern is a
2149 * $ set the VAR_MATCH_END bit of flags.
2153 *-----------------------------------------------------------------------
2156 VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
2157 int errnum, const char **tstr, int delim, int *flags,
2158 int *length, VarPattern *pattern)
2169 #define IS_A_MATCH(cp, delim) \
2170 ((cp[0] == '\\') && ((cp[1] == delim) || \
2171 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
2174 * Skim through until the matching delimiter is found;
2175 * pick up variable substitutions on the way. Also allow
2176 * backslashes to quote the delimiter, $, and \, but don't
2177 * touch other backslashes.
2179 for (cp = *tstr; *cp && (*cp != delim); cp++) {
2180 if (IS_A_MATCH(cp, delim)) {
2181 Buf_AddByte(&buf, cp[1]);
2183 } else if (*cp == '$') {
2184 if (cp[1] == delim) {
2186 Buf_AddByte(&buf, *cp);
2189 * Unescaped $ at end of pattern => anchor
2192 *flags |= VAR_MATCH_END;
2194 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
2200 * If unescaped dollar sign not before the
2201 * delimiter, assume it's a variable
2202 * substitution and recurse.
2204 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2205 Buf_AddBytes(&buf, strlen(cp2), cp2);
2210 const char *cp2 = &cp[1];
2212 if (*cp2 == PROPEN || *cp2 == BROPEN) {
2214 * Find the end of this variable reference
2215 * and suck it in without further ado.
2216 * It will be interperated later.
2219 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
2222 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
2223 if (cp2[-1] != '\\') {
2230 Buf_AddBytes(&buf, cp2 - cp, cp);
2233 Buf_AddByte(&buf, *cp);
2237 else if (pattern && *cp == '&')
2238 Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
2240 Buf_AddByte(&buf, *cp);
2250 *length = Buf_Size(&buf);
2251 rstr = Buf_Destroy(&buf, FALSE);
2253 fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
2258 *-----------------------------------------------------------------------
2260 * Quote shell meta-characters in the string
2268 *-----------------------------------------------------------------------
2275 /* This should cover most shells :-( */
2276 static const char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
2277 const char *newline;
2280 if ((newline = Shell_GetNewline()) == NULL)
2282 nlen = strlen(newline);
2285 while (*str != '\0') {
2286 if ((len = strcspn(str, meta)) != 0) {
2287 Buf_AddBytes(&buf, len, str);
2289 } else if (*str == '\n') {
2290 Buf_AddBytes(&buf, nlen, newline);
2293 Buf_AddByte(&buf, '\\');
2294 Buf_AddByte(&buf, *str);
2298 str = Buf_Destroy(&buf, FALSE);
2300 fprintf(debug_file, "QuoteMeta: [%s]\n", str);
2305 *-----------------------------------------------------------------------
2307 * Hash the string using the MurmurHash3 algorithm.
2308 * Output is computed using 32bit Little Endian arithmetic.
2311 * str String to modify
2314 * Hash value of str, encoded as 8 hex digits.
2319 *-----------------------------------------------------------------------
2324 static const char hexdigits[16] = "0123456789abcdef";
2327 unsigned char *ustr = (unsigned char *)str;
2328 uint32_t h, k, c1, c2;
2335 for (len = len2; len; ) {
2339 k = (ustr[3] << 24) | (ustr[2] << 16) | (ustr[1] << 8) | ustr[0];
2344 k |= (ustr[2] << 16);
2346 k |= (ustr[1] << 8);
2351 c1 = c1 * 5 + 0x7b7d159cU;
2352 c2 = c2 * 5 + 0x6bce6396U;
2354 k = (k << 11) ^ (k >> 21);
2356 h = (h << 13) ^ (h >> 19);
2357 h = h * 5 + 0x52dce729U;
2367 for (len = 0; len < 8; ++len) {
2368 Buf_AddByte(&buf, hexdigits[h & 15]);
2372 return Buf_Destroy(&buf, FALSE);
2376 VarStrftime(const char *fmt, int zulu)
2384 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2386 buf[sizeof(buf) - 1] = '\0';
2387 return bmake_strdup(buf);
2391 * Now we need to apply any modifiers the user wants applied.
2393 * :M<pattern> words which match the given <pattern>.
2394 * <pattern> is of the standard file
2396 * :N<pattern> words which do not match the given <pattern>.
2397 * :S<d><pat1><d><pat2><d>[1gW]
2398 * Substitute <pat2> for <pat1> in the value
2399 * :C<d><pat1><d><pat2><d>[1gW]
2400 * Substitute <pat2> for regex <pat1> in the value
2401 * :H Substitute the head of each word
2402 * :T Substitute the tail of each word
2403 * :E Substitute the extension (minus '.') of
2405 * :R Substitute the root of each word
2406 * (pathname minus the suffix).
2407 * :O ("Order") Alphabeticaly sort words in variable.
2408 * :Ox ("intermiX") Randomize words in variable.
2409 * :u ("uniq") Remove adjacent duplicate words.
2410 * :tu Converts the variable contents to uppercase.
2411 * :tl Converts the variable contents to lowercase.
2412 * :ts[c] Sets varSpace - the char used to
2413 * separate words to 'c'. If 'c' is
2414 * omitted then no separation is used.
2415 * :tW Treat the variable contents as a single
2416 * word, even if it contains spaces.
2417 * (Mnemonic: one big 'W'ord.)
2418 * :tw Treat the variable contents as multiple
2419 * space-separated words.
2420 * (Mnemonic: many small 'w'ords.)
2421 * :[index] Select a single word from the value.
2422 * :[start..end] Select multiple words from the value.
2423 * :[*] or :[0] Select the entire value, as a single
2424 * word. Equivalent to :tW.
2425 * :[@] Select the entire value, as multiple
2426 * words. Undoes the effect of :[*].
2427 * Equivalent to :tw.
2428 * :[#] Returns the number of words in the value.
2430 * :?<true-value>:<false-value>
2431 * If the variable evaluates to true, return
2432 * true value, else return the second value.
2433 * :lhs=rhs Like :S, but the rhs goes to the end of
2435 * :sh Treat the current value as a command
2436 * to be run, new value is its output.
2437 * The following added so we can handle ODE makefiles.
2438 * :@<tmpvar>@<newval>@
2439 * Assign a temporary local variable <tmpvar>
2440 * to the current value of each word in turn
2441 * and replace each word with the result of
2442 * evaluating <newval>
2443 * :D<newval> Use <newval> as value if variable defined
2444 * :U<newval> Use <newval> as value if variable undefined
2445 * :L Use the name of the variable as the value.
2446 * :P Use the path of the node that has the same
2447 * name as the variable as the value. This
2448 * basically includes an implied :L so that
2449 * the common method of refering to the path
2450 * of your dependent 'x' in a rule is to use
2451 * the form '${x:P}'.
2452 * :!<cmd>! Run cmd much the same as :sh run's the
2453 * current value of the variable.
2454 * The ::= modifiers, actually assign a value to the variable.
2455 * Their main purpose is in supporting modifiers of .for loop
2456 * iterators and other obscure uses. They always expand to
2457 * nothing. In a target rule that would otherwise expand to an
2458 * empty line they can be preceded with @: to keep make happy.
2462 * .for i in ${.TARGET} ${.TARGET:R}.gz
2467 * ::=<str> Assigns <str> as the new value of variable.
2468 * ::?=<str> Assigns <str> as value of variable if
2469 * it was not already set.
2470 * ::+=<str> Appends <str> to variable.
2471 * ::!=<cmd> Assigns output of <cmd> as the new value of
2475 /* we now have some modifiers with long names */
2476 #define STRMOD_MATCH(s, want, n) \
2477 (strncmp(s, want, n) == 0 && (s[n] == endc || s[n] == ':'))
2480 ApplyModifiers(char *nstr, const char *tstr,
2481 int startc, int endc,
2482 Var *v, GNode *ctxt, Boolean errnum,
2483 int *lengthPtr, void **freePtr)
2486 const char *cp; /* Secondary pointer into str (place marker
2488 char *newStr; /* New value to return */
2489 char termc; /* Character which terminated scan */
2490 int cnt; /* Used to count brace pairs when variable in
2491 * in parens or braces */
2493 int modifier; /* that we are processing */
2494 Var_Parse_State parsestate; /* Flags passed to helper functions */
2497 parsestate.oneBigWord = FALSE;
2498 parsestate.varSpace = ' '; /* word separator */
2502 while (*tstr && *tstr != endc) {
2506 * We may have some complex modifiers in a variable.
2513 rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
2516 * If we have not parsed up to endc or ':',
2517 * we are not interested.
2519 if (rval != NULL && *rval &&
2520 (c = tstr[rlen]) != '\0' &&
2529 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
2530 rval, rlen, tstr, rlen, tstr + rlen);
2535 if (rval != NULL && *rval) {
2538 nstr = ApplyModifiers(nstr, rval,
2540 v, ctxt, errnum, &used, freePtr);
2541 if (nstr == var_Error
2542 || (nstr == varNoError && errnum == 0)
2543 || strlen(rval) != (size_t) used) {
2546 goto out; /* error already reported */
2553 else if (!*tstr && endc) {
2554 Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name);
2561 fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", v->name,
2565 switch ((modifier = *tstr)) {
2568 if (tstr[1] == '=' ||
2570 (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
2572 * "::=", "::!=", "::+=", or "::?="
2574 GNode *v_ctxt; /* context where v belongs */
2580 if (v->name[0] == 0)
2586 if (v->flags & VAR_JUNK) {
2588 * We need to bmake_strdup() it incase
2589 * VarGetPattern() recurses.
2592 v->name = bmake_strdup(v->name);
2593 } else if (ctxt != VAR_GLOBAL) {
2594 Var *gv = VarFind(v->name, ctxt, 0);
2596 v_ctxt = VAR_GLOBAL;
2598 VarFreeEnv(gv, TRUE);
2601 switch ((how = *tstr)) {
2611 delim = startc == PROPEN ? PRCLOSE : BRCLOSE;
2614 pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2618 if (v->flags & VAR_JUNK) {
2619 /* restore original name */
2623 if (pattern.rhs == NULL)
2631 Var_Append(v->name, pattern.rhs, v_ctxt);
2634 newStr = Cmd_Exec(pattern.rhs, &emsg);
2638 Var_Set(v->name, newStr, v_ctxt, 0);
2643 if ((v->flags & VAR_JUNK) == 0)
2647 Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2650 free(UNCONST(pattern.rhs));
2654 goto default_case; /* "::<unrecognised>" */
2659 int flags = VAR_NOSUBST;
2663 if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum,
2665 &flags, &loop.tvarLen,
2669 if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum,
2671 &flags, &loop.strLen,
2678 loop.errnum = errnum;
2680 newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
2687 #ifdef MAKE_FREEBSD_UL
2691 /* we have to be careful, since :U is used internally */
2692 if (nc == ':' || nc == endc) {
2693 char *dp = bmake_strdup(nstr);
2694 for (newStr = dp; *dp; dp++)
2695 *dp = toupper((unsigned char)*dp);
2698 break; /* yes inside the conditional */
2705 Buffer buf; /* Buffer for patterns */
2706 int wantit; /* want data in buffer */
2709 * Pass through tstr looking for 1) escaped delimiters,
2710 * '$'s and backslashes (place the escaped character in
2711 * uninterpreted) and 2) unescaped $'s that aren't before
2712 * the delimiter (expand the variable substitution).
2713 * The result is left in the Buffer buf.
2717 *cp != endc && *cp != ':' && *cp != '\0';
2719 if ((*cp == '\\') &&
2725 Buf_AddByte(&buf, cp[1]);
2727 } else if (*cp == '$') {
2729 * If unescaped dollar sign, assume it's a
2730 * variable substitution and recurse.
2736 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2737 Buf_AddBytes(&buf, strlen(cp2), cp2);
2742 Buf_AddByte(&buf, *cp);
2749 wantit = ((v->flags & VAR_JUNK) != 0);
2751 wantit = ((v->flags & VAR_JUNK) == 0);
2752 if ((v->flags & VAR_JUNK) != 0)
2753 v->flags |= VAR_KEEP;
2755 newStr = Buf_Destroy(&buf, FALSE);
2758 Buf_Destroy(&buf, TRUE);
2763 #ifdef MAKE_FREEBSD_UL
2765 char *dp = bmake_strdup(nstr);
2766 for (newStr = dp; *dp; dp++)
2767 *dp = tolower((unsigned char)*dp);
2775 if ((v->flags & VAR_JUNK) != 0)
2776 v->flags |= VAR_KEEP;
2777 newStr = bmake_strdup(v->name);
2786 if ((v->flags & VAR_JUNK) != 0)
2787 v->flags |= VAR_KEEP;
2788 gn = Targ_FindNode(v->name, TARG_NOCREATE);
2789 if (gn == NULL || gn->type & OP_NOPATH) {
2791 } else if (gn->path) {
2792 newStr = bmake_strdup(gn->path);
2794 newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
2797 newStr = bmake_strdup(v->name);
2812 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2814 NULL, &pattern.rightLen,
2817 newStr = Cmd_Exec(pattern.rhs, &emsg);
2818 free(UNCONST(pattern.rhs));
2823 if (v->flags & VAR_JUNK) {
2824 v->flags |= VAR_KEEP;
2831 * Look for the closing ']', recursively
2832 * expanding any embedded variables.
2834 * estr is a pointer to the expanded result,
2835 * which we must free().
2839 cp = tstr+1; /* point to char after '[' */
2840 delim = ']'; /* look for closing ']' */
2841 estr = VarGetPattern(ctxt, &parsestate,
2845 goto cleanup; /* report missing ']' */
2846 /* now cp points just after the closing ']' */
2848 if (cp[0] != ':' && cp[0] != endc) {
2849 /* Found junk after ']' */
2853 if (estr[0] == '\0') {
2854 /* Found empty square brackets in ":[]". */
2857 } else if (estr[0] == '#' && estr[1] == '\0') {
2861 * We will need enough space for the decimal
2862 * representation of an int. We calculate the
2863 * space needed for the octal representation,
2864 * and add enough slop to cope with a '-' sign
2865 * (which should never be needed) and a '\0'
2866 * string terminator.
2869 (sizeof(int) * CHAR_BIT + 2) / 3 + 2;
2871 newStr = bmake_malloc(newStrSize);
2872 if (parsestate.oneBigWord) {
2873 strncpy(newStr, "1", newStrSize);
2875 /* XXX: brk_string() is a rather expensive
2876 * way of counting words. */
2881 av = brk_string(nstr, &ac, FALSE, &as);
2882 snprintf(newStr, newStrSize, "%d", ac);
2889 } else if (estr[0] == '*' && estr[1] == '\0') {
2891 parsestate.oneBigWord = TRUE;
2896 } else if (estr[0] == '@' && estr[1] == '\0') {
2898 parsestate.oneBigWord = FALSE;
2905 * We expect estr to contain a single
2906 * integer for :[N], or two integers
2907 * separated by ".." for :[start..end].
2911 VarSelectWords_t seldata = { 0, 0 };
2913 seldata.start = strtol(estr, &ep, 0);
2915 /* Found junk instead of a number */
2918 } else if (ep[0] == '\0') {
2919 /* Found only one integer in :[N] */
2920 seldata.end = seldata.start;
2921 } else if (ep[0] == '.' && ep[1] == '.' &&
2923 /* Expecting another integer after ".." */
2925 seldata.end = strtol(ep, &ep, 0);
2926 if (ep[0] != '\0') {
2927 /* Found junk after ".." */
2932 /* Found junk instead of ".." */
2937 * Now seldata is properly filled in,
2938 * but we still have to check for 0 as
2941 if (seldata.start == 0 && seldata.end == 0) {
2942 /* ":[0]" or perhaps ":[0..0]" */
2943 parsestate.oneBigWord = TRUE;
2948 } else if (seldata.start == 0 ||
2950 /* ":[0..N]" or ":[N..0]" */
2955 * Normal case: select the words
2956 * described by seldata.
2958 newStr = VarSelectWords(ctxt, &parsestate,
2968 cp = tstr + 1; /* make sure it is set */
2969 if (STRMOD_MATCH(tstr, "gmtime", 6)) {
2970 newStr = VarStrftime(nstr, 1);
2978 cp = tstr + 1; /* make sure it is set */
2979 if (STRMOD_MATCH(tstr, "hash", 4)) {
2980 newStr = VarHash(nstr);
2988 cp = tstr + 1; /* make sure it is set */
2989 if (STRMOD_MATCH(tstr, "localtime", 9)) {
2990 newStr = VarStrftime(nstr, 0);
2999 cp = tstr + 1; /* make sure it is set */
3000 if (tstr[1] != endc && tstr[1] != ':') {
3001 if (tstr[1] == 's') {
3003 * Use the char (if any) at tstr[2]
3004 * as the word separator.
3008 if (tstr[2] != endc &&
3009 (tstr[3] == endc || tstr[3] == ':')) {
3010 /* ":ts<unrecognised><endc>" or
3011 * ":ts<unrecognised>:" */
3012 parsestate.varSpace = tstr[2];
3014 } else if (tstr[2] == endc || tstr[2] == ':') {
3015 /* ":ts<endc>" or ":ts:" */
3016 parsestate.varSpace = 0; /* no separator */
3018 } else if (tstr[2] == '\\') {
3021 parsestate.varSpace = '\n';
3025 parsestate.varSpace = '\t';
3029 if (isdigit((unsigned char)tstr[3])) {
3032 parsestate.varSpace =
3033 strtoul(&tstr[3], &ep, 0);
3034 if (*ep != ':' && *ep != endc)
3039 * ":ts<backslash><unrecognised>".
3047 * Found ":ts<unrecognised><unrecognised>".
3055 * We cannot be certain that VarModify
3056 * will be used - even if there is a
3057 * subsequent modifier, so do a no-op
3058 * VarSubstitute now to for str to be
3059 * re-expanded without the spaces.
3061 pattern.flags = VAR_SUB_ONE;
3062 pattern.lhs = pattern.rhs = "\032";
3063 pattern.leftLen = pattern.rightLen = 1;
3065 newStr = VarModify(ctxt, &parsestate, nstr,
3068 } else if (tstr[2] == endc || tstr[2] == ':') {
3070 * Check for two-character options:
3073 if (tstr[1] == 'A') { /* absolute path */
3074 newStr = VarModify(ctxt, &parsestate, nstr,
3078 } else if (tstr[1] == 'u') {
3079 char *dp = bmake_strdup(nstr);
3080 for (newStr = dp; *dp; dp++)
3081 *dp = toupper((unsigned char)*dp);
3084 } else if (tstr[1] == 'l') {
3085 char *dp = bmake_strdup(nstr);
3086 for (newStr = dp; *dp; dp++)
3087 *dp = tolower((unsigned char)*dp);
3090 } else if (tstr[1] == 'W' || tstr[1] == 'w') {
3091 parsestate.oneBigWord = (tstr[1] == 'W');
3096 /* Found ":t<unrecognised>:" or
3097 * ":t<unrecognised><endc>". */
3102 * Found ":t<unrecognised><unrecognised>".
3108 * Found ":t<endc>" or ":t:".
3118 const char *endpat; /* points just after end of pattern */
3120 Boolean copy; /* pattern should be, or has been, copied */
3128 * In the loop below, ignore ':' unless we are at
3129 * (or back to) the original brace level.
3130 * XXX This will likely not work right if $() and ${}
3134 *cp != '\0' && !(*cp == ':' && nest == 1);
3139 cp[1] == endc || cp[1] == startc)) {
3149 if (*cp == '(' || *cp == '{')
3151 if (*cp == ')' || *cp == '}') {
3161 * Need to compress the \:'s out of the pattern, so
3162 * allocate enough room to hold the uncompressed
3163 * pattern (note that cp started at tstr+1, so
3164 * cp - tstr takes the null byte into account) and
3165 * compress the pattern into the space.
3167 pattern = bmake_malloc(cp - tstr);
3168 for (cp2 = pattern, cp = tstr + 1;
3172 if ((*cp == '\\') && (cp+1 < endpat) &&
3173 (cp[1] == ':' || cp[1] == endc)) {
3182 * Either Var_Subst or VarModify will need a
3183 * nul-terminated string soon, so construct one now.
3185 pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
3189 * pattern contains embedded '$', so use Var_Subst to
3193 pattern = Var_Subst(NULL, cp2, ctxt, errnum);
3197 fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
3198 v->name, nstr, pattern);
3200 newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
3203 newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
3212 Var_Parse_State tmpparsestate;
3215 tmpparsestate = parsestate;
3220 * If pattern begins with '^', it is anchored to the
3221 * start of the word -- skip over it and flag pattern.
3224 pattern.flags |= VAR_MATCH_START;
3229 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3236 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3243 * Check for global substitution. If 'g' after the final
3244 * delimiter, substitution is global and is marked that
3250 pattern.flags |= VAR_SUB_GLOBAL;
3253 pattern.flags |= VAR_SUB_ONE;
3256 tmpparsestate.oneBigWord = TRUE;
3263 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3268 * Free the two strings.
3270 free(UNCONST(pattern.lhs));
3271 free(UNCONST(pattern.rhs));
3280 /* find ':', and then substitute accordingly */
3286 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3292 /* BROPEN or PROPEN */
3294 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3302 if (Cond_EvalExpression(NULL, v->name, &value, 0)
3304 Error("Bad conditional expression `%s' in %s?%s:%s",
3305 v->name, v->name, pattern.lhs, pattern.rhs);
3310 newStr = UNCONST(pattern.lhs);
3311 free(UNCONST(pattern.rhs));
3313 newStr = UNCONST(pattern.rhs);
3314 free(UNCONST(pattern.lhs));
3316 if (v->flags & VAR_JUNK) {
3317 v->flags |= VAR_KEEP;
3324 VarREPattern pattern;
3327 Var_Parse_State tmpparsestate;
3330 tmpparsestate = parsestate;
3336 if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim,
3337 NULL, NULL, NULL)) == NULL)
3340 if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
3341 errnum, &cp, delim, NULL,
3342 NULL, NULL)) == NULL){
3350 pattern.flags |= VAR_SUB_GLOBAL;
3353 pattern.flags |= VAR_SUB_ONE;
3356 tmpparsestate.oneBigWord = TRUE;
3364 error = regcomp(&pattern.re, re, REG_EXTENDED);
3367 *lengthPtr = cp - start + 1;
3368 VarREError(error, &pattern.re, "RE substitution error");
3369 free(pattern.replace);
3373 pattern.nsub = pattern.re.re_nsub + 1;
3374 if (pattern.nsub < 1)
3376 if (pattern.nsub > 10)
3378 pattern.matches = bmake_malloc(pattern.nsub *
3379 sizeof(regmatch_t));
3380 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3383 regfree(&pattern.re);
3384 free(pattern.replace);
3385 free(pattern.matches);
3391 if (tstr[1] == endc || tstr[1] == ':') {
3392 newStr = VarQuote(nstr);
3399 if (tstr[1] == endc || tstr[1] == ':') {
3400 newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
3408 if (tstr[1] == endc || tstr[1] == ':') {
3409 newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
3417 if (tstr[1] == endc || tstr[1] == ':') {
3418 newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
3426 if (tstr[1] == endc || tstr[1] == ':') {
3427 newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
3438 cp = tstr + 1; /* skip to the rest in any case */
3439 if (tstr[1] == endc || tstr[1] == ':') {
3442 } else if ( (tstr[1] == 'x') &&
3443 (tstr[2] == endc || tstr[2] == ':') ) {
3450 newStr = VarOrder(nstr, otype);
3454 if (tstr[1] == endc || tstr[1] == ':') {
3455 newStr = VarUniq(nstr);
3463 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
3465 newStr = Cmd_Exec(nstr, &emsg);
3479 * This can either be a bogus modifier or a System-V
3480 * substitution command.
3488 * First we make a pass through the string trying
3489 * to verify it is a SYSV-make-style translation:
3490 * it must be: <string1>=<string2>)
3494 while (*cp != '\0' && cnt) {
3497 /* continue looking for endc */
3499 else if (*cp == endc)
3501 else if (*cp == startc)
3506 if (*cp == endc && eqFound) {
3509 * Now we break this sucker into the lhs and
3510 * rhs. We must null terminate them of course.
3514 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
3515 errnum, &cp, delim, &pattern.flags,
3516 &pattern.leftLen, NULL)) == NULL)
3519 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
3520 errnum, &cp, delim, NULL, &pattern.rightLen,
3525 * SYSV modifications happen through the whole
3526 * string. Note the pattern is anchored at the end.
3530 if (pattern.leftLen == 0 && *nstr == '\0') {
3531 newStr = nstr; /* special case */
3533 newStr = VarModify(ctxt, &parsestate, nstr,
3537 free(UNCONST(pattern.lhs));
3538 free(UNCONST(pattern.rhs));
3542 Error("Unknown modifier '%c'", *tstr);
3544 *cp != ':' && *cp != endc && *cp != '\0';
3553 fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
3554 v->name, modifier, newStr);
3557 if (newStr != nstr) {
3563 if (nstr != var_Error && nstr != varNoError) {
3567 if (termc == '\0' && endc != '\0') {
3568 Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier);
3569 } else if (termc == ':') {
3575 *lengthPtr = tstr - start;
3580 Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
3584 *lengthPtr = cp - start;
3586 Error("Unclosed substitution for %s (%c missing)",
3596 *-----------------------------------------------------------------------
3598 * Given the start of a variable invocation, extract the variable
3599 * name and find its value, then modify it according to the
3603 * str The string to parse
3604 * ctxt The context for the variable
3605 * errnum TRUE if undefined variables are an error
3606 * lengthPtr OUT: The length of the specification
3607 * freePtr OUT: Non-NULL if caller should free *freePtr
3610 * The (possibly-modified) value of the variable or var_Error if the
3611 * specification is invalid. The length of the specification is
3612 * placed in *lengthPtr (for invalid specifications, this is just
3614 * If *freePtr is non-NULL then it's a pointer that the caller
3615 * should pass to free() to free memory used by the result.
3620 *-----------------------------------------------------------------------
3622 /* coverity[+alloc : arg-*4] */
3624 Var_Parse(const char *str, GNode *ctxt, Boolean errnum, int *lengthPtr,
3627 const char *tstr; /* Pointer into str */
3628 Var *v; /* Variable in invocation */
3629 Boolean haveModifier;/* TRUE if have modifiers for the variable */
3630 char endc; /* Ending character when variable in parens
3632 char startc; /* Starting character when variable in parens
3634 int vlen; /* Length of variable name */
3635 const char *start; /* Points to original start of str */
3636 char *nstr; /* New string, used during expansion */
3637 Boolean dynamic; /* TRUE if the variable is local and we're
3638 * expanding it in a non-local context. This
3639 * is done to support dynamic sources. The
3640 * result is just the invocation, unaltered */
3641 Var_Parse_State parsestate; /* Flags passed to helper functions */
3647 parsestate.oneBigWord = FALSE;
3648 parsestate.varSpace = ' '; /* word separator */
3651 if (startc != PROPEN && startc != BROPEN) {
3653 * If it's not bounded by braces of some sort, life is much simpler.
3654 * We just need to check for the first character and return the
3655 * value if it exists.
3658 /* Error out some really stupid names */
3659 if (startc == '\0' || strchr(")}:$", startc)) {
3666 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3670 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
3672 * If substituting a local variable in a non-local context,
3673 * assume it's for dynamic source stuff. We have to handle
3674 * this specially and return the longhand for the variable
3675 * with the dollar sign escaped so it makes it back to the
3676 * caller. Only four of the local variables are treated
3677 * specially as they are the only four that will be set
3678 * when dynamic sources are expanded.
3682 return UNCONST("$(.TARGET)");
3684 return UNCONST("$(.ARCHIVE)");
3686 return UNCONST("$(.PREFIX)");
3688 return UNCONST("$(.MEMBER)");
3694 return (errnum ? var_Error : varNoError);
3696 haveModifier = FALSE;
3701 Buffer buf; /* Holds the variable name */
3703 endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3707 * Skip to the end character or a colon, whichever comes first.
3709 for (tstr = str + 2;
3710 *tstr != '\0' && *tstr != endc && *tstr != ':';
3714 * A variable inside a variable, expand
3719 char *rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
3721 Buf_AddBytes(&buf, strlen(rval), rval);
3728 Buf_AddByte(&buf, *tstr);
3731 haveModifier = TRUE;
3732 } else if (*tstr != '\0') {
3733 haveModifier = FALSE;
3736 * If we never did find the end character, return NULL
3737 * right now, setting the length to be the distance to
3738 * the end of the string, since that's what make does.
3740 *lengthPtr = tstr - str;
3741 Buf_Destroy(&buf, TRUE);
3744 str = Buf_GetAll(&buf, &vlen);
3747 * At this point, str points into newly allocated memory from
3748 * buf, containing only the name of the variable.
3750 * start and tstr point into the const string that was pointed
3751 * to by the original value of the str parameter. start points
3752 * to the '$' at the beginning of the string, while tstr points
3753 * to the char just after the end of the variable name -- this
3754 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3757 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3759 * Check also for bogus D and F forms of local variables since we're
3760 * in a local context and the name is the right length.
3762 if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
3763 (vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
3764 strchr("@%*!<>", str[0]) != NULL) {
3766 * Well, it's local -- go look for it.
3770 v = VarFind(name, ctxt, 0);
3774 * No need for nested expansion or anything, as we're
3775 * the only one who sets these things and we sure don't
3776 * but nested invocations in them...
3778 nstr = Buf_GetAll(&v->val, NULL);
3780 if (str[1] == 'D') {
3781 nstr = VarModify(ctxt, &parsestate, nstr, VarHead,
3784 nstr = VarModify(ctxt, &parsestate, nstr, VarTail,
3788 * Resulting string is dynamically allocated, so
3789 * tell caller to free it.
3792 *lengthPtr = tstr-start+1;
3793 Buf_Destroy(&buf, TRUE);
3794 VarFreeEnv(v, TRUE);
3801 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
3802 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3805 * If substituting a local variable in a non-local context,
3806 * assume it's for dynamic source stuff. We have to handle
3807 * this specially and return the longhand for the variable
3808 * with the dollar sign escaped so it makes it back to the
3809 * caller. Only four of the local variables are treated
3810 * specially as they are the only four that will be set
3811 * when dynamic sources are expanded.
3821 } else if ((vlen > 2) && (*str == '.') &&
3822 isupper((unsigned char) str[1]) &&
3823 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3828 if ((strncmp(str, ".TARGET", len) == 0) ||
3829 (strncmp(str, ".ARCHIVE", len) == 0) ||
3830 (strncmp(str, ".PREFIX", len) == 0) ||
3831 (strncmp(str, ".MEMBER", len) == 0))
3837 if (!haveModifier) {
3839 * No modifiers -- have specification length so we can return
3842 *lengthPtr = tstr - start + 1;
3844 char *pstr = bmake_strndup(start, *lengthPtr);
3846 Buf_Destroy(&buf, TRUE);
3849 Buf_Destroy(&buf, TRUE);
3850 return (errnum ? var_Error : varNoError);
3854 * Still need to get to the end of the variable specification,
3855 * so kludge up a Var structure for the modifications
3857 v = bmake_malloc(sizeof(Var));
3858 v->name = UNCONST(str);
3859 Buf_Init(&v->val, 1);
3860 v->flags = VAR_JUNK;
3861 Buf_Destroy(&buf, FALSE);
3864 Buf_Destroy(&buf, TRUE);
3867 if (v->flags & VAR_IN_USE) {
3868 Fatal("Variable %s is recursive.", v->name);
3871 v->flags |= VAR_IN_USE;
3874 * Before doing any modification, we have to make sure the value
3875 * has been fully expanded. If it looks like recursion might be
3876 * necessary (there's a dollar sign somewhere in the variable's value)
3877 * we just call Var_Subst to do any other substitutions that are
3878 * necessary. Note that the value returned by Var_Subst will have
3879 * been dynamically-allocated, so it will need freeing when we
3882 nstr = Buf_GetAll(&v->val, NULL);
3883 if (strchr(nstr, '$') != NULL) {
3884 nstr = Var_Subst(NULL, nstr, ctxt, errnum);
3888 v->flags &= ~VAR_IN_USE;
3890 if ((nstr != NULL) && haveModifier) {
3893 * Skip initial colon.
3897 nstr = ApplyModifiers(nstr, tstr, startc, endc,
3898 v, ctxt, errnum, &used, freePtr);
3902 *lengthPtr = tstr - start + 1;
3904 *lengthPtr = tstr - start;
3907 if (v->flags & VAR_FROM_ENV) {
3908 Boolean destroy = FALSE;
3910 if (nstr != Buf_GetAll(&v->val, NULL)) {
3914 * Returning the value unmodified, so tell the caller to free
3919 VarFreeEnv(v, destroy);
3920 } else if (v->flags & VAR_JUNK) {
3922 * Perform any free'ing needed and set *freePtr to NULL so the caller
3923 * doesn't try to free a static pointer.
3924 * If VAR_KEEP is also set then we want to keep str as is.
3926 if (!(v->flags & VAR_KEEP)) {
3932 nstr = bmake_strndup(start, *lengthPtr);
3935 nstr = errnum ? var_Error : varNoError;
3938 if (nstr != Buf_GetAll(&v->val, NULL))
3939 Buf_Destroy(&v->val, TRUE);
3947 *-----------------------------------------------------------------------
3949 * Substitute for all variables in the given string in the given context
3950 * If undefErr is TRUE, Parse_Error will be called when an undefined
3951 * variable is encountered.
3954 * var Named variable || NULL for all
3955 * str the string which to substitute
3956 * ctxt the context wherein to find variables
3957 * undefErr TRUE if undefineds are an error
3960 * The resulting string.
3963 * None. The old string must be freed by the caller
3964 *-----------------------------------------------------------------------
3967 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
3969 Buffer buf; /* Buffer for forming things */
3970 char *val; /* Value to substitute for a variable */
3971 int length; /* Length of the variable invocation */
3972 Boolean trailingBslash; /* variable ends in \ */
3973 void *freeIt = NULL; /* Set if it should be freed */
3974 static Boolean errorReported; /* Set true if an error has already
3975 * been reported to prevent a plethora
3976 * of messages when recursing */
3979 errorReported = FALSE;
3980 trailingBslash = FALSE;
3983 if (*str == '\n' && trailingBslash)
3984 Buf_AddByte(&buf, ' ');
3985 if (var == NULL && (*str == '$') && (str[1] == '$')) {
3987 * A dollar sign may be escaped either with another dollar sign.
3988 * In such a case, we skip over the escape character and store the
3989 * dollar sign into the buffer directly.
3992 Buf_AddByte(&buf, *str);
3994 } else if (*str != '$') {
3996 * Skip as many characters as possible -- either to the end of
3997 * the string or to the next dollar sign (variable invocation).
4001 for (cp = str++; *str != '$' && *str != '\0'; str++)
4003 Buf_AddBytes(&buf, str - cp, cp);
4008 if (str[1] == '\0') {
4009 /* A trailing $ is kind of a special case */
4010 Buf_AddByte(&buf, str[0]);
4013 } else if (str[1] != PROPEN && str[1] != BROPEN) {
4014 if (str[1] != *var || strlen(var) > 1) {
4015 Buf_AddBytes(&buf, 2, str);
4027 * Scan up to the end of the variable name.
4029 for (p = &str[2]; *p &&
4030 *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
4034 * A variable inside the variable. We cannot expand
4035 * the external variable yet, so we try again with
4039 Buf_AddBytes(&buf, p - str, str);
4044 if (strncmp(var, str + 2, p - str - 2) != 0 ||
4045 var[p - str - 2] != '\0') {
4047 * Not the variable we want to expand, scan
4048 * until the next variable
4050 for (;*p != '$' && *p != '\0'; p++)
4052 Buf_AddBytes(&buf, p - str, str);
4065 val = Var_Parse(str, ctxt, undefErr, &length, &freeIt);
4068 * When we come down here, val should either point to the
4069 * value of this variable, suitably modified, or be NULL.
4070 * Length should be the total length of the potential
4071 * variable invocation (from $ to end character...)
4073 if (val == var_Error || val == varNoError) {
4075 * If performing old-time variable substitution, skip over
4076 * the variable and continue with the substitution. Otherwise,
4077 * store the dollar sign and advance str so we continue with
4082 } else if (undefErr) {
4084 * If variable is undefined, complain and skip the
4085 * variable. The complaint will stop us from doing anything
4086 * when the file is parsed.
4088 if (!errorReported) {
4089 Parse_Error(PARSE_FATAL,
4090 "Undefined variable \"%.*s\"",length,str);
4093 errorReported = TRUE;
4095 Buf_AddByte(&buf, *str);
4100 * We've now got a variable structure to store in. But first,
4101 * advance the string pointer.
4106 * Copy all the characters from the variable value straight
4107 * into the new string.
4109 length = strlen(val);
4110 Buf_AddBytes(&buf, length, val);
4111 trailingBslash = length > 0 && val[length - 1] == '\\';
4120 return Buf_DestroyCompact(&buf);
4124 *-----------------------------------------------------------------------
4126 * Return the tail from each of a list of words. Used to set the
4127 * System V local variables.
4130 * file Filename to modify
4133 * The resulting string.
4138 *-----------------------------------------------------------------------
4142 Var_GetTail(char *file)
4144 return(VarModify(file, VarTail, NULL));
4148 *-----------------------------------------------------------------------
4150 * Find the leading components of a (list of) filename(s).
4151 * XXX: VarHead does not replace foo by ., as (sun) System V make
4155 * file Filename to manipulate
4158 * The leading components.
4163 *-----------------------------------------------------------------------
4166 Var_GetHead(char *file)
4168 return(VarModify(file, VarHead, NULL));
4173 *-----------------------------------------------------------------------
4175 * Initialize the module
4181 * The VAR_CMD and VAR_GLOBAL contexts are created
4182 *-----------------------------------------------------------------------
4187 VAR_GLOBAL = Targ_NewGN("Global");
4188 VAR_CMD = Targ_NewGN("Command");
4199 /****************** PRINT DEBUGGING INFO *****************/
4201 VarPrintVar(void *vp)
4204 fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
4208 *-----------------------------------------------------------------------
4210 * print all variables in a context
4211 *-----------------------------------------------------------------------
4214 Var_Dump(GNode *ctxt)
4219 for (h = Hash_EnumFirst(&ctxt->context, &search);
4221 h = Hash_EnumNext(&search)) {
4222 VarPrintVar(Hash_GetValue(h));