1 /* $NetBSD: var.c,v 1.173 2013/02/24 19:43:37 christos 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.173 2013/02/24 19:43:37 christos 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.173 2013/02/24 19:43:37 christos 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)
544 ln = Hash_FindEntry(&ctxt->context, name);
546 fprintf(debug_file, "%s:delete %s%s\n",
547 ctxt->name, name, ln ? "" : " (not found)");
552 v = (Var *)Hash_GetValue(ln);
553 if ((v->flags & VAR_EXPORTED)) {
556 if (strcmp(MAKE_EXPORTED, v->name) == 0) {
557 var_exportedVars = VAR_EXPORTED_NONE;
559 if (v->name != ln->name)
561 Hash_DeleteEntry(&ctxt->context, ln);
562 Buf_Destroy(&v->val, TRUE);
570 * We ignore make internal variables (those which start with '.')
571 * Also we jump through some hoops to avoid calling setenv
572 * more than necessary since it can leak.
573 * We only manipulate flags of vars if 'parent' is set.
576 Var_Export1(const char *name, int parent)
584 return 0; /* skip internals */
588 * If it is one of the vars that should only appear in
589 * local context, skip it, else we can get Var_Subst
600 v = VarFind(name, VAR_GLOBAL, 0);
605 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
606 return 0; /* nothing to do */
608 val = Buf_GetAll(&v->val, NULL);
609 if (strchr(val, '$')) {
612 * Flag this as something we need to re-export.
613 * No point actually exporting it now though,
614 * the child can do it at the last minute.
616 v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
619 if (v->flags & VAR_IN_USE) {
621 * We recursed while exporting in a child.
622 * This isn't going to end well, just skip it.
626 n = snprintf(tmp, sizeof(tmp), "${%s}", name);
627 if (n < (int)sizeof(tmp)) {
628 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
629 setenv(name, val, 1);
634 v->flags &= ~VAR_REEXPORT; /* once will do */
636 if (parent || !(v->flags & VAR_EXPORTED)) {
637 setenv(name, val, 1);
641 * This is so Var_Set knows to call Var_Export again...
644 v->flags |= VAR_EXPORTED;
650 * This gets called from our children.
662 if (VAR_EXPORTED_NONE == var_exportedVars)
665 if (VAR_EXPORTED_ALL == var_exportedVars) {
667 * Ouch! This is crazy...
669 for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
671 var = Hash_EnumNext(&state)) {
672 v = (Var *)Hash_GetValue(var);
673 Var_Export1(v->name, 0);
678 * We have a number of exported vars,
680 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
681 if (n < (int)sizeof(tmp)) {
687 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
688 av = brk_string(val, &ac, FALSE, &as);
689 for (i = 0; i < ac; i++) {
690 Var_Export1(av[i], 0);
699 * This is called when .export is seen or
700 * .MAKE.EXPORTED is modified.
701 * It is also called when any exported var is modified.
704 Var_Export(char *str, int isExport)
714 if (isExport && (!str || !str[0])) {
715 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
719 if (strncmp(str, "-env", 4) == 0) {
723 track = VAR_EXPORT_PARENT;
725 val = Var_Subst(NULL, str, VAR_GLOBAL, 0);
726 av = brk_string(val, &ac, FALSE, &as);
727 for (i = 0; i < ac; i++) {
732 * If it is one of the vars that should only appear in
733 * local context, skip it, else we can get Var_Subst
744 if (Var_Export1(name, track)) {
745 if (VAR_EXPORTED_ALL != var_exportedVars)
746 var_exportedVars = VAR_EXPORTED_YES;
747 if (isExport && track) {
748 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
759 * This is called when .unexport[-env] is seen.
761 extern char **environ;
764 Var_UnExport(char *str)
769 Boolean unexport_env;
772 if (!str || !str[0]) {
773 return; /* assert? */
779 unexport_env = (strncmp(str, "-env", 4) == 0);
783 cp = getenv(MAKE_LEVEL); /* we should preserve this */
784 if (environ == savedEnv) {
785 /* we have been here before! */
786 newenv = bmake_realloc(environ, 2 * sizeof(char *));
792 newenv = bmake_malloc(2 * sizeof(char *));
796 /* Note: we cannot safely free() the original environ. */
797 environ = savedEnv = newenv;
800 setenv(MAKE_LEVEL, cp, 1);
801 #ifdef MAKE_LEVEL_SAFE
802 setenv(MAKE_LEVEL_SAFE, cp, 1);
805 for (; *str != '\n' && isspace((unsigned char) *str); str++)
807 if (str[0] && str[0] != '\n') {
813 /* Using .MAKE.EXPORTED */
814 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
815 if (n < (int)sizeof(tmp)) {
816 vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
826 av = brk_string(vlist, &ac, FALSE, &as);
827 for (i = 0; i < ac; i++) {
828 v = VarFind(av[i], VAR_GLOBAL, 0);
832 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
835 v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT);
837 * If we are unexporting a list,
838 * remove each one from .MAKE.EXPORTED.
839 * If we are removing them all,
840 * just delete .MAKE.EXPORTED below.
843 n = snprintf(tmp, sizeof(tmp),
844 "${" MAKE_EXPORTED ":N%s}", v->name);
845 if (n < (int)sizeof(tmp)) {
846 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
847 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0);
855 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
862 *-----------------------------------------------------------------------
864 * Set the variable name to the value val in the given context.
867 * name name of variable to set
868 * val value to give to the variable
869 * ctxt context in which to set it
875 * If the variable doesn't yet exist, a new record is created for it.
876 * Else the old value is freed and the new one stuck in its place
879 * The variable is searched for only in its context before being
880 * created in that context. I.e. if the context is VAR_GLOBAL,
881 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
882 * VAR_CMD->context is searched. This is done to avoid the literally
883 * thousands of unnecessary strcmp's that used to be done to
884 * set, say, $(@) or $(<).
885 * If the context is VAR_GLOBAL though, we check if the variable
886 * was set in VAR_CMD from the command line and skip it if so.
887 *-----------------------------------------------------------------------
890 Var_Set(const char *name, const char *val, GNode *ctxt, int flags)
893 char *expanded_name = NULL;
896 * We only look for a variable in the given context since anything set
897 * here will override anything in a lower context, so there's not much
898 * point in searching them all just to save a bit of memory...
900 if (strchr(name, '$') != NULL) {
901 expanded_name = Var_Subst(NULL, name, ctxt, 0);
902 if (expanded_name[0] == 0) {
904 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
905 "name expands to empty string - ignored\n",
911 name = expanded_name;
913 if (ctxt == VAR_GLOBAL) {
914 v = VarFind(name, VAR_CMD, 0);
916 if ((v->flags & VAR_FROM_CMD)) {
918 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
925 v = VarFind(name, ctxt, 0);
927 VarAdd(name, val, ctxt);
930 Buf_AddBytes(&v->val, strlen(val), val);
933 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
935 if ((v->flags & VAR_EXPORTED)) {
936 Var_Export1(name, VAR_EXPORT_PARENT);
940 * Any variables given on the command line are automatically exported
941 * to the environment (as per POSIX standard)
943 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
945 /* we just added it */
946 v = VarFind(name, ctxt, 0);
949 v->flags |= VAR_FROM_CMD;
951 * If requested, don't export these in the environment
952 * individually. We still put them in MAKEOVERRIDES so
953 * that the command-line settings continue to override
956 if (varNoExportEnv != TRUE)
957 setenv(name, val, 1);
959 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
962 * Another special case.
963 * Several make's support this sort of mechanism for tracking
964 * recursion - but each uses a different name.
965 * We allow the makefiles to update .MAKE.LEVEL and ensure
966 * children see a correctly incremented value.
968 if (ctxt == VAR_GLOBAL && strcmp(MAKE_LEVEL, name) == 0) {
973 snprintf(tmp, sizeof(tmp), "%u", level + 1);
974 setenv(MAKE_LEVEL, tmp, 1);
975 #ifdef MAKE_LEVEL_SAFE
976 setenv(MAKE_LEVEL_SAFE, tmp, 1);
979 #ifdef MAKE_FREEBSD_UL
980 if (strcmp(MAKE_FREEBSD_UL, name) == 0) {
981 FreeBSD_UL = getBoolean(MAKE_FREEBSD_UL, FALSE);
987 if (expanded_name != NULL)
994 *-----------------------------------------------------------------------
996 * The variable of the given name has the given value appended to it in
1000 * name name of variable to modify
1001 * val String to append to it
1002 * ctxt Context in which this should occur
1008 * If the variable doesn't exist, it is created. Else the strings
1009 * are concatenated (with a space in between).
1012 * Only if the variable is being sought in the global context is the
1013 * environment searched.
1014 * XXX: Knows its calling circumstances in that if called with ctxt
1015 * an actual target, it will only search that context since only
1016 * a local variable could be being appended to. This is actually
1017 * a big win and must be tolerated.
1018 *-----------------------------------------------------------------------
1021 Var_Append(const char *name, const char *val, GNode *ctxt)
1025 char *expanded_name = NULL;
1027 if (strchr(name, '$') != NULL) {
1028 expanded_name = Var_Subst(NULL, name, ctxt, 0);
1029 if (expanded_name[0] == 0) {
1031 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
1032 "name expands to empty string - ignored\n",
1035 free(expanded_name);
1038 name = expanded_name;
1041 v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
1044 VarAdd(name, val, ctxt);
1046 Buf_AddByte(&v->val, ' ');
1047 Buf_AddBytes(&v->val, strlen(val), val);
1050 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
1051 Buf_GetAll(&v->val, NULL));
1054 if (v->flags & VAR_FROM_ENV) {
1056 * If the original variable came from the environment, we
1057 * have to install it in the global context (we could place
1058 * it in the environment, but then we should provide a way to
1059 * export other variables...)
1061 v->flags &= ~VAR_FROM_ENV;
1062 h = Hash_CreateEntry(&ctxt->context, name, NULL);
1063 Hash_SetValue(h, v);
1066 if (expanded_name != NULL)
1067 free(expanded_name);
1071 *-----------------------------------------------------------------------
1073 * See if the given variable exists.
1076 * name Variable to find
1077 * ctxt Context in which to start search
1080 * TRUE if it does, FALSE if it doesn't
1085 *-----------------------------------------------------------------------
1088 Var_Exists(const char *name, GNode *ctxt)
1093 if ((cp = strchr(name, '$')) != NULL) {
1094 cp = Var_Subst(NULL, name, ctxt, FALSE);
1096 v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
1103 (void)VarFreeEnv(v, TRUE);
1109 *-----------------------------------------------------------------------
1111 * Return the value of the named variable in the given context
1115 * ctxt context in which to search for it
1118 * The value if the variable exists, NULL if it doesn't
1122 *-----------------------------------------------------------------------
1125 Var_Value(const char *name, GNode *ctxt, char **frp)
1129 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1132 char *p = (Buf_GetAll(&v->val, NULL));
1133 if (VarFreeEnv(v, FALSE))
1142 *-----------------------------------------------------------------------
1144 * Remove the tail of the given word and place the result in the given
1149 * addSpace True if need to add a space to the buffer
1150 * before sticking in the head
1151 * buf Buffer in which to store it
1154 * TRUE if characters were added to the buffer (a space needs to be
1155 * added to the buffer before the next word).
1158 * The trimmed word is added to the buffer.
1160 *-----------------------------------------------------------------------
1163 VarHead(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1164 char *word, Boolean addSpace, Buffer *buf,
1169 slash = strrchr(word, '/');
1170 if (slash != NULL) {
1171 if (addSpace && vpstate->varSpace) {
1172 Buf_AddByte(buf, vpstate->varSpace);
1175 Buf_AddBytes(buf, strlen(word), word);
1180 * If no directory part, give . (q.v. the POSIX standard)
1182 if (addSpace && vpstate->varSpace)
1183 Buf_AddByte(buf, vpstate->varSpace);
1184 Buf_AddByte(buf, '.');
1186 return(dummy ? TRUE : TRUE);
1190 *-----------------------------------------------------------------------
1192 * Remove the head of the given word and place the result in the given
1197 * addSpace True if need to add a space to the buffer
1198 * before adding the tail
1199 * buf Buffer in which to store it
1202 * TRUE if characters were added to the buffer (a space needs to be
1203 * added to the buffer before the next word).
1206 * The trimmed word is added to the buffer.
1208 *-----------------------------------------------------------------------
1211 VarTail(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1212 char *word, Boolean addSpace, Buffer *buf,
1217 if (addSpace && vpstate->varSpace) {
1218 Buf_AddByte(buf, vpstate->varSpace);
1221 slash = strrchr(word, '/');
1222 if (slash != NULL) {
1224 Buf_AddBytes(buf, strlen(slash), slash);
1227 Buf_AddBytes(buf, strlen(word), word);
1229 return (dummy ? TRUE : TRUE);
1233 *-----------------------------------------------------------------------
1235 * Place the suffix of the given word in the given buffer.
1239 * addSpace TRUE if need to add a space before placing the
1240 * suffix in the buffer
1241 * buf Buffer in which to store it
1244 * TRUE if characters were added to the buffer (a space needs to be
1245 * added to the buffer before the next word).
1248 * The suffix from the word is placed in the buffer.
1250 *-----------------------------------------------------------------------
1253 VarSuffix(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1254 char *word, Boolean addSpace, Buffer *buf,
1259 dot = strrchr(word, '.');
1261 if (addSpace && vpstate->varSpace) {
1262 Buf_AddByte(buf, vpstate->varSpace);
1265 Buf_AddBytes(buf, strlen(dot), dot);
1269 return (dummy ? addSpace : addSpace);
1273 *-----------------------------------------------------------------------
1275 * Remove the suffix of the given word and place the result in the
1280 * addSpace TRUE if need to add a space to the buffer
1281 * before placing the root in it
1282 * buf Buffer in which to store it
1285 * TRUE if characters were added to the buffer (a space needs to be
1286 * added to the buffer before the next word).
1289 * The trimmed word is added to the buffer.
1291 *-----------------------------------------------------------------------
1294 VarRoot(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1295 char *word, Boolean addSpace, Buffer *buf,
1300 if (addSpace && vpstate->varSpace) {
1301 Buf_AddByte(buf, vpstate->varSpace);
1304 dot = strrchr(word, '.');
1307 Buf_AddBytes(buf, strlen(word), word);
1310 Buf_AddBytes(buf, strlen(word), word);
1312 return (dummy ? TRUE : TRUE);
1316 *-----------------------------------------------------------------------
1318 * Place the word in the buffer if it matches the given pattern.
1319 * Callback function for VarModify to implement the :M modifier.
1322 * word Word to examine
1323 * addSpace TRUE if need to add a space to the buffer
1324 * before adding the word, if it matches
1325 * buf Buffer in which to store it
1326 * pattern Pattern the word must match
1329 * TRUE if a space should be placed in the buffer before the next
1333 * The word may be copied to the buffer.
1335 *-----------------------------------------------------------------------
1338 VarMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1339 char *word, Boolean addSpace, Buffer *buf,
1343 fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
1344 if (Str_Match(word, (char *)pattern)) {
1345 if (addSpace && vpstate->varSpace) {
1346 Buf_AddByte(buf, vpstate->varSpace);
1349 Buf_AddBytes(buf, strlen(word), word);
1356 *-----------------------------------------------------------------------
1358 * Place the word in the buffer if it matches the given pattern.
1359 * Callback function for VarModify to implement the System V %
1363 * word Word to examine
1364 * addSpace TRUE if need to add a space to the buffer
1365 * before adding the word, if it matches
1366 * buf Buffer in which to store it
1367 * patp Pattern the word must match
1370 * TRUE if a space should be placed in the buffer before the next
1374 * The word may be copied to the buffer.
1376 *-----------------------------------------------------------------------
1379 VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
1380 char *word, Boolean addSpace, Buffer *buf,
1385 VarPattern *pat = (VarPattern *)patp;
1388 if (addSpace && vpstate->varSpace)
1389 Buf_AddByte(buf, vpstate->varSpace);
1393 if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
1394 varexp = Var_Subst(NULL, pat->rhs, ctx, 0);
1395 Str_SYSVSubst(buf, varexp, ptr, len);
1398 Buf_AddBytes(buf, strlen(word), word);
1407 *-----------------------------------------------------------------------
1409 * Place the word in the buffer if it doesn't match the given pattern.
1410 * Callback function for VarModify to implement the :N modifier.
1413 * word Word to examine
1414 * addSpace TRUE if need to add a space to the buffer
1415 * before adding the word, if it matches
1416 * buf Buffer in which to store it
1417 * pattern Pattern the word must match
1420 * TRUE if a space should be placed in the buffer before the next
1424 * The word may be copied to the buffer.
1426 *-----------------------------------------------------------------------
1429 VarNoMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1430 char *word, Boolean addSpace, Buffer *buf,
1433 if (!Str_Match(word, (char *)pattern)) {
1434 if (addSpace && vpstate->varSpace) {
1435 Buf_AddByte(buf, vpstate->varSpace);
1438 Buf_AddBytes(buf, strlen(word), word);
1445 *-----------------------------------------------------------------------
1447 * Perform a string-substitution on the given word, placing the
1448 * result in the passed buffer.
1451 * word Word to modify
1452 * addSpace True if space should be added before
1454 * buf Buffer for result
1455 * patternp Pattern for substitution
1458 * TRUE if a space is needed before more characters are added.
1463 *-----------------------------------------------------------------------
1466 VarSubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1467 char *word, Boolean addSpace, Buffer *buf,
1470 int wordLen; /* Length of word */
1471 char *cp; /* General pointer */
1472 VarPattern *pattern = (VarPattern *)patternp;
1474 wordLen = strlen(word);
1475 if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
1476 (VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1478 * Still substituting -- break it down into simple anchored cases
1479 * and if none of them fits, perform the general substitution case.
1481 if ((pattern->flags & VAR_MATCH_START) &&
1482 (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
1484 * Anchored at start and beginning of word matches pattern
1486 if ((pattern->flags & VAR_MATCH_END) &&
1487 (wordLen == pattern->leftLen)) {
1489 * Also anchored at end and matches to the end (word
1490 * is same length as pattern) add space and rhs only
1491 * if rhs is non-null.
1493 if (pattern->rightLen != 0) {
1494 if (addSpace && vpstate->varSpace) {
1495 Buf_AddByte(buf, vpstate->varSpace);
1498 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1500 pattern->flags |= VAR_SUB_MATCHED;
1501 } else if (pattern->flags & VAR_MATCH_END) {
1503 * Doesn't match to end -- copy word wholesale
1508 * Matches at start but need to copy in trailing characters
1510 if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1511 if (addSpace && vpstate->varSpace) {
1512 Buf_AddByte(buf, vpstate->varSpace);
1516 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1517 Buf_AddBytes(buf, wordLen - pattern->leftLen,
1518 (word + pattern->leftLen));
1519 pattern->flags |= VAR_SUB_MATCHED;
1521 } else if (pattern->flags & VAR_MATCH_START) {
1523 * Had to match at start of word and didn't -- copy whole word.
1526 } else if (pattern->flags & VAR_MATCH_END) {
1528 * Anchored at end, Find only place match could occur (leftLen
1529 * characters from the end of the word) and see if it does. Note
1530 * that because the $ will be left at the end of the lhs, we have
1533 cp = word + (wordLen - pattern->leftLen);
1535 (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
1537 * Match found. If we will place characters in the buffer,
1538 * add a space before hand as indicated by addSpace, then
1539 * stuff in the initial, unmatched part of the word followed
1540 * by the right-hand-side.
1542 if (((cp - word) + pattern->rightLen) != 0) {
1543 if (addSpace && vpstate->varSpace) {
1544 Buf_AddByte(buf, vpstate->varSpace);
1548 Buf_AddBytes(buf, cp - word, word);
1549 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1550 pattern->flags |= VAR_SUB_MATCHED;
1553 * Had to match at end and didn't. Copy entire word.
1559 * Pattern is unanchored: search for the pattern in the word using
1560 * String_FindSubstring, copying unmatched portions and the
1561 * right-hand-side for each match found, handling non-global
1562 * substitutions correctly, etc. When the loop is done, any
1563 * remaining part of the word (word and wordLen are adjusted
1564 * accordingly through the loop) is copied straight into the
1566 * addSpace is set FALSE as soon as a space is added to the
1573 origSize = Buf_Size(buf);
1575 cp = Str_FindSubstring(word, pattern->lhs);
1577 if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1578 Buf_AddByte(buf, vpstate->varSpace);
1581 Buf_AddBytes(buf, cp-word, word);
1582 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1583 wordLen -= (cp - word) + pattern->leftLen;
1584 word = cp + pattern->leftLen;
1588 if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
1591 pattern->flags |= VAR_SUB_MATCHED;
1597 if (addSpace && vpstate->varSpace) {
1598 Buf_AddByte(buf, vpstate->varSpace);
1600 Buf_AddBytes(buf, wordLen, word);
1603 * If added characters to the buffer, need to add a space
1604 * before we add any more. If we didn't add any, just return
1605 * the previous value of addSpace.
1607 return ((Buf_Size(buf) != origSize) || addSpace);
1612 if (addSpace && vpstate->varSpace) {
1613 Buf_AddByte(buf, vpstate->varSpace);
1615 Buf_AddBytes(buf, wordLen, word);
1621 *-----------------------------------------------------------------------
1623 * Print the error caused by a regcomp or regexec call.
1629 * An error gets printed.
1631 *-----------------------------------------------------------------------
1634 VarREError(int errnum, regex_t *pat, const char *str)
1639 errlen = regerror(errnum, pat, 0, 0);
1640 errbuf = bmake_malloc(errlen);
1641 regerror(errnum, pat, errbuf, errlen);
1642 Error("%s: %s", str, errbuf);
1648 *-----------------------------------------------------------------------
1649 * VarRESubstitute --
1650 * Perform a regex substitution on the given word, placing the
1651 * result in the passed buffer.
1654 * TRUE if a space is needed before more characters are added.
1659 *-----------------------------------------------------------------------
1662 VarRESubstitute(GNode *ctx MAKE_ATTR_UNUSED,
1663 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1664 char *word, Boolean addSpace, Buffer *buf,
1674 #define MAYBE_ADD_SPACE() \
1675 if (addSpace && !added) \
1676 Buf_AddByte(buf, ' '); \
1683 if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1684 (VAR_SUB_ONE|VAR_SUB_MATCHED))
1688 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1693 pat->flags |= VAR_SUB_MATCHED;
1694 if (pat->matches[0].rm_so > 0) {
1696 Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1699 for (rp = pat->replace; *rp; rp++) {
1700 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1702 Buf_AddByte(buf,rp[1]);
1705 else if ((*rp == '&') ||
1706 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1724 if (n > pat->nsub) {
1725 Error("No subexpression %s", &errstr[0]);
1728 } else if ((pat->matches[n].rm_so == -1) &&
1729 (pat->matches[n].rm_eo == -1)) {
1730 Error("No match for subexpression %s", &errstr[0]);
1734 subbuf = wp + pat->matches[n].rm_so;
1735 sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1740 Buf_AddBytes(buf, sublen, subbuf);
1744 Buf_AddByte(buf, *rp);
1747 wp += pat->matches[0].rm_eo;
1748 if (pat->flags & VAR_SUB_GLOBAL) {
1749 flags |= REG_NOTBOL;
1750 if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1752 Buf_AddByte(buf, *wp);
1761 Buf_AddBytes(buf, strlen(wp), wp);
1765 VarREError(xrv, &pat->re, "Unexpected regex error");
1770 Buf_AddBytes(buf,strlen(wp),wp);
1774 return(addSpace||added);
1781 *-----------------------------------------------------------------------
1783 * Implements the :@<temp>@<string>@ modifier of ODE make.
1784 * We set the temp variable named in pattern.lhs to word and expand
1785 * pattern.rhs storing the result in the passed buffer.
1788 * word Word to modify
1789 * addSpace True if space should be added before
1791 * buf Buffer for result
1792 * pattern Datafor substitution
1795 * TRUE if a space is needed before more characters are added.
1800 *-----------------------------------------------------------------------
1803 VarLoopExpand(GNode *ctx MAKE_ATTR_UNUSED,
1804 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1805 char *word, Boolean addSpace, Buffer *buf,
1808 VarLoop_t *loop = (VarLoop_t *)loopp;
1812 if (word && *word) {
1813 Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
1814 s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum);
1815 if (s != NULL && *s != '\0') {
1816 if (addSpace && *s != '\n')
1817 Buf_AddByte(buf, ' ');
1818 Buf_AddBytes(buf, (slen = strlen(s)), s);
1819 addSpace = (slen > 0 && s[slen - 1] != '\n');
1828 *-----------------------------------------------------------------------
1830 * Implements the :[start..end] modifier.
1831 * This is a special case of VarModify since we want to be able
1832 * to scan the list backwards if start > end.
1835 * str String whose words should be trimmed
1836 * seldata words to select
1839 * A string of all the words selected.
1844 *-----------------------------------------------------------------------
1847 VarSelectWords(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1848 const char *str, VarSelectWords_t *seldata)
1850 Buffer buf; /* Buffer for the new string */
1851 Boolean addSpace; /* TRUE if need to add a space to the
1852 * buffer before adding the trimmed
1854 char **av; /* word list */
1855 char *as; /* word list memory */
1857 int start, end, step;
1862 if (vpstate->oneBigWord) {
1863 /* fake what brk_string() would do if there were only one word */
1865 av = bmake_malloc((ac + 1) * sizeof(char *));
1866 as = bmake_strdup(str);
1870 av = brk_string(str, &ac, FALSE, &as);
1874 * Now sanitize seldata.
1875 * If seldata->start or seldata->end are negative, convert them to
1876 * the positive equivalents (-1 gets converted to argc, -2 gets
1877 * converted to (argc-1), etc.).
1879 if (seldata->start < 0)
1880 seldata->start = ac + seldata->start + 1;
1881 if (seldata->end < 0)
1882 seldata->end = ac + seldata->end + 1;
1885 * We avoid scanning more of the list than we need to.
1887 if (seldata->start > seldata->end) {
1888 start = MIN(ac, seldata->start) - 1;
1889 end = MAX(0, seldata->end - 1);
1892 start = MAX(0, seldata->start - 1);
1893 end = MIN(ac, seldata->end);
1898 (step < 0 && i >= end) || (step > 0 && i < end);
1900 if (av[i] && *av[i]) {
1901 if (addSpace && vpstate->varSpace) {
1902 Buf_AddByte(&buf, vpstate->varSpace);
1904 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
1912 return Buf_Destroy(&buf, FALSE);
1918 * Replace each word with the result of realpath()
1922 VarRealpath(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1923 char *word, Boolean addSpace, Buffer *buf,
1924 void *patternp MAKE_ATTR_UNUSED)
1927 char rbuf[MAXPATHLEN];
1930 if (addSpace && vpstate->varSpace) {
1931 Buf_AddByte(buf, vpstate->varSpace);
1934 rp = realpath(word, rbuf);
1935 if (rp && *rp == '/' && stat(rp, &st) == 0)
1938 Buf_AddBytes(buf, strlen(word), word);
1943 *-----------------------------------------------------------------------
1945 * Modify each of the words of the passed string using the given
1946 * function. Used to implement all modifiers.
1949 * str String whose words should be trimmed
1950 * modProc Function to use to modify them
1951 * datum Datum to pass it
1954 * A string of all the words modified appropriately.
1959 *-----------------------------------------------------------------------
1962 VarModify(GNode *ctx, Var_Parse_State *vpstate,
1964 Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
1965 Boolean, Buffer *, void *),
1968 Buffer buf; /* Buffer for the new string */
1969 Boolean addSpace; /* TRUE if need to add a space to the
1970 * buffer before adding the trimmed
1972 char **av; /* word list */
1973 char *as; /* word list memory */
1979 if (vpstate->oneBigWord) {
1980 /* fake what brk_string() would do if there were only one word */
1982 av = bmake_malloc((ac + 1) * sizeof(char *));
1983 as = bmake_strdup(str);
1987 av = brk_string(str, &ac, FALSE, &as);
1990 for (i = 0; i < ac; i++) {
1991 addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum);
1997 return Buf_Destroy(&buf, FALSE);
2002 VarWordCompare(const void *a, const void *b)
2004 int r = strcmp(*(const char * const *)a, *(const char * const *)b);
2009 *-----------------------------------------------------------------------
2011 * Order the words in the string.
2014 * str String whose words should be sorted.
2015 * otype How to order: s - sort, x - random.
2018 * A string containing the words ordered.
2023 *-----------------------------------------------------------------------
2026 VarOrder(const char *str, const char otype)
2028 Buffer buf; /* Buffer for the new string */
2029 char **av; /* word list [first word does not count] */
2030 char *as; /* word list memory */
2035 av = brk_string(str, &ac, FALSE, &as);
2039 case 's': /* sort alphabetically */
2040 qsort(av, ac, sizeof(char *), VarWordCompare);
2042 case 'x': /* randomize */
2048 * We will use [ac..2] range for mod factors. This will produce
2049 * random numbers in [(ac-1)..0] interval, and minimal
2050 * reasonable value for mod factor is 2 (the mod 1 will produce
2051 * 0 with probability 1).
2053 for (i = ac-1; i > 0; i--) {
2054 rndidx = random() % (i + 1);
2062 } /* end of switch */
2064 for (i = 0; i < ac; i++) {
2065 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2067 Buf_AddByte(&buf, ' ');
2073 return Buf_Destroy(&buf, FALSE);
2078 *-----------------------------------------------------------------------
2080 * Remove adjacent duplicate words.
2083 * str String whose words should be sorted
2086 * A string containing the resulting words.
2091 *-----------------------------------------------------------------------
2094 VarUniq(const char *str)
2096 Buffer buf; /* Buffer for new string */
2097 char **av; /* List of words to affect */
2098 char *as; /* Word list memory */
2102 av = brk_string(str, &ac, FALSE, &as);
2105 for (j = 0, i = 1; i < ac; i++)
2106 if (strcmp(av[i], av[j]) != 0 && (++j != i))
2111 for (i = 0; i < ac; i++) {
2112 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2114 Buf_AddByte(&buf, ' ');
2120 return Buf_Destroy(&buf, FALSE);
2125 *-----------------------------------------------------------------------
2127 * Pass through the tstr looking for 1) escaped delimiters,
2128 * '$'s and backslashes (place the escaped character in
2129 * uninterpreted) and 2) unescaped $'s that aren't before
2130 * the delimiter (expand the variable substitution unless flags
2131 * has VAR_NOSUBST set).
2132 * Return the expanded string or NULL if the delimiter was missing
2133 * If pattern is specified, handle escaped ampersands, and replace
2134 * unescaped ampersands with the lhs of the pattern.
2137 * A string of all the words modified appropriately.
2138 * If length is specified, return the string length of the buffer
2139 * If flags is specified and the last character of the pattern is a
2140 * $ set the VAR_MATCH_END bit of flags.
2144 *-----------------------------------------------------------------------
2147 VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
2148 int errnum, const char **tstr, int delim, int *flags,
2149 int *length, VarPattern *pattern)
2160 #define IS_A_MATCH(cp, delim) \
2161 ((cp[0] == '\\') && ((cp[1] == delim) || \
2162 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
2165 * Skim through until the matching delimiter is found;
2166 * pick up variable substitutions on the way. Also allow
2167 * backslashes to quote the delimiter, $, and \, but don't
2168 * touch other backslashes.
2170 for (cp = *tstr; *cp && (*cp != delim); cp++) {
2171 if (IS_A_MATCH(cp, delim)) {
2172 Buf_AddByte(&buf, cp[1]);
2174 } else if (*cp == '$') {
2175 if (cp[1] == delim) {
2177 Buf_AddByte(&buf, *cp);
2180 * Unescaped $ at end of pattern => anchor
2183 *flags |= VAR_MATCH_END;
2185 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
2191 * If unescaped dollar sign not before the
2192 * delimiter, assume it's a variable
2193 * substitution and recurse.
2195 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2196 Buf_AddBytes(&buf, strlen(cp2), cp2);
2201 const char *cp2 = &cp[1];
2203 if (*cp2 == PROPEN || *cp2 == BROPEN) {
2205 * Find the end of this variable reference
2206 * and suck it in without further ado.
2207 * It will be interperated later.
2210 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
2213 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
2214 if (cp2[-1] != '\\') {
2221 Buf_AddBytes(&buf, cp2 - cp, cp);
2224 Buf_AddByte(&buf, *cp);
2228 else if (pattern && *cp == '&')
2229 Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
2231 Buf_AddByte(&buf, *cp);
2241 *length = Buf_Size(&buf);
2242 rstr = Buf_Destroy(&buf, FALSE);
2244 fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
2249 *-----------------------------------------------------------------------
2251 * Quote shell meta-characters in the string
2259 *-----------------------------------------------------------------------
2266 /* This should cover most shells :-( */
2267 static const char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
2268 const char *newline;
2271 if ((newline = Shell_GetNewline()) == NULL)
2273 nlen = strlen(newline);
2276 while (*str != '\0') {
2277 if ((len = strcspn(str, meta)) != 0) {
2278 Buf_AddBytes(&buf, len, str);
2280 } else if (*str == '\n') {
2281 Buf_AddBytes(&buf, nlen, newline);
2284 Buf_AddByte(&buf, '\\');
2285 Buf_AddByte(&buf, *str);
2289 str = Buf_Destroy(&buf, FALSE);
2291 fprintf(debug_file, "QuoteMeta: [%s]\n", str);
2296 *-----------------------------------------------------------------------
2298 * Hash the string using the MurmurHash3 algorithm.
2299 * Output is computed using 32bit Little Endian arithmetic.
2302 * str String to modify
2305 * Hash value of str, encoded as 8 hex digits.
2310 *-----------------------------------------------------------------------
2315 static const char hexdigits[16] = "0123456789abcdef";
2318 unsigned char *ustr = (unsigned char *)str;
2319 uint32_t h, k, c1, c2;
2328 for (len = len2; len; ) {
2332 k = (ustr[3] << 24) | (ustr[2] << 16) | (ustr[1] << 8) | ustr[0];
2337 k |= (ustr[2] << 16);
2339 k |= (ustr[1] << 8);
2344 c1 = c1 * 5 + 0x7b7d159cU;
2345 c2 = c2 * 5 + 0x6bce6396U;
2347 k = (k << 11) ^ (k >> 21);
2349 h = (h << 13) ^ (h >> 19);
2350 h = h * 5 + 0x52dce729U;
2360 for (len = 0; len < 8; ++len) {
2361 Buf_AddByte(&buf, hexdigits[h & 15]);
2365 return Buf_Destroy(&buf, FALSE);
2369 VarStrftime(const char *fmt, int zulu)
2377 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2379 buf[sizeof(buf) - 1] = '\0';
2380 return bmake_strdup(buf);
2384 * Now we need to apply any modifiers the user wants applied.
2386 * :M<pattern> words which match the given <pattern>.
2387 * <pattern> is of the standard file
2389 * :N<pattern> words which do not match the given <pattern>.
2390 * :S<d><pat1><d><pat2><d>[1gW]
2391 * Substitute <pat2> for <pat1> in the value
2392 * :C<d><pat1><d><pat2><d>[1gW]
2393 * Substitute <pat2> for regex <pat1> in the value
2394 * :H Substitute the head of each word
2395 * :T Substitute the tail of each word
2396 * :E Substitute the extension (minus '.') of
2398 * :R Substitute the root of each word
2399 * (pathname minus the suffix).
2400 * :O ("Order") Alphabeticaly sort words in variable.
2401 * :Ox ("intermiX") Randomize words in variable.
2402 * :u ("uniq") Remove adjacent duplicate words.
2403 * :tu Converts the variable contents to uppercase.
2404 * :tl Converts the variable contents to lowercase.
2405 * :ts[c] Sets varSpace - the char used to
2406 * separate words to 'c'. If 'c' is
2407 * omitted then no separation is used.
2408 * :tW Treat the variable contents as a single
2409 * word, even if it contains spaces.
2410 * (Mnemonic: one big 'W'ord.)
2411 * :tw Treat the variable contents as multiple
2412 * space-separated words.
2413 * (Mnemonic: many small 'w'ords.)
2414 * :[index] Select a single word from the value.
2415 * :[start..end] Select multiple words from the value.
2416 * :[*] or :[0] Select the entire value, as a single
2417 * word. Equivalent to :tW.
2418 * :[@] Select the entire value, as multiple
2419 * words. Undoes the effect of :[*].
2420 * Equivalent to :tw.
2421 * :[#] Returns the number of words in the value.
2423 * :?<true-value>:<false-value>
2424 * If the variable evaluates to true, return
2425 * true value, else return the second value.
2426 * :lhs=rhs Like :S, but the rhs goes to the end of
2428 * :sh Treat the current value as a command
2429 * to be run, new value is its output.
2430 * The following added so we can handle ODE makefiles.
2431 * :@<tmpvar>@<newval>@
2432 * Assign a temporary local variable <tmpvar>
2433 * to the current value of each word in turn
2434 * and replace each word with the result of
2435 * evaluating <newval>
2436 * :D<newval> Use <newval> as value if variable defined
2437 * :U<newval> Use <newval> as value if variable undefined
2438 * :L Use the name of the variable as the value.
2439 * :P Use the path of the node that has the same
2440 * name as the variable as the value. This
2441 * basically includes an implied :L so that
2442 * the common method of refering to the path
2443 * of your dependent 'x' in a rule is to use
2444 * the form '${x:P}'.
2445 * :!<cmd>! Run cmd much the same as :sh run's the
2446 * current value of the variable.
2447 * The ::= modifiers, actually assign a value to the variable.
2448 * Their main purpose is in supporting modifiers of .for loop
2449 * iterators and other obscure uses. They always expand to
2450 * nothing. In a target rule that would otherwise expand to an
2451 * empty line they can be preceded with @: to keep make happy.
2455 * .for i in ${.TARGET} ${.TARGET:R}.gz
2460 * ::=<str> Assigns <str> as the new value of variable.
2461 * ::?=<str> Assigns <str> as value of variable if
2462 * it was not already set.
2463 * ::+=<str> Appends <str> to variable.
2464 * ::!=<cmd> Assigns output of <cmd> as the new value of
2468 /* we now have some modifiers with long names */
2469 #define STRMOD_MATCH(s, want, n) \
2470 (strncmp(s, want, n) == 0 && (s[n] == endc || s[n] == ':'))
2473 ApplyModifiers(char *nstr, const char *tstr,
2474 int startc, int endc,
2475 Var *v, GNode *ctxt, Boolean errnum,
2476 int *lengthPtr, void **freePtr)
2479 const char *cp; /* Secondary pointer into str (place marker
2481 char *newStr; /* New value to return */
2482 char termc; /* Character which terminated scan */
2483 int cnt; /* Used to count brace pairs when variable in
2484 * in parens or braces */
2486 int modifier; /* that we are processing */
2487 Var_Parse_State parsestate; /* Flags passed to helper functions */
2490 parsestate.oneBigWord = FALSE;
2491 parsestate.varSpace = ' '; /* word separator */
2495 while (*tstr && *tstr != endc) {
2499 * We may have some complex modifiers in a variable.
2506 rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
2509 * If we have not parsed up to endc or ':',
2510 * we are not interested.
2512 if (rval != NULL && *rval &&
2513 (c = tstr[rlen]) != '\0' &&
2522 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
2523 rval, rlen, tstr, rlen, tstr + rlen);
2528 if (rval != NULL && *rval) {
2531 nstr = ApplyModifiers(nstr, rval,
2533 v, ctxt, errnum, &used, freePtr);
2534 if (nstr == var_Error
2535 || (nstr == varNoError && errnum == 0)
2536 || strlen(rval) != (size_t) used) {
2539 goto out; /* error already reported */
2546 else if (!*tstr && endc) {
2547 Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name);
2554 fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", v->name,
2558 switch ((modifier = *tstr)) {
2561 if (tstr[1] == '=' ||
2563 (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
2565 * "::=", "::!=", "::+=", or "::?="
2567 GNode *v_ctxt; /* context where v belongs */
2573 if (v->name[0] == 0)
2579 if (v->flags & VAR_JUNK) {
2581 * We need to bmake_strdup() it incase
2582 * VarGetPattern() recurses.
2585 v->name = bmake_strdup(v->name);
2586 } else if (ctxt != VAR_GLOBAL) {
2587 Var *gv = VarFind(v->name, ctxt, 0);
2589 v_ctxt = VAR_GLOBAL;
2591 VarFreeEnv(gv, TRUE);
2594 switch ((how = *tstr)) {
2604 delim = startc == PROPEN ? PRCLOSE : BRCLOSE;
2607 pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2611 if (v->flags & VAR_JUNK) {
2612 /* restore original name */
2616 if (pattern.rhs == NULL)
2624 Var_Append(v->name, pattern.rhs, v_ctxt);
2627 newStr = Cmd_Exec(pattern.rhs, &emsg);
2631 Var_Set(v->name, newStr, v_ctxt, 0);
2636 if ((v->flags & VAR_JUNK) == 0)
2640 Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2643 free(UNCONST(pattern.rhs));
2647 goto default_case; /* "::<unrecognised>" */
2652 int flags = VAR_NOSUBST;
2656 if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum,
2658 &flags, &loop.tvarLen,
2662 if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum,
2664 &flags, &loop.strLen,
2671 loop.errnum = errnum;
2673 newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
2680 #ifdef MAKE_FREEBSD_UL
2684 /* we have to be careful, since :U is used internally */
2685 if (nc == ':' || nc == endc) {
2686 char *dp = bmake_strdup(nstr);
2687 for (newStr = dp; *dp; dp++)
2688 *dp = toupper((unsigned char)*dp);
2691 break; /* yes inside the conditional */
2698 Buffer buf; /* Buffer for patterns */
2699 int wantit; /* want data in buffer */
2702 * Pass through tstr looking for 1) escaped delimiters,
2703 * '$'s and backslashes (place the escaped character in
2704 * uninterpreted) and 2) unescaped $'s that aren't before
2705 * the delimiter (expand the variable substitution).
2706 * The result is left in the Buffer buf.
2710 *cp != endc && *cp != ':' && *cp != '\0';
2712 if ((*cp == '\\') &&
2718 Buf_AddByte(&buf, cp[1]);
2720 } else if (*cp == '$') {
2722 * If unescaped dollar sign, assume it's a
2723 * variable substitution and recurse.
2729 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2730 Buf_AddBytes(&buf, strlen(cp2), cp2);
2735 Buf_AddByte(&buf, *cp);
2742 wantit = ((v->flags & VAR_JUNK) != 0);
2744 wantit = ((v->flags & VAR_JUNK) == 0);
2745 if ((v->flags & VAR_JUNK) != 0)
2746 v->flags |= VAR_KEEP;
2748 newStr = Buf_Destroy(&buf, FALSE);
2751 Buf_Destroy(&buf, TRUE);
2756 #ifdef MAKE_FREEBSD_UL
2758 char *dp = bmake_strdup(nstr);
2759 for (newStr = dp; *dp; dp++)
2760 *dp = tolower((unsigned char)*dp);
2768 if ((v->flags & VAR_JUNK) != 0)
2769 v->flags |= VAR_KEEP;
2770 newStr = bmake_strdup(v->name);
2779 if ((v->flags & VAR_JUNK) != 0)
2780 v->flags |= VAR_KEEP;
2781 gn = Targ_FindNode(v->name, TARG_NOCREATE);
2782 if (gn == NULL || gn->type & OP_NOPATH) {
2784 } else if (gn->path) {
2785 newStr = bmake_strdup(gn->path);
2787 newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
2790 newStr = bmake_strdup(v->name);
2805 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2807 NULL, &pattern.rightLen,
2810 newStr = Cmd_Exec(pattern.rhs, &emsg);
2811 free(UNCONST(pattern.rhs));
2816 if (v->flags & VAR_JUNK) {
2817 v->flags |= VAR_KEEP;
2824 * Look for the closing ']', recursively
2825 * expanding any embedded variables.
2827 * estr is a pointer to the expanded result,
2828 * which we must free().
2832 cp = tstr+1; /* point to char after '[' */
2833 delim = ']'; /* look for closing ']' */
2834 estr = VarGetPattern(ctxt, &parsestate,
2838 goto cleanup; /* report missing ']' */
2839 /* now cp points just after the closing ']' */
2841 if (cp[0] != ':' && cp[0] != endc) {
2842 /* Found junk after ']' */
2846 if (estr[0] == '\0') {
2847 /* Found empty square brackets in ":[]". */
2850 } else if (estr[0] == '#' && estr[1] == '\0') {
2854 * We will need enough space for the decimal
2855 * representation of an int. We calculate the
2856 * space needed for the octal representation,
2857 * and add enough slop to cope with a '-' sign
2858 * (which should never be needed) and a '\0'
2859 * string terminator.
2862 (sizeof(int) * CHAR_BIT + 2) / 3 + 2;
2864 newStr = bmake_malloc(newStrSize);
2865 if (parsestate.oneBigWord) {
2866 strncpy(newStr, "1", newStrSize);
2868 /* XXX: brk_string() is a rather expensive
2869 * way of counting words. */
2874 av = brk_string(nstr, &ac, FALSE, &as);
2875 snprintf(newStr, newStrSize, "%d", ac);
2882 } else if (estr[0] == '*' && estr[1] == '\0') {
2884 parsestate.oneBigWord = TRUE;
2889 } else if (estr[0] == '@' && estr[1] == '\0') {
2891 parsestate.oneBigWord = FALSE;
2898 * We expect estr to contain a single
2899 * integer for :[N], or two integers
2900 * separated by ".." for :[start..end].
2904 VarSelectWords_t seldata = { 0, 0 };
2906 seldata.start = strtol(estr, &ep, 0);
2908 /* Found junk instead of a number */
2911 } else if (ep[0] == '\0') {
2912 /* Found only one integer in :[N] */
2913 seldata.end = seldata.start;
2914 } else if (ep[0] == '.' && ep[1] == '.' &&
2916 /* Expecting another integer after ".." */
2918 seldata.end = strtol(ep, &ep, 0);
2919 if (ep[0] != '\0') {
2920 /* Found junk after ".." */
2925 /* Found junk instead of ".." */
2930 * Now seldata is properly filled in,
2931 * but we still have to check for 0 as
2934 if (seldata.start == 0 && seldata.end == 0) {
2935 /* ":[0]" or perhaps ":[0..0]" */
2936 parsestate.oneBigWord = TRUE;
2941 } else if (seldata.start == 0 ||
2943 /* ":[0..N]" or ":[N..0]" */
2948 * Normal case: select the words
2949 * described by seldata.
2951 newStr = VarSelectWords(ctxt, &parsestate,
2961 cp = tstr + 1; /* make sure it is set */
2962 if (STRMOD_MATCH(tstr, "gmtime", 6)) {
2963 newStr = VarStrftime(nstr, 1);
2971 cp = tstr + 1; /* make sure it is set */
2972 if (STRMOD_MATCH(tstr, "hash", 4)) {
2973 newStr = VarHash(nstr);
2981 cp = tstr + 1; /* make sure it is set */
2982 if (STRMOD_MATCH(tstr, "localtime", 9)) {
2983 newStr = VarStrftime(nstr, 0);
2992 cp = tstr + 1; /* make sure it is set */
2993 if (tstr[1] != endc && tstr[1] != ':') {
2994 if (tstr[1] == 's') {
2996 * Use the char (if any) at tstr[2]
2997 * as the word separator.
3001 if (tstr[2] != endc &&
3002 (tstr[3] == endc || tstr[3] == ':')) {
3003 /* ":ts<unrecognised><endc>" or
3004 * ":ts<unrecognised>:" */
3005 parsestate.varSpace = tstr[2];
3007 } else if (tstr[2] == endc || tstr[2] == ':') {
3008 /* ":ts<endc>" or ":ts:" */
3009 parsestate.varSpace = 0; /* no separator */
3011 } else if (tstr[2] == '\\') {
3014 parsestate.varSpace = '\n';
3018 parsestate.varSpace = '\t';
3022 if (isdigit((unsigned char)tstr[3])) {
3025 parsestate.varSpace =
3026 strtoul(&tstr[3], &ep, 0);
3027 if (*ep != ':' && *ep != endc)
3032 * ":ts<backslash><unrecognised>".
3040 * Found ":ts<unrecognised><unrecognised>".
3048 * We cannot be certain that VarModify
3049 * will be used - even if there is a
3050 * subsequent modifier, so do a no-op
3051 * VarSubstitute now to for str to be
3052 * re-expanded without the spaces.
3054 pattern.flags = VAR_SUB_ONE;
3055 pattern.lhs = pattern.rhs = "\032";
3056 pattern.leftLen = pattern.rightLen = 1;
3058 newStr = VarModify(ctxt, &parsestate, nstr,
3061 } else if (tstr[2] == endc || tstr[2] == ':') {
3063 * Check for two-character options:
3066 if (tstr[1] == 'A') { /* absolute path */
3067 newStr = VarModify(ctxt, &parsestate, nstr,
3071 } else if (tstr[1] == 'u') {
3072 char *dp = bmake_strdup(nstr);
3073 for (newStr = dp; *dp; dp++)
3074 *dp = toupper((unsigned char)*dp);
3077 } else if (tstr[1] == 'l') {
3078 char *dp = bmake_strdup(nstr);
3079 for (newStr = dp; *dp; dp++)
3080 *dp = tolower((unsigned char)*dp);
3083 } else if (tstr[1] == 'W' || tstr[1] == 'w') {
3084 parsestate.oneBigWord = (tstr[1] == 'W');
3089 /* Found ":t<unrecognised>:" or
3090 * ":t<unrecognised><endc>". */
3095 * Found ":t<unrecognised><unrecognised>".
3101 * Found ":t<endc>" or ":t:".
3111 const char *endpat; /* points just after end of pattern */
3113 Boolean copy; /* pattern should be, or has been, copied */
3121 * In the loop below, ignore ':' unless we are at
3122 * (or back to) the original brace level.
3123 * XXX This will likely not work right if $() and ${}
3127 *cp != '\0' && !(*cp == ':' && nest == 1);
3132 cp[1] == endc || cp[1] == startc)) {
3142 if (*cp == '(' || *cp == '{')
3144 if (*cp == ')' || *cp == '}') {
3154 * Need to compress the \:'s out of the pattern, so
3155 * allocate enough room to hold the uncompressed
3156 * pattern (note that cp started at tstr+1, so
3157 * cp - tstr takes the null byte into account) and
3158 * compress the pattern into the space.
3160 pattern = bmake_malloc(cp - tstr);
3161 for (cp2 = pattern, cp = tstr + 1;
3165 if ((*cp == '\\') && (cp+1 < endpat) &&
3166 (cp[1] == ':' || cp[1] == endc)) {
3175 * Either Var_Subst or VarModify will need a
3176 * nul-terminated string soon, so construct one now.
3178 pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
3182 * pattern contains embedded '$', so use Var_Subst to
3186 pattern = Var_Subst(NULL, cp2, ctxt, errnum);
3190 fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
3191 v->name, nstr, pattern);
3193 newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
3196 newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
3205 Var_Parse_State tmpparsestate;
3208 tmpparsestate = parsestate;
3213 * If pattern begins with '^', it is anchored to the
3214 * start of the word -- skip over it and flag pattern.
3217 pattern.flags |= VAR_MATCH_START;
3222 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3229 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3236 * Check for global substitution. If 'g' after the final
3237 * delimiter, substitution is global and is marked that
3243 pattern.flags |= VAR_SUB_GLOBAL;
3246 pattern.flags |= VAR_SUB_ONE;
3249 tmpparsestate.oneBigWord = TRUE;
3256 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3261 * Free the two strings.
3263 free(UNCONST(pattern.lhs));
3264 free(UNCONST(pattern.rhs));
3273 /* find ':', and then substitute accordingly */
3279 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3285 /* BROPEN or PROPEN */
3287 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3295 if (Cond_EvalExpression(NULL, v->name, &value, 0)
3297 Error("Bad conditional expression `%s' in %s?%s:%s",
3298 v->name, v->name, pattern.lhs, pattern.rhs);
3303 newStr = UNCONST(pattern.lhs);
3304 free(UNCONST(pattern.rhs));
3306 newStr = UNCONST(pattern.rhs);
3307 free(UNCONST(pattern.lhs));
3309 if (v->flags & VAR_JUNK) {
3310 v->flags |= VAR_KEEP;
3317 VarREPattern pattern;
3320 Var_Parse_State tmpparsestate;
3323 tmpparsestate = parsestate;
3329 if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim,
3330 NULL, NULL, NULL)) == NULL)
3333 if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
3334 errnum, &cp, delim, NULL,
3335 NULL, NULL)) == NULL){
3343 pattern.flags |= VAR_SUB_GLOBAL;
3346 pattern.flags |= VAR_SUB_ONE;
3349 tmpparsestate.oneBigWord = TRUE;
3357 error = regcomp(&pattern.re, re, REG_EXTENDED);
3360 *lengthPtr = cp - start + 1;
3361 VarREError(error, &pattern.re, "RE substitution error");
3362 free(pattern.replace);
3366 pattern.nsub = pattern.re.re_nsub + 1;
3367 if (pattern.nsub < 1)
3369 if (pattern.nsub > 10)
3371 pattern.matches = bmake_malloc(pattern.nsub *
3372 sizeof(regmatch_t));
3373 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3376 regfree(&pattern.re);
3377 free(pattern.replace);
3378 free(pattern.matches);
3384 if (tstr[1] == endc || tstr[1] == ':') {
3385 newStr = VarQuote(nstr);
3392 if (tstr[1] == endc || tstr[1] == ':') {
3393 newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
3401 if (tstr[1] == endc || tstr[1] == ':') {
3402 newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
3410 if (tstr[1] == endc || tstr[1] == ':') {
3411 newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
3419 if (tstr[1] == endc || tstr[1] == ':') {
3420 newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
3431 cp = tstr + 1; /* skip to the rest in any case */
3432 if (tstr[1] == endc || tstr[1] == ':') {
3435 } else if ( (tstr[1] == 'x') &&
3436 (tstr[2] == endc || tstr[2] == ':') ) {
3443 newStr = VarOrder(nstr, otype);
3447 if (tstr[1] == endc || tstr[1] == ':') {
3448 newStr = VarUniq(nstr);
3456 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
3458 newStr = Cmd_Exec(nstr, &emsg);
3472 * This can either be a bogus modifier or a System-V
3473 * substitution command.
3481 * First we make a pass through the string trying
3482 * to verify it is a SYSV-make-style translation:
3483 * it must be: <string1>=<string2>)
3487 while (*cp != '\0' && cnt) {
3490 /* continue looking for endc */
3492 else if (*cp == endc)
3494 else if (*cp == startc)
3499 if (*cp == endc && eqFound) {
3502 * Now we break this sucker into the lhs and
3503 * rhs. We must null terminate them of course.
3507 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
3508 errnum, &cp, delim, &pattern.flags,
3509 &pattern.leftLen, NULL)) == NULL)
3512 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
3513 errnum, &cp, delim, NULL, &pattern.rightLen,
3518 * SYSV modifications happen through the whole
3519 * string. Note the pattern is anchored at the end.
3523 if (pattern.leftLen == 0 && *nstr == '\0') {
3524 newStr = nstr; /* special case */
3526 newStr = VarModify(ctxt, &parsestate, nstr,
3530 free(UNCONST(pattern.lhs));
3531 free(UNCONST(pattern.rhs));
3535 Error("Unknown modifier '%c'", *tstr);
3537 *cp != ':' && *cp != endc && *cp != '\0';
3546 fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
3547 v->name, modifier, newStr);
3550 if (newStr != nstr) {
3556 if (nstr != var_Error && nstr != varNoError) {
3560 if (termc == '\0' && endc != '\0') {
3561 Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier);
3562 } else if (termc == ':') {
3568 *lengthPtr = tstr - start;
3573 Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
3577 *lengthPtr = cp - start;
3579 Error("Unclosed substitution for %s (%c missing)",
3589 *-----------------------------------------------------------------------
3591 * Given the start of a variable invocation, extract the variable
3592 * name and find its value, then modify it according to the
3596 * str The string to parse
3597 * ctxt The context for the variable
3598 * errnum TRUE if undefined variables are an error
3599 * lengthPtr OUT: The length of the specification
3600 * freePtr OUT: Non-NULL if caller should free *freePtr
3603 * The (possibly-modified) value of the variable or var_Error if the
3604 * specification is invalid. The length of the specification is
3605 * placed in *lengthPtr (for invalid specifications, this is just
3607 * If *freePtr is non-NULL then it's a pointer that the caller
3608 * should pass to free() to free memory used by the result.
3613 *-----------------------------------------------------------------------
3615 /* coverity[+alloc : arg-*4] */
3617 Var_Parse(const char *str, GNode *ctxt, Boolean errnum, int *lengthPtr,
3620 const char *tstr; /* Pointer into str */
3621 Var *v; /* Variable in invocation */
3622 Boolean haveModifier;/* TRUE if have modifiers for the variable */
3623 char endc; /* Ending character when variable in parens
3625 char startc; /* Starting character when variable in parens
3627 int vlen; /* Length of variable name */
3628 const char *start; /* Points to original start of str */
3629 char *nstr; /* New string, used during expansion */
3630 Boolean dynamic; /* TRUE if the variable is local and we're
3631 * expanding it in a non-local context. This
3632 * is done to support dynamic sources. The
3633 * result is just the invocation, unaltered */
3634 Var_Parse_State parsestate; /* Flags passed to helper functions */
3640 parsestate.oneBigWord = FALSE;
3641 parsestate.varSpace = ' '; /* word separator */
3644 if (startc != PROPEN && startc != BROPEN) {
3646 * If it's not bounded by braces of some sort, life is much simpler.
3647 * We just need to check for the first character and return the
3648 * value if it exists.
3651 /* Error out some really stupid names */
3652 if (startc == '\0' || strchr(")}:$", startc)) {
3659 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3663 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
3665 * If substituting a local variable in a non-local context,
3666 * assume it's for dynamic source stuff. We have to handle
3667 * this specially and return the longhand for the variable
3668 * with the dollar sign escaped so it makes it back to the
3669 * caller. Only four of the local variables are treated
3670 * specially as they are the only four that will be set
3671 * when dynamic sources are expanded.
3675 return UNCONST("$(.TARGET)");
3677 return UNCONST("$(.ARCHIVE)");
3679 return UNCONST("$(.PREFIX)");
3681 return UNCONST("$(.MEMBER)");
3687 return (errnum ? var_Error : varNoError);
3689 haveModifier = FALSE;
3694 Buffer buf; /* Holds the variable name */
3696 endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3700 * Skip to the end character or a colon, whichever comes first.
3702 for (tstr = str + 2;
3703 *tstr != '\0' && *tstr != endc && *tstr != ':';
3707 * A variable inside a variable, expand
3712 char *rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
3714 Buf_AddBytes(&buf, strlen(rval), rval);
3721 Buf_AddByte(&buf, *tstr);
3724 haveModifier = TRUE;
3725 } else if (*tstr != '\0') {
3726 haveModifier = FALSE;
3729 * If we never did find the end character, return NULL
3730 * right now, setting the length to be the distance to
3731 * the end of the string, since that's what make does.
3733 *lengthPtr = tstr - str;
3734 Buf_Destroy(&buf, TRUE);
3737 str = Buf_GetAll(&buf, &vlen);
3740 * At this point, str points into newly allocated memory from
3741 * buf, containing only the name of the variable.
3743 * start and tstr point into the const string that was pointed
3744 * to by the original value of the str parameter. start points
3745 * to the '$' at the beginning of the string, while tstr points
3746 * to the char just after the end of the variable name -- this
3747 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3750 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3752 * Check also for bogus D and F forms of local variables since we're
3753 * in a local context and the name is the right length.
3755 if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
3756 (vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
3757 strchr("@%*!<>", str[0]) != NULL) {
3759 * Well, it's local -- go look for it.
3763 v = VarFind(name, ctxt, 0);
3767 * No need for nested expansion or anything, as we're
3768 * the only one who sets these things and we sure don't
3769 * but nested invocations in them...
3771 nstr = Buf_GetAll(&v->val, NULL);
3773 if (str[1] == 'D') {
3774 nstr = VarModify(ctxt, &parsestate, nstr, VarHead,
3777 nstr = VarModify(ctxt, &parsestate, nstr, VarTail,
3781 * Resulting string is dynamically allocated, so
3782 * tell caller to free it.
3785 *lengthPtr = tstr-start+1;
3786 Buf_Destroy(&buf, TRUE);
3787 VarFreeEnv(v, TRUE);
3794 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
3795 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3798 * If substituting a local variable in a non-local context,
3799 * assume it's for dynamic source stuff. We have to handle
3800 * this specially and return the longhand for the variable
3801 * with the dollar sign escaped so it makes it back to the
3802 * caller. Only four of the local variables are treated
3803 * specially as they are the only four that will be set
3804 * when dynamic sources are expanded.
3814 } else if ((vlen > 2) && (*str == '.') &&
3815 isupper((unsigned char) str[1]) &&
3816 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3821 if ((strncmp(str, ".TARGET", len) == 0) ||
3822 (strncmp(str, ".ARCHIVE", len) == 0) ||
3823 (strncmp(str, ".PREFIX", len) == 0) ||
3824 (strncmp(str, ".MEMBER", len) == 0))
3830 if (!haveModifier) {
3832 * No modifiers -- have specification length so we can return
3835 *lengthPtr = tstr - start + 1;
3837 char *pstr = bmake_strndup(start, *lengthPtr);
3839 Buf_Destroy(&buf, TRUE);
3842 Buf_Destroy(&buf, TRUE);
3843 return (errnum ? var_Error : varNoError);
3847 * Still need to get to the end of the variable specification,
3848 * so kludge up a Var structure for the modifications
3850 v = bmake_malloc(sizeof(Var));
3851 v->name = UNCONST(str);
3852 Buf_Init(&v->val, 1);
3853 v->flags = VAR_JUNK;
3854 Buf_Destroy(&buf, FALSE);
3857 Buf_Destroy(&buf, TRUE);
3860 if (v->flags & VAR_IN_USE) {
3861 Fatal("Variable %s is recursive.", v->name);
3864 v->flags |= VAR_IN_USE;
3867 * Before doing any modification, we have to make sure the value
3868 * has been fully expanded. If it looks like recursion might be
3869 * necessary (there's a dollar sign somewhere in the variable's value)
3870 * we just call Var_Subst to do any other substitutions that are
3871 * necessary. Note that the value returned by Var_Subst will have
3872 * been dynamically-allocated, so it will need freeing when we
3875 nstr = Buf_GetAll(&v->val, NULL);
3876 if (strchr(nstr, '$') != NULL) {
3877 nstr = Var_Subst(NULL, nstr, ctxt, errnum);
3881 v->flags &= ~VAR_IN_USE;
3883 if ((nstr != NULL) && haveModifier) {
3886 * Skip initial colon.
3890 nstr = ApplyModifiers(nstr, tstr, startc, endc,
3891 v, ctxt, errnum, &used, freePtr);
3895 *lengthPtr = tstr - start + 1;
3897 *lengthPtr = tstr - start;
3900 if (v->flags & VAR_FROM_ENV) {
3901 Boolean destroy = FALSE;
3903 if (nstr != Buf_GetAll(&v->val, NULL)) {
3907 * Returning the value unmodified, so tell the caller to free
3912 VarFreeEnv(v, destroy);
3913 } else if (v->flags & VAR_JUNK) {
3915 * Perform any free'ing needed and set *freePtr to NULL so the caller
3916 * doesn't try to free a static pointer.
3917 * If VAR_KEEP is also set then we want to keep str as is.
3919 if (!(v->flags & VAR_KEEP)) {
3925 nstr = bmake_strndup(start, *lengthPtr);
3928 nstr = errnum ? var_Error : varNoError;
3931 if (nstr != Buf_GetAll(&v->val, NULL))
3932 Buf_Destroy(&v->val, TRUE);
3940 *-----------------------------------------------------------------------
3942 * Substitute for all variables in the given string in the given context
3943 * If undefErr is TRUE, Parse_Error will be called when an undefined
3944 * variable is encountered.
3947 * var Named variable || NULL for all
3948 * str the string which to substitute
3949 * ctxt the context wherein to find variables
3950 * undefErr TRUE if undefineds are an error
3953 * The resulting string.
3956 * None. The old string must be freed by the caller
3957 *-----------------------------------------------------------------------
3960 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
3962 Buffer buf; /* Buffer for forming things */
3963 char *val; /* Value to substitute for a variable */
3964 int length; /* Length of the variable invocation */
3965 Boolean trailingBslash; /* variable ends in \ */
3966 void *freeIt = NULL; /* Set if it should be freed */
3967 static Boolean errorReported; /* Set true if an error has already
3968 * been reported to prevent a plethora
3969 * of messages when recursing */
3972 errorReported = FALSE;
3973 trailingBslash = FALSE;
3976 if (*str == '\n' && trailingBslash)
3977 Buf_AddByte(&buf, ' ');
3978 if (var == NULL && (*str == '$') && (str[1] == '$')) {
3980 * A dollar sign may be escaped either with another dollar sign.
3981 * In such a case, we skip over the escape character and store the
3982 * dollar sign into the buffer directly.
3985 Buf_AddByte(&buf, *str);
3987 } else if (*str != '$') {
3989 * Skip as many characters as possible -- either to the end of
3990 * the string or to the next dollar sign (variable invocation).
3994 for (cp = str++; *str != '$' && *str != '\0'; str++)
3996 Buf_AddBytes(&buf, str - cp, cp);
4001 if (str[1] == '\0') {
4002 /* A trailing $ is kind of a special case */
4003 Buf_AddByte(&buf, str[0]);
4006 } else if (str[1] != PROPEN && str[1] != BROPEN) {
4007 if (str[1] != *var || strlen(var) > 1) {
4008 Buf_AddBytes(&buf, 2, str);
4020 * Scan up to the end of the variable name.
4022 for (p = &str[2]; *p &&
4023 *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
4027 * A variable inside the variable. We cannot expand
4028 * the external variable yet, so we try again with
4032 Buf_AddBytes(&buf, p - str, str);
4037 if (strncmp(var, str + 2, p - str - 2) != 0 ||
4038 var[p - str - 2] != '\0') {
4040 * Not the variable we want to expand, scan
4041 * until the next variable
4043 for (;*p != '$' && *p != '\0'; p++)
4045 Buf_AddBytes(&buf, p - str, str);
4058 val = Var_Parse(str, ctxt, undefErr, &length, &freeIt);
4061 * When we come down here, val should either point to the
4062 * value of this variable, suitably modified, or be NULL.
4063 * Length should be the total length of the potential
4064 * variable invocation (from $ to end character...)
4066 if (val == var_Error || val == varNoError) {
4068 * If performing old-time variable substitution, skip over
4069 * the variable and continue with the substitution. Otherwise,
4070 * store the dollar sign and advance str so we continue with
4075 } else if (undefErr) {
4077 * If variable is undefined, complain and skip the
4078 * variable. The complaint will stop us from doing anything
4079 * when the file is parsed.
4081 if (!errorReported) {
4082 Parse_Error(PARSE_FATAL,
4083 "Undefined variable \"%.*s\"",length,str);
4086 errorReported = TRUE;
4088 Buf_AddByte(&buf, *str);
4093 * We've now got a variable structure to store in. But first,
4094 * advance the string pointer.
4099 * Copy all the characters from the variable value straight
4100 * into the new string.
4102 length = strlen(val);
4103 Buf_AddBytes(&buf, length, val);
4104 trailingBslash = length > 0 && val[length - 1] == '\\';
4113 return Buf_DestroyCompact(&buf);
4117 *-----------------------------------------------------------------------
4119 * Return the tail from each of a list of words. Used to set the
4120 * System V local variables.
4123 * file Filename to modify
4126 * The resulting string.
4131 *-----------------------------------------------------------------------
4135 Var_GetTail(char *file)
4137 return(VarModify(file, VarTail, NULL));
4141 *-----------------------------------------------------------------------
4143 * Find the leading components of a (list of) filename(s).
4144 * XXX: VarHead does not replace foo by ., as (sun) System V make
4148 * file Filename to manipulate
4151 * The leading components.
4156 *-----------------------------------------------------------------------
4159 Var_GetHead(char *file)
4161 return(VarModify(file, VarHead, NULL));
4166 *-----------------------------------------------------------------------
4168 * Initialize the module
4174 * The VAR_CMD and VAR_GLOBAL contexts are created
4175 *-----------------------------------------------------------------------
4180 VAR_GLOBAL = Targ_NewGN("Global");
4181 VAR_CMD = Targ_NewGN("Command");
4192 /****************** PRINT DEBUGGING INFO *****************/
4194 VarPrintVar(void *vp)
4197 fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
4201 *-----------------------------------------------------------------------
4203 * print all variables in a context
4204 *-----------------------------------------------------------------------
4207 Var_Dump(GNode *ctxt)
4212 for (h = Hash_EnumFirst(&ctxt->context, &search);
4214 h = Hash_EnumNext(&search)) {
4215 VarPrintVar(Hash_GetValue(h));