2 * Copyright (c) 1988, 1989, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1989 by Berkeley Softworks
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. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)var.c 8.3 (Berkeley) 3/19/94
39 * $FreeBSD: src/usr.bin/make/var.c,v 1.16.2.3 2002/02/27 14:18:57 cjc Exp $
40 * $DragonFly: src/usr.bin/make/var.c,v 1.28 2004/12/17 21:09:04 okumoto Exp $
45 * Variable-handling functions
48 * Var_Set Set the value of a variable in the given
49 * context. The variable is created if it doesn't
50 * yet exist. The value and variable name need not
53 * Var_Append Append more characters to an existing variable
54 * in the given context. The variable needn't
55 * exist already -- it will be created if it doesn't.
56 * A space is placed between the old value and the
59 * Var_Exists See if a variable exists.
61 * Var_Value Return the value of a variable in a context or
62 * NULL if the variable is undefined.
64 * Var_Subst Substitute named variable, or all variables if
65 * NULL in a string using
66 * the given context as the top-most one. If the
67 * third argument is non-zero, Parse_Error is
68 * called if any variables are undefined.
70 * Var_Parse Parse a variable expansion from a string and
71 * return the result and the number of characters
74 * Var_Delete Delete a variable in a context.
76 * Var_Init Initialize this module.
79 * Var_Dump Print out all variables defined in the given
82 * XXX: There's a lot of duplication in these functions.
86 #include <sys/types.h>
94 * This is a harmless return value for Var_Parse that can be used by Var_Subst
95 * to determine if there was an error in parsing -- easier than returning
96 * a flag, as things outside this module don't give a hoot.
98 char var_Error[] = "";
101 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
102 * set false. Why not just use a constant? Well, gcc likes to condense
103 * identical string instances...
105 static char varNoError[] = "";
108 * Internally, variables are contained in four different contexts.
109 * 1) the environment. They may not be changed. If an environment
110 * variable is appended-to, the result is placed in the global
112 * 2) the global context. Variables set in the Makefile are located in
113 * the global context. It is the penultimate context searched when
115 * 3) the command-line context. All variables set on the command line
116 * are placed in this context. They are UNALTERABLE once placed here.
117 * 4) the local context. Each target has associated with it a context
118 * list. On this list are located the structures describing such
119 * local variables as $(@) and $(*)
120 * The four contexts are searched in the reverse order from which they are
123 GNode *VAR_GLOBAL; /* variables from the makefile */
124 GNode *VAR_CMD; /* variables defined on the command-line */
126 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
127 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
128 #define FIND_ENV 0x4 /* look in the environment also */
130 static void VarPossiblyExpand(char **, GNode *);
131 static Var *VarFind(char *, GNode *, int);
132 static void VarAdd(char *, char *, GNode *);
133 static void VarDelete(void *);
134 static char *VarGetPattern(GNode *, int, char **, int, int *, size_t *,
136 static char *VarModify(char *,
137 Boolean (*)(const char *, Boolean, Buffer, void *),
139 static int VarPrintVar(void *, void *);
142 *-----------------------------------------------------------------------
144 * See if the given variable matches the named one. Called from
145 * Lst_Find when searching for a variable of a given name.
148 * 0 if they match. non-zero otherwise.
152 *-----------------------------------------------------------------------
155 VarCmp(const void *v, const void *name)
158 return (strcmp(name, ((const Var *)v)->name));
162 *-----------------------------------------------------------------------
163 * VarPossiblyExpand --
164 * Expand a variable name's embedded variables in the given context.
167 * The contents of name, possibly expanded.
170 * The caller must free the new contents or old contents of name.
171 *-----------------------------------------------------------------------
174 VarPossiblyExpand(char **name, GNode *ctxt)
177 if (strchr(*name, '$') != NULL)
178 *name = Var_Subst(NULL, *name, ctxt, 0);
180 *name = estrdup(*name);
184 *-----------------------------------------------------------------------
186 * Find the given variable in the given context and any other contexts
190 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
191 * FIND_CMD set means to look in the VAR_CMD context too
192 * FIND_ENV set means to look in the environment
195 * A pointer to the structure describing the desired variable or
196 * NULL if the variable does not exist.
200 *-----------------------------------------------------------------------
203 VarFind(char *name, GNode *ctxt, int flags)
205 Boolean localCheckEnvFirst;
210 * If the variable name begins with a '.', it could very well be one of
211 * the local ones. We check the name against all the local variables
212 * and substitute the short version in for 'name' if it matches one of
215 if (*name == '.' && isupper((unsigned char)name[1]))
218 if (!strcmp(name, ".ALLSRC"))
220 if (!strcmp(name, ".ARCHIVE"))
224 if (!strcmp(name, ".IMPSRC"))
228 if (!strcmp(name, ".MEMBER"))
232 if (!strcmp(name, ".OODATE"))
236 if (!strcmp(name, ".PREFIX"))
240 if (!strcmp(name, ".TARGET"))
246 * Note whether this is one of the specific variables we were told through
247 * the -E flag to use environment-variable-override for.
249 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
250 localCheckEnvFirst = TRUE;
252 localCheckEnvFirst = FALSE;
256 * First look for the variable in the given context. If it's not there,
257 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
258 * depending on the FIND_* flags in 'flags'
260 var = Lst_Find(&ctxt->context, name, VarCmp);
262 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
263 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
265 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
266 !checkEnvFirst && !localCheckEnvFirst)
268 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
270 if ((var == NULL) && (flags & FIND_ENV)) {
273 if ((env = getenv(name)) != NULL) {
276 v = emalloc(sizeof(Var));
277 v->name = estrdup(name);
281 v->val = Buf_Init(len);
282 Buf_AddBytes(v->val, len, (Byte *)env);
284 v->flags = VAR_FROM_ENV;
286 } else if ((checkEnvFirst || localCheckEnvFirst) &&
287 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
289 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
293 return (Lst_Datum(var));
298 } else if (var == NULL) {
301 return (Lst_Datum(var));
306 *-----------------------------------------------------------------------
308 * Add a new variable of name name and value val to the given context.
314 * The new variable is placed at the front of the given context
315 * The name and val arguments are duplicated so they may
317 *-----------------------------------------------------------------------
320 VarAdd(char *name, char *val, GNode *ctxt)
325 v = emalloc(sizeof(Var));
327 v->name = estrdup(name);
329 len = val ? strlen(val) : 0;
330 v->val = Buf_Init(len+1);
331 Buf_AddBytes(v->val, len, (Byte *)val);
335 Lst_AtFront(&ctxt->context, v);
336 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
340 *-----------------------------------------------------------------------
342 * Delete a variable and all the space associated with it.
349 *-----------------------------------------------------------------------
357 Buf_Destroy(v->val, TRUE);
362 *-----------------------------------------------------------------------
364 * Remove a variable from a context.
370 * The Var structure is removed and freed.
372 *-----------------------------------------------------------------------
375 Var_Delete(char *name, GNode *ctxt)
379 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
380 ln = Lst_Find(&ctxt->context, name, VarCmp);
382 VarDelete(Lst_Datum(ln));
383 Lst_Remove(&ctxt->context, ln);
388 *-----------------------------------------------------------------------
390 * Set the variable name to the value val in the given context.
396 * If the variable doesn't yet exist, a new record is created for it.
397 * Else the old value is freed and the new one stuck in its place
400 * The variable is searched for only in its context before being
401 * created in that context. I.e. if the context is VAR_GLOBAL,
402 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
403 * VAR_CMD->context is searched. This is done to avoid the literally
404 * thousands of unnecessary strcmp's that used to be done to
405 * set, say, $(@) or $(<).
406 *-----------------------------------------------------------------------
409 Var_Set(char *name, char *val, GNode *ctxt)
414 * We only look for a variable in the given context since anything set
415 * here will override anything in a lower context, so there's not much
416 * point in searching them all just to save a bit of memory...
418 VarPossiblyExpand(&name, ctxt);
419 v = VarFind(name, ctxt, 0);
421 VarAdd(name, val, ctxt);
423 Buf_Discard(v->val, Buf_Size(v->val));
424 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
426 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
429 * Any variables given on the command line are automatically exported
430 * to the environment (as per POSIX standard)
432 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
433 setenv(name, val, 1);
440 * Set the VAR_TO_ENV flag on a variable
443 Var_SetEnv (char *name, GNode *ctxt)
447 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
449 if ((v->flags & VAR_TO_ENV) == 0) {
450 v->flags |= VAR_TO_ENV;
451 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
454 Error("Cannot set environment flag on non-existant variable %s", name);
459 *-----------------------------------------------------------------------
461 * The variable of the given name has the given value appended to it in
468 * If the variable doesn't exist, it is created. Else the strings
469 * are concatenated (with a space in between).
472 * Only if the variable is being sought in the global context is the
473 * environment searched.
474 * XXX: Knows its calling circumstances in that if called with ctxt
475 * an actual target, it will only search that context since only
476 * a local variable could be being appended to. This is actually
477 * a big win and must be tolerated.
478 *-----------------------------------------------------------------------
481 Var_Append(char *name, char *val, GNode *ctxt)
485 VarPossiblyExpand(&name, ctxt);
486 v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
489 VarAdd(name, val, ctxt);
491 Buf_AddByte(v->val, (Byte)' ');
492 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
494 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name,
495 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
497 if (v->flags & VAR_FROM_ENV) {
499 * If the original variable came from the environment, we
500 * have to install it in the global context (we could place
501 * it in the environment, but then we should provide a way to
502 * export other variables...)
504 v->flags &= ~VAR_FROM_ENV;
505 Lst_AtFront(&ctxt->context, v);
512 *-----------------------------------------------------------------------
514 * See if the given variable exists.
517 * TRUE if it does, FALSE if it doesn't
522 *-----------------------------------------------------------------------
525 Var_Exists(char *name, GNode *ctxt)
529 VarPossiblyExpand(&name, ctxt);
530 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
535 } else if (v->flags & VAR_FROM_ENV) {
537 Buf_Destroy(v->val, TRUE);
544 *-----------------------------------------------------------------------
546 * Return the value of the named variable in the given context
549 * The value if the variable exists, NULL if it doesn't
553 *-----------------------------------------------------------------------
556 Var_Value(char *name, GNode *ctxt, char **frp)
560 VarPossiblyExpand(&name, ctxt);
561 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
565 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
567 if (v->flags & VAR_FROM_ENV) {
568 Buf_Destroy(v->val, FALSE);
580 *-----------------------------------------------------------------------
582 * Print the error caused by a regcomp or regexec call.
588 * An error gets printed.
590 *-----------------------------------------------------------------------
593 VarREError(int err, regex_t *pat, const char *str)
598 errlen = regerror(err, pat, 0, 0);
599 errbuf = emalloc(errlen);
600 regerror(err, pat, errbuf, errlen);
601 Error("%s: %s", str, errbuf);
606 *-----------------------------------------------------------------------
608 * Modify each of the words of the passed string using the given
609 * function. Used to implement all modifiers.
612 * A string of all the words modified appropriately.
617 *-----------------------------------------------------------------------
620 VarModify(char *str, Boolean (*modProc)(const char *, Boolean, Buffer, void *),
623 Buffer buf; /* Buffer for the new string */
624 Boolean addSpace; /* TRUE if need to add a space to the
625 * buffer before adding the trimmed
627 char **av; /* word list [first word does not count] */
633 av = brk_string(str, &ac, FALSE);
635 for (i = 1; i < ac; i++)
636 addSpace = (*modProc)(av[i], addSpace, buf, datum);
638 Buf_AddByte (buf, '\0');
639 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
640 Buf_Destroy(buf, FALSE);
645 *-----------------------------------------------------------------------
647 * Sort the words in the string.
650 * str String whose words should be sorted
651 * cmp A comparison function to control the ordering
654 * A string containing the words sorted
659 *-----------------------------------------------------------------------
662 VarSortWords(char *str, int (*cmp)(const void *, const void *))
669 av = brk_string(str, &ac, FALSE);
670 qsort(av + 1, ac - 1, sizeof(char *), cmp);
671 for (i = 1; i < ac; i++) {
672 Buf_AddBytes(buf, strlen(av[i]), (Byte *)av[i]);
673 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
675 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
676 Buf_Destroy(buf, FALSE);
681 SortIncreasing(const void *l, const void *r)
684 return (strcmp(*(const char* const*)l, *(const char* const*)r));
688 *-----------------------------------------------------------------------
690 * Pass through the tstr looking for 1) escaped delimiters,
691 * '$'s and backslashes (place the escaped character in
692 * uninterpreted) and 2) unescaped $'s that aren't before
693 * the delimiter (expand the variable substitution unless flags
694 * has VAR_NOSUBST set).
695 * Return the expanded string or NULL if the delimiter was missing
696 * If pattern is specified, handle escaped ampersands, and replace
697 * unescaped ampersands with the lhs of the pattern.
700 * A string of all the words modified appropriately.
701 * If length is specified, return the string length of the buffer
702 * If flags is specified and the last character of the pattern is a
703 * $ set the VAR_MATCH_END bit of flags.
707 *-----------------------------------------------------------------------
710 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
711 size_t *length, VarPattern *pattern)
714 Buffer buf = Buf_Init(0);
720 #define IS_A_MATCH(cp, delim) \
721 ((cp[0] == '\\') && ((cp[1] == delim) || \
722 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
725 * Skim through until the matching delimiter is found;
726 * pick up variable substitutions on the way. Also allow
727 * backslashes to quote the delimiter, $, and \, but don't
728 * touch other backslashes.
730 for (cp = *tstr; *cp && (*cp != delim); cp++) {
731 if (IS_A_MATCH(cp, delim)) {
732 Buf_AddByte(buf, (Byte)cp[1]);
734 } else if (*cp == '$') {
735 if (cp[1] == delim) {
737 Buf_AddByte(buf, (Byte)*cp);
740 * Unescaped $ at end of pattern => anchor
743 *flags |= VAR_MATCH_END;
745 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
751 * If unescaped dollar sign not before the
752 * delimiter, assume it's a variable
753 * substitution and recurse.
755 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
756 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
763 if (*cp2 == '(' || *cp2 == '{') {
765 * Find the end of this variable reference
766 * and suck it in without further ado.
767 * It will be interperated later.
770 int want = (*cp2 == '(') ? ')' : '}';
773 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
774 if (cp2[-1] != '\\') {
781 Buf_AddBytes(buf, cp2 - cp, (Byte *)cp);
784 Buf_AddByte(buf, (Byte)*cp);
788 else if (pattern && *cp == '&')
789 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
791 Buf_AddByte(buf, (Byte)*cp);
794 Buf_AddByte(buf, (Byte)'\0');
802 cp = (char *)Buf_GetAll(buf, length);
803 *length -= 1; /* Don't count the NULL */
804 Buf_Destroy(buf, FALSE);
810 *-----------------------------------------------------------------------
812 * Quote shell meta-characters in the string
820 *-----------------------------------------------------------------------
823 Var_Quote(const char *str)
827 /* This should cover most shells :-( */
828 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
830 buf = Buf_Init(MAKE_BSIZE);
831 for (; *str; str++) {
832 if (strchr(meta, *str) != NULL)
833 Buf_AddByte(buf, (Byte)'\\');
834 Buf_AddByte(buf, (Byte)*str);
836 Buf_AddByte(buf, (Byte)'\0');
837 retstr = Buf_GetAll (buf, (int *)NULL);
838 Buf_Destroy(buf, FALSE);
843 *-----------------------------------------------------------------------
845 * Given the start of a variable invocation, extract the variable
846 * name and find its value, then modify it according to the
850 * The (possibly-modified) value of the variable or var_Error if the
851 * specification is invalid. The length of the specification is
852 * placed in *lengthPtr (for invalid specifications, this is just
853 * 2 to skip the '$' and the following letter, or 1 if '$' was the
854 * last character in the string).
855 * A Boolean in *freePtr telling whether the returned string should
856 * be freed by the caller.
861 *-----------------------------------------------------------------------
864 Var_Parse(char *str, GNode *ctxt, Boolean err, size_t *lengthPtr,
867 char *tstr; /* Pointer into str */
868 Var *v; /* Variable in invocation */
869 char *cp; /* Secondary pointer into str (place marker
871 Boolean haveModifier;/* TRUE if have modifiers for the variable */
872 char endc; /* Ending character when variable in parens
874 char startc=0; /* Starting character when variable in parens
876 int cnt; /* Used to count brace pairs when variable in
877 * in parens or braces */
880 Boolean dynamic; /* TRUE if the variable is local and we're
881 * expanding it in a non-local context. This
882 * is done to support dynamic sources. The
883 * result is just the invocation, unaltered */
884 int vlen; /* length of variable name, after embedded variable
891 if (str[1] != '(' && str[1] != '{') {
893 * If it's not bounded by braces of some sort, life is much simpler.
894 * We just need to check for the first character and return the
895 * value if it exists.
902 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
903 if (v == (Var *)NULL) {
909 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
911 * If substituting a local variable in a non-local context,
912 * assume it's for dynamic source stuff. We have to handle
913 * this specially and return the longhand for the variable
914 * with the dollar sign escaped so it makes it back to the
915 * caller. Only four of the local variables are treated
916 * specially as they are the only four that will be set
917 * when dynamic sources are expanded.
919 /* XXX: It looks like $% and $! are reversed here */
922 return ("$(.TARGET)");
924 return ("$(.ARCHIVE)");
926 return ("$(.PREFIX)");
928 return ("$(.MEMBER)");
936 return (err ? var_Error : varNoError);
938 haveModifier = FALSE;
943 /* build up expanded variable name in this buffer */
944 Buffer buf = Buf_Init(MAKE_BSIZE);
947 endc = startc == '(' ? ')' : '}';
950 * Skip to the end character or a colon, whichever comes first,
951 * replacing embedded variables as we go.
953 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
957 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
959 if (rval == var_Error) {
960 Fatal("Error expanding embedded variable.");
961 } else if (rval != NULL) {
962 Buf_AddBytes(buf, strlen(rval), (Byte *)rval);
968 Buf_AddByte(buf, (Byte)*tstr);
972 * If we never did find the end character, return NULL
973 * right now, setting the length to be the distance to
974 * the end of the string, since that's what make does.
976 *lengthPtr = tstr - str;
980 haveModifier = (*tstr == ':');
983 Buf_AddByte(buf, (Byte)'\0');
984 str = Buf_GetAll(buf, (size_t *)NULL);
987 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
988 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
989 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
992 * Check for bogus D and F forms of local variables since we're
993 * in a local context and the name is the right length.
1007 * Well, it's local -- go look for it.
1011 v = VarFind(vname, ctxt, 0);
1013 if (v != NULL && !haveModifier) {
1015 * No need for nested expansion or anything, as we're
1016 * the only one who sets these things and we sure don't
1017 * put nested invocations in them...
1019 val = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1021 if (str[1] == 'D') {
1022 val = VarModify(val, VarHead, (void *)NULL);
1024 val = VarModify(val, VarTail, (void *)NULL);
1027 * Resulting string is dynamically allocated, so
1028 * tell caller to free it.
1031 *lengthPtr = tstr-start+1;
1033 Buf_Destroy(buf, TRUE);
1043 if (v == (Var *)NULL) {
1045 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
1046 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1049 * If substituting a local variable in a non-local context,
1050 * assume it's for dynamic source stuff. We have to handle
1051 * this specially and return the longhand for the variable
1052 * with the dollar sign escaped so it makes it back to the
1053 * caller. Only four of the local variables are treated
1054 * specially as they are the only four that will be set
1055 * when dynamic sources are expanded.
1067 } else if ((vlen > 2) && (str[0] == '.') &&
1068 isupper((unsigned char)str[1]) &&
1069 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1074 if ((strncmp(str, ".TARGET", len) == 0) ||
1075 (strncmp(str, ".ARCHIVE", len) == 0) ||
1076 (strncmp(str, ".PREFIX", len) == 0) ||
1077 (strncmp(str, ".MEMBER", len) == 0))
1083 if (!haveModifier) {
1085 * No modifiers -- have specification length so we can return
1088 *lengthPtr = tstr - start + 1;
1091 str = emalloc(*lengthPtr + 1);
1092 strncpy(str, start, *lengthPtr);
1093 str[*lengthPtr] = '\0';
1095 Buf_Destroy(buf, TRUE);
1098 Buf_Destroy(buf, TRUE);
1099 return (err ? var_Error : varNoError);
1103 * Still need to get to the end of the variable specification,
1104 * so kludge up a Var structure for the modifications
1106 v = emalloc(sizeof(Var));
1107 v->name = estrdup(str);
1108 v->val = Buf_Init(1);
1109 v->flags = VAR_JUNK;
1112 Buf_Destroy(buf, TRUE);
1115 if (v->flags & VAR_IN_USE) {
1116 Fatal("Variable %s is recursive.", v->name);
1119 v->flags |= VAR_IN_USE;
1122 * Before doing any modification, we have to make sure the value
1123 * has been fully expanded. If it looks like recursion might be
1124 * necessary (there's a dollar sign somewhere in the variable's value)
1125 * we just call Var_Subst to do any other substitutions that are
1126 * necessary. Note that the value returned by Var_Subst will have
1127 * been dynamically-allocated, so it will need freeing when we
1130 str = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1131 if (strchr(str, '$') != (char *)NULL) {
1132 str = Var_Subst(NULL, str, ctxt, err);
1136 v->flags &= ~VAR_IN_USE;
1139 * Now we need to apply any modifiers the user wants applied.
1141 * :M<pattern> words which match the given <pattern>.
1142 * <pattern> is of the standard file
1144 * :S<d><pat1><d><pat2><d>[g]
1145 * Substitute <pat2> for <pat1> in the value
1146 * :C<d><pat1><d><pat2><d>[g]
1147 * Substitute <pat2> for regex <pat1> in the value
1148 * :H Substitute the head of each word
1149 * :T Substitute the tail of each word
1150 * :E Substitute the extension (minus '.') of
1152 * :R Substitute the root of each word
1153 * (pathname minus the suffix).
1154 * :lhs=rhs Like :S, but the rhs goes to the end of
1156 * :U Converts variable to upper-case.
1157 * :L Converts variable to lower-case.
1159 if ((str != NULL) && haveModifier) {
1161 * Skip initial colon while putting it back.
1164 while (*tstr != endc) {
1165 char *newStr; /* New value to return */
1166 char termc; /* Character which terminated scan */
1168 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1179 *cp != '\0' && *cp != ':' && *cp != endc;
1182 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
1191 * Need to compress the \:'s out of the pattern, so
1192 * allocate enough room to hold the uncompressed
1193 * pattern (note that cp started at tstr+1, so
1194 * cp - tstr takes the null byte into account) and
1195 * compress the pattern into the space.
1197 pattern = emalloc(cp - tstr);
1198 for (cp2 = pattern, cp = tstr + 1;
1202 if ((*cp == '\\') &&
1203 (cp[1] == ':' || cp[1] == endc)) {
1212 if (*tstr == 'M' || *tstr == 'm') {
1213 newStr = VarModify(str, VarMatch, pattern);
1215 newStr = VarModify(str, VarNoMatch, pattern);
1226 Buffer buf; /* Buffer for patterns */
1233 * If pattern begins with '^', it is anchored to the
1234 * start of the word -- skip over it and flag pattern.
1237 pattern.flags |= VAR_MATCH_START;
1244 * Pass through the lhs looking for 1) escaped delimiters,
1245 * '$'s and backslashes (place the escaped character in
1246 * uninterpreted) and 2) unescaped $'s that aren't before
1247 * the delimiter (expand the variable substitution).
1248 * The result is left in the Buffer buf.
1250 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1251 if ((*cp == '\\') &&
1256 Buf_AddByte(buf, (Byte)cp[1]);
1258 } else if (*cp == '$') {
1261 * If unescaped dollar sign not before the
1262 * delimiter, assume it's a variable
1263 * substitution and recurse.
1269 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1270 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1277 * Unescaped $ at end of pattern => anchor
1280 pattern.flags |= VAR_MATCH_END;
1283 Buf_AddByte(buf, (Byte)*cp);
1287 Buf_AddByte(buf, (Byte)'\0');
1290 * If lhs didn't end with the delimiter, complain and
1294 Fatal("Unclosed substitution for %s (%c missing)",
1299 * Fetch pattern and destroy buffer, but preserve the data
1300 * in it, since that's our lhs. Note that Buf_GetAll
1301 * will return the actual number of bytes, which includes
1302 * the null byte, so we have to decrement the length by
1305 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1307 Buf_Destroy(buf, FALSE);
1310 * Now comes the replacement string. Three things need to
1311 * be done here: 1) need to compress escaped delimiters and
1312 * ampersands and 2) need to replace unescaped ampersands
1313 * with the l.h.s. (since this isn't regexp, we can do
1314 * it right here) and 3) expand any variable substitutions.
1319 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1320 if ((*cp == '\\') &&
1326 Buf_AddByte(buf, (Byte)cp[1]);
1328 } else if ((*cp == '$') && (cp[1] != del)) {
1333 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1334 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1339 } else if (*cp == '&') {
1340 Buf_AddBytes(buf, pattern.leftLen,
1341 (Byte *)pattern.lhs);
1343 Buf_AddByte(buf, (Byte)*cp);
1347 Buf_AddByte(buf, (Byte)'\0');
1350 * If didn't end in delimiter character, complain
1353 Fatal("Unclosed substitution for %s (%c missing)",
1357 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1359 Buf_Destroy(buf, FALSE);
1362 * Check for global substitution. If 'g' after the final
1363 * delimiter, substitution is global and is marked that
1368 pattern.flags |= VAR_SUB_GLOBAL;
1373 * Global substitution of the empty string causes an
1374 * infinite number of matches, unless anchored by '^'
1375 * (start of string) or '$' (end of string). Catch the
1376 * infinite substitution here.
1377 * Note that flags can only contain the 3 bits we're
1378 * interested in so we don't have to mask unrelated
1379 * bits. We can test for equality.
1381 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1382 Fatal("Global substitution of the empty string");
1385 newStr = VarModify(str, VarSubstitute, &pattern);
1387 * Free the two strings.
1395 VarREPattern pattern;
1405 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1406 NULL, NULL)) == NULL) {
1407 /* was: goto cleanup */
1408 *lengthPtr = cp - start + 1;
1412 Fatal("Unclosed substitution for %s (%c missing)",
1417 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1418 delim, NULL, NULL, NULL)) == NULL){
1421 /* was: goto cleanup */
1422 *lengthPtr = cp - start + 1;
1426 Fatal("Unclosed substitution for %s (%c missing)",
1434 pattern.flags |= VAR_SUB_GLOBAL;
1437 pattern.flags |= VAR_SUB_ONE;
1447 error = regcomp(&pattern.re, re, REG_EXTENDED);
1450 *lengthPtr = cp - start + 1;
1451 VarREError(error, &pattern.re, "RE substitution error");
1452 free(pattern.replace);
1456 pattern.nsub = pattern.re.re_nsub + 1;
1457 if (pattern.nsub < 1)
1459 if (pattern.nsub > 10)
1461 pattern.matches = emalloc(pattern.nsub *
1462 sizeof(regmatch_t));
1463 newStr = VarModify(str, VarRESubstitute, &pattern);
1464 regfree(&pattern.re);
1465 free(pattern.replace);
1466 free(pattern.matches);
1470 if (tstr[1] == endc || tstr[1] == ':') {
1472 buf = Buf_Init(MAKE_BSIZE);
1473 for (cp = str; *cp ; cp++)
1474 Buf_AddByte(buf, (Byte)tolower(*cp));
1476 Buf_AddByte(buf, (Byte)'\0');
1477 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1478 Buf_Destroy(buf, FALSE);
1486 if (tstr[1] == endc || tstr[1] == ':') {
1487 newStr = VarSortWords(str, SortIncreasing);
1494 if (tstr[1] == endc || tstr[1] == ':') {
1495 newStr = Var_Quote(str);
1502 if (tstr[1] == endc || tstr[1] == ':') {
1503 newStr = VarModify(str, VarTail, (void *)NULL);
1510 if (tstr[1] == endc || tstr[1] == ':') {
1512 buf = Buf_Init(MAKE_BSIZE);
1513 for (cp = str; *cp ; cp++)
1514 Buf_AddByte(buf, (Byte)toupper(*cp));
1516 Buf_AddByte(buf, (Byte)'\0');
1517 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1518 Buf_Destroy(buf, FALSE);
1526 if (tstr[1] == endc || tstr[1] == ':') {
1527 newStr = VarModify(str, VarHead, (void *)NULL);
1534 if (tstr[1] == endc || tstr[1] == ':') {
1535 newStr = VarModify(str, VarSuffix, (void *)NULL);
1542 if (tstr[1] == endc || tstr[1] == ':') {
1543 newStr = VarModify(str, VarRoot, (void *)NULL);
1551 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1553 newStr = Cmd_Exec(str, &error);
1566 * This can either be a bogus modifier or a System-V
1567 * substitution command.
1575 * First we make a pass through the string trying
1576 * to verify it is a SYSV-make-style translation:
1577 * it must be: <string1>=<string2>)
1581 while (*cp != '\0' && cnt) {
1584 /* continue looking for endc */
1586 else if (*cp == endc)
1588 else if (*cp == startc)
1593 if (*cp == endc && eqFound) {
1596 * Now we break this sucker into the lhs and
1597 * rhs. We must null terminate them of course.
1602 if ((pattern.lhs = VarGetPattern(ctxt,
1603 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1605 /* was: goto cleanup */
1606 *lengthPtr = cp - start + 1;
1610 Fatal("Unclosed substitution for %s (%c missing)",
1616 if ((pattern.rhs = VarGetPattern(ctxt,
1617 err, &cp, delim, NULL, &pattern.rightLen,
1618 &pattern)) == NULL) {
1619 /* was: goto cleanup */
1620 *lengthPtr = cp - start + 1;
1624 Fatal("Unclosed substitution for %s (%c missing)",
1630 * SYSV modifications happen through the whole
1631 * string. Note the pattern is anchored at the end.
1635 newStr = VarModify(str, VarSYSVMatch, &pattern);
1644 Error("Unknown modifier '%c'\n", *tstr);
1646 *cp != ':' && *cp != endc && *cp != '\0';
1654 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1660 if (str != var_Error) {
1665 if (termc == '\0') {
1666 Error("Unclosed variable specification for %s", v->name);
1667 } else if (termc == ':') {
1674 *lengthPtr = tstr - start + 1;
1676 *lengthPtr = tstr - start + 1;
1680 if (v->flags & VAR_FROM_ENV) {
1681 Boolean destroy = FALSE;
1683 if (str != (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1687 * Returning the value unmodified, so tell the caller to free
1693 Buf_Destroy(v->val, destroy);
1695 } else if (v->flags & VAR_JUNK) {
1697 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1698 * doesn't try to free a static pointer.
1705 Buf_Destroy(v->val, TRUE);
1708 str = emalloc(*lengthPtr + 1);
1709 strncpy(str, start, *lengthPtr);
1710 str[*lengthPtr] = '\0';
1713 str = err ? var_Error : varNoError;
1720 *-----------------------------------------------------------------------
1722 * Substitute for all variables in the given string in the given context
1723 * If undefErr is TRUE, Parse_Error will be called when an undefined
1724 * variable is encountered.
1727 * The resulting string.
1730 * None. The old string must be freed by the caller
1731 *-----------------------------------------------------------------------
1734 Var_Subst(char *var, char *str, GNode *ctxt, Boolean undefErr)
1736 Buffer buf; /* Buffer for forming things */
1737 char *val; /* Value to substitute for a variable */
1738 size_t length; /* Length of the variable invocation */
1739 Boolean doFree; /* Set true if val should be freed */
1740 static Boolean errorReported; /* Set true if an error has already
1741 * been reported to prevent a plethora
1742 * of messages when recursing */
1744 buf = Buf_Init(MAKE_BSIZE);
1745 errorReported = FALSE;
1748 if (var == NULL && (*str == '$') && (str[1] == '$')) {
1750 * A dollar sign may be escaped either with another dollar sign.
1751 * In such a case, we skip over the escape character and store the
1752 * dollar sign into the buffer directly.
1755 Buf_AddByte(buf, (Byte)*str);
1757 } else if (*str != '$') {
1759 * Skip as many characters as possible -- either to the end of
1760 * the string or to the next dollar sign (variable invocation).
1764 for (cp = str++; *str != '$' && *str != '\0'; str++)
1766 Buf_AddBytes(buf, str - cp, (Byte *)cp);
1771 if (str[1] != '(' && str[1] != '{') {
1772 if (str[1] != *var || var[1] != '\0') {
1773 Buf_AddBytes(buf, 2, (Byte *)str);
1785 * Scan up to the end of the variable name.
1787 for (p = &str[2]; *p &&
1788 *p != ':' && *p != ')' && *p != '}'; p++)
1792 * A variable inside the variable. We cannot expand
1793 * the external variable yet, so we try again with
1797 Buf_AddBytes(buf, p - str, (Byte *)str);
1802 if (strncmp(var, str + 2, p - str - 2) != 0 ||
1803 var[p - str - 2] != '\0') {
1805 * Not the variable we want to expand, scan
1806 * until the next variable
1808 for (;*p != '$' && *p != '\0'; p++)
1810 Buf_AddBytes(buf, p - str, (Byte *)str);
1823 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1826 * When we come down here, val should either point to the
1827 * value of this variable, suitably modified, or be NULL.
1828 * Length should be the total length of the potential
1829 * variable invocation (from $ to end character...)
1831 if (val == var_Error || val == varNoError) {
1833 * If performing old-time variable substitution, skip over
1834 * the variable and continue with the substitution. Otherwise,
1835 * store the dollar sign and advance str so we continue with
1840 } else if (undefErr) {
1842 * If variable is undefined, complain and skip the
1843 * variable. The complaint will stop us from doing anything
1844 * when the file is parsed.
1846 if (!errorReported) {
1847 Parse_Error(PARSE_FATAL,
1848 "Undefined variable \"%.*s\"",length,str);
1851 errorReported = TRUE;
1853 Buf_AddByte (buf, (Byte)*str);
1858 * We've now got a variable structure to store in. But first,
1859 * advance the string pointer.
1864 * Copy all the characters from the variable value straight
1865 * into the new string.
1867 Buf_AddBytes(buf, strlen(val), (Byte *)val);
1875 Buf_AddByte(buf, '\0');
1876 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
1877 Buf_Destroy(buf, FALSE);
1882 *-----------------------------------------------------------------------
1884 * Return the tail from each of a list of words. Used to set the
1885 * System V local variables.
1888 * The resulting string.
1893 *-----------------------------------------------------------------------
1896 Var_GetTail(char *file)
1899 return (VarModify(file, VarTail, (void *)NULL));
1903 *-----------------------------------------------------------------------
1905 * Find the leading components of a (list of) filename(s).
1906 * XXX: VarHead does not replace foo by ., as (sun) System V make
1910 * The leading components.
1915 *-----------------------------------------------------------------------
1918 Var_GetHead(char *file)
1921 return (VarModify(file, VarHead, (void *)NULL));
1925 *-----------------------------------------------------------------------
1927 * Initialize the module
1933 * The VAR_CMD and VAR_GLOBAL contexts are created
1934 *-----------------------------------------------------------------------
1940 VAR_GLOBAL = Targ_NewGN("Global");
1941 VAR_CMD = Targ_NewGN("Command");
1951 /****************** PRINT DEBUGGING INFO *****************/
1953 VarPrintVar(void *vp, void *dummy __unused)
1955 Var *v = (Var *) vp;
1957 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
1962 *-----------------------------------------------------------------------
1964 * print all variables in a context
1965 *-----------------------------------------------------------------------
1968 Var_Dump(GNode *ctxt)
1971 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);