1 /* $NetBSD: var.c,v 1.184 2013/09/04 15:38:26 sjg Exp $ */
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
39 * This code is derived from software contributed to Berkeley by
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement:
52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission.
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
72 static char rcsid[] = "$NetBSD: var.c,v 1.184 2013/09/04 15:38:26 sjg Exp $";
74 #include <sys/cdefs.h>
77 static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 3/19/94";
79 __RCSID("$NetBSD: var.c,v 1.184 2013/09/04 15:38:26 sjg Exp $");
86 * Variable-handling functions
89 * Var_Set Set the value of a variable in the given
90 * context. The variable is created if it doesn't
91 * yet exist. The value and variable name need not
94 * Var_Append Append more characters to an existing variable
95 * in the given context. The variable needn't
96 * exist already -- it will be created if it doesn't.
97 * A space is placed between the old value and the
100 * Var_Exists See if a variable exists.
102 * Var_Value Return the value of a variable in a context or
103 * NULL if the variable is undefined.
105 * Var_Subst Substitute named variable, or all variables if
106 * NULL in a string using
107 * the given context as the top-most one. If the
108 * third argument is non-zero, Parse_Error is
109 * called if any variables are undefined.
111 * Var_Parse Parse a variable expansion from a string and
112 * return the result and the number of characters
115 * Var_Delete Delete a variable in a context.
117 * Var_Init Initialize this module.
120 * Var_Dump Print out all variables defined in the given
123 * XXX: There's a lot of duplication in these functions.
126 #include <sys/stat.h>
128 #include <sys/types.h>
132 #include <inttypes.h>
142 extern int makelevel;
144 * This lets us tell if we have replaced the original environ
145 * (which we cannot free).
147 char **savedEnv = NULL;
150 * This is a harmless return value for Var_Parse that can be used by Var_Subst
151 * to determine if there was an error in parsing -- easier than returning
152 * a flag, as things outside this module don't give a hoot.
154 char var_Error[] = "";
157 * Similar to var_Error, but returned when the 'errnum' flag for Var_Parse is
158 * set false. Why not just use a constant? Well, gcc likes to condense
159 * identical string instances...
161 static char varNoError[] = "";
164 * Internally, variables are contained in four different contexts.
165 * 1) the environment. They may not be changed. If an environment
166 * variable is appended-to, the result is placed in the global
168 * 2) the global context. Variables set in the Makefile are located in
169 * the global context. It is the penultimate context searched when
171 * 3) the command-line context. All variables set on the command line
172 * are placed in this context. They are UNALTERABLE once placed here.
173 * 4) the local context. Each target has associated with it a context
174 * list. On this list are located the structures describing such
175 * local variables as $(@) and $(*)
176 * The four contexts are searched in the reverse order from which they are
179 GNode *VAR_INTERNAL; /* variables from make itself */
180 GNode *VAR_GLOBAL; /* variables from the makefile */
181 GNode *VAR_CMD; /* variables defined on the command-line */
183 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
184 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
185 #define FIND_ENV 0x4 /* look in the environment also */
188 char *name; /* the variable's name */
189 Buffer val; /* its value */
190 int flags; /* miscellaneous status flags */
191 #define VAR_IN_USE 1 /* Variable's value currently being used.
192 * Used to avoid recursion */
193 #define VAR_FROM_ENV 2 /* Variable comes from the environment */
194 #define VAR_JUNK 4 /* Variable is a junk variable that
195 * should be destroyed when done with
196 * it. Used by Var_Parse for undefined,
197 * modified variables */
198 #define VAR_KEEP 8 /* Variable is VAR_JUNK, but we found
199 * a use for it in some modifier and
200 * the value is therefore valid */
201 #define VAR_EXPORTED 16 /* Variable is exported */
202 #define VAR_REEXPORT 32 /* Indicate if var needs re-export.
203 * This would be true if it contains $'s
205 #define VAR_FROM_CMD 64 /* Variable came from command line */
209 * Exporting vars is expensive so skip it if we can
211 #define VAR_EXPORTED_NONE 0
212 #define VAR_EXPORTED_YES 1
213 #define VAR_EXPORTED_ALL 2
214 static int var_exportedVars = VAR_EXPORTED_NONE;
216 * We pass this to Var_Export when doing the initial export
217 * or after updating an exported var.
219 #define VAR_EXPORT_PARENT 1
221 /* Var*Pattern flags */
222 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
223 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
224 #define VAR_SUB_MATCHED 0x04 /* There was a match */
225 #define VAR_MATCH_START 0x08 /* Match at start of word */
226 #define VAR_MATCH_END 0x10 /* Match at end of word */
227 #define VAR_NOSUBST 0x20 /* don't expand vars in VarGetPattern */
230 #define VAR_NO_EXPORT 0x01 /* do not export */
234 * The following fields are set by Var_Parse() when it
235 * encounters modifiers that need to keep state for use by
236 * subsequent modifiers within the same variable expansion.
238 Byte varSpace; /* Word separator in expansions */
239 Boolean oneBigWord; /* TRUE if we will treat the variable as a
240 * single big word, even if it contains
241 * embedded spaces (as opposed to the
242 * usual behaviour of treating it as
243 * several space-separated words). */
246 /* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/",
247 * to VarSYSVMatch() for ":lhs=rhs". */
249 const char *lhs; /* String to match */
250 int leftLen; /* Length of string */
251 const char *rhs; /* Replacement string (w/ &'s removed) */
252 int rightLen; /* Length of replacement */
256 /* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */
258 GNode *ctxt; /* variable context */
259 char *tvar; /* name of temp var */
261 char *str; /* string to expand */
263 int errnum; /* errnum for not defined */
267 /* struct passed as 'void *' to VarRESubstitute() for ":C///" */
277 /* struct passed to VarSelectWords() for ":[start..end]" */
279 int start; /* first word to select */
280 int end; /* last word to select */
283 static Var *VarFind(const char *, GNode *, int);
284 static void VarAdd(const char *, const char *, GNode *);
285 static Boolean VarHead(GNode *, Var_Parse_State *,
286 char *, Boolean, Buffer *, void *);
287 static Boolean VarTail(GNode *, Var_Parse_State *,
288 char *, Boolean, Buffer *, void *);
289 static Boolean VarSuffix(GNode *, Var_Parse_State *,
290 char *, Boolean, Buffer *, void *);
291 static Boolean VarRoot(GNode *, Var_Parse_State *,
292 char *, Boolean, Buffer *, void *);
293 static Boolean VarMatch(GNode *, Var_Parse_State *,
294 char *, Boolean, Buffer *, void *);
296 static Boolean VarSYSVMatch(GNode *, Var_Parse_State *,
297 char *, Boolean, Buffer *, void *);
299 static Boolean VarNoMatch(GNode *, Var_Parse_State *,
300 char *, Boolean, Buffer *, void *);
302 static void VarREError(int, regex_t *, const char *);
303 static Boolean VarRESubstitute(GNode *, Var_Parse_State *,
304 char *, Boolean, Buffer *, void *);
306 static Boolean VarSubstitute(GNode *, Var_Parse_State *,
307 char *, Boolean, Buffer *, void *);
308 static Boolean VarLoopExpand(GNode *, Var_Parse_State *,
309 char *, Boolean, Buffer *, void *);
310 static char *VarGetPattern(GNode *, Var_Parse_State *,
311 int, const char **, int, int *, int *,
313 static char *VarQuote(char *);
314 static char *VarHash(char *);
315 static char *VarModify(GNode *, Var_Parse_State *,
317 Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *),
319 static char *VarOrder(const char *, const char);
320 static char *VarUniq(const char *);
321 static int VarWordCompare(const void *, const void *);
322 static void VarPrintVar(void *);
330 *-----------------------------------------------------------------------
332 * Find the given variable in the given context and any other contexts
337 * ctxt context in which to find it
338 * flags FIND_GLOBAL set means to look in the
339 * VAR_GLOBAL context as well. FIND_CMD set means
340 * to look in the VAR_CMD context also. FIND_ENV
341 * set means to look in the environment
344 * A pointer to the structure describing the desired variable or
345 * NULL if the variable does not exist.
349 *-----------------------------------------------------------------------
352 VarFind(const char *name, GNode *ctxt, int flags)
358 * If the variable name begins with a '.', it could very well be one of
359 * the local ones. We check the name against all the local variables
360 * and substitute the short version in for 'name' if it matches one of
363 if (*name == '.' && isupper((unsigned char) name[1]))
366 if (!strcmp(name, ".ALLSRC"))
368 if (!strcmp(name, ".ARCHIVE"))
372 if (!strcmp(name, ".IMPSRC"))
376 if (!strcmp(name, ".MEMBER"))
380 if (!strcmp(name, ".OODATE"))
384 if (!strcmp(name, ".PREFIX"))
388 if (!strcmp(name, ".TARGET"))
393 /* for compatibility with gmake */
394 if (name[0] == '^' && name[1] == '\0')
399 * First look for the variable in the given context. If it's not there,
400 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
401 * depending on the FIND_* flags in 'flags'
403 var = Hash_FindEntry(&ctxt->context, name);
405 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
406 var = Hash_FindEntry(&VAR_CMD->context, name);
408 if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
409 (ctxt != VAR_GLOBAL))
411 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
412 if ((var == NULL) && (ctxt != VAR_INTERNAL)) {
413 /* VAR_INTERNAL is subordinate to VAR_GLOBAL */
414 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
417 if ((var == NULL) && (flags & FIND_ENV)) {
420 if ((env = getenv(name)) != NULL) {
423 v = bmake_malloc(sizeof(Var));
424 v->name = bmake_strdup(name);
428 Buf_Init(&v->val, len + 1);
429 Buf_AddBytes(&v->val, len, env);
431 v->flags = VAR_FROM_ENV;
433 } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
434 (ctxt != VAR_GLOBAL))
436 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
437 if ((var == NULL) && (ctxt != VAR_INTERNAL)) {
438 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
443 return ((Var *)Hash_GetValue(var));
448 } else if (var == NULL) {
451 return ((Var *)Hash_GetValue(var));
456 *-----------------------------------------------------------------------
458 * If the variable is an environment variable, free it
462 * destroy true if the value buffer should be destroyed.
465 * 1 if it is an environment variable 0 ow.
468 * The variable is free'ed if it is an environent variable.
469 *-----------------------------------------------------------------------
472 VarFreeEnv(Var *v, Boolean destroy)
474 if ((v->flags & VAR_FROM_ENV) == 0)
477 Buf_Destroy(&v->val, destroy);
483 *-----------------------------------------------------------------------
485 * Add a new variable of name name and value val to the given context
488 * name name of variable to add
489 * val value to set it to
490 * ctxt context in which to set it
496 * The new variable is placed at the front of the given context
497 * The name and val arguments are duplicated so they may
499 *-----------------------------------------------------------------------
502 VarAdd(const char *name, const char *val, GNode *ctxt)
508 v = bmake_malloc(sizeof(Var));
510 len = val ? strlen(val) : 0;
511 Buf_Init(&v->val, len+1);
512 Buf_AddBytes(&v->val, len, val);
516 h = Hash_CreateEntry(&ctxt->context, name, NULL);
520 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
525 *-----------------------------------------------------------------------
527 * Remove a variable from a context.
533 * The Var structure is removed and freed.
535 *-----------------------------------------------------------------------
538 Var_Delete(const char *name, GNode *ctxt)
543 if (strchr(name, '$')) {
544 cp = Var_Subst(NULL, name, VAR_GLOBAL, 0);
546 cp = __DECONST(char *,name); /* XXX */
548 ln = Hash_FindEntry(&ctxt->context, cp);
550 fprintf(debug_file, "%s:delete %s%s\n",
551 ctxt->name, cp, ln ? "" : " (not found)");
559 v = (Var *)Hash_GetValue(ln);
560 if ((v->flags & VAR_EXPORTED)) {
563 if (strcmp(MAKE_EXPORTED, v->name) == 0) {
564 var_exportedVars = VAR_EXPORTED_NONE;
566 if (v->name != ln->name)
568 Hash_DeleteEntry(&ctxt->context, ln);
569 Buf_Destroy(&v->val, TRUE);
577 * We ignore make internal variables (those which start with '.')
578 * Also we jump through some hoops to avoid calling setenv
579 * more than necessary since it can leak.
580 * We only manipulate flags of vars if 'parent' is set.
583 Var_Export1(const char *name, int parent)
591 return 0; /* skip internals */
595 * If it is one of the vars that should only appear in
596 * local context, skip it, else we can get Var_Subst
607 v = VarFind(name, VAR_GLOBAL, 0);
612 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
613 return 0; /* nothing to do */
615 val = Buf_GetAll(&v->val, NULL);
616 if (strchr(val, '$')) {
619 * Flag this as something we need to re-export.
620 * No point actually exporting it now though,
621 * the child can do it at the last minute.
623 v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
626 if (v->flags & VAR_IN_USE) {
628 * We recursed while exporting in a child.
629 * This isn't going to end well, just skip it.
633 n = snprintf(tmp, sizeof(tmp), "${%s}", name);
634 if (n < (int)sizeof(tmp)) {
635 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
636 setenv(name, val, 1);
641 v->flags &= ~VAR_REEXPORT; /* once will do */
643 if (parent || !(v->flags & VAR_EXPORTED)) {
644 setenv(name, val, 1);
648 * This is so Var_Set knows to call Var_Export again...
651 v->flags |= VAR_EXPORTED;
657 * This gets called from our children.
670 * Several make's support this sort of mechanism for tracking
671 * recursion - but each uses a different name.
672 * We allow the makefiles to update MAKELEVEL and ensure
673 * children see a correctly incremented value.
675 snprintf(tmp, sizeof(tmp), "%d", makelevel + 1);
676 setenv(MAKE_LEVEL_ENV, tmp, 1);
678 if (VAR_EXPORTED_NONE == var_exportedVars)
681 if (VAR_EXPORTED_ALL == var_exportedVars) {
683 * Ouch! This is crazy...
685 for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
687 var = Hash_EnumNext(&state)) {
688 v = (Var *)Hash_GetValue(var);
689 Var_Export1(v->name, 0);
694 * We have a number of exported vars,
696 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
697 if (n < (int)sizeof(tmp)) {
703 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
704 av = brk_string(val, &ac, FALSE, &as);
705 for (i = 0; i < ac; i++) {
706 Var_Export1(av[i], 0);
715 * This is called when .export is seen or
716 * .MAKE.EXPORTED is modified.
717 * It is also called when any exported var is modified.
720 Var_Export(char *str, int isExport)
730 if (isExport && (!str || !str[0])) {
731 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
735 if (strncmp(str, "-env", 4) == 0) {
739 track = VAR_EXPORT_PARENT;
741 val = Var_Subst(NULL, str, VAR_GLOBAL, 0);
742 av = brk_string(val, &ac, FALSE, &as);
743 for (i = 0; i < ac; i++) {
748 * If it is one of the vars that should only appear in
749 * local context, skip it, else we can get Var_Subst
760 if (Var_Export1(name, track)) {
761 if (VAR_EXPORTED_ALL != var_exportedVars)
762 var_exportedVars = VAR_EXPORTED_YES;
763 if (isExport && track) {
764 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
775 * This is called when .unexport[-env] is seen.
777 extern char **environ;
780 Var_UnExport(char *str)
785 Boolean unexport_env;
788 if (!str || !str[0]) {
789 return; /* assert? */
795 unexport_env = (strncmp(str, "-env", 4) == 0);
799 cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */
800 if (environ == savedEnv) {
801 /* we have been here before! */
802 newenv = bmake_realloc(environ, 2 * sizeof(char *));
808 newenv = bmake_malloc(2 * sizeof(char *));
812 /* Note: we cannot safely free() the original environ. */
813 environ = savedEnv = newenv;
816 setenv(MAKE_LEVEL_ENV, cp, 1);
818 for (; *str != '\n' && isspace((unsigned char) *str); str++)
820 if (str[0] && str[0] != '\n') {
826 /* Using .MAKE.EXPORTED */
827 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
828 if (n < (int)sizeof(tmp)) {
829 vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
839 av = brk_string(vlist, &ac, FALSE, &as);
840 for (i = 0; i < ac; i++) {
841 v = VarFind(av[i], VAR_GLOBAL, 0);
845 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
848 v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT);
850 * If we are unexporting a list,
851 * remove each one from .MAKE.EXPORTED.
852 * If we are removing them all,
853 * just delete .MAKE.EXPORTED below.
856 n = snprintf(tmp, sizeof(tmp),
857 "${" MAKE_EXPORTED ":N%s}", v->name);
858 if (n < (int)sizeof(tmp)) {
859 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
860 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0);
868 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
875 *-----------------------------------------------------------------------
877 * Set the variable name to the value val in the given context.
880 * name name of variable to set
881 * val value to give to the variable
882 * ctxt context in which to set it
888 * If the variable doesn't yet exist, a new record is created for it.
889 * Else the old value is freed and the new one stuck in its place
892 * The variable is searched for only in its context before being
893 * created in that context. I.e. if the context is VAR_GLOBAL,
894 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
895 * VAR_CMD->context is searched. This is done to avoid the literally
896 * thousands of unnecessary strcmp's that used to be done to
897 * set, say, $(@) or $(<).
898 * If the context is VAR_GLOBAL though, we check if the variable
899 * was set in VAR_CMD from the command line and skip it if so.
900 *-----------------------------------------------------------------------
903 Var_Set(const char *name, const char *val, GNode *ctxt, int flags)
906 char *expanded_name = NULL;
909 * We only look for a variable in the given context since anything set
910 * here will override anything in a lower context, so there's not much
911 * point in searching them all just to save a bit of memory...
913 if (strchr(name, '$') != NULL) {
914 expanded_name = Var_Subst(NULL, name, ctxt, 0);
915 if (expanded_name[0] == 0) {
917 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
918 "name expands to empty string - ignored\n",
924 name = expanded_name;
926 if (ctxt == VAR_GLOBAL) {
927 v = VarFind(name, VAR_CMD, 0);
929 if ((v->flags & VAR_FROM_CMD)) {
931 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
938 v = VarFind(name, ctxt, 0);
940 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
942 * This var would normally prevent the same name being added
943 * to VAR_GLOBAL, so delete it from there if needed.
944 * Otherwise -V name may show the wrong value.
946 Var_Delete(name, VAR_GLOBAL);
948 VarAdd(name, val, ctxt);
951 Buf_AddBytes(&v->val, strlen(val), val);
954 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
956 if ((v->flags & VAR_EXPORTED)) {
957 Var_Export1(name, VAR_EXPORT_PARENT);
961 * Any variables given on the command line are automatically exported
962 * to the environment (as per POSIX standard)
964 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
966 /* we just added it */
967 v = VarFind(name, ctxt, 0);
970 v->flags |= VAR_FROM_CMD;
972 * If requested, don't export these in the environment
973 * individually. We still put them in MAKEOVERRIDES so
974 * that the command-line settings continue to override
977 if (varNoExportEnv != TRUE)
978 setenv(name, val, 1);
980 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
984 if (expanded_name != NULL)
991 *-----------------------------------------------------------------------
993 * The variable of the given name has the given value appended to it in
997 * name name of variable to modify
998 * val String to append to it
999 * ctxt Context in which this should occur
1005 * If the variable doesn't exist, it is created. Else the strings
1006 * are concatenated (with a space in between).
1009 * Only if the variable is being sought in the global context is the
1010 * environment searched.
1011 * XXX: Knows its calling circumstances in that if called with ctxt
1012 * an actual target, it will only search that context since only
1013 * a local variable could be being appended to. This is actually
1014 * a big win and must be tolerated.
1015 *-----------------------------------------------------------------------
1018 Var_Append(const char *name, const char *val, GNode *ctxt)
1022 char *expanded_name = NULL;
1024 if (strchr(name, '$') != NULL) {
1025 expanded_name = Var_Subst(NULL, name, ctxt, 0);
1026 if (expanded_name[0] == 0) {
1028 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
1029 "name expands to empty string - ignored\n",
1032 free(expanded_name);
1035 name = expanded_name;
1038 v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
1041 VarAdd(name, val, ctxt);
1043 Buf_AddByte(&v->val, ' ');
1044 Buf_AddBytes(&v->val, strlen(val), val);
1047 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
1048 Buf_GetAll(&v->val, NULL));
1051 if (v->flags & VAR_FROM_ENV) {
1053 * If the original variable came from the environment, we
1054 * have to install it in the global context (we could place
1055 * it in the environment, but then we should provide a way to
1056 * export other variables...)
1058 v->flags &= ~VAR_FROM_ENV;
1059 h = Hash_CreateEntry(&ctxt->context, name, NULL);
1060 Hash_SetValue(h, v);
1063 if (expanded_name != NULL)
1064 free(expanded_name);
1068 *-----------------------------------------------------------------------
1070 * See if the given variable exists.
1073 * name Variable to find
1074 * ctxt Context in which to start search
1077 * TRUE if it does, FALSE if it doesn't
1082 *-----------------------------------------------------------------------
1085 Var_Exists(const char *name, GNode *ctxt)
1090 if ((cp = strchr(name, '$')) != NULL) {
1091 cp = Var_Subst(NULL, name, ctxt, FALSE);
1093 v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
1100 (void)VarFreeEnv(v, TRUE);
1106 *-----------------------------------------------------------------------
1108 * Return the value of the named variable in the given context
1112 * ctxt context in which to search for it
1115 * The value if the variable exists, NULL if it doesn't
1119 *-----------------------------------------------------------------------
1122 Var_Value(const char *name, GNode *ctxt, char **frp)
1126 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1129 char *p = (Buf_GetAll(&v->val, NULL));
1130 if (VarFreeEnv(v, FALSE))
1139 *-----------------------------------------------------------------------
1141 * Remove the tail of the given word and place the result in the given
1146 * addSpace True if need to add a space to the buffer
1147 * before sticking in the head
1148 * buf Buffer in which to store it
1151 * TRUE if characters were added to the buffer (a space needs to be
1152 * added to the buffer before the next word).
1155 * The trimmed word is added to the buffer.
1157 *-----------------------------------------------------------------------
1160 VarHead(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1161 char *word, Boolean addSpace, Buffer *buf,
1166 slash = strrchr(word, '/');
1167 if (slash != NULL) {
1168 if (addSpace && vpstate->varSpace) {
1169 Buf_AddByte(buf, vpstate->varSpace);
1172 Buf_AddBytes(buf, strlen(word), word);
1177 * If no directory part, give . (q.v. the POSIX standard)
1179 if (addSpace && vpstate->varSpace)
1180 Buf_AddByte(buf, vpstate->varSpace);
1181 Buf_AddByte(buf, '.');
1183 return(dummy ? TRUE : TRUE);
1187 *-----------------------------------------------------------------------
1189 * Remove the head of the given word and place the result in the given
1194 * addSpace True if need to add a space to the buffer
1195 * before adding the tail
1196 * buf Buffer in which to store it
1199 * TRUE if characters were added to the buffer (a space needs to be
1200 * added to the buffer before the next word).
1203 * The trimmed word is added to the buffer.
1205 *-----------------------------------------------------------------------
1208 VarTail(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1209 char *word, Boolean addSpace, Buffer *buf,
1214 if (addSpace && vpstate->varSpace) {
1215 Buf_AddByte(buf, vpstate->varSpace);
1218 slash = strrchr(word, '/');
1219 if (slash != NULL) {
1221 Buf_AddBytes(buf, strlen(slash), slash);
1224 Buf_AddBytes(buf, strlen(word), word);
1226 return (dummy ? TRUE : TRUE);
1230 *-----------------------------------------------------------------------
1232 * Place the suffix of the given word in the given buffer.
1236 * addSpace TRUE if need to add a space before placing the
1237 * suffix in the buffer
1238 * buf Buffer in which to store it
1241 * TRUE if characters were added to the buffer (a space needs to be
1242 * added to the buffer before the next word).
1245 * The suffix from the word is placed in the buffer.
1247 *-----------------------------------------------------------------------
1250 VarSuffix(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1251 char *word, Boolean addSpace, Buffer *buf,
1256 dot = strrchr(word, '.');
1258 if (addSpace && vpstate->varSpace) {
1259 Buf_AddByte(buf, vpstate->varSpace);
1262 Buf_AddBytes(buf, strlen(dot), dot);
1266 return (dummy ? addSpace : addSpace);
1270 *-----------------------------------------------------------------------
1272 * Remove the suffix of the given word and place the result in the
1277 * addSpace TRUE if need to add a space to the buffer
1278 * before placing the root in it
1279 * buf Buffer in which to store it
1282 * TRUE if characters were added to the buffer (a space needs to be
1283 * added to the buffer before the next word).
1286 * The trimmed word is added to the buffer.
1288 *-----------------------------------------------------------------------
1291 VarRoot(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1292 char *word, Boolean addSpace, Buffer *buf,
1297 if (addSpace && vpstate->varSpace) {
1298 Buf_AddByte(buf, vpstate->varSpace);
1301 dot = strrchr(word, '.');
1304 Buf_AddBytes(buf, strlen(word), word);
1307 Buf_AddBytes(buf, strlen(word), word);
1309 return (dummy ? TRUE : TRUE);
1313 *-----------------------------------------------------------------------
1315 * Place the word in the buffer if it matches the given pattern.
1316 * Callback function for VarModify to implement the :M modifier.
1319 * word Word to examine
1320 * addSpace TRUE if need to add a space to the buffer
1321 * before adding the word, if it matches
1322 * buf Buffer in which to store it
1323 * pattern Pattern the word must match
1326 * TRUE if a space should be placed in the buffer before the next
1330 * The word may be copied to the buffer.
1332 *-----------------------------------------------------------------------
1335 VarMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1336 char *word, Boolean addSpace, Buffer *buf,
1340 fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
1341 if (Str_Match(word, (char *)pattern)) {
1342 if (addSpace && vpstate->varSpace) {
1343 Buf_AddByte(buf, vpstate->varSpace);
1346 Buf_AddBytes(buf, strlen(word), word);
1353 *-----------------------------------------------------------------------
1355 * Place the word in the buffer if it matches the given pattern.
1356 * Callback function for VarModify to implement the System V %
1360 * word Word to examine
1361 * addSpace TRUE if need to add a space to the buffer
1362 * before adding the word, if it matches
1363 * buf Buffer in which to store it
1364 * patp Pattern the word must match
1367 * TRUE if a space should be placed in the buffer before the next
1371 * The word may be copied to the buffer.
1373 *-----------------------------------------------------------------------
1376 VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
1377 char *word, Boolean addSpace, Buffer *buf,
1382 VarPattern *pat = (VarPattern *)patp;
1385 if (addSpace && vpstate->varSpace)
1386 Buf_AddByte(buf, vpstate->varSpace);
1390 if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
1391 varexp = Var_Subst(NULL, pat->rhs, ctx, 0);
1392 Str_SYSVSubst(buf, varexp, ptr, len);
1395 Buf_AddBytes(buf, strlen(word), word);
1404 *-----------------------------------------------------------------------
1406 * Place the word in the buffer if it doesn't match the given pattern.
1407 * Callback function for VarModify to implement the :N modifier.
1410 * word Word to examine
1411 * addSpace TRUE if need to add a space to the buffer
1412 * before adding the word, if it matches
1413 * buf Buffer in which to store it
1414 * pattern Pattern the word must match
1417 * TRUE if a space should be placed in the buffer before the next
1421 * The word may be copied to the buffer.
1423 *-----------------------------------------------------------------------
1426 VarNoMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1427 char *word, Boolean addSpace, Buffer *buf,
1430 if (!Str_Match(word, (char *)pattern)) {
1431 if (addSpace && vpstate->varSpace) {
1432 Buf_AddByte(buf, vpstate->varSpace);
1435 Buf_AddBytes(buf, strlen(word), word);
1442 *-----------------------------------------------------------------------
1444 * Perform a string-substitution on the given word, placing the
1445 * result in the passed buffer.
1448 * word Word to modify
1449 * addSpace True if space should be added before
1451 * buf Buffer for result
1452 * patternp Pattern for substitution
1455 * TRUE if a space is needed before more characters are added.
1460 *-----------------------------------------------------------------------
1463 VarSubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1464 char *word, Boolean addSpace, Buffer *buf,
1467 int wordLen; /* Length of word */
1468 char *cp; /* General pointer */
1469 VarPattern *pattern = (VarPattern *)patternp;
1471 wordLen = strlen(word);
1472 if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
1473 (VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1475 * Still substituting -- break it down into simple anchored cases
1476 * and if none of them fits, perform the general substitution case.
1478 if ((pattern->flags & VAR_MATCH_START) &&
1479 (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
1481 * Anchored at start and beginning of word matches pattern
1483 if ((pattern->flags & VAR_MATCH_END) &&
1484 (wordLen == pattern->leftLen)) {
1486 * Also anchored at end and matches to the end (word
1487 * is same length as pattern) add space and rhs only
1488 * if rhs is non-null.
1490 if (pattern->rightLen != 0) {
1491 if (addSpace && vpstate->varSpace) {
1492 Buf_AddByte(buf, vpstate->varSpace);
1495 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1497 pattern->flags |= VAR_SUB_MATCHED;
1498 } else if (pattern->flags & VAR_MATCH_END) {
1500 * Doesn't match to end -- copy word wholesale
1505 * Matches at start but need to copy in trailing characters
1507 if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1508 if (addSpace && vpstate->varSpace) {
1509 Buf_AddByte(buf, vpstate->varSpace);
1513 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1514 Buf_AddBytes(buf, wordLen - pattern->leftLen,
1515 (word + pattern->leftLen));
1516 pattern->flags |= VAR_SUB_MATCHED;
1518 } else if (pattern->flags & VAR_MATCH_START) {
1520 * Had to match at start of word and didn't -- copy whole word.
1523 } else if (pattern->flags & VAR_MATCH_END) {
1525 * Anchored at end, Find only place match could occur (leftLen
1526 * characters from the end of the word) and see if it does. Note
1527 * that because the $ will be left at the end of the lhs, we have
1530 cp = word + (wordLen - pattern->leftLen);
1532 (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
1534 * Match found. If we will place characters in the buffer,
1535 * add a space before hand as indicated by addSpace, then
1536 * stuff in the initial, unmatched part of the word followed
1537 * by the right-hand-side.
1539 if (((cp - word) + pattern->rightLen) != 0) {
1540 if (addSpace && vpstate->varSpace) {
1541 Buf_AddByte(buf, vpstate->varSpace);
1545 Buf_AddBytes(buf, cp - word, word);
1546 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1547 pattern->flags |= VAR_SUB_MATCHED;
1550 * Had to match at end and didn't. Copy entire word.
1556 * Pattern is unanchored: search for the pattern in the word using
1557 * String_FindSubstring, copying unmatched portions and the
1558 * right-hand-side for each match found, handling non-global
1559 * substitutions correctly, etc. When the loop is done, any
1560 * remaining part of the word (word and wordLen are adjusted
1561 * accordingly through the loop) is copied straight into the
1563 * addSpace is set FALSE as soon as a space is added to the
1570 origSize = Buf_Size(buf);
1572 cp = Str_FindSubstring(word, pattern->lhs);
1574 if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1575 Buf_AddByte(buf, vpstate->varSpace);
1578 Buf_AddBytes(buf, cp-word, word);
1579 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1580 wordLen -= (cp - word) + pattern->leftLen;
1581 word = cp + pattern->leftLen;
1585 if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
1588 pattern->flags |= VAR_SUB_MATCHED;
1594 if (addSpace && vpstate->varSpace) {
1595 Buf_AddByte(buf, vpstate->varSpace);
1597 Buf_AddBytes(buf, wordLen, word);
1600 * If added characters to the buffer, need to add a space
1601 * before we add any more. If we didn't add any, just return
1602 * the previous value of addSpace.
1604 return ((Buf_Size(buf) != origSize) || addSpace);
1609 if (addSpace && vpstate->varSpace) {
1610 Buf_AddByte(buf, vpstate->varSpace);
1612 Buf_AddBytes(buf, wordLen, word);
1618 *-----------------------------------------------------------------------
1620 * Print the error caused by a regcomp or regexec call.
1626 * An error gets printed.
1628 *-----------------------------------------------------------------------
1631 VarREError(int errnum, regex_t *pat, const char *str)
1636 errlen = regerror(errnum, pat, 0, 0);
1637 errbuf = bmake_malloc(errlen);
1638 regerror(errnum, pat, errbuf, errlen);
1639 Error("%s: %s", str, errbuf);
1645 *-----------------------------------------------------------------------
1646 * VarRESubstitute --
1647 * Perform a regex substitution on the given word, placing the
1648 * result in the passed buffer.
1651 * TRUE if a space is needed before more characters are added.
1656 *-----------------------------------------------------------------------
1659 VarRESubstitute(GNode *ctx MAKE_ATTR_UNUSED,
1660 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1661 char *word, Boolean addSpace, Buffer *buf,
1671 #define MAYBE_ADD_SPACE() \
1672 if (addSpace && !added) \
1673 Buf_AddByte(buf, ' '); \
1680 if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1681 (VAR_SUB_ONE|VAR_SUB_MATCHED))
1685 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1690 pat->flags |= VAR_SUB_MATCHED;
1691 if (pat->matches[0].rm_so > 0) {
1693 Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1696 for (rp = pat->replace; *rp; rp++) {
1697 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1699 Buf_AddByte(buf,rp[1]);
1702 else if ((*rp == '&') ||
1703 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1721 if (n > pat->nsub) {
1722 Error("No subexpression %s", &errstr[0]);
1725 } else if ((pat->matches[n].rm_so == -1) &&
1726 (pat->matches[n].rm_eo == -1)) {
1727 Error("No match for subexpression %s", &errstr[0]);
1731 subbuf = wp + pat->matches[n].rm_so;
1732 sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1737 Buf_AddBytes(buf, sublen, subbuf);
1741 Buf_AddByte(buf, *rp);
1744 wp += pat->matches[0].rm_eo;
1745 if (pat->flags & VAR_SUB_GLOBAL) {
1746 flags |= REG_NOTBOL;
1747 if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1749 Buf_AddByte(buf, *wp);
1758 Buf_AddBytes(buf, strlen(wp), wp);
1762 VarREError(xrv, &pat->re, "Unexpected regex error");
1767 Buf_AddBytes(buf,strlen(wp),wp);
1771 return(addSpace||added);
1778 *-----------------------------------------------------------------------
1780 * Implements the :@<temp>@<string>@ modifier of ODE make.
1781 * We set the temp variable named in pattern.lhs to word and expand
1782 * pattern.rhs storing the result in the passed buffer.
1785 * word Word to modify
1786 * addSpace True if space should be added before
1788 * buf Buffer for result
1789 * pattern Datafor substitution
1792 * TRUE if a space is needed before more characters are added.
1797 *-----------------------------------------------------------------------
1800 VarLoopExpand(GNode *ctx MAKE_ATTR_UNUSED,
1801 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1802 char *word, Boolean addSpace, Buffer *buf,
1805 VarLoop_t *loop = (VarLoop_t *)loopp;
1809 if (word && *word) {
1810 Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
1811 s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum);
1812 if (s != NULL && *s != '\0') {
1813 if (addSpace && *s != '\n')
1814 Buf_AddByte(buf, ' ');
1815 Buf_AddBytes(buf, (slen = strlen(s)), s);
1816 addSpace = (slen > 0 && s[slen - 1] != '\n');
1825 *-----------------------------------------------------------------------
1827 * Implements the :[start..end] modifier.
1828 * This is a special case of VarModify since we want to be able
1829 * to scan the list backwards if start > end.
1832 * str String whose words should be trimmed
1833 * seldata words to select
1836 * A string of all the words selected.
1841 *-----------------------------------------------------------------------
1844 VarSelectWords(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1845 const char *str, VarSelectWords_t *seldata)
1847 Buffer buf; /* Buffer for the new string */
1848 Boolean addSpace; /* TRUE if need to add a space to the
1849 * buffer before adding the trimmed
1851 char **av; /* word list */
1852 char *as; /* word list memory */
1854 int start, end, step;
1859 if (vpstate->oneBigWord) {
1860 /* fake what brk_string() would do if there were only one word */
1862 av = bmake_malloc((ac + 1) * sizeof(char *));
1863 as = bmake_strdup(str);
1867 av = brk_string(str, &ac, FALSE, &as);
1871 * Now sanitize seldata.
1872 * If seldata->start or seldata->end are negative, convert them to
1873 * the positive equivalents (-1 gets converted to argc, -2 gets
1874 * converted to (argc-1), etc.).
1876 if (seldata->start < 0)
1877 seldata->start = ac + seldata->start + 1;
1878 if (seldata->end < 0)
1879 seldata->end = ac + seldata->end + 1;
1882 * We avoid scanning more of the list than we need to.
1884 if (seldata->start > seldata->end) {
1885 start = MIN(ac, seldata->start) - 1;
1886 end = MAX(0, seldata->end - 1);
1889 start = MAX(0, seldata->start - 1);
1890 end = MIN(ac, seldata->end);
1895 (step < 0 && i >= end) || (step > 0 && i < end);
1897 if (av[i] && *av[i]) {
1898 if (addSpace && vpstate->varSpace) {
1899 Buf_AddByte(&buf, vpstate->varSpace);
1901 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
1909 return Buf_Destroy(&buf, FALSE);
1915 * Replace each word with the result of realpath()
1919 VarRealpath(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1920 char *word, Boolean addSpace, Buffer *buf,
1921 void *patternp MAKE_ATTR_UNUSED)
1924 char rbuf[MAXPATHLEN];
1927 if (addSpace && vpstate->varSpace) {
1928 Buf_AddByte(buf, vpstate->varSpace);
1931 rp = realpath(word, rbuf);
1932 if (rp && *rp == '/' && stat(rp, &st) == 0)
1935 Buf_AddBytes(buf, strlen(word), word);
1940 *-----------------------------------------------------------------------
1942 * Modify each of the words of the passed string using the given
1943 * function. Used to implement all modifiers.
1946 * str String whose words should be trimmed
1947 * modProc Function to use to modify them
1948 * datum Datum to pass it
1951 * A string of all the words modified appropriately.
1956 *-----------------------------------------------------------------------
1959 VarModify(GNode *ctx, Var_Parse_State *vpstate,
1961 Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
1962 Boolean, Buffer *, void *),
1965 Buffer buf; /* Buffer for the new string */
1966 Boolean addSpace; /* TRUE if need to add a space to the
1967 * buffer before adding the trimmed
1969 char **av; /* word list */
1970 char *as; /* word list memory */
1976 if (vpstate->oneBigWord) {
1977 /* fake what brk_string() would do if there were only one word */
1979 av = bmake_malloc((ac + 1) * sizeof(char *));
1980 as = bmake_strdup(str);
1984 av = brk_string(str, &ac, FALSE, &as);
1987 for (i = 0; i < ac; i++) {
1988 addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum);
1994 return Buf_Destroy(&buf, FALSE);
1999 VarWordCompare(const void *a, const void *b)
2001 int r = strcmp(*(const char * const *)a, *(const char * const *)b);
2006 *-----------------------------------------------------------------------
2008 * Order the words in the string.
2011 * str String whose words should be sorted.
2012 * otype How to order: s - sort, x - random.
2015 * A string containing the words ordered.
2020 *-----------------------------------------------------------------------
2023 VarOrder(const char *str, const char otype)
2025 Buffer buf; /* Buffer for the new string */
2026 char **av; /* word list [first word does not count] */
2027 char *as; /* word list memory */
2032 av = brk_string(str, &ac, FALSE, &as);
2036 case 's': /* sort alphabetically */
2037 qsort(av, ac, sizeof(char *), VarWordCompare);
2039 case 'x': /* randomize */
2045 * We will use [ac..2] range for mod factors. This will produce
2046 * random numbers in [(ac-1)..0] interval, and minimal
2047 * reasonable value for mod factor is 2 (the mod 1 will produce
2048 * 0 with probability 1).
2050 for (i = ac-1; i > 0; i--) {
2051 rndidx = random() % (i + 1);
2059 } /* end of switch */
2061 for (i = 0; i < ac; i++) {
2062 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2064 Buf_AddByte(&buf, ' ');
2070 return Buf_Destroy(&buf, FALSE);
2075 *-----------------------------------------------------------------------
2077 * Remove adjacent duplicate words.
2080 * str String whose words should be sorted
2083 * A string containing the resulting words.
2088 *-----------------------------------------------------------------------
2091 VarUniq(const char *str)
2093 Buffer buf; /* Buffer for new string */
2094 char **av; /* List of words to affect */
2095 char *as; /* Word list memory */
2099 av = brk_string(str, &ac, FALSE, &as);
2102 for (j = 0, i = 1; i < ac; i++)
2103 if (strcmp(av[i], av[j]) != 0 && (++j != i))
2108 for (i = 0; i < ac; i++) {
2109 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2111 Buf_AddByte(&buf, ' ');
2117 return Buf_Destroy(&buf, FALSE);
2122 *-----------------------------------------------------------------------
2124 * Pass through the tstr looking for 1) escaped delimiters,
2125 * '$'s and backslashes (place the escaped character in
2126 * uninterpreted) and 2) unescaped $'s that aren't before
2127 * the delimiter (expand the variable substitution unless flags
2128 * has VAR_NOSUBST set).
2129 * Return the expanded string or NULL if the delimiter was missing
2130 * If pattern is specified, handle escaped ampersands, and replace
2131 * unescaped ampersands with the lhs of the pattern.
2134 * A string of all the words modified appropriately.
2135 * If length is specified, return the string length of the buffer
2136 * If flags is specified and the last character of the pattern is a
2137 * $ set the VAR_MATCH_END bit of flags.
2141 *-----------------------------------------------------------------------
2144 VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
2145 int errnum, const char **tstr, int delim, int *flags,
2146 int *length, VarPattern *pattern)
2157 #define IS_A_MATCH(cp, delim) \
2158 ((cp[0] == '\\') && ((cp[1] == delim) || \
2159 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
2162 * Skim through until the matching delimiter is found;
2163 * pick up variable substitutions on the way. Also allow
2164 * backslashes to quote the delimiter, $, and \, but don't
2165 * touch other backslashes.
2167 for (cp = *tstr; *cp && (*cp != delim); cp++) {
2168 if (IS_A_MATCH(cp, delim)) {
2169 Buf_AddByte(&buf, cp[1]);
2171 } else if (*cp == '$') {
2172 if (cp[1] == delim) {
2174 Buf_AddByte(&buf, *cp);
2177 * Unescaped $ at end of pattern => anchor
2180 *flags |= VAR_MATCH_END;
2182 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
2188 * If unescaped dollar sign not before the
2189 * delimiter, assume it's a variable
2190 * substitution and recurse.
2192 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2193 Buf_AddBytes(&buf, strlen(cp2), cp2);
2198 const char *cp2 = &cp[1];
2200 if (*cp2 == PROPEN || *cp2 == BROPEN) {
2202 * Find the end of this variable reference
2203 * and suck it in without further ado.
2204 * It will be interperated later.
2207 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
2210 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
2211 if (cp2[-1] != '\\') {
2218 Buf_AddBytes(&buf, cp2 - cp, cp);
2221 Buf_AddByte(&buf, *cp);
2225 else if (pattern && *cp == '&')
2226 Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
2228 Buf_AddByte(&buf, *cp);
2238 *length = Buf_Size(&buf);
2239 rstr = Buf_Destroy(&buf, FALSE);
2241 fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
2246 *-----------------------------------------------------------------------
2248 * Quote shell meta-characters in the string
2256 *-----------------------------------------------------------------------
2263 /* This should cover most shells :-( */
2264 static const char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
2265 const char *newline;
2268 if ((newline = Shell_GetNewline()) == NULL)
2270 nlen = strlen(newline);
2273 while (*str != '\0') {
2274 if ((len = strcspn(str, meta)) != 0) {
2275 Buf_AddBytes(&buf, len, str);
2277 } else if (*str == '\n') {
2278 Buf_AddBytes(&buf, nlen, newline);
2281 Buf_AddByte(&buf, '\\');
2282 Buf_AddByte(&buf, *str);
2286 str = Buf_Destroy(&buf, FALSE);
2288 fprintf(debug_file, "QuoteMeta: [%s]\n", str);
2293 *-----------------------------------------------------------------------
2295 * Hash the string using the MurmurHash3 algorithm.
2296 * Output is computed using 32bit Little Endian arithmetic.
2299 * str String to modify
2302 * Hash value of str, encoded as 8 hex digits.
2307 *-----------------------------------------------------------------------
2312 static const char hexdigits[16] = "0123456789abcdef";
2315 unsigned char *ustr = (unsigned char *)str;
2316 uint32_t h, k, c1, c2;
2323 for (len = len2; len; ) {
2327 k = (ustr[3] << 24) | (ustr[2] << 16) | (ustr[1] << 8) | ustr[0];
2332 k |= (ustr[2] << 16);
2334 k |= (ustr[1] << 8);
2339 c1 = c1 * 5 + 0x7b7d159cU;
2340 c2 = c2 * 5 + 0x6bce6396U;
2342 k = (k << 11) ^ (k >> 21);
2344 h = (h << 13) ^ (h >> 19);
2345 h = h * 5 + 0x52dce729U;
2355 for (len = 0; len < 8; ++len) {
2356 Buf_AddByte(&buf, hexdigits[h & 15]);
2360 return Buf_Destroy(&buf, FALSE);
2364 VarStrftime(const char *fmt, int zulu)
2372 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2374 buf[sizeof(buf) - 1] = '\0';
2375 return bmake_strdup(buf);
2379 * Now we need to apply any modifiers the user wants applied.
2381 * :M<pattern> words which match the given <pattern>.
2382 * <pattern> is of the standard file
2384 * :N<pattern> words which do not match the given <pattern>.
2385 * :S<d><pat1><d><pat2><d>[1gW]
2386 * Substitute <pat2> for <pat1> in the value
2387 * :C<d><pat1><d><pat2><d>[1gW]
2388 * Substitute <pat2> for regex <pat1> in the value
2389 * :H Substitute the head of each word
2390 * :T Substitute the tail of each word
2391 * :E Substitute the extension (minus '.') of
2393 * :R Substitute the root of each word
2394 * (pathname minus the suffix).
2395 * :O ("Order") Alphabeticaly sort words in variable.
2396 * :Ox ("intermiX") Randomize words in variable.
2397 * :u ("uniq") Remove adjacent duplicate words.
2398 * :tu Converts the variable contents to uppercase.
2399 * :tl Converts the variable contents to lowercase.
2400 * :ts[c] Sets varSpace - the char used to
2401 * separate words to 'c'. If 'c' is
2402 * omitted then no separation is used.
2403 * :tW Treat the variable contents as a single
2404 * word, even if it contains spaces.
2405 * (Mnemonic: one big 'W'ord.)
2406 * :tw Treat the variable contents as multiple
2407 * space-separated words.
2408 * (Mnemonic: many small 'w'ords.)
2409 * :[index] Select a single word from the value.
2410 * :[start..end] Select multiple words from the value.
2411 * :[*] or :[0] Select the entire value, as a single
2412 * word. Equivalent to :tW.
2413 * :[@] Select the entire value, as multiple
2414 * words. Undoes the effect of :[*].
2415 * Equivalent to :tw.
2416 * :[#] Returns the number of words in the value.
2418 * :?<true-value>:<false-value>
2419 * If the variable evaluates to true, return
2420 * true value, else return the second value.
2421 * :lhs=rhs Like :S, but the rhs goes to the end of
2423 * :sh Treat the current value as a command
2424 * to be run, new value is its output.
2425 * The following added so we can handle ODE makefiles.
2426 * :@<tmpvar>@<newval>@
2427 * Assign a temporary local variable <tmpvar>
2428 * to the current value of each word in turn
2429 * and replace each word with the result of
2430 * evaluating <newval>
2431 * :D<newval> Use <newval> as value if variable defined
2432 * :U<newval> Use <newval> as value if variable undefined
2433 * :L Use the name of the variable as the value.
2434 * :P Use the path of the node that has the same
2435 * name as the variable as the value. This
2436 * basically includes an implied :L so that
2437 * the common method of refering to the path
2438 * of your dependent 'x' in a rule is to use
2439 * the form '${x:P}'.
2440 * :!<cmd>! Run cmd much the same as :sh run's the
2441 * current value of the variable.
2442 * The ::= modifiers, actually assign a value to the variable.
2443 * Their main purpose is in supporting modifiers of .for loop
2444 * iterators and other obscure uses. They always expand to
2445 * nothing. In a target rule that would otherwise expand to an
2446 * empty line they can be preceded with @: to keep make happy.
2450 * .for i in ${.TARGET} ${.TARGET:R}.gz
2455 * ::=<str> Assigns <str> as the new value of variable.
2456 * ::?=<str> Assigns <str> as value of variable if
2457 * it was not already set.
2458 * ::+=<str> Appends <str> to variable.
2459 * ::!=<cmd> Assigns output of <cmd> as the new value of
2463 /* we now have some modifiers with long names */
2464 #define STRMOD_MATCH(s, want, n) \
2465 (strncmp(s, want, n) == 0 && (s[n] == endc || s[n] == ':'))
2468 ApplyModifiers(char *nstr, const char *tstr,
2469 int startc, int endc,
2470 Var *v, GNode *ctxt, Boolean errnum,
2471 int *lengthPtr, void **freePtr)
2474 const char *cp; /* Secondary pointer into str (place marker
2476 char *newStr; /* New value to return */
2477 char termc; /* Character which terminated scan */
2478 int cnt; /* Used to count brace pairs when variable in
2479 * in parens or braces */
2481 int modifier; /* that we are processing */
2482 Var_Parse_State parsestate; /* Flags passed to helper functions */
2485 parsestate.oneBigWord = FALSE;
2486 parsestate.varSpace = ' '; /* word separator */
2490 while (*tstr && *tstr != endc) {
2494 * We may have some complex modifiers in a variable.
2501 rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
2504 * If we have not parsed up to endc or ':',
2505 * we are not interested.
2507 if (rval != NULL && *rval &&
2508 (c = tstr[rlen]) != '\0' &&
2517 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
2518 rval, rlen, tstr, rlen, tstr + rlen);
2523 if (rval != NULL && *rval) {
2526 nstr = ApplyModifiers(nstr, rval,
2528 v, ctxt, errnum, &used, freePtr);
2529 if (nstr == var_Error
2530 || (nstr == varNoError && errnum == 0)
2531 || strlen(rval) != (size_t) used) {
2534 goto out; /* error already reported */
2541 else if (!*tstr && endc) {
2542 Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name);
2549 fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", v->name,
2553 switch ((modifier = *tstr)) {
2556 if (tstr[1] == '=' ||
2558 (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
2560 * "::=", "::!=", "::+=", or "::?="
2562 GNode *v_ctxt; /* context where v belongs */
2568 if (v->name[0] == 0)
2574 if (v->flags & VAR_JUNK) {
2576 * We need to bmake_strdup() it incase
2577 * VarGetPattern() recurses.
2580 v->name = bmake_strdup(v->name);
2581 } else if (ctxt != VAR_GLOBAL) {
2582 Var *gv = VarFind(v->name, ctxt, 0);
2584 v_ctxt = VAR_GLOBAL;
2586 VarFreeEnv(gv, TRUE);
2589 switch ((how = *tstr)) {
2599 delim = startc == PROPEN ? PRCLOSE : BRCLOSE;
2602 pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2606 if (v->flags & VAR_JUNK) {
2607 /* restore original name */
2611 if (pattern.rhs == NULL)
2619 Var_Append(v->name, pattern.rhs, v_ctxt);
2622 newStr = Cmd_Exec(pattern.rhs, &emsg);
2626 Var_Set(v->name, newStr, v_ctxt, 0);
2631 if ((v->flags & VAR_JUNK) == 0)
2635 Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2638 free(UNCONST(pattern.rhs));
2642 goto default_case; /* "::<unrecognised>" */
2647 int flags = VAR_NOSUBST;
2651 if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum,
2653 &flags, &loop.tvarLen,
2657 if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum,
2659 &flags, &loop.strLen,
2666 loop.errnum = errnum;
2668 newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
2677 Buffer buf; /* Buffer for patterns */
2678 int wantit; /* want data in buffer */
2681 * Pass through tstr looking for 1) escaped delimiters,
2682 * '$'s and backslashes (place the escaped character in
2683 * uninterpreted) and 2) unescaped $'s that aren't before
2684 * the delimiter (expand the variable substitution).
2685 * The result is left in the Buffer buf.
2689 *cp != endc && *cp != ':' && *cp != '\0';
2691 if ((*cp == '\\') &&
2697 Buf_AddByte(&buf, cp[1]);
2699 } else if (*cp == '$') {
2701 * If unescaped dollar sign, assume it's a
2702 * variable substitution and recurse.
2708 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2709 Buf_AddBytes(&buf, strlen(cp2), cp2);
2714 Buf_AddByte(&buf, *cp);
2721 wantit = ((v->flags & VAR_JUNK) != 0);
2723 wantit = ((v->flags & VAR_JUNK) == 0);
2724 if ((v->flags & VAR_JUNK) != 0)
2725 v->flags |= VAR_KEEP;
2727 newStr = Buf_Destroy(&buf, FALSE);
2730 Buf_Destroy(&buf, TRUE);
2736 if ((v->flags & VAR_JUNK) != 0)
2737 v->flags |= VAR_KEEP;
2738 newStr = bmake_strdup(v->name);
2747 if ((v->flags & VAR_JUNK) != 0)
2748 v->flags |= VAR_KEEP;
2749 gn = Targ_FindNode(v->name, TARG_NOCREATE);
2750 if (gn == NULL || gn->type & OP_NOPATH) {
2752 } else if (gn->path) {
2753 newStr = bmake_strdup(gn->path);
2755 newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
2758 newStr = bmake_strdup(v->name);
2773 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2775 NULL, &pattern.rightLen,
2778 newStr = Cmd_Exec(pattern.rhs, &emsg);
2779 free(UNCONST(pattern.rhs));
2784 if (v->flags & VAR_JUNK) {
2785 v->flags |= VAR_KEEP;
2792 * Look for the closing ']', recursively
2793 * expanding any embedded variables.
2795 * estr is a pointer to the expanded result,
2796 * which we must free().
2800 cp = tstr+1; /* point to char after '[' */
2801 delim = ']'; /* look for closing ']' */
2802 estr = VarGetPattern(ctxt, &parsestate,
2806 goto cleanup; /* report missing ']' */
2807 /* now cp points just after the closing ']' */
2809 if (cp[0] != ':' && cp[0] != endc) {
2810 /* Found junk after ']' */
2814 if (estr[0] == '\0') {
2815 /* Found empty square brackets in ":[]". */
2818 } else if (estr[0] == '#' && estr[1] == '\0') {
2822 * We will need enough space for the decimal
2823 * representation of an int. We calculate the
2824 * space needed for the octal representation,
2825 * and add enough slop to cope with a '-' sign
2826 * (which should never be needed) and a '\0'
2827 * string terminator.
2830 (sizeof(int) * CHAR_BIT + 2) / 3 + 2;
2832 newStr = bmake_malloc(newStrSize);
2833 if (parsestate.oneBigWord) {
2834 strncpy(newStr, "1", newStrSize);
2836 /* XXX: brk_string() is a rather expensive
2837 * way of counting words. */
2842 av = brk_string(nstr, &ac, FALSE, &as);
2843 snprintf(newStr, newStrSize, "%d", ac);
2850 } else if (estr[0] == '*' && estr[1] == '\0') {
2852 parsestate.oneBigWord = TRUE;
2857 } else if (estr[0] == '@' && estr[1] == '\0') {
2859 parsestate.oneBigWord = FALSE;
2866 * We expect estr to contain a single
2867 * integer for :[N], or two integers
2868 * separated by ".." for :[start..end].
2872 VarSelectWords_t seldata = { 0, 0 };
2874 seldata.start = strtol(estr, &ep, 0);
2876 /* Found junk instead of a number */
2879 } else if (ep[0] == '\0') {
2880 /* Found only one integer in :[N] */
2881 seldata.end = seldata.start;
2882 } else if (ep[0] == '.' && ep[1] == '.' &&
2884 /* Expecting another integer after ".." */
2886 seldata.end = strtol(ep, &ep, 0);
2887 if (ep[0] != '\0') {
2888 /* Found junk after ".." */
2893 /* Found junk instead of ".." */
2898 * Now seldata is properly filled in,
2899 * but we still have to check for 0 as
2902 if (seldata.start == 0 && seldata.end == 0) {
2903 /* ":[0]" or perhaps ":[0..0]" */
2904 parsestate.oneBigWord = TRUE;
2909 } else if (seldata.start == 0 ||
2911 /* ":[0..N]" or ":[N..0]" */
2916 * Normal case: select the words
2917 * described by seldata.
2919 newStr = VarSelectWords(ctxt, &parsestate,
2929 cp = tstr + 1; /* make sure it is set */
2930 if (STRMOD_MATCH(tstr, "gmtime", 6)) {
2931 newStr = VarStrftime(nstr, 1);
2939 cp = tstr + 1; /* make sure it is set */
2940 if (STRMOD_MATCH(tstr, "hash", 4)) {
2941 newStr = VarHash(nstr);
2949 cp = tstr + 1; /* make sure it is set */
2950 if (STRMOD_MATCH(tstr, "localtime", 9)) {
2951 newStr = VarStrftime(nstr, 0);
2960 cp = tstr + 1; /* make sure it is set */
2961 if (tstr[1] != endc && tstr[1] != ':') {
2962 if (tstr[1] == 's') {
2964 * Use the char (if any) at tstr[2]
2965 * as the word separator.
2969 if (tstr[2] != endc &&
2970 (tstr[3] == endc || tstr[3] == ':')) {
2971 /* ":ts<unrecognised><endc>" or
2972 * ":ts<unrecognised>:" */
2973 parsestate.varSpace = tstr[2];
2975 } else if (tstr[2] == endc || tstr[2] == ':') {
2976 /* ":ts<endc>" or ":ts:" */
2977 parsestate.varSpace = 0; /* no separator */
2979 } else if (tstr[2] == '\\') {
2982 parsestate.varSpace = '\n';
2986 parsestate.varSpace = '\t';
2990 if (isdigit((unsigned char)tstr[3])) {
2993 parsestate.varSpace =
2994 strtoul(&tstr[3], &ep, 0);
2995 if (*ep != ':' && *ep != endc)
3000 * ":ts<backslash><unrecognised>".
3008 * Found ":ts<unrecognised><unrecognised>".
3016 * We cannot be certain that VarModify
3017 * will be used - even if there is a
3018 * subsequent modifier, so do a no-op
3019 * VarSubstitute now to for str to be
3020 * re-expanded without the spaces.
3022 pattern.flags = VAR_SUB_ONE;
3023 pattern.lhs = pattern.rhs = "\032";
3024 pattern.leftLen = pattern.rightLen = 1;
3026 newStr = VarModify(ctxt, &parsestate, nstr,
3029 } else if (tstr[2] == endc || tstr[2] == ':') {
3031 * Check for two-character options:
3034 if (tstr[1] == 'A') { /* absolute path */
3035 newStr = VarModify(ctxt, &parsestate, nstr,
3039 } else if (tstr[1] == 'u') {
3040 char *dp = bmake_strdup(nstr);
3041 for (newStr = dp; *dp; dp++)
3042 *dp = toupper((unsigned char)*dp);
3045 } else if (tstr[1] == 'l') {
3046 char *dp = bmake_strdup(nstr);
3047 for (newStr = dp; *dp; dp++)
3048 *dp = tolower((unsigned char)*dp);
3051 } else if (tstr[1] == 'W' || tstr[1] == 'w') {
3052 parsestate.oneBigWord = (tstr[1] == 'W');
3057 /* Found ":t<unrecognised>:" or
3058 * ":t<unrecognised><endc>". */
3063 * Found ":t<unrecognised><unrecognised>".
3069 * Found ":t<endc>" or ":t:".
3079 const char *endpat; /* points just after end of pattern */
3081 Boolean copy; /* pattern should be, or has been, copied */
3089 * In the loop below, ignore ':' unless we are at
3090 * (or back to) the original brace level.
3091 * XXX This will likely not work right if $() and ${}
3095 *cp != '\0' && !(*cp == ':' && nest == 1);
3100 cp[1] == endc || cp[1] == startc)) {
3110 if (*cp == '(' || *cp == '{')
3112 if (*cp == ')' || *cp == '}') {
3122 * Need to compress the \:'s out of the pattern, so
3123 * allocate enough room to hold the uncompressed
3124 * pattern (note that cp started at tstr+1, so
3125 * cp - tstr takes the null byte into account) and
3126 * compress the pattern into the space.
3128 pattern = bmake_malloc(cp - tstr);
3129 for (cp2 = pattern, cp = tstr + 1;
3133 if ((*cp == '\\') && (cp+1 < endpat) &&
3134 (cp[1] == ':' || cp[1] == endc)) {
3143 * Either Var_Subst or VarModify will need a
3144 * nul-terminated string soon, so construct one now.
3146 pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
3150 * pattern contains embedded '$', so use Var_Subst to
3154 pattern = Var_Subst(NULL, cp2, ctxt, errnum);
3158 fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
3159 v->name, nstr, pattern);
3161 newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
3164 newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
3173 Var_Parse_State tmpparsestate;
3176 tmpparsestate = parsestate;
3181 * If pattern begins with '^', it is anchored to the
3182 * start of the word -- skip over it and flag pattern.
3185 pattern.flags |= VAR_MATCH_START;
3190 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3197 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3204 * Check for global substitution. If 'g' after the final
3205 * delimiter, substitution is global and is marked that
3211 pattern.flags |= VAR_SUB_GLOBAL;
3214 pattern.flags |= VAR_SUB_ONE;
3217 tmpparsestate.oneBigWord = TRUE;
3224 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3229 * Free the two strings.
3231 free(UNCONST(pattern.lhs));
3232 free(UNCONST(pattern.rhs));
3241 /* find ':', and then substitute accordingly */
3247 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3253 /* BROPEN or PROPEN */
3255 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3263 if (Cond_EvalExpression(NULL, v->name, &value, 0)
3265 Error("Bad conditional expression `%s' in %s?%s:%s",
3266 v->name, v->name, pattern.lhs, pattern.rhs);
3271 newStr = UNCONST(pattern.lhs);
3272 free(UNCONST(pattern.rhs));
3274 newStr = UNCONST(pattern.rhs);
3275 free(UNCONST(pattern.lhs));
3277 if (v->flags & VAR_JUNK) {
3278 v->flags |= VAR_KEEP;
3285 VarREPattern pattern;
3288 Var_Parse_State tmpparsestate;
3291 tmpparsestate = parsestate;
3297 if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim,
3298 NULL, NULL, NULL)) == NULL)
3301 if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
3302 errnum, &cp, delim, NULL,
3303 NULL, NULL)) == NULL){
3311 pattern.flags |= VAR_SUB_GLOBAL;
3314 pattern.flags |= VAR_SUB_ONE;
3317 tmpparsestate.oneBigWord = TRUE;
3325 error = regcomp(&pattern.re, re, REG_EXTENDED);
3328 *lengthPtr = cp - start + 1;
3329 VarREError(error, &pattern.re, "RE substitution error");
3330 free(pattern.replace);
3334 pattern.nsub = pattern.re.re_nsub + 1;
3335 if (pattern.nsub < 1)
3337 if (pattern.nsub > 10)
3339 pattern.matches = bmake_malloc(pattern.nsub *
3340 sizeof(regmatch_t));
3341 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3344 regfree(&pattern.re);
3345 free(pattern.replace);
3346 free(pattern.matches);
3352 if (tstr[1] == endc || tstr[1] == ':') {
3353 newStr = VarQuote(nstr);
3360 if (tstr[1] == endc || tstr[1] == ':') {
3361 newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
3369 if (tstr[1] == endc || tstr[1] == ':') {
3370 newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
3378 if (tstr[1] == endc || tstr[1] == ':') {
3379 newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
3387 if (tstr[1] == endc || tstr[1] == ':') {
3388 newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
3399 cp = tstr + 1; /* skip to the rest in any case */
3400 if (tstr[1] == endc || tstr[1] == ':') {
3403 } else if ( (tstr[1] == 'x') &&
3404 (tstr[2] == endc || tstr[2] == ':') ) {
3411 newStr = VarOrder(nstr, otype);
3415 if (tstr[1] == endc || tstr[1] == ':') {
3416 newStr = VarUniq(nstr);
3424 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
3426 newStr = Cmd_Exec(nstr, &emsg);
3440 * This can either be a bogus modifier or a System-V
3441 * substitution command.
3449 * First we make a pass through the string trying
3450 * to verify it is a SYSV-make-style translation:
3451 * it must be: <string1>=<string2>)
3455 while (*cp != '\0' && cnt) {
3458 /* continue looking for endc */
3460 else if (*cp == endc)
3462 else if (*cp == startc)
3467 if (*cp == endc && eqFound) {
3470 * Now we break this sucker into the lhs and
3471 * rhs. We must null terminate them of course.
3475 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
3476 errnum, &cp, delim, &pattern.flags,
3477 &pattern.leftLen, NULL)) == NULL)
3480 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
3481 errnum, &cp, delim, NULL, &pattern.rightLen,
3486 * SYSV modifications happen through the whole
3487 * string. Note the pattern is anchored at the end.
3491 if (pattern.leftLen == 0 && *nstr == '\0') {
3492 newStr = nstr; /* special case */
3494 newStr = VarModify(ctxt, &parsestate, nstr,
3498 free(UNCONST(pattern.lhs));
3499 free(UNCONST(pattern.rhs));
3503 Error("Unknown modifier '%c'", *tstr);
3505 *cp != ':' && *cp != endc && *cp != '\0';
3514 fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
3515 v->name, modifier, newStr);
3518 if (newStr != nstr) {
3524 if (nstr != var_Error && nstr != varNoError) {
3528 if (termc == '\0' && endc != '\0') {
3529 Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier);
3530 } else if (termc == ':') {
3536 *lengthPtr = tstr - start;
3541 Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
3545 *lengthPtr = cp - start;
3547 Error("Unclosed substitution for %s (%c missing)",
3557 *-----------------------------------------------------------------------
3559 * Given the start of a variable invocation, extract the variable
3560 * name and find its value, then modify it according to the
3564 * str The string to parse
3565 * ctxt The context for the variable
3566 * errnum TRUE if undefined variables are an error
3567 * lengthPtr OUT: The length of the specification
3568 * freePtr OUT: Non-NULL if caller should free *freePtr
3571 * The (possibly-modified) value of the variable or var_Error if the
3572 * specification is invalid. The length of the specification is
3573 * placed in *lengthPtr (for invalid specifications, this is just
3575 * If *freePtr is non-NULL then it's a pointer that the caller
3576 * should pass to free() to free memory used by the result.
3581 *-----------------------------------------------------------------------
3583 /* coverity[+alloc : arg-*4] */
3585 Var_Parse(const char *str, GNode *ctxt, Boolean errnum, int *lengthPtr,
3588 const char *tstr; /* Pointer into str */
3589 Var *v; /* Variable in invocation */
3590 Boolean haveModifier;/* TRUE if have modifiers for the variable */
3591 char endc; /* Ending character when variable in parens
3593 char startc; /* Starting character when variable in parens
3595 int vlen; /* Length of variable name */
3596 const char *start; /* Points to original start of str */
3597 char *nstr; /* New string, used during expansion */
3598 Boolean dynamic; /* TRUE if the variable is local and we're
3599 * expanding it in a non-local context. This
3600 * is done to support dynamic sources. The
3601 * result is just the invocation, unaltered */
3602 Var_Parse_State parsestate; /* Flags passed to helper functions */
3608 parsestate.oneBigWord = FALSE;
3609 parsestate.varSpace = ' '; /* word separator */
3612 if (startc != PROPEN && startc != BROPEN) {
3614 * If it's not bounded by braces of some sort, life is much simpler.
3615 * We just need to check for the first character and return the
3616 * value if it exists.
3619 /* Error out some really stupid names */
3620 if (startc == '\0' || strchr(")}:$", startc)) {
3627 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3631 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
3633 * If substituting a local variable in a non-local context,
3634 * assume it's for dynamic source stuff. We have to handle
3635 * this specially and return the longhand for the variable
3636 * with the dollar sign escaped so it makes it back to the
3637 * caller. Only four of the local variables are treated
3638 * specially as they are the only four that will be set
3639 * when dynamic sources are expanded.
3643 return UNCONST("$(.TARGET)");
3645 return UNCONST("$(.ARCHIVE)");
3647 return UNCONST("$(.PREFIX)");
3649 return UNCONST("$(.MEMBER)");
3655 return (errnum ? var_Error : varNoError);
3657 haveModifier = FALSE;
3662 Buffer buf; /* Holds the variable name */
3664 endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3668 * Skip to the end character or a colon, whichever comes first.
3670 for (tstr = str + 2;
3671 *tstr != '\0' && *tstr != endc && *tstr != ':';
3675 * A variable inside a variable, expand
3680 char *rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
3682 Buf_AddBytes(&buf, strlen(rval), rval);
3689 Buf_AddByte(&buf, *tstr);
3692 haveModifier = TRUE;
3693 } else if (*tstr != '\0') {
3694 haveModifier = FALSE;
3697 * If we never did find the end character, return NULL
3698 * right now, setting the length to be the distance to
3699 * the end of the string, since that's what make does.
3701 *lengthPtr = tstr - str;
3702 Buf_Destroy(&buf, TRUE);
3705 str = Buf_GetAll(&buf, &vlen);
3708 * At this point, str points into newly allocated memory from
3709 * buf, containing only the name of the variable.
3711 * start and tstr point into the const string that was pointed
3712 * to by the original value of the str parameter. start points
3713 * to the '$' at the beginning of the string, while tstr points
3714 * to the char just after the end of the variable name -- this
3715 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3718 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3720 * Check also for bogus D and F forms of local variables since we're
3721 * in a local context and the name is the right length.
3723 if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
3724 (vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
3725 strchr("@%*!<>", str[0]) != NULL) {
3727 * Well, it's local -- go look for it.
3731 v = VarFind(name, ctxt, 0);
3735 * No need for nested expansion or anything, as we're
3736 * the only one who sets these things and we sure don't
3737 * but nested invocations in them...
3739 nstr = Buf_GetAll(&v->val, NULL);
3741 if (str[1] == 'D') {
3742 nstr = VarModify(ctxt, &parsestate, nstr, VarHead,
3745 nstr = VarModify(ctxt, &parsestate, nstr, VarTail,
3749 * Resulting string is dynamically allocated, so
3750 * tell caller to free it.
3753 *lengthPtr = tstr-start+1;
3754 Buf_Destroy(&buf, TRUE);
3755 VarFreeEnv(v, TRUE);
3762 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
3763 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3766 * If substituting a local variable in a non-local context,
3767 * assume it's for dynamic source stuff. We have to handle
3768 * this specially and return the longhand for the variable
3769 * with the dollar sign escaped so it makes it back to the
3770 * caller. Only four of the local variables are treated
3771 * specially as they are the only four that will be set
3772 * when dynamic sources are expanded.
3782 } else if ((vlen > 2) && (*str == '.') &&
3783 isupper((unsigned char) str[1]) &&
3784 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3789 if ((strncmp(str, ".TARGET", len) == 0) ||
3790 (strncmp(str, ".ARCHIVE", len) == 0) ||
3791 (strncmp(str, ".PREFIX", len) == 0) ||
3792 (strncmp(str, ".MEMBER", len) == 0))
3798 if (!haveModifier) {
3800 * No modifiers -- have specification length so we can return
3803 *lengthPtr = tstr - start + 1;
3805 char *pstr = bmake_strndup(start, *lengthPtr);
3807 Buf_Destroy(&buf, TRUE);
3810 Buf_Destroy(&buf, TRUE);
3811 return (errnum ? var_Error : varNoError);
3815 * Still need to get to the end of the variable specification,
3816 * so kludge up a Var structure for the modifications
3818 v = bmake_malloc(sizeof(Var));
3819 v->name = UNCONST(str);
3820 Buf_Init(&v->val, 1);
3821 v->flags = VAR_JUNK;
3822 Buf_Destroy(&buf, FALSE);
3825 Buf_Destroy(&buf, TRUE);
3828 if (v->flags & VAR_IN_USE) {
3829 Fatal("Variable %s is recursive.", v->name);
3832 v->flags |= VAR_IN_USE;
3835 * Before doing any modification, we have to make sure the value
3836 * has been fully expanded. If it looks like recursion might be
3837 * necessary (there's a dollar sign somewhere in the variable's value)
3838 * we just call Var_Subst to do any other substitutions that are
3839 * necessary. Note that the value returned by Var_Subst will have
3840 * been dynamically-allocated, so it will need freeing when we
3843 nstr = Buf_GetAll(&v->val, NULL);
3844 if (strchr(nstr, '$') != NULL) {
3845 nstr = Var_Subst(NULL, nstr, ctxt, errnum);
3849 v->flags &= ~VAR_IN_USE;
3851 if ((nstr != NULL) && haveModifier) {
3854 * Skip initial colon.
3858 nstr = ApplyModifiers(nstr, tstr, startc, endc,
3859 v, ctxt, errnum, &used, freePtr);
3863 *lengthPtr = tstr - start + 1;
3865 *lengthPtr = tstr - start;
3868 if (v->flags & VAR_FROM_ENV) {
3869 Boolean destroy = FALSE;
3871 if (nstr != Buf_GetAll(&v->val, NULL)) {
3875 * Returning the value unmodified, so tell the caller to free
3880 VarFreeEnv(v, destroy);
3881 } else if (v->flags & VAR_JUNK) {
3883 * Perform any free'ing needed and set *freePtr to NULL so the caller
3884 * doesn't try to free a static pointer.
3885 * If VAR_KEEP is also set then we want to keep str as is.
3887 if (!(v->flags & VAR_KEEP)) {
3893 nstr = bmake_strndup(start, *lengthPtr);
3896 nstr = errnum ? var_Error : varNoError;
3899 if (nstr != Buf_GetAll(&v->val, NULL))
3900 Buf_Destroy(&v->val, TRUE);
3908 *-----------------------------------------------------------------------
3910 * Substitute for all variables in the given string in the given context
3911 * If undefErr is TRUE, Parse_Error will be called when an undefined
3912 * variable is encountered.
3915 * var Named variable || NULL for all
3916 * str the string which to substitute
3917 * ctxt the context wherein to find variables
3918 * undefErr TRUE if undefineds are an error
3921 * The resulting string.
3924 * None. The old string must be freed by the caller
3925 *-----------------------------------------------------------------------
3928 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
3930 Buffer buf; /* Buffer for forming things */
3931 char *val; /* Value to substitute for a variable */
3932 int length; /* Length of the variable invocation */
3933 Boolean trailingBslash; /* variable ends in \ */
3934 void *freeIt = NULL; /* Set if it should be freed */
3935 static Boolean errorReported; /* Set true if an error has already
3936 * been reported to prevent a plethora
3937 * of messages when recursing */
3940 errorReported = FALSE;
3941 trailingBslash = FALSE;
3944 if (*str == '\n' && trailingBslash)
3945 Buf_AddByte(&buf, ' ');
3946 if (var == NULL && (*str == '$') && (str[1] == '$')) {
3948 * A dollar sign may be escaped either with another dollar sign.
3949 * In such a case, we skip over the escape character and store the
3950 * dollar sign into the buffer directly.
3953 Buf_AddByte(&buf, *str);
3955 } else if (*str != '$') {
3957 * Skip as many characters as possible -- either to the end of
3958 * the string or to the next dollar sign (variable invocation).
3962 for (cp = str++; *str != '$' && *str != '\0'; str++)
3964 Buf_AddBytes(&buf, str - cp, cp);
3969 if (str[1] == '\0') {
3970 /* A trailing $ is kind of a special case */
3971 Buf_AddByte(&buf, str[0]);
3974 } else if (str[1] != PROPEN && str[1] != BROPEN) {
3975 if (str[1] != *var || strlen(var) > 1) {
3976 Buf_AddBytes(&buf, 2, str);
3988 * Scan up to the end of the variable name.
3990 for (p = &str[2]; *p &&
3991 *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
3995 * A variable inside the variable. We cannot expand
3996 * the external variable yet, so we try again with
4000 Buf_AddBytes(&buf, p - str, str);
4005 if (strncmp(var, str + 2, p - str - 2) != 0 ||
4006 var[p - str - 2] != '\0') {
4008 * Not the variable we want to expand, scan
4009 * until the next variable
4011 for (;*p != '$' && *p != '\0'; p++)
4013 Buf_AddBytes(&buf, p - str, str);
4026 val = Var_Parse(str, ctxt, undefErr, &length, &freeIt);
4029 * When we come down here, val should either point to the
4030 * value of this variable, suitably modified, or be NULL.
4031 * Length should be the total length of the potential
4032 * variable invocation (from $ to end character...)
4034 if (val == var_Error || val == varNoError) {
4036 * If performing old-time variable substitution, skip over
4037 * the variable and continue with the substitution. Otherwise,
4038 * store the dollar sign and advance str so we continue with
4043 } else if (undefErr) {
4045 * If variable is undefined, complain and skip the
4046 * variable. The complaint will stop us from doing anything
4047 * when the file is parsed.
4049 if (!errorReported) {
4050 Parse_Error(PARSE_FATAL,
4051 "Undefined variable \"%.*s\"",length,str);
4054 errorReported = TRUE;
4056 Buf_AddByte(&buf, *str);
4061 * We've now got a variable structure to store in. But first,
4062 * advance the string pointer.
4067 * Copy all the characters from the variable value straight
4068 * into the new string.
4070 length = strlen(val);
4071 Buf_AddBytes(&buf, length, val);
4072 trailingBslash = length > 0 && val[length - 1] == '\\';
4081 return Buf_DestroyCompact(&buf);
4085 *-----------------------------------------------------------------------
4087 * Return the tail from each of a list of words. Used to set the
4088 * System V local variables.
4091 * file Filename to modify
4094 * The resulting string.
4099 *-----------------------------------------------------------------------
4103 Var_GetTail(char *file)
4105 return(VarModify(file, VarTail, NULL));
4109 *-----------------------------------------------------------------------
4111 * Find the leading components of a (list of) filename(s).
4112 * XXX: VarHead does not replace foo by ., as (sun) System V make
4116 * file Filename to manipulate
4119 * The leading components.
4124 *-----------------------------------------------------------------------
4127 Var_GetHead(char *file)
4129 return(VarModify(file, VarHead, NULL));
4134 *-----------------------------------------------------------------------
4136 * Initialize the module
4142 * The VAR_CMD and VAR_GLOBAL contexts are created
4143 *-----------------------------------------------------------------------
4148 VAR_INTERNAL = Targ_NewGN("Internal");
4149 VAR_GLOBAL = Targ_NewGN("Global");
4150 VAR_CMD = Targ_NewGN("Command");
4161 /****************** PRINT DEBUGGING INFO *****************/
4163 VarPrintVar(void *vp)
4166 fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
4170 *-----------------------------------------------------------------------
4172 * print all variables in a context
4173 *-----------------------------------------------------------------------
4176 Var_Dump(GNode *ctxt)
4181 for (h = Hash_EnumFirst(&ctxt->context, &search);
4183 h = Hash_EnumNext(&search)) {
4184 VarPrintVar(Hash_GetValue(h));