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.23 2004/12/16 23:24:09 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 static Lst allVars; /* List of all variables */
128 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
129 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
130 #define FIND_ENV 0x4 /* look in the environment also */
132 static int VarCmp(void *, void *);
133 static void VarPossiblyExpand(char **, GNode *);
134 static Var *VarFind(char *, GNode *, int);
135 static void VarAdd(char *, char *, GNode *);
136 static void VarDelete(void *);
137 static char *VarGetPattern(GNode *, int, char **, int, int *, size_t *,
139 static char *VarModify(char *, Boolean (*)(const char *, Boolean, Buffer, void *),
141 static int VarPrintVar(void *, void *);
144 *-----------------------------------------------------------------------
146 * See if the given variable matches the named one. Called from
147 * Lst_Find when searching for a variable of a given name.
150 * 0 if they match. non-zero otherwise.
154 *-----------------------------------------------------------------------
157 VarCmp(void *v, void *name)
160 return (strcmp(name, ((Var *)v)->name));
164 *-----------------------------------------------------------------------
165 * VarPossiblyExpand --
166 * Expand a variable name's embedded variables in the given context.
169 * The contents of name, possibly expanded.
172 * The caller must free the new contents or old contents of name.
173 *-----------------------------------------------------------------------
176 VarPossiblyExpand(char **name, GNode *ctxt)
179 if (strchr(*name, '$') != NULL)
180 *name = Var_Subst(NULL, *name, ctxt, 0);
182 *name = estrdup(*name);
186 *-----------------------------------------------------------------------
188 * Find the given variable in the given context and any other contexts
192 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
193 * FIND_CMD set means to look in the VAR_CMD context too
194 * FIND_ENV set means to look in the environment
197 * A pointer to the structure describing the desired variable or
198 * NULL if the variable does not exist.
202 *-----------------------------------------------------------------------
205 VarFind(char *name, GNode *ctxt, int flags)
207 Boolean localCheckEnvFirst;
212 * If the variable name begins with a '.', it could very well be one of
213 * the local ones. We check the name against all the local variables
214 * and substitute the short version in for 'name' if it matches one of
217 if (*name == '.' && isupper((unsigned char)name[1]))
220 if (!strcmp(name, ".ALLSRC"))
222 if (!strcmp(name, ".ARCHIVE"))
226 if (!strcmp(name, ".IMPSRC"))
230 if (!strcmp(name, ".MEMBER"))
234 if (!strcmp(name, ".OODATE"))
238 if (!strcmp(name, ".PREFIX"))
242 if (!strcmp(name, ".TARGET"))
248 * Note whether this is one of the specific variables we were told through
249 * the -E flag to use environment-variable-override for.
251 if (Lst_Find(envFirstVars, name, (CompareProc *)strcmp) != NULL) {
252 localCheckEnvFirst = TRUE;
254 localCheckEnvFirst = FALSE;
258 * First look for the variable in the given context. If it's not there,
259 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
260 * depending on the FIND_* flags in 'flags'
262 var = Lst_Find(ctxt->context, name, VarCmp);
264 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
265 var = Lst_Find(VAR_CMD->context, name, VarCmp);
267 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
268 !checkEnvFirst && !localCheckEnvFirst)
270 var = Lst_Find(VAR_GLOBAL->context, name, VarCmp);
272 if ((var == NULL) && (flags & FIND_ENV)) {
275 if ((env = getenv(name)) != NULL) {
278 v = emalloc(sizeof(Var));
279 v->name = estrdup(name);
283 v->val = Buf_Init(len);
284 Buf_AddBytes(v->val, len, (Byte *)env);
286 v->flags = VAR_FROM_ENV;
288 } else if ((checkEnvFirst || localCheckEnvFirst) &&
289 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
291 var = Lst_Find(VAR_GLOBAL->context, name, VarCmp);
295 return (Lst_Datum(var));
300 } else if (var == NULL) {
303 return (Lst_Datum(var));
308 *-----------------------------------------------------------------------
310 * Add a new variable of name name and value val to the given context.
316 * The new variable is placed at the front of the given context
317 * The name and val arguments are duplicated so they may
319 *-----------------------------------------------------------------------
322 VarAdd(char *name, char *val, GNode *ctxt)
327 v = emalloc(sizeof(Var));
329 v->name = estrdup(name);
331 len = val ? strlen(val) : 0;
332 v->val = Buf_Init(len+1);
333 Buf_AddBytes(v->val, len, (Byte *)val);
337 Lst_AtFront(ctxt->context, v);
338 Lst_AtEnd(allVars, v);
339 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
343 *-----------------------------------------------------------------------
345 * Delete a variable and all the space associated with it.
352 *-----------------------------------------------------------------------
360 Buf_Destroy(v->val, TRUE);
365 *-----------------------------------------------------------------------
367 * Remove a variable from a context.
373 * The Var structure is removed and freed.
375 *-----------------------------------------------------------------------
378 Var_Delete(char *name, GNode *ctxt)
382 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
383 ln = Lst_Find(ctxt->context, name, VarCmp);
388 Lst_Remove(ctxt->context, ln);
389 ln = Lst_Member(allVars, v);
390 Lst_Remove(allVars, ln);
396 *-----------------------------------------------------------------------
398 * Set the variable name to the value val in the given context.
404 * If the variable doesn't yet exist, a new record is created for it.
405 * Else the old value is freed and the new one stuck in its place
408 * The variable is searched for only in its context before being
409 * created in that context. I.e. if the context is VAR_GLOBAL,
410 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
411 * VAR_CMD->context is searched. This is done to avoid the literally
412 * thousands of unnecessary strcmp's that used to be done to
413 * set, say, $(@) or $(<).
414 *-----------------------------------------------------------------------
417 Var_Set(char *name, char *val, GNode *ctxt)
422 * We only look for a variable in the given context since anything set
423 * here will override anything in a lower context, so there's not much
424 * point in searching them all just to save a bit of memory...
426 VarPossiblyExpand(&name, ctxt);
427 v = VarFind(name, ctxt, 0);
429 VarAdd(name, val, ctxt);
431 Buf_Discard(v->val, Buf_Size(v->val));
432 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
434 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
437 * Any variables given on the command line are automatically exported
438 * to the environment (as per POSIX standard)
440 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
441 setenv(name, val, 1);
448 * Set the VAR_TO_ENV flag on a variable
451 Var_SetEnv (char *name, GNode *ctxt)
455 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
457 if ((v->flags & VAR_TO_ENV) == 0) {
458 v->flags |= VAR_TO_ENV;
459 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
462 Error("Cannot set environment flag on non-existant variable %s", name);
467 *-----------------------------------------------------------------------
469 * The variable of the given name has the given value appended to it in
476 * If the variable doesn't exist, it is created. Else the strings
477 * are concatenated (with a space in between).
480 * Only if the variable is being sought in the global context is the
481 * environment searched.
482 * XXX: Knows its calling circumstances in that if called with ctxt
483 * an actual target, it will only search that context since only
484 * a local variable could be being appended to. This is actually
485 * a big win and must be tolerated.
486 *-----------------------------------------------------------------------
489 Var_Append(char *name, char *val, GNode *ctxt)
493 VarPossiblyExpand(&name, ctxt);
494 v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
497 VarAdd(name, val, ctxt);
499 Buf_AddByte(v->val, (Byte)' ');
500 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
502 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name,
503 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
505 if (v->flags & VAR_FROM_ENV) {
507 * If the original variable came from the environment, we
508 * have to install it in the global context (we could place
509 * it in the environment, but then we should provide a way to
510 * export other variables...)
512 v->flags &= ~VAR_FROM_ENV;
513 Lst_AtFront(ctxt->context, v);
520 *-----------------------------------------------------------------------
522 * See if the given variable exists.
525 * TRUE if it does, FALSE if it doesn't
530 *-----------------------------------------------------------------------
533 Var_Exists(char *name, GNode *ctxt)
537 VarPossiblyExpand(&name, ctxt);
538 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
543 } else if (v->flags & VAR_FROM_ENV) {
545 Buf_Destroy(v->val, TRUE);
552 *-----------------------------------------------------------------------
554 * Return the value of the named variable in the given context
557 * The value if the variable exists, NULL if it doesn't
561 *-----------------------------------------------------------------------
564 Var_Value(char *name, GNode *ctxt, char **frp)
568 VarPossiblyExpand(&name, ctxt);
569 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
573 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
575 if (v->flags & VAR_FROM_ENV) {
576 Buf_Destroy(v->val, FALSE);
588 *-----------------------------------------------------------------------
590 * Print the error caused by a regcomp or regexec call.
596 * An error gets printed.
598 *-----------------------------------------------------------------------
601 VarREError(int err, regex_t *pat, const char *str)
606 errlen = regerror(err, pat, 0, 0);
607 errbuf = emalloc(errlen);
608 regerror(err, pat, errbuf, errlen);
609 Error("%s: %s", str, errbuf);
614 *-----------------------------------------------------------------------
616 * Modify each of the words of the passed string using the given
617 * function. Used to implement all modifiers.
620 * A string of all the words modified appropriately.
625 *-----------------------------------------------------------------------
628 VarModify(char *str, Boolean (*modProc)(const char *, Boolean, Buffer, void *),
631 Buffer buf; /* Buffer for the new string */
632 Boolean addSpace; /* TRUE if need to add a space to the
633 * buffer before adding the trimmed
635 char **av; /* word list [first word does not count] */
641 av = brk_string(str, &ac, FALSE);
643 for (i = 1; i < ac; i++)
644 addSpace = (*modProc)(av[i], addSpace, buf, datum);
646 Buf_AddByte (buf, '\0');
647 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
648 Buf_Destroy(buf, FALSE);
653 *-----------------------------------------------------------------------
655 * Sort the words in the string.
658 * str String whose words should be sorted
659 * cmp A comparison function to control the ordering
662 * A string containing the words sorted
667 *-----------------------------------------------------------------------
670 VarSortWords(char *str, int (*cmp)(const void *, const void *))
677 av = brk_string(str, &ac, FALSE);
678 qsort(av + 1, ac - 1, sizeof(char *), cmp);
679 for (i = 1; i < ac; i++) {
680 Buf_AddBytes(buf, strlen(av[i]), (Byte *)av[i]);
681 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
683 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
684 Buf_Destroy(buf, FALSE);
689 SortIncreasing(const void *l, const void *r)
692 return (strcmp(*(const char* const*)l, *(const char* const*)r));
696 *-----------------------------------------------------------------------
698 * Pass through the tstr looking for 1) escaped delimiters,
699 * '$'s and backslashes (place the escaped character in
700 * uninterpreted) and 2) unescaped $'s that aren't before
701 * the delimiter (expand the variable substitution unless flags
702 * has VAR_NOSUBST set).
703 * Return the expanded string or NULL if the delimiter was missing
704 * If pattern is specified, handle escaped ampersands, and replace
705 * unescaped ampersands with the lhs of the pattern.
708 * A string of all the words modified appropriately.
709 * If length is specified, return the string length of the buffer
710 * If flags is specified and the last character of the pattern is a
711 * $ set the VAR_MATCH_END bit of flags.
715 *-----------------------------------------------------------------------
718 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
719 size_t *length, VarPattern *pattern)
722 Buffer buf = Buf_Init(0);
728 #define IS_A_MATCH(cp, delim) \
729 ((cp[0] == '\\') && ((cp[1] == delim) || \
730 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
733 * Skim through until the matching delimiter is found;
734 * pick up variable substitutions on the way. Also allow
735 * backslashes to quote the delimiter, $, and \, but don't
736 * touch other backslashes.
738 for (cp = *tstr; *cp && (*cp != delim); cp++) {
739 if (IS_A_MATCH(cp, delim)) {
740 Buf_AddByte(buf, (Byte)cp[1]);
742 } else if (*cp == '$') {
743 if (cp[1] == delim) {
745 Buf_AddByte(buf, (Byte)*cp);
748 * Unescaped $ at end of pattern => anchor
751 *flags |= VAR_MATCH_END;
753 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
759 * If unescaped dollar sign not before the
760 * delimiter, assume it's a variable
761 * substitution and recurse.
763 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
764 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
771 if (*cp2 == '(' || *cp2 == '{') {
773 * Find the end of this variable reference
774 * and suck it in without further ado.
775 * It will be interperated later.
778 int want = (*cp2 == '(') ? ')' : '}';
781 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
782 if (cp2[-1] != '\\') {
789 Buf_AddBytes(buf, cp2 - cp, (Byte *)cp);
792 Buf_AddByte(buf, (Byte)*cp);
796 else if (pattern && *cp == '&')
797 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
799 Buf_AddByte(buf, (Byte)*cp);
802 Buf_AddByte(buf, (Byte)'\0');
810 cp = (char *)Buf_GetAll(buf, length);
811 *length -= 1; /* Don't count the NULL */
812 Buf_Destroy(buf, FALSE);
818 *-----------------------------------------------------------------------
820 * Quote shell meta-characters in the string
828 *-----------------------------------------------------------------------
831 Var_Quote(const char *str)
835 /* This should cover most shells :-( */
836 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
838 buf = Buf_Init(MAKE_BSIZE);
839 for (; *str; str++) {
840 if (strchr(meta, *str) != NULL)
841 Buf_AddByte(buf, (Byte)'\\');
842 Buf_AddByte(buf, (Byte)*str);
844 Buf_AddByte(buf, (Byte)'\0');
845 retstr = Buf_GetAll (buf, (int *)NULL);
846 Buf_Destroy(buf, FALSE);
851 *-----------------------------------------------------------------------
853 * Given the start of a variable invocation, extract the variable
854 * name and find its value, then modify it according to the
858 * The (possibly-modified) value of the variable or var_Error if the
859 * specification is invalid. The length of the specification is
860 * placed in *lengthPtr (for invalid specifications, this is just
861 * 2 to skip the '$' and the following letter, or 1 if '$' was the
862 * last character in the string).
863 * A Boolean in *freePtr telling whether the returned string should
864 * be freed by the caller.
869 *-----------------------------------------------------------------------
872 Var_Parse(char *str, GNode *ctxt, Boolean err, size_t *lengthPtr,
875 char *tstr; /* Pointer into str */
876 Var *v; /* Variable in invocation */
877 char *cp; /* Secondary pointer into str (place marker
879 Boolean haveModifier;/* TRUE if have modifiers for the variable */
880 char endc; /* Ending character when variable in parens
882 char startc=0; /* Starting character when variable in parens
884 int cnt; /* Used to count brace pairs when variable in
885 * in parens or braces */
888 Boolean dynamic; /* TRUE if the variable is local and we're
889 * expanding it in a non-local context. This
890 * is done to support dynamic sources. The
891 * result is just the invocation, unaltered */
892 int vlen; /* length of variable name, after embedded variable
899 if (str[1] != '(' && str[1] != '{') {
901 * If it's not bounded by braces of some sort, life is much simpler.
902 * We just need to check for the first character and return the
903 * value if it exists.
910 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
911 if (v == (Var *)NULL) {
917 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
919 * If substituting a local variable in a non-local context,
920 * assume it's for dynamic source stuff. We have to handle
921 * this specially and return the longhand for the variable
922 * with the dollar sign escaped so it makes it back to the
923 * caller. Only four of the local variables are treated
924 * specially as they are the only four that will be set
925 * when dynamic sources are expanded.
927 /* XXX: It looks like $% and $! are reversed here */
930 return ("$(.TARGET)");
932 return ("$(.ARCHIVE)");
934 return ("$(.PREFIX)");
936 return ("$(.MEMBER)");
944 return (err ? var_Error : varNoError);
946 haveModifier = FALSE;
951 /* build up expanded variable name in this buffer */
952 Buffer buf = Buf_Init(MAKE_BSIZE);
955 endc = startc == '(' ? ')' : '}';
958 * Skip to the end character or a colon, whichever comes first,
959 * replacing embedded variables as we go.
961 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
965 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
967 if (rval == var_Error) {
968 Fatal("Error expanding embedded variable.");
969 } else if (rval != NULL) {
970 Buf_AddBytes(buf, strlen(rval), (Byte *)rval);
976 Buf_AddByte(buf, (Byte)*tstr);
980 * If we never did find the end character, return NULL
981 * right now, setting the length to be the distance to
982 * the end of the string, since that's what make does.
984 *lengthPtr = tstr - str;
988 haveModifier = (*tstr == ':');
991 Buf_AddByte(buf, (Byte)'\0');
992 str = Buf_GetAll(buf, (size_t *)NULL);
995 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
996 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
997 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
1000 * Check for bogus D and F forms of local variables since we're
1001 * in a local context and the name is the right length.
1015 * Well, it's local -- go look for it.
1019 v = VarFind(vname, ctxt, 0);
1021 if (v != NULL && !haveModifier) {
1023 * No need for nested expansion or anything, as we're
1024 * the only one who sets these things and we sure don't
1025 * put nested invocations in them...
1027 val = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1029 if (str[1] == 'D') {
1030 val = VarModify(val, VarHead, (void *)NULL);
1032 val = VarModify(val, VarTail, (void *)NULL);
1035 * Resulting string is dynamically allocated, so
1036 * tell caller to free it.
1039 *lengthPtr = tstr-start+1;
1041 Buf_Destroy(buf, TRUE);
1051 if (v == (Var *)NULL) {
1053 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
1054 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1057 * If substituting a local variable in a non-local context,
1058 * assume it's for dynamic source stuff. We have to handle
1059 * this specially and return the longhand for the variable
1060 * with the dollar sign escaped so it makes it back to the
1061 * caller. Only four of the local variables are treated
1062 * specially as they are the only four that will be set
1063 * when dynamic sources are expanded.
1075 } else if ((vlen > 2) && (str[0] == '.') &&
1076 isupper((unsigned char)str[1]) &&
1077 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1082 if ((strncmp(str, ".TARGET", len) == 0) ||
1083 (strncmp(str, ".ARCHIVE", len) == 0) ||
1084 (strncmp(str, ".PREFIX", len) == 0) ||
1085 (strncmp(str, ".MEMBER", len) == 0))
1091 if (!haveModifier) {
1093 * No modifiers -- have specification length so we can return
1096 *lengthPtr = tstr - start + 1;
1099 str = emalloc(*lengthPtr + 1);
1100 strncpy(str, start, *lengthPtr);
1101 str[*lengthPtr] = '\0';
1103 Buf_Destroy(buf, TRUE);
1106 Buf_Destroy(buf, TRUE);
1107 return (err ? var_Error : varNoError);
1111 * Still need to get to the end of the variable specification,
1112 * so kludge up a Var structure for the modifications
1114 v = emalloc(sizeof(Var));
1115 v->name = estrdup(str);
1116 v->val = Buf_Init(1);
1117 v->flags = VAR_JUNK;
1120 Buf_Destroy(buf, TRUE);
1123 if (v->flags & VAR_IN_USE) {
1124 Fatal("Variable %s is recursive.", v->name);
1127 v->flags |= VAR_IN_USE;
1130 * Before doing any modification, we have to make sure the value
1131 * has been fully expanded. If it looks like recursion might be
1132 * necessary (there's a dollar sign somewhere in the variable's value)
1133 * we just call Var_Subst to do any other substitutions that are
1134 * necessary. Note that the value returned by Var_Subst will have
1135 * been dynamically-allocated, so it will need freeing when we
1138 str = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1139 if (strchr(str, '$') != (char *)NULL) {
1140 str = Var_Subst(NULL, str, ctxt, err);
1144 v->flags &= ~VAR_IN_USE;
1147 * Now we need to apply any modifiers the user wants applied.
1149 * :M<pattern> words which match the given <pattern>.
1150 * <pattern> is of the standard file
1152 * :S<d><pat1><d><pat2><d>[g]
1153 * Substitute <pat2> for <pat1> in the value
1154 * :C<d><pat1><d><pat2><d>[g]
1155 * Substitute <pat2> for regex <pat1> in the value
1156 * :H Substitute the head of each word
1157 * :T Substitute the tail of each word
1158 * :E Substitute the extension (minus '.') of
1160 * :R Substitute the root of each word
1161 * (pathname minus the suffix).
1162 * :lhs=rhs Like :S, but the rhs goes to the end of
1164 * :U Converts variable to upper-case.
1165 * :L Converts variable to lower-case.
1167 if ((str != NULL) && haveModifier) {
1169 * Skip initial colon while putting it back.
1172 while (*tstr != endc) {
1173 char *newStr; /* New value to return */
1174 char termc; /* Character which terminated scan */
1176 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1187 *cp != '\0' && *cp != ':' && *cp != endc;
1190 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
1199 * Need to compress the \:'s out of the pattern, so
1200 * allocate enough room to hold the uncompressed
1201 * pattern (note that cp started at tstr+1, so
1202 * cp - tstr takes the null byte into account) and
1203 * compress the pattern into the space.
1205 pattern = emalloc(cp - tstr);
1206 for (cp2 = pattern, cp = tstr + 1;
1210 if ((*cp == '\\') &&
1211 (cp[1] == ':' || cp[1] == endc)) {
1220 if (*tstr == 'M' || *tstr == 'm') {
1221 newStr = VarModify(str, VarMatch, pattern);
1223 newStr = VarModify(str, VarNoMatch, pattern);
1234 Buffer buf; /* Buffer for patterns */
1241 * If pattern begins with '^', it is anchored to the
1242 * start of the word -- skip over it and flag pattern.
1245 pattern.flags |= VAR_MATCH_START;
1252 * Pass through the lhs looking for 1) escaped delimiters,
1253 * '$'s and backslashes (place the escaped character in
1254 * uninterpreted) and 2) unescaped $'s that aren't before
1255 * the delimiter (expand the variable substitution).
1256 * The result is left in the Buffer buf.
1258 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1259 if ((*cp == '\\') &&
1264 Buf_AddByte(buf, (Byte)cp[1]);
1266 } else if (*cp == '$') {
1269 * If unescaped dollar sign not before the
1270 * delimiter, assume it's a variable
1271 * substitution and recurse.
1277 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1278 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1285 * Unescaped $ at end of pattern => anchor
1288 pattern.flags |= VAR_MATCH_END;
1291 Buf_AddByte(buf, (Byte)*cp);
1295 Buf_AddByte(buf, (Byte)'\0');
1298 * If lhs didn't end with the delimiter, complain and
1302 Fatal("Unclosed substitution for %s (%c missing)",
1307 * Fetch pattern and destroy buffer, but preserve the data
1308 * in it, since that's our lhs. Note that Buf_GetAll
1309 * will return the actual number of bytes, which includes
1310 * the null byte, so we have to decrement the length by
1313 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1315 Buf_Destroy(buf, FALSE);
1318 * Now comes the replacement string. Three things need to
1319 * be done here: 1) need to compress escaped delimiters and
1320 * ampersands and 2) need to replace unescaped ampersands
1321 * with the l.h.s. (since this isn't regexp, we can do
1322 * it right here) and 3) expand any variable substitutions.
1327 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1328 if ((*cp == '\\') &&
1334 Buf_AddByte(buf, (Byte)cp[1]);
1336 } else if ((*cp == '$') && (cp[1] != del)) {
1341 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1342 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1347 } else if (*cp == '&') {
1348 Buf_AddBytes(buf, pattern.leftLen,
1349 (Byte *)pattern.lhs);
1351 Buf_AddByte(buf, (Byte)*cp);
1355 Buf_AddByte(buf, (Byte)'\0');
1358 * If didn't end in delimiter character, complain
1361 Fatal("Unclosed substitution for %s (%c missing)",
1365 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1367 Buf_Destroy(buf, FALSE);
1370 * Check for global substitution. If 'g' after the final
1371 * delimiter, substitution is global and is marked that
1376 pattern.flags |= VAR_SUB_GLOBAL;
1381 * Global substitution of the empty string causes an
1382 * infinite number of matches, unless anchored by '^'
1383 * (start of string) or '$' (end of string). Catch the
1384 * infinite substitution here.
1385 * Note that flags can only contain the 3 bits we're
1386 * interested in so we don't have to mask unrelated
1387 * bits. We can test for equality.
1389 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1390 Fatal("Global substitution of the empty string");
1393 newStr = VarModify(str, VarSubstitute, &pattern);
1395 * Free the two strings.
1403 VarREPattern pattern;
1413 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1414 NULL, NULL)) == NULL) {
1415 /* was: goto cleanup */
1416 *lengthPtr = cp - start + 1;
1420 Fatal("Unclosed substitution for %s (%c missing)",
1425 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1426 delim, NULL, NULL, NULL)) == NULL){
1429 /* was: goto cleanup */
1430 *lengthPtr = cp - start + 1;
1434 Fatal("Unclosed substitution for %s (%c missing)",
1442 pattern.flags |= VAR_SUB_GLOBAL;
1445 pattern.flags |= VAR_SUB_ONE;
1455 error = regcomp(&pattern.re, re, REG_EXTENDED);
1458 *lengthPtr = cp - start + 1;
1459 VarREError(error, &pattern.re, "RE substitution error");
1460 free(pattern.replace);
1464 pattern.nsub = pattern.re.re_nsub + 1;
1465 if (pattern.nsub < 1)
1467 if (pattern.nsub > 10)
1469 pattern.matches = emalloc(pattern.nsub *
1470 sizeof(regmatch_t));
1471 newStr = VarModify(str, VarRESubstitute, &pattern);
1472 regfree(&pattern.re);
1473 free(pattern.replace);
1474 free(pattern.matches);
1478 if (tstr[1] == endc || tstr[1] == ':') {
1480 buf = Buf_Init(MAKE_BSIZE);
1481 for (cp = str; *cp ; cp++)
1482 Buf_AddByte(buf, (Byte)tolower(*cp));
1484 Buf_AddByte(buf, (Byte)'\0');
1485 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1486 Buf_Destroy(buf, FALSE);
1494 if (tstr[1] == endc || tstr[1] == ':') {
1495 newStr = VarSortWords(str, SortIncreasing);
1502 if (tstr[1] == endc || tstr[1] == ':') {
1503 newStr = Var_Quote(str);
1510 if (tstr[1] == endc || tstr[1] == ':') {
1511 newStr = VarModify(str, VarTail, (void *)NULL);
1518 if (tstr[1] == endc || tstr[1] == ':') {
1520 buf = Buf_Init(MAKE_BSIZE);
1521 for (cp = str; *cp ; cp++)
1522 Buf_AddByte(buf, (Byte)toupper(*cp));
1524 Buf_AddByte(buf, (Byte)'\0');
1525 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1526 Buf_Destroy(buf, FALSE);
1534 if (tstr[1] == endc || tstr[1] == ':') {
1535 newStr = VarModify(str, VarHead, (void *)NULL);
1542 if (tstr[1] == endc || tstr[1] == ':') {
1543 newStr = VarModify(str, VarSuffix, (void *)NULL);
1550 if (tstr[1] == endc || tstr[1] == ':') {
1551 newStr = VarModify(str, VarRoot, (void *)NULL);
1559 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1561 newStr = Cmd_Exec(str, &error);
1574 * This can either be a bogus modifier or a System-V
1575 * substitution command.
1583 * First we make a pass through the string trying
1584 * to verify it is a SYSV-make-style translation:
1585 * it must be: <string1>=<string2>)
1589 while (*cp != '\0' && cnt) {
1592 /* continue looking for endc */
1594 else if (*cp == endc)
1596 else if (*cp == startc)
1601 if (*cp == endc && eqFound) {
1604 * Now we break this sucker into the lhs and
1605 * rhs. We must null terminate them of course.
1610 if ((pattern.lhs = VarGetPattern(ctxt,
1611 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1613 /* was: goto cleanup */
1614 *lengthPtr = cp - start + 1;
1618 Fatal("Unclosed substitution for %s (%c missing)",
1624 if ((pattern.rhs = VarGetPattern(ctxt,
1625 err, &cp, delim, NULL, &pattern.rightLen,
1626 &pattern)) == NULL) {
1627 /* was: goto cleanup */
1628 *lengthPtr = cp - start + 1;
1632 Fatal("Unclosed substitution for %s (%c missing)",
1638 * SYSV modifications happen through the whole
1639 * string. Note the pattern is anchored at the end.
1643 newStr = VarModify(str, VarSYSVMatch, &pattern);
1652 Error("Unknown modifier '%c'\n", *tstr);
1654 *cp != ':' && *cp != endc && *cp != '\0';
1662 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1668 if (str != var_Error) {
1673 if (termc == '\0') {
1674 Error("Unclosed variable specification for %s", v->name);
1675 } else if (termc == ':') {
1682 *lengthPtr = tstr - start + 1;
1684 *lengthPtr = tstr - start + 1;
1688 if (v->flags & VAR_FROM_ENV) {
1689 Boolean destroy = FALSE;
1691 if (str != (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1695 * Returning the value unmodified, so tell the caller to free
1701 Buf_Destroy(v->val, destroy);
1703 } else if (v->flags & VAR_JUNK) {
1705 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1706 * doesn't try to free a static pointer.
1713 Buf_Destroy(v->val, TRUE);
1716 str = emalloc(*lengthPtr + 1);
1717 strncpy(str, start, *lengthPtr);
1718 str[*lengthPtr] = '\0';
1721 str = err ? var_Error : varNoError;
1728 *-----------------------------------------------------------------------
1730 * Substitute for all variables in the given string in the given context
1731 * If undefErr is TRUE, Parse_Error will be called when an undefined
1732 * variable is encountered.
1735 * The resulting string.
1738 * None. The old string must be freed by the caller
1739 *-----------------------------------------------------------------------
1742 Var_Subst(char *var, char *str, GNode *ctxt, Boolean undefErr)
1744 Buffer buf; /* Buffer for forming things */
1745 char *val; /* Value to substitute for a variable */
1746 size_t length; /* Length of the variable invocation */
1747 Boolean doFree; /* Set true if val should be freed */
1748 static Boolean errorReported; /* Set true if an error has already
1749 * been reported to prevent a plethora
1750 * of messages when recursing */
1752 buf = Buf_Init(MAKE_BSIZE);
1753 errorReported = FALSE;
1756 if (var == NULL && (*str == '$') && (str[1] == '$')) {
1758 * A dollar sign may be escaped either with another dollar sign.
1759 * In such a case, we skip over the escape character and store the
1760 * dollar sign into the buffer directly.
1763 Buf_AddByte(buf, (Byte)*str);
1765 } else if (*str != '$') {
1767 * Skip as many characters as possible -- either to the end of
1768 * the string or to the next dollar sign (variable invocation).
1772 for (cp = str++; *str != '$' && *str != '\0'; str++)
1774 Buf_AddBytes(buf, str - cp, (Byte *)cp);
1779 if (str[1] != '(' && str[1] != '{') {
1780 if (str[1] != *var || var[1] != '\0') {
1781 Buf_AddBytes(buf, 2, (Byte *)str);
1793 * Scan up to the end of the variable name.
1795 for (p = &str[2]; *p &&
1796 *p != ':' && *p != ')' && *p != '}'; p++)
1800 * A variable inside the variable. We cannot expand
1801 * the external variable yet, so we try again with
1805 Buf_AddBytes(buf, p - str, (Byte *)str);
1810 if (strncmp(var, str + 2, p - str - 2) != 0 ||
1811 var[p - str - 2] != '\0') {
1813 * Not the variable we want to expand, scan
1814 * until the next variable
1816 for (;*p != '$' && *p != '\0'; p++)
1818 Buf_AddBytes(buf, p - str, (Byte *)str);
1831 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1834 * When we come down here, val should either point to the
1835 * value of this variable, suitably modified, or be NULL.
1836 * Length should be the total length of the potential
1837 * variable invocation (from $ to end character...)
1839 if (val == var_Error || val == varNoError) {
1841 * If performing old-time variable substitution, skip over
1842 * the variable and continue with the substitution. Otherwise,
1843 * store the dollar sign and advance str so we continue with
1848 } else if (undefErr) {
1850 * If variable is undefined, complain and skip the
1851 * variable. The complaint will stop us from doing anything
1852 * when the file is parsed.
1854 if (!errorReported) {
1855 Parse_Error(PARSE_FATAL,
1856 "Undefined variable \"%.*s\"",length,str);
1859 errorReported = TRUE;
1861 Buf_AddByte (buf, (Byte)*str);
1866 * We've now got a variable structure to store in. But first,
1867 * advance the string pointer.
1872 * Copy all the characters from the variable value straight
1873 * into the new string.
1875 Buf_AddBytes(buf, strlen(val), (Byte *)val);
1883 Buf_AddByte(buf, '\0');
1884 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
1885 Buf_Destroy(buf, FALSE);
1890 *-----------------------------------------------------------------------
1892 * Return the tail from each of a list of words. Used to set the
1893 * System V local variables.
1896 * The resulting string.
1901 *-----------------------------------------------------------------------
1904 Var_GetTail(char *file)
1907 return (VarModify(file, VarTail, (void *)NULL));
1911 *-----------------------------------------------------------------------
1913 * Find the leading components of a (list of) filename(s).
1914 * XXX: VarHead does not replace foo by ., as (sun) System V make
1918 * The leading components.
1923 *-----------------------------------------------------------------------
1926 Var_GetHead(char *file)
1929 return (VarModify(file, VarHead, (void *)NULL));
1933 *-----------------------------------------------------------------------
1935 * Initialize the module
1941 * The VAR_CMD and VAR_GLOBAL contexts are created
1942 *-----------------------------------------------------------------------
1948 VAR_GLOBAL = Targ_NewGN("Global");
1949 VAR_CMD = Targ_NewGN("Command");
1950 allVars = Lst_Init();
1958 Lst_Destroy(allVars, VarDelete);
1962 /****************** PRINT DEBUGGING INFO *****************/
1964 VarPrintVar(void *vp, void *dummy __unused)
1966 Var *v = (Var *) vp;
1968 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
1973 *-----------------------------------------------------------------------
1975 * print all variables in a context
1976 *-----------------------------------------------------------------------
1979 Var_Dump(GNode *ctxt)
1982 Lst_ForEach (ctxt->context, VarPrintVar, (void *)NULL);