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.60 2005/02/06 23:17:16 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.
102 * This is a harmless return value for Var_Parse that can be used by Var_Subst
103 * to determine if there was an error in parsing -- easier than returning
104 * a flag, as things outside this module don't give a hoot.
106 char var_Error[] = "";
109 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
110 * set false. Why not just use a constant? Well, gcc likes to condense
111 * identical string instances...
113 static char varNoError[] = "";
116 * Internally, variables are contained in four different contexts.
117 * 1) the environment. They may not be changed. If an environment
118 * variable is appended-to, the result is placed in the global
120 * 2) the global context. Variables set in the Makefile are located in
121 * the global context. It is the penultimate context searched when
123 * 3) the command-line context. All variables set on the command line
124 * are placed in this context. They are UNALTERABLE once placed here.
125 * 4) the local context. Each target has associated with it a context
126 * list. On this list are located the structures describing such
127 * local variables as $(@) and $(*)
128 * The four contexts are searched in the reverse order from which they are
131 GNode *VAR_GLOBAL; /* variables from the makefile */
132 GNode *VAR_CMD; /* variables defined on the command-line */
134 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
135 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
136 #define FIND_ENV 0x4 /* look in the environment also */
138 #define OPEN_PAREN '('
139 #define CLOSE_PAREN ')'
140 #define OPEN_BRACKET '{'
141 #define CLOSE_BRACKET '}'
143 static Var *VarCreate(const char [], const char [], int);
144 static void VarDestroy(Var *, Boolean);
145 static char *VarGetPattern(GNode *, int, char **, int, int *, size_t *,
147 static char *VarModify(char *, VarModifyProc *, void *);
148 static int VarPrintVar(void *, void *);
151 *-----------------------------------------------------------------------
153 * See if the given variable matches the named one. Called from
154 * Lst_Find when searching for a variable of a given name.
157 * 0 if they match. non-zero otherwise.
161 *-----------------------------------------------------------------------
164 VarCmp(const void *v, const void *name)
167 return (strcmp(name, ((const Var *)v)->name));
171 *-----------------------------------------------------------------------
172 * VarPossiblyExpand --
173 * Expand a variable name's embedded variables in the given context.
176 * The contents of name, possibly expanded.
177 *-----------------------------------------------------------------------
180 VarPossiblyExpand(const char *name, GNode *ctxt)
185 * XXX make a temporary copy of the name because Var_Subst insists
186 * on writing into the string.
189 if (strchr(name, '$') != NULL) {
193 buf = Var_Subst(NULL, tmp, ctxt, 0);
194 str = Buf_GetAll(buf, NULL);
195 Buf_Destroy(buf, FALSE);
204 *-----------------------------------------------------------------------
206 * Find the given variable in the given context and any other contexts
210 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
211 * FIND_CMD set means to look in the VAR_CMD context too
212 * FIND_ENV set means to look in the environment
215 * A pointer to the structure describing the desired variable or
216 * NULL if the variable does not exist.
220 *-----------------------------------------------------------------------
223 VarFind(const char *name, GNode *ctxt, int flags)
225 Boolean localCheckEnvFirst;
230 * If the variable name begins with a '.', it could very well be one of
231 * the local ones. We check the name against all the local variables
232 * and substitute the short version in for 'name' if it matches one of
235 if (name[0] == '.' && isupper((unsigned char)name[1]))
238 if (!strcmp(name, ".ALLSRC"))
240 if (!strcmp(name, ".ARCHIVE"))
244 if (!strcmp(name, ".IMPSRC"))
248 if (!strcmp(name, ".MEMBER"))
252 if (!strcmp(name, ".OODATE"))
256 if (!strcmp(name, ".PREFIX"))
260 if (!strcmp(name, ".TARGET"))
266 * Note whether this is one of the specific variables we were told through
267 * the -E flag to use environment-variable-override for.
269 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
270 localCheckEnvFirst = TRUE;
272 localCheckEnvFirst = FALSE;
276 * First look for the variable in the given context. If it's not there,
277 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
278 * depending on the FIND_* flags in 'flags'
280 var = Lst_Find(&ctxt->context, name, VarCmp);
282 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
283 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
285 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
286 !checkEnvFirst && !localCheckEnvFirst)
288 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
290 if ((var == NULL) && (flags & FIND_ENV)) {
293 if ((env = getenv(name)) != NULL) {
294 v = VarCreate(name, env, VAR_FROM_ENV);
297 } else if ((checkEnvFirst || localCheckEnvFirst) &&
298 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
300 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
304 return (Lst_Datum(var));
309 } else if (var == NULL) {
312 return (Lst_Datum(var));
317 *-----------------------------------------------------------------------
319 * Add a new variable of name name and value val to the given context.
325 * The new variable is placed at the front of the given context
326 * The name and val arguments are duplicated so they may
328 *-----------------------------------------------------------------------
331 VarAdd(const char *name, const char *val, GNode *ctxt)
333 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
335 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
339 * Create a Var object.
341 * @param name Name of variable.
342 * @param value Value of variable.
343 * @param flags Flags set on variable.
346 VarCreate(const char name[], const char value[], int flags)
350 v = emalloc(sizeof(Var));
351 v->name = estrdup(name);
352 v->val = Buf_Init(0);
356 Buf_Append(v->val, value);
362 * Destroy a Var object.
364 * @param v Object to destroy.
365 * @param f true if internal buffer in Buffer object is to be
369 VarDestroy(Var *v, Boolean f)
371 Buf_Destroy(v->val, f);
377 *-----------------------------------------------------------------------
379 * Remove a variable from a context.
385 * The Var structure is removed and freed.
387 *-----------------------------------------------------------------------
390 Var_Delete(const char *name, GNode *ctxt)
394 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
395 ln = Lst_Find(&ctxt->context, name, VarCmp);
397 VarDestroy(Lst_Datum(ln), TRUE);
398 Lst_Remove(&ctxt->context, ln);
403 *-----------------------------------------------------------------------
405 * Set the variable name to the value val in the given context.
411 * If the variable doesn't yet exist, a new record is created for it.
412 * Else the old value is freed and the new one stuck in its place
415 * The variable is searched for only in its context before being
416 * created in that context. I.e. if the context is VAR_GLOBAL,
417 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
418 * VAR_CMD->context is searched. This is done to avoid the literally
419 * thousands of unnecessary strcmp's that used to be done to
420 * set, say, $(@) or $(<).
421 *-----------------------------------------------------------------------
424 Var_Set(const char *name, const char *val, GNode *ctxt)
430 * We only look for a variable in the given context since anything set
431 * here will override anything in a lower context, so there's not much
432 * point in searching them all just to save a bit of memory...
434 n = VarPossiblyExpand(name, ctxt);
435 v = VarFind(n, ctxt, 0);
437 VarAdd(n, val, ctxt);
440 Buf_Append(v->val, val);
442 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
445 * Any variables given on the command line are automatically exported
446 * to the environment (as per POSIX standard)
448 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
456 * Set the VAR_TO_ENV flag on a variable
459 Var_SetEnv(const char *name, GNode *ctxt)
463 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
465 if ((v->flags & VAR_TO_ENV) == 0) {
466 v->flags |= VAR_TO_ENV;
467 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
470 Error("Cannot set environment flag on non-existant variable %s", name);
475 *-----------------------------------------------------------------------
477 * The variable of the given name has the given value appended to it in
484 * If the variable doesn't exist, it is created. Else the strings
485 * are concatenated (with a space in between).
488 * Only if the variable is being sought in the global context is the
489 * environment searched.
490 * XXX: Knows its calling circumstances in that if called with ctxt
491 * an actual target, it will only search that context since only
492 * a local variable could be being appended to. This is actually
493 * a big win and must be tolerated.
494 *-----------------------------------------------------------------------
497 Var_Append(const char *name, const char *val, GNode *ctxt)
502 n = VarPossiblyExpand(name, ctxt);
503 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
506 VarAdd(n, val, ctxt);
508 Buf_AddByte(v->val, (Byte)' ');
509 Buf_Append(v->val, val);
511 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
512 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
514 if (v->flags & VAR_FROM_ENV) {
516 * If the original variable came from the environment, we
517 * have to install it in the global context (we could place
518 * it in the environment, but then we should provide a way to
519 * export other variables...)
521 v->flags &= ~VAR_FROM_ENV;
522 Lst_AtFront(&ctxt->context, v);
529 *-----------------------------------------------------------------------
531 * See if the given variable exists.
534 * TRUE if it does, FALSE if it doesn't
539 *-----------------------------------------------------------------------
542 Var_Exists(const char *name, GNode *ctxt)
547 n = VarPossiblyExpand(name, ctxt);
548 v = VarFind(n, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
553 } else if (v->flags & VAR_FROM_ENV) {
560 *-----------------------------------------------------------------------
562 * Return the value of the named variable in the given context
565 * The value if the variable exists, NULL if it doesn't
569 *-----------------------------------------------------------------------
572 Var_Value(const char *name, GNode *ctxt, char **frp)
577 n = VarPossiblyExpand(name, ctxt);
578 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
582 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
584 if (v->flags & VAR_FROM_ENV) {
585 VarDestroy(v, FALSE);
595 *-----------------------------------------------------------------------
597 * Modify each of the words of the passed string using the given
598 * function. Used to implement all modifiers.
601 * A string of all the words modified appropriately.
606 *-----------------------------------------------------------------------
609 VarModify(char *str, VarModifyProc *modProc, void *datum)
611 Buffer *buf; /* Buffer for the new string */
612 Boolean addSpace; /* TRUE if need to add a space to the
613 * buffer before adding the trimmed
615 char **av; /* word list [first word does not count] */
621 av = brk_string(str, &ac, FALSE);
623 for (i = 1; i < ac; i++)
624 addSpace = (*modProc)(av[i], addSpace, buf, datum);
626 Buf_AddByte(buf, '\0');
627 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
628 Buf_Destroy(buf, FALSE);
633 *-----------------------------------------------------------------------
635 * Sort the words in the string.
638 * str String whose words should be sorted
639 * cmp A comparison function to control the ordering
642 * A string containing the words sorted
647 *-----------------------------------------------------------------------
650 VarSortWords(char *str, int (*cmp)(const void *, const void *))
657 av = brk_string(str, &ac, FALSE);
658 qsort(av + 1, ac - 1, sizeof(char *), cmp);
659 for (i = 1; i < ac; i++) {
660 Buf_Append(buf, av[i]);
661 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
663 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
664 Buf_Destroy(buf, FALSE);
669 SortIncreasing(const void *l, const void *r)
672 return (strcmp(*(const char* const*)l, *(const char* const*)r));
676 *-----------------------------------------------------------------------
678 * Pass through the tstr looking for 1) escaped delimiters,
679 * '$'s and backslashes (place the escaped character in
680 * uninterpreted) and 2) unescaped $'s that aren't before
681 * the delimiter (expand the variable substitution unless flags
682 * has VAR_NOSUBST set).
683 * Return the expanded string or NULL if the delimiter was missing
684 * If pattern is specified, handle escaped ampersands, and replace
685 * unescaped ampersands with the lhs of the pattern.
688 * A string of all the words modified appropriately.
689 * If length is specified, return the string length of the buffer
690 * If flags is specified and the last character of the pattern is a
691 * $ set the VAR_MATCH_END bit of flags.
695 *-----------------------------------------------------------------------
698 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
699 size_t *length, VarPattern *pattern)
702 Buffer *buf = Buf_Init(0);
708 #define IS_A_MATCH(cp, delim) \
709 ((cp[0] == '\\') && ((cp[1] == delim) || \
710 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
713 * Skim through until the matching delimiter is found;
714 * pick up variable substitutions on the way. Also allow
715 * backslashes to quote the delimiter, $, and \, but don't
716 * touch other backslashes.
718 for (cp = *tstr; *cp && (*cp != delim); cp++) {
719 if (IS_A_MATCH(cp, delim)) {
720 Buf_AddByte(buf, (Byte)cp[1]);
722 } else if (*cp == '$') {
723 if (cp[1] == delim) {
725 Buf_AddByte(buf, (Byte)*cp);
728 * Unescaped $ at end of pattern => anchor
731 *flags |= VAR_MATCH_END;
733 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
739 * If unescaped dollar sign not before the
740 * delimiter, assume it's a variable
741 * substitution and recurse.
743 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
744 Buf_Append(buf, cp2);
751 if (*cp2 == OPEN_PAREN || *cp2 == OPEN_BRACKET) {
753 * Find the end of this variable reference
754 * and suck it in without further ado.
755 * It will be interperated later.
758 int want = (*cp2 == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACKET;
761 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
762 if (cp2[-1] != '\\') {
769 Buf_AppendRange(buf, cp, cp2);
772 Buf_AddByte(buf, (Byte)*cp);
776 else if (pattern && *cp == '&')
777 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
779 Buf_AddByte(buf, (Byte)*cp);
782 Buf_AddByte(buf, (Byte)'\0');
790 cp = (char *)Buf_GetAll(buf, length);
791 *length -= 1; /* Don't count the NULL */
792 Buf_Destroy(buf, FALSE);
798 *-----------------------------------------------------------------------
800 * Quote shell meta-characters in the string
808 *-----------------------------------------------------------------------
811 Var_Quote(const char *str)
814 /* This should cover most shells :-( */
815 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
818 buf = Buf_Init(MAKE_BSIZE);
819 for (; *str; str++) {
820 if (strchr(meta, *str) != NULL)
821 Buf_AddByte(buf, (Byte)'\\');
822 Buf_AddByte(buf, (Byte)*str);
824 Buf_AddByte(buf, (Byte)'\0');
825 ret = Buf_GetAll(buf, NULL);
826 Buf_Destroy(buf, FALSE);
831 *-----------------------------------------------------------------------
833 * Print the error caused by a regcomp or regexec call.
839 * An error gets printed.
841 *-----------------------------------------------------------------------
844 VarREError(int err, regex_t *pat, const char *str)
849 errlen = regerror(err, pat, 0, 0);
850 errbuf = emalloc(errlen);
851 regerror(err, pat, errbuf, errlen);
852 Error("%s: %s", str, errbuf);
857 *-----------------------------------------------------------------------
859 * Given the start of a variable invocation, extract the variable
860 * name and find its value, then modify it according to the
864 * The (possibly-modified) value of the variable or var_Error if the
865 * specification is invalid. The length of the specification is
866 * placed in *lengthPtr (for invalid specifications, this is just
867 * 2 to skip the '$' and the following letter, or 1 if '$' was the
868 * last character in the string).
869 * A Boolean in *freePtr telling whether the returned string should
870 * be freed by the caller.
875 *-----------------------------------------------------------------------
878 Var_Parse(char *str, GNode *ctxt, Boolean err, size_t *lengthPtr,
881 char *tstr; /* Pointer into str */
882 Var *v; /* Variable in invocation */
883 char *cp; /* Secondary pointer into str (place marker
885 Boolean haveModifier;/* TRUE if have modifiers for the variable */
886 char endc; /* Ending character when variable in parens
888 char startc=0; /* Starting character when variable in parens
890 int cnt; /* Used to count brace pairs when variable in
891 * in parens or braces */
894 Boolean dynamic; /* TRUE if the variable is local and we're
895 * expanding it in a non-local context. This
896 * is done to support dynamic sources. The
897 * result is just the invocation, unaltered */
898 int vlen; /* length of variable name, after embedded variable
906 * It is assumed that Var_Parse() is called with str[0] == '$'
909 if (str[1] != OPEN_PAREN && str[1] != OPEN_BRACKET) {
911 * If it's not bounded by braces of some sort, life is much simpler.
912 * We just need to check for the first character and return the
913 * value if it exists.
920 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
921 if (v == (Var *)NULL) {
927 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
929 * If substituting a local variable in a non-local context,
930 * assume it's for dynamic source stuff. We have to handle
931 * this specially and return the longhand for the variable
932 * with the dollar sign escaped so it makes it back to the
933 * caller. Only four of the local variables are treated
934 * specially as they are the only four that will be set
935 * when dynamic sources are expanded.
937 /* XXX: It looks like $% and $! are reversed here */
940 return ("$(.TARGET)");
942 return ("$(.ARCHIVE)");
944 return ("$(.PREFIX)");
946 return ("$(.MEMBER)");
954 return (err ? var_Error : varNoError);
956 haveModifier = FALSE;
961 /* build up expanded variable name in this buffer */
962 Buffer *buf = Buf_Init(MAKE_BSIZE);
965 * Skip to the end character or a colon, whichever comes first,
966 * replacing embedded variables as we go.
969 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACKET;
972 while (*tstr != '\0' && *tstr != endc && *tstr != ':') {
978 rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
979 if (rval == var_Error) {
980 Fatal("Error expanding embedded variable.");
981 } else if (rval != NULL) {
982 Buf_Append(buf, rval);
988 Buf_AddByte(buf, (Byte)*tstr);
995 * If we never did find the end character, return NULL
996 * right now, setting the length to be the distance to
997 * the end of the string, since that's what make does.
999 *lengthPtr = tstr - str;
1003 haveModifier = (*tstr == ':');
1004 *tstr = '\0'; /* modify input string */
1006 Buf_AddByte(buf, (Byte)'\0');
1007 str = Buf_GetAll(buf, (size_t *)NULL);
1010 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1011 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
1012 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
1015 * Check for bogus D and F forms of local variables since we're
1016 * in a local context and the name is the right length.
1030 * Well, it's local -- go look for it.
1034 v = VarFind(vname, ctxt, 0);
1036 if (v != NULL && !haveModifier) {
1038 * No need for nested expansion or anything, as we're
1039 * the only one who sets these things and we sure don't
1040 * put nested invocations in them...
1042 val = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1044 if (str[1] == 'D') {
1045 val = VarModify(val, VarHead, (void *)NULL);
1047 val = VarModify(val, VarTail, (void *)NULL);
1050 * Resulting string is dynamically allocated, so
1051 * tell caller to free it.
1054 *lengthPtr = tstr-start+1;
1056 Buf_Destroy(buf, TRUE);
1066 if (v == (Var *)NULL) {
1068 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
1069 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1072 * If substituting a local variable in a non-local context,
1073 * assume it's for dynamic source stuff. We have to handle
1074 * this specially and return the longhand for the variable
1075 * with the dollar sign escaped so it makes it back to the
1076 * caller. Only four of the local variables are treated
1077 * specially as they are the only four that will be set
1078 * when dynamic sources are expanded.
1090 } else if ((vlen > 2) && (str[0] == '.') &&
1091 isupper((unsigned char)str[1]) &&
1092 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1097 if ((strncmp(str, ".TARGET", len) == 0) ||
1098 (strncmp(str, ".ARCHIVE", len) == 0) ||
1099 (strncmp(str, ".PREFIX", len) == 0) ||
1100 (strncmp(str, ".MEMBER", len) == 0))
1106 if (!haveModifier) {
1108 * No modifiers -- have specification length so we can return
1111 *lengthPtr = tstr - start + 1;
1114 str = emalloc(*lengthPtr + 1);
1115 strncpy(str, start, *lengthPtr);
1116 str[*lengthPtr] = '\0';
1118 Buf_Destroy(buf, TRUE);
1121 Buf_Destroy(buf, TRUE);
1122 return (err ? var_Error : varNoError);
1126 * Still need to get to the end of the variable specification,
1127 * so kludge up a Var structure for the modifications
1129 v = VarCreate(str, NULL, VAR_JUNK);
1132 Buf_Destroy(buf, TRUE);
1135 if (v->flags & VAR_IN_USE) {
1136 Fatal("Variable %s is recursive.", v->name);
1139 v->flags |= VAR_IN_USE;
1143 * Before doing any modification, we have to make sure the value
1144 * has been fully expanded. If it looks like recursion might be
1145 * necessary (there's a dollar sign somewhere in the variable's value)
1146 * we just call Var_Subst to do any other substitutions that are
1147 * necessary. Note that the value returned by Var_Subst will have
1148 * been dynamically-allocated, so it will need freeing when we
1151 str = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1152 if (strchr(str, '$') != NULL) {
1155 buf = Var_Subst(NULL, str, ctxt, err);
1156 str = Buf_GetAll(buf, NULL);
1157 Buf_Destroy(buf, FALSE);
1162 v->flags &= ~VAR_IN_USE;
1165 * Now we need to apply any modifiers the user wants applied.
1167 * :M<pattern> words which match the given <pattern>.
1168 * <pattern> is of the standard file
1170 * :S<d><pat1><d><pat2><d>[g]
1171 * Substitute <pat2> for <pat1> in the value
1172 * :C<d><pat1><d><pat2><d>[g]
1173 * Substitute <pat2> for regex <pat1> in the value
1174 * :H Substitute the head of each word
1175 * :T Substitute the tail of each word
1176 * :E Substitute the extension (minus '.') of
1178 * :R Substitute the root of each word
1179 * (pathname minus the suffix).
1180 * :lhs=rhs Like :S, but the rhs goes to the end of
1182 * :U Converts variable to upper-case.
1183 * :L Converts variable to lower-case.
1185 if ((str != NULL) && haveModifier) {
1187 * Skip initial colon while putting it back.
1190 while (*tstr != endc) {
1191 char *newStr; /* New value to return */
1192 char termc; /* Character which terminated scan */
1194 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1205 *cp != '\0' && *cp != ':' && *cp != endc;
1208 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
1217 * Need to compress the \:'s out of the pattern, so
1218 * allocate enough room to hold the uncompressed
1219 * pattern (note that cp started at tstr+1, so
1220 * cp - tstr takes the null byte into account) and
1221 * compress the pattern into the space.
1223 pattern = emalloc(cp - tstr);
1224 for (cp2 = pattern, cp = tstr + 1;
1228 if ((*cp == '\\') &&
1229 (cp[1] == ':' || cp[1] == endc)) {
1238 if (*tstr == 'M' || *tstr == 'm') {
1239 newStr = VarModify(str, VarMatch, pattern);
1241 newStr = VarModify(str, VarNoMatch, pattern);
1252 Buffer *buf; /* Buffer for patterns */
1259 * If pattern begins with '^', it is anchored to the
1260 * start of the word -- skip over it and flag pattern.
1263 pattern.flags |= VAR_MATCH_START;
1270 * Pass through the lhs looking for 1) escaped delimiters,
1271 * '$'s and backslashes (place the escaped character in
1272 * uninterpreted) and 2) unescaped $'s that aren't before
1273 * the delimiter (expand the variable substitution).
1274 * The result is left in the Buffer buf.
1276 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1277 if ((*cp == '\\') &&
1282 Buf_AddByte(buf, (Byte)cp[1]);
1284 } else if (*cp == '$') {
1287 * If unescaped dollar sign not before the
1288 * delimiter, assume it's a variable
1289 * substitution and recurse.
1295 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1296 Buf_Append(buf, cp2);
1303 * Unescaped $ at end of pattern => anchor
1306 pattern.flags |= VAR_MATCH_END;
1309 Buf_AddByte(buf, (Byte)*cp);
1313 Buf_AddByte(buf, (Byte)'\0');
1316 * If lhs didn't end with the delimiter, complain and
1320 Fatal("Unclosed substitution for %s (%c missing)",
1325 * Fetch pattern and destroy buffer, but preserve the data
1326 * in it, since that's our lhs. Note that Buf_GetAll
1327 * will return the actual number of bytes, which includes
1328 * the null byte, so we have to decrement the length by
1331 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1333 Buf_Destroy(buf, FALSE);
1336 * Now comes the replacement string. Three things need to
1337 * be done here: 1) need to compress escaped delimiters and
1338 * ampersands and 2) need to replace unescaped ampersands
1339 * with the l.h.s. (since this isn't regexp, we can do
1340 * it right here) and 3) expand any variable substitutions.
1345 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1346 if ((*cp == '\\') &&
1352 Buf_AddByte(buf, (Byte)cp[1]);
1354 } else if ((*cp == '$') && (cp[1] != del)) {
1359 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1360 Buf_Append(buf, cp2);
1365 } else if (*cp == '&') {
1366 Buf_AddBytes(buf, pattern.leftLen,
1367 (Byte *)pattern.lhs);
1369 Buf_AddByte(buf, (Byte)*cp);
1373 Buf_AddByte(buf, (Byte)'\0');
1376 * If didn't end in delimiter character, complain
1379 Fatal("Unclosed substitution for %s (%c missing)",
1383 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1385 Buf_Destroy(buf, FALSE);
1388 * Check for global substitution. If 'g' after the final
1389 * delimiter, substitution is global and is marked that
1394 pattern.flags |= VAR_SUB_GLOBAL;
1399 * Global substitution of the empty string causes an
1400 * infinite number of matches, unless anchored by '^'
1401 * (start of string) or '$' (end of string). Catch the
1402 * infinite substitution here.
1403 * Note that flags can only contain the 3 bits we're
1404 * interested in so we don't have to mask unrelated
1405 * bits. We can test for equality.
1407 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1408 Fatal("Global substitution of the empty string");
1411 newStr = VarModify(str, VarSubstitute, &pattern);
1413 * Free the two strings.
1421 VarREPattern pattern;
1431 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1432 NULL, NULL)) == NULL) {
1433 /* was: goto cleanup */
1434 *lengthPtr = cp - start + 1;
1438 Fatal("Unclosed substitution for %s (%c missing)",
1443 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1444 delim, NULL, NULL, NULL)) == NULL){
1447 /* was: goto cleanup */
1448 *lengthPtr = cp - start + 1;
1452 Fatal("Unclosed substitution for %s (%c missing)",
1460 pattern.flags |= VAR_SUB_GLOBAL;
1463 pattern.flags |= VAR_SUB_ONE;
1473 error = regcomp(&pattern.re, re, REG_EXTENDED);
1476 *lengthPtr = cp - start + 1;
1477 VarREError(error, &pattern.re, "RE substitution error");
1478 free(pattern.replace);
1482 pattern.nsub = pattern.re.re_nsub + 1;
1483 if (pattern.nsub < 1)
1485 if (pattern.nsub > 10)
1487 pattern.matches = emalloc(pattern.nsub *
1488 sizeof(regmatch_t));
1489 newStr = VarModify(str, VarRESubstitute, &pattern);
1490 regfree(&pattern.re);
1491 free(pattern.replace);
1492 free(pattern.matches);
1496 if (tstr[1] == endc || tstr[1] == ':') {
1498 buf = Buf_Init(MAKE_BSIZE);
1499 for (cp = str; *cp ; cp++)
1500 Buf_AddByte(buf, (Byte)tolower(*cp));
1502 Buf_AddByte(buf, (Byte)'\0');
1503 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1504 Buf_Destroy(buf, FALSE);
1512 if (tstr[1] == endc || tstr[1] == ':') {
1513 newStr = VarSortWords(str, SortIncreasing);
1520 if (tstr[1] == endc || tstr[1] == ':') {
1521 newStr = Var_Quote(str);
1528 if (tstr[1] == endc || tstr[1] == ':') {
1529 newStr = VarModify(str, VarTail, (void *)NULL);
1536 if (tstr[1] == endc || tstr[1] == ':') {
1538 buf = Buf_Init(MAKE_BSIZE);
1539 for (cp = str; *cp ; cp++)
1540 Buf_AddByte(buf, (Byte)toupper(*cp));
1542 Buf_AddByte(buf, (Byte)'\0');
1543 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1544 Buf_Destroy(buf, FALSE);
1552 if (tstr[1] == endc || tstr[1] == ':') {
1553 newStr = VarModify(str, VarHead, (void *)NULL);
1560 if (tstr[1] == endc || tstr[1] == ':') {
1561 newStr = VarModify(str, VarSuffix, (void *)NULL);
1568 if (tstr[1] == endc || tstr[1] == ':') {
1569 newStr = VarModify(str, VarRoot, (void *)NULL);
1577 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1580 Buffer *buf = Cmd_Exec(str, &error);
1581 newStr = Buf_GetAll(buf, NULL);
1582 Buf_Destroy(buf, FALSE);
1596 * This can either be a bogus modifier or a System-V
1597 * substitution command.
1605 * First we make a pass through the string trying
1606 * to verify it is a SYSV-make-style translation:
1607 * it must be: <string1>=<string2>)
1611 while (*cp != '\0' && cnt) {
1614 /* continue looking for endc */
1616 else if (*cp == endc)
1618 else if (*cp == startc)
1623 if (*cp == endc && eqFound) {
1626 * Now we break this sucker into the lhs and
1627 * rhs. We must null terminate them of course.
1632 if ((pattern.lhs = VarGetPattern(ctxt,
1633 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1635 /* was: goto cleanup */
1636 *lengthPtr = cp - start + 1;
1640 Fatal("Unclosed substitution for %s (%c missing)",
1646 if ((pattern.rhs = VarGetPattern(ctxt,
1647 err, &cp, delim, NULL, &pattern.rightLen,
1648 &pattern)) == NULL) {
1649 /* was: goto cleanup */
1650 *lengthPtr = cp - start + 1;
1654 Fatal("Unclosed substitution for %s (%c missing)",
1660 * SYSV modifications happen through the whole
1661 * string. Note the pattern is anchored at the end.
1665 newStr = VarModify(str, VarSYSVMatch, &pattern);
1674 Error("Unknown modifier '%c'\n", *tstr);
1676 *cp != ':' && *cp != endc && *cp != '\0';
1684 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1690 if (str != var_Error) {
1695 if (termc == '\0') {
1696 Error("Unclosed variable specification for %s", v->name);
1697 } else if (termc == ':') {
1704 *lengthPtr = tstr - start + 1;
1706 *lengthPtr = tstr - start + 1;
1710 if (v->flags & VAR_FROM_ENV) {
1711 Boolean destroy = FALSE;
1713 if (str != (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1717 * Returning the value unmodified, so tell the caller to free
1722 VarDestroy(v, destroy);
1723 } else if (v->flags & VAR_JUNK) {
1725 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1726 * doesn't try to free a static pointer.
1732 VarDestroy(v, TRUE);
1734 str = emalloc(*lengthPtr + 1);
1735 strncpy(str, start, *lengthPtr);
1736 str[*lengthPtr] = '\0';
1739 str = err ? var_Error : varNoError;
1746 *-----------------------------------------------------------------------
1748 * Substitute for all variables in the given string in the given context
1749 * If undefErr is TRUE, Parse_Error will be called when an undefined
1750 * variable is encountered.
1753 * The resulting string.
1756 * None. The old string must be freed by the caller
1757 *-----------------------------------------------------------------------
1760 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1762 Boolean errorReported;
1763 Buffer *buf; /* Buffer for forming things */
1766 * Set TRUE if an error has already been reported to prevent a
1767 * plethora of messages when recursing.
1769 errorReported = FALSE;
1773 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1775 * A dollar sign may be escaped either with another dollar sign.
1776 * In such a case, we skip over the escape character and store the
1777 * dollar sign into the buffer directly.
1779 Buf_AddByte(buf, (Byte)str[0]);
1782 } else if (str[0] == '$') {
1783 char *val; /* Value to substitute for a variable */
1784 size_t length; /* Length of the variable invocation */
1785 Boolean doFree; /* Set true if val should be freed */
1787 * Variable invocation.
1792 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACKET) {
1793 const char *p = str + 2;
1796 * Scan up to the end of the variable name.
1798 while (*p != '\0' &&
1800 *p != CLOSE_PAREN &&
1801 *p != CLOSE_BRACKET &&
1807 * A variable inside the variable. We cannot expand
1808 * the external variable yet, so we try again with
1812 Buf_AppendRange(buf, str, p);
1817 if (var[p - (str + 2)] == '\0' && strncmp(var, str + 2, p - (str + 2)) == 0) {
1821 * Not the variable we want to expand, scan
1822 * until the next variable
1824 while (*p != '$' && *p != '\0')
1827 Buf_AppendRange(buf, str, p);
1834 * Single letter variable name.
1836 if (var[1] == '\0' && str[1] == var[0]) {
1839 Buf_AddBytes(buf, 2, (const Byte *)str);
1850 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1853 * When we come down here, val should either point to the
1854 * value of this variable, suitably modified, or be NULL.
1855 * Length should be the total length of the potential
1856 * variable invocation (from $ to end character...)
1858 if (val == var_Error || val == varNoError) {
1860 * If performing old-time variable substitution, skip over
1861 * the variable and continue with the substitution. Otherwise,
1862 * store the dollar sign and advance str so we continue with
1867 } else if (undefErr) {
1869 * If variable is undefined, complain and skip the
1870 * variable. The complaint will stop us from doing anything
1871 * when the file is parsed.
1873 if (!errorReported) {
1874 Parse_Error(PARSE_FATAL,
1875 "Undefined variable \"%.*s\"",length,str);
1878 errorReported = TRUE;
1880 Buf_AddByte(buf, (Byte)*str);
1885 * We've now got a variable structure to store in. But first,
1886 * advance the string pointer.
1891 * Copy all the characters from the variable value straight
1892 * into the new string.
1894 Buf_Append(buf, val);
1902 * Skip as many characters as possible -- either to the end of
1903 * the string or to the next dollar sign (variable invocation).
1905 const char *cp = str;
1909 } while (str[0] != '$' && str[0] != '\0');
1911 Buf_AppendRange(buf, cp, str);
1919 *-----------------------------------------------------------------------
1921 * Return the tail from each of a list of words. Used to set the
1922 * System V local variables.
1925 * The resulting string.
1930 *-----------------------------------------------------------------------
1933 Var_GetTail(char *file)
1936 return (VarModify(file, VarTail, (void *)NULL));
1940 *-----------------------------------------------------------------------
1942 * Find the leading components of a (list of) filename(s).
1943 * XXX: VarHead does not replace foo by ., as (sun) System V make
1947 * The leading components.
1952 *-----------------------------------------------------------------------
1955 Var_GetHead(char *file)
1958 return (VarModify(file, VarHead, (void *)NULL));
1962 *-----------------------------------------------------------------------
1964 * Initialize the module
1970 * The VAR_CMD and VAR_GLOBAL contexts are created
1971 *-----------------------------------------------------------------------
1977 VAR_GLOBAL = Targ_NewGN("Global");
1978 VAR_CMD = Targ_NewGN("Command");
1981 /****************** PRINT DEBUGGING INFO *****************/
1983 VarPrintVar(void *vp, void *dummy __unused)
1985 Var *v = (Var *) vp;
1987 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
1992 *-----------------------------------------------------------------------
1994 * print all variables in a context
1995 *-----------------------------------------------------------------------
1998 Var_Dump(GNode *ctxt)
2001 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);