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.83 2005/02/11 10:49:01 harti Exp $
40 * $DragonFly: src/usr.bin/make/var.c,v 1.100 2005/02/15 11:15:11 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_BRACE '{'
141 #define CLOSE_BRACE '}'
143 static char *VarGetPattern(GNode *, int, char **, int, int *, size_t *,
145 static int VarPrintVar(void *, void *);
148 * Create a Var object.
150 * @param name Name of variable.
151 * @param value Value of variable.
152 * @param flags Flags set on variable.
155 VarCreate(const char name[], const char value[], int flags)
159 v = emalloc(sizeof(Var));
160 v->name = estrdup(name);
161 v->val = Buf_Init(0);
165 Buf_Append(v->val, value);
171 * Destroy a Var object.
173 * @param v Object to destroy.
174 * @param f true if internal buffer in Buffer object is to be
178 VarDestroy(Var *v, Boolean f)
181 Buf_Destroy(v->val, f);
187 *-----------------------------------------------------------------------
189 * See if the given variable matches the named one. Called from
190 * Lst_Find when searching for a variable of a given name.
193 * 0 if they match. non-zero otherwise.
197 *-----------------------------------------------------------------------
200 VarCmp(const void *v, const void *name)
203 return (strcmp(name, ((const Var *)v)->name));
207 *-----------------------------------------------------------------------
208 * VarPossiblyExpand --
209 * Expand a variable name's embedded variables in the given context.
212 * The contents of name, possibly expanded.
213 *-----------------------------------------------------------------------
216 VarPossiblyExpand(const char *name, GNode *ctxt)
221 * XXX make a temporary copy of the name because Var_Subst insists
222 * on writing into the string.
225 if (strchr(name, '$') != NULL) {
229 buf = Var_Subst(NULL, tmp, ctxt, 0);
230 str = Buf_GetAll(buf, NULL);
231 Buf_Destroy(buf, FALSE);
240 *-----------------------------------------------------------------------
242 * Find the given variable in the given context and any other contexts
246 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
247 * FIND_CMD set means to look in the VAR_CMD context too
248 * FIND_ENV set means to look in the environment
251 * A pointer to the structure describing the desired variable or
252 * NULL if the variable does not exist.
256 *-----------------------------------------------------------------------
259 VarFind(const char *name, GNode *ctxt, int flags)
261 Boolean localCheckEnvFirst;
266 * If the variable name begins with a '.', it could very well be one of
267 * the local ones. We check the name against all the local variables
268 * and substitute the short version in for 'name' if it matches one of
271 if (name[0] == '.') {
274 if (!strcmp(name, ".ALLSRC"))
276 if (!strcmp(name, ".ARCHIVE"))
280 if (!strcmp(name, ".IMPSRC"))
284 if (!strcmp(name, ".MEMBER"))
288 if (!strcmp(name, ".OODATE"))
292 if (!strcmp(name, ".PREFIX"))
296 if (!strcmp(name, ".TARGET"))
305 * Note whether this is one of the specific variables we were told
306 * through the -E flag to use environment-variable-override for.
308 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
309 localCheckEnvFirst = TRUE;
311 localCheckEnvFirst = FALSE;
315 * First look for the variable in the given context. If it's not there,
316 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
317 * in that order, depending on the FIND_* flags in 'flags'
319 var = Lst_Find(&ctxt->context, name, VarCmp);
322 return (Lst_Datum(var));
325 /* not there - try command line context */
326 if ((flags & FIND_CMD) && (ctxt != VAR_CMD)) {
327 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
329 return (Lst_Datum(var));
332 /* not there - try global context, but only if not -e/-E */
333 if ((flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
334 !checkEnvFirst && !localCheckEnvFirst) {
335 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
337 return (Lst_Datum(var));
340 if (!(flags & FIND_ENV))
341 /* we were not told to look into the environment */
344 /* look in the environment */
345 if ((env = getenv(name)) != NULL) {
346 /* craft this variable from the environment value */
347 return (VarCreate(name, env, VAR_FROM_ENV));
350 /* deferred check for the environment (in case of -e/-E) */
351 if ((checkEnvFirst || localCheckEnvFirst) &&
352 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL)) {
353 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
355 return (Lst_Datum(var));
361 *-----------------------------------------------------------------------
363 * Add a new variable of name name and value val to the given context.
369 * The new variable is placed at the front of the given context
370 * The name and val arguments are duplicated so they may
372 *-----------------------------------------------------------------------
375 VarAdd(const char *name, const char *val, GNode *ctxt)
378 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
380 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
384 *-----------------------------------------------------------------------
386 * Remove a variable from a context.
392 * The Var structure is removed and freed.
394 *-----------------------------------------------------------------------
397 Var_Delete(const char *name, GNode *ctxt)
401 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
402 ln = Lst_Find(&ctxt->context, name, VarCmp);
404 VarDestroy(Lst_Datum(ln), TRUE);
405 Lst_Remove(&ctxt->context, ln);
410 *-----------------------------------------------------------------------
412 * Set the variable name to the value val in the given context.
418 * If the variable doesn't yet exist, a new record is created for it.
419 * Else the old value is freed and the new one stuck in its place
422 * The variable is searched for only in its context before being
423 * created in that context. I.e. if the context is VAR_GLOBAL,
424 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
425 * VAR_CMD->context is searched. This is done to avoid the literally
426 * thousands of unnecessary strcmp's that used to be done to
427 * set, say, $(@) or $(<).
428 *-----------------------------------------------------------------------
431 Var_Set(const char *name, const char *val, GNode *ctxt)
437 * We only look for a variable in the given context since anything set
438 * here will override anything in a lower context, so there's not much
439 * point in searching them all just to save a bit of memory...
441 n = VarPossiblyExpand(name, ctxt);
442 v = VarFind(n, ctxt, 0);
444 VarAdd(n, val, ctxt);
447 Buf_Append(v->val, val);
449 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
452 * Any variables given on the command line are automatically exported
453 * to the environment (as per POSIX standard)
455 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
463 * Set the VAR_TO_ENV flag on a variable
466 Var_SetEnv(const char *name, GNode *ctxt)
470 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
472 if ((v->flags & VAR_TO_ENV) == 0) {
473 v->flags |= VAR_TO_ENV;
474 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
477 Error("Cannot set environment flag on non-existant variable %s", name);
482 *-----------------------------------------------------------------------
484 * The variable of the given name has the given value appended to it in
491 * If the variable doesn't exist, it is created. Else the strings
492 * are concatenated (with a space in between).
495 * Only if the variable is being sought in the global context is the
496 * environment searched.
497 * XXX: Knows its calling circumstances in that if called with ctxt
498 * an actual target, it will only search that context since only
499 * a local variable could be being appended to. This is actually
500 * a big win and must be tolerated.
501 *-----------------------------------------------------------------------
504 Var_Append(const char *name, const char *val, GNode *ctxt)
509 n = VarPossiblyExpand(name, ctxt);
510 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
513 VarAdd(n, val, ctxt);
515 Buf_AddByte(v->val, (Byte)' ');
516 Buf_Append(v->val, val);
518 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
519 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
521 if (v->flags & VAR_FROM_ENV) {
523 * If the original variable came from the environment, we
524 * have to install it in the global context (we could place
525 * it in the environment, but then we should provide a way to
526 * export other variables...)
528 v->flags &= ~VAR_FROM_ENV;
529 Lst_AtFront(&ctxt->context, v);
536 *-----------------------------------------------------------------------
538 * See if the given variable exists.
541 * TRUE if it does, FALSE if it doesn't
546 *-----------------------------------------------------------------------
549 Var_Exists(const char *name, GNode *ctxt)
554 n = VarPossiblyExpand(name, ctxt);
555 v = VarFind(n, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
560 } else if (v->flags & VAR_FROM_ENV) {
567 *-----------------------------------------------------------------------
569 * Return the value of the named variable in the given context
572 * The value if the variable exists, NULL if it doesn't
576 *-----------------------------------------------------------------------
579 Var_Value(const char *name, GNode *ctxt, char **frp)
584 n = VarPossiblyExpand(name, ctxt);
585 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
589 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
591 if (v->flags & VAR_FROM_ENV) {
592 VarDestroy(v, FALSE);
602 *-----------------------------------------------------------------------
604 * Modify each of the words of the passed string using the given
605 * function. Used to implement all modifiers.
608 * A string of all the words modified appropriately.
613 *-----------------------------------------------------------------------
616 VarModify(char *str, VarModifyProc *modProc, void *datum)
618 Buffer *buf; /* Buffer for the new string */
619 Boolean addSpace; /* TRUE if need to add a space to the
620 * buffer before adding the trimmed
622 char **av; /* word list [first word does not count] */
628 av = brk_string(str, &ac, FALSE);
630 for (i = 1; i < ac; i++)
631 addSpace = (*modProc)(av[i], addSpace, buf, datum);
633 Buf_AddByte(buf, '\0');
634 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
635 Buf_Destroy(buf, FALSE);
640 *-----------------------------------------------------------------------
642 * Sort the words in the string.
645 * str String whose words should be sorted
646 * cmp A comparison function to control the ordering
649 * A string containing the words sorted
654 *-----------------------------------------------------------------------
657 VarSortWords(char *str, int (*cmp)(const void *, const void *))
664 av = brk_string(str, &ac, FALSE);
665 qsort(av + 1, ac - 1, sizeof(char *), cmp);
666 for (i = 1; i < ac; i++) {
667 Buf_Append(buf, av[i]);
668 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
670 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
671 Buf_Destroy(buf, FALSE);
676 SortIncreasing(const void *l, const void *r)
679 return (strcmp(*(const char* const*)l, *(const char* const*)r));
683 *-----------------------------------------------------------------------
685 * Pass through the tstr looking for 1) escaped delimiters,
686 * '$'s and backslashes (place the escaped character in
687 * uninterpreted) and 2) unescaped $'s that aren't before
688 * the delimiter (expand the variable substitution unless flags
689 * has VAR_NOSUBST set).
690 * Return the expanded string or NULL if the delimiter was missing
691 * If pattern is specified, handle escaped ampersands, and replace
692 * unescaped ampersands with the lhs of the pattern.
695 * A string of all the words modified appropriately.
696 * If length is specified, return the string length of the buffer
697 * If flags is specified and the last character of the pattern is a
698 * $ set the VAR_MATCH_END bit of flags.
702 *-----------------------------------------------------------------------
705 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
706 size_t *length, VarPattern *pattern)
709 Buffer *buf = Buf_Init(0);
715 #define IS_A_MATCH(cp, delim) \
716 ((cp[0] == '\\') && ((cp[1] == delim) || \
717 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
720 * Skim through until the matching delimiter is found;
721 * pick up variable substitutions on the way. Also allow
722 * backslashes to quote the delimiter, $, and \, but don't
723 * touch other backslashes.
725 for (cp = *tstr; *cp && (*cp != delim); cp++) {
726 if (IS_A_MATCH(cp, delim)) {
727 Buf_AddByte(buf, (Byte)cp[1]);
729 } else if (*cp == '$') {
730 if (cp[1] == delim) {
732 Buf_AddByte(buf, (Byte)*cp);
735 * Unescaped $ at end of pattern => anchor
738 *flags |= VAR_MATCH_END;
740 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
746 * If unescaped dollar sign not before the
747 * delimiter, assume it's a variable
748 * substitution and recurse.
750 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
751 Buf_Append(buf, cp2);
758 if (*cp2 == OPEN_PAREN || *cp2 == OPEN_BRACE) {
760 * Find the end of this variable reference
761 * and suck it in without further ado.
762 * It will be interperated later.
765 int want = (*cp2 == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
768 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
769 if (cp2[-1] != '\\') {
776 Buf_AppendRange(buf, cp, cp2);
779 Buf_AddByte(buf, (Byte)*cp);
783 else if (pattern && *cp == '&')
784 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
786 Buf_AddByte(buf, (Byte)*cp);
789 Buf_AddByte(buf, (Byte)'\0');
797 cp = (char *)Buf_GetAll(buf, length);
798 *length -= 1; /* Don't count the NULL */
799 Buf_Destroy(buf, FALSE);
805 *-----------------------------------------------------------------------
807 * Quote shell meta-characters in the string
815 *-----------------------------------------------------------------------
818 Var_Quote(const char *str)
821 /* This should cover most shells :-( */
822 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
825 buf = Buf_Init(MAKE_BSIZE);
826 for (; *str; str++) {
827 if (strchr(meta, *str) != NULL)
828 Buf_AddByte(buf, (Byte)'\\');
829 Buf_AddByte(buf, (Byte)*str);
831 Buf_AddByte(buf, (Byte)'\0');
832 ret = Buf_GetAll(buf, NULL);
833 Buf_Destroy(buf, FALSE);
838 *-----------------------------------------------------------------------
840 * Print the error caused by a regcomp or regexec call.
846 * An error gets printed.
848 *-----------------------------------------------------------------------
851 VarREError(int err, regex_t *pat, const char *str)
856 errlen = regerror(err, pat, 0, 0);
857 errbuf = emalloc(errlen);
858 regerror(err, pat, errbuf, errlen);
859 Error("%s: %s", str, errbuf);
864 * Make sure this variable is fully expanded.
867 VarExpand(Var *v, GNode *ctxt, Boolean err)
872 if (v->flags & VAR_IN_USE) {
873 Fatal("Variable %s is recursive.", v->name);
877 v->flags |= VAR_IN_USE;
880 * Before doing any modification, we have to make sure the
881 * value has been fully expanded. If it looks like recursion
882 * might be necessary (there's a dollar sign somewhere in the
883 * variable's value) we just call Var_Subst to do any other
884 * substitutions that are necessary. Note that the value
885 * returned by Var_Subst will have been
886 * dynamically-allocated, so it will need freeing when we
889 value = (char *)Buf_GetAll(v->val, (size_t *)NULL);
890 if (strchr(value, '$') == NULL) {
891 result = strdup(value);
895 buf = Var_Subst(NULL, value, ctxt, err);
896 result = Buf_GetAll(buf, NULL);
897 Buf_Destroy(buf, FALSE);
900 v->flags &= ~VAR_IN_USE;
906 * Check if brackets contain a variable name.
909 VarParseLong(char foo[], GNode *ctxt, Boolean err, size_t *lengthPtr,
912 const char *input = foo;
915 Var *v; /* Variable in invocation */
917 size_t vlen; /* length of variable name, after embedded variable
919 Boolean haveModifier; /* TRUE if have modifiers for the variable */
920 char endc; /* Ending character when variable in parens
922 char startc; /* Starting character when variable in parens
924 char *tstr; /* Pointer into str */
925 Boolean dynamic; /* TRUE if the variable is local and we're
926 * expanding it in a non-local context. This
927 * is done to support dynamic sources. The
928 * result is just the invocation, unaltered */
930 /* build up expanded variable name in this buffer */
931 Buffer *buf = Buf_Init(MAKE_BSIZE);
934 * Skip to the end character or a colon, whichever comes first,
935 * replacing embedded variables as we go.
938 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
941 while (*tstr != '\0' && *tstr != endc && *tstr != ':') {
947 rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
948 if (rval == var_Error) {
949 Fatal("Error expanding embedded variable.");
952 Buf_Append(buf, rval);
958 Buf_AddByte(buf, (Byte)*tstr);
965 * If we never did find the end character, return NULL
966 * right now, setting the length to be the distance to
967 * the end of the string, since that's what make does.
970 *lengthPtr = tstr - input;
974 haveModifier = (*tstr == ':');
975 *tstr = '\0'; /* modify input string */
977 vname = Buf_GetAll(buf, (size_t *)NULL); /* REPLACE str */
978 vlen = strlen(vname);
980 v = VarFind(vname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
983 (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
984 (vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))
987 * Check for bogus D and F forms of local variables since we're
988 * in a local context and the name is the right length.
990 if (strchr("!%*<>@", vname[0]) != NULL) {
995 * Well, it's local -- go look for it.
1000 v = VarFind(name, ctxt, 0);
1001 if (v != NULL && !haveModifier) {
1003 * No need for nested expansion or anything, as we're
1004 * the only one who sets these things and we sure don't
1005 * put nested invocations in them...
1007 val = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1009 if (vname[1] == 'D') {
1010 val = VarModify(val, VarHead, (void *)NULL);
1012 val = VarModify(val, VarTail, (void *)NULL);
1015 * Resulting string is dynamically allocated, so
1016 * tell caller to free it.
1019 *lengthPtr = tstr - input + 1;
1021 Buf_Destroy(buf, TRUE);
1028 if (((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) &&
1030 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))))
1033 * If substituting a local variable in a non-local context,
1034 * assume it's for dynamic source stuff. We have to handle
1035 * this specially and return the longhand for the variable
1036 * with the dollar sign escaped so it makes it back to the
1037 * caller. Only four of the local variables are treated
1038 * specially as they are the only four that will be set
1039 * when dynamic sources are expanded.
1041 if (strchr("!%*@", vname[0]) != NULL) {
1046 } else if (((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) &&
1048 (vname[0] == '.') &&
1049 isupper((unsigned char)vname[1]))
1054 if ((strncmp(vname, ".TARGET", len) == 0) ||
1055 (strncmp(vname, ".ARCHIVE", len) == 0) ||
1056 (strncmp(vname, ".PREFIX", len) == 0) ||
1057 (strncmp(vname, ".MEMBER", len) == 0))
1069 * Still need to get to the end of the variable specification,
1070 * so kludge up a Var structure for the modifications
1072 v = VarCreate(vname, NULL, VAR_JUNK);
1076 * No modifiers -- have specification length so we can return
1081 size_t rlen = tstr - input + 1;
1083 result = emalloc(rlen + 1);
1084 strncpy(result, input, rlen);
1085 result[rlen] = '\0';
1091 Buf_Destroy(buf, TRUE);
1095 *lengthPtr = tstr - input + 1;
1098 Buf_Destroy(buf, TRUE);
1099 return (err ? var_Error : varNoError);
1106 Buf_Destroy(buf, TRUE);
1108 rw_str = VarExpand(v, ctxt, err);
1112 * Now we need to apply any modifiers the user wants applied.
1115 * words which match the given <pattern>.
1116 * <pattern> is of the standard file
1118 * :S<d><pat1><d><pat2><d>[g]
1119 * Substitute <pat2> for <pat1> in the value
1120 * :C<d><pat1><d><pat2><d>[g]
1121 * Substitute <pat2> for regex <pat1> in the value
1122 * :H Substitute the head of each word
1123 * :T Substitute the tail of each word
1124 * :E Substitute the extension (minus '.') of
1126 * :R Substitute the root of each word
1127 * (pathname minus the suffix).
1129 * Like :S, but the rhs goes to the end of
1131 * :U Converts variable to upper-case.
1132 * :L Converts variable to lower-case.
1137 * Skip initial colon while putting it back.
1140 while (*tstr != endc) {
1141 char *newStr; /* New value to return */
1142 char termc; /* Character which terminated scan */
1144 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, rw_str));
1155 *cp != '\0' && *cp != ':' && *cp != endc;
1158 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
1167 * Need to compress the \:'s out of the pattern, so
1168 * allocate enough room to hold the uncompressed
1169 * pattern (note that cp started at tstr+1, so
1170 * cp - tstr takes the null byte into account) and
1171 * compress the pattern into the space.
1173 pattern = emalloc(cp - tstr);
1174 for (cp2 = pattern, cp = tstr + 1;
1178 if ((*cp == '\\') &&
1179 (cp[1] == ':' || cp[1] == endc)) {
1188 if (*tstr == 'M' || *tstr == 'm') {
1189 newStr = VarModify(rw_str, VarMatch, pattern);
1191 newStr = VarModify(rw_str, VarNoMatch, pattern);
1202 Buffer *buf; /* Buffer for patterns */
1209 * If pattern begins with '^', it is anchored to the
1210 * start of the word -- skip over it and flag pattern.
1213 pattern.flags |= VAR_MATCH_START;
1220 * Pass through the lhs looking for 1) escaped delimiters,
1221 * '$'s and backslashes (place the escaped character in
1222 * uninterpreted) and 2) unescaped $'s that aren't before
1223 * the delimiter (expand the variable substitution).
1224 * The result is left in the Buffer buf.
1226 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1227 if ((*cp == '\\') &&
1232 Buf_AddByte(buf, (Byte)cp[1]);
1234 } else if (*cp == '$') {
1237 * If unescaped dollar sign not before the
1238 * delimiter, assume it's a variable
1239 * substitution and recurse.
1245 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1246 Buf_Append(buf, cp2);
1253 * Unescaped $ at end of pattern => anchor
1256 pattern.flags |= VAR_MATCH_END;
1259 Buf_AddByte(buf, (Byte)*cp);
1263 Buf_AddByte(buf, (Byte)'\0');
1266 * If lhs didn't end with the delimiter, complain and
1270 Fatal("Unclosed substitution for %s (%c missing)",
1275 * Fetch pattern and destroy buffer, but preserve the data
1276 * in it, since that's our lhs. Note that Buf_GetAll
1277 * will return the actual number of bytes, which includes
1278 * the null byte, so we have to decrement the length by
1281 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1283 Buf_Destroy(buf, FALSE);
1286 * Now comes the replacement string. Three things need to
1287 * be done here: 1) need to compress escaped delimiters and
1288 * ampersands and 2) need to replace unescaped ampersands
1289 * with the l.h.s. (since this isn't regexp, we can do
1290 * it right here) and 3) expand any variable substitutions.
1295 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1296 if ((*cp == '\\') &&
1302 Buf_AddByte(buf, (Byte)cp[1]);
1304 } else if ((*cp == '$') && (cp[1] != del)) {
1309 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1310 Buf_Append(buf, cp2);
1315 } else if (*cp == '&') {
1316 Buf_AddBytes(buf, pattern.leftLen,
1317 (Byte *)pattern.lhs);
1319 Buf_AddByte(buf, (Byte)*cp);
1323 Buf_AddByte(buf, (Byte)'\0');
1326 * If didn't end in delimiter character, complain
1329 Fatal("Unclosed substitution for %s (%c missing)",
1333 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1335 Buf_Destroy(buf, FALSE);
1338 * Check for global substitution. If 'g' after the final
1339 * delimiter, substitution is global and is marked that
1344 pattern.flags |= VAR_SUB_GLOBAL;
1349 * Global substitution of the empty string causes an
1350 * infinite number of matches, unless anchored by '^'
1351 * (start of string) or '$' (end of string). Catch the
1352 * infinite substitution here.
1353 * Note that flags can only contain the 3 bits we're
1354 * interested in so we don't have to mask unrelated
1355 * bits. We can test for equality.
1357 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1358 Fatal("Global substitution of the empty string");
1361 newStr = VarModify(rw_str, VarSubstitute, &pattern);
1363 * Free the two strings.
1372 VarREPattern pattern;
1382 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1383 NULL, NULL)) == NULL) {
1384 /* was: goto cleanup */
1385 *lengthPtr = cp - input + 1;
1389 Fatal("Unclosed substitution for %s (%c missing)",
1394 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1395 delim, NULL, NULL, NULL)) == NULL){
1398 /* was: goto cleanup */
1399 *lengthPtr = cp - input + 1;
1403 Fatal("Unclosed substitution for %s (%c missing)",
1411 pattern.flags |= VAR_SUB_GLOBAL;
1414 pattern.flags |= VAR_SUB_ONE;
1424 error = regcomp(&pattern.re, re, REG_EXTENDED);
1427 *lengthPtr = cp - input + 1;
1428 VarREError(error, &pattern.re, "RE substitution error");
1429 free(pattern.replace);
1433 pattern.nsub = pattern.re.re_nsub + 1;
1434 if (pattern.nsub < 1)
1436 if (pattern.nsub > 10)
1438 pattern.matches = emalloc(pattern.nsub *
1439 sizeof(regmatch_t));
1440 newStr = VarModify(rw_str, VarRESubstitute, &pattern);
1441 regfree(&pattern.re);
1442 free(pattern.replace);
1443 free(pattern.matches);
1447 if (tstr[1] == endc || tstr[1] == ':') {
1449 buf = Buf_Init(MAKE_BSIZE);
1450 for (cp = rw_str; *cp ; cp++)
1451 Buf_AddByte(buf, (Byte)tolower(*cp));
1453 Buf_AddByte(buf, (Byte)'\0');
1454 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1455 Buf_Destroy(buf, FALSE);
1463 if (tstr[1] == endc || tstr[1] == ':') {
1464 newStr = VarSortWords(rw_str, SortIncreasing);
1471 if (tstr[1] == endc || tstr[1] == ':') {
1472 newStr = Var_Quote(rw_str);
1479 if (tstr[1] == endc || tstr[1] == ':') {
1480 newStr = VarModify(rw_str, VarTail, (void *)NULL);
1487 if (tstr[1] == endc || tstr[1] == ':') {
1489 buf = Buf_Init(MAKE_BSIZE);
1490 for (cp = rw_str; *cp ; cp++)
1491 Buf_AddByte(buf, (Byte)toupper(*cp));
1493 Buf_AddByte(buf, (Byte)'\0');
1494 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1495 Buf_Destroy(buf, FALSE);
1503 if (tstr[1] == endc || tstr[1] == ':') {
1504 newStr = VarModify(rw_str, VarHead, (void *)NULL);
1511 if (tstr[1] == endc || tstr[1] == ':') {
1512 newStr = VarModify(rw_str, VarSuffix, (void *)NULL);
1519 if (tstr[1] == endc || tstr[1] == ':') {
1520 newStr = VarModify(rw_str, VarRoot, (void *)NULL);
1528 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1532 buf = Cmd_Exec(rw_str, &error);
1533 newStr = Buf_GetAll(buf, NULL);
1534 Buf_Destroy(buf, FALSE);
1537 Error(error, rw_str);
1548 * This can either be a bogus modifier or a System-V
1549 * substitution command.
1558 * First we make a pass through the string trying
1559 * to verify it is a SYSV-make-style translation:
1560 * it must be: <string1>=<string2>)
1564 while (*cp != '\0' && cnt) {
1567 /* continue looking for endc */
1569 else if (*cp == endc)
1571 else if (*cp == startc)
1576 if (*cp == endc && eqFound) {
1580 * Now we break this sucker into the lhs and
1581 * rhs. We must null terminate them of course.
1586 if ((pattern.lhs = VarGetPattern(ctxt,
1587 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1589 /* was: goto cleanup */
1590 *lengthPtr = cp - input + 1;
1594 Fatal("Unclosed substitution for %s (%c missing)",
1600 if ((pattern.rhs = VarGetPattern(ctxt,
1601 err, &cp, delim, NULL, &pattern.rightLen,
1602 &pattern)) == NULL) {
1603 /* was: goto cleanup */
1604 *lengthPtr = cp - input + 1;
1608 Fatal("Unclosed substitution for %s (%c missing)",
1614 * SYSV modifications happen through the whole
1615 * string. Note the pattern is anchored at the end.
1619 newStr = VarModify(rw_str, VarSYSVMatch, &pattern);
1628 Error("Unknown modifier '%c'\n", *tstr);
1630 *cp != ':' && *cp != endc && *cp != '\0';
1638 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1644 if (rw_str != var_Error) {
1649 if (termc == '\0') {
1650 Error("Unclosed variable specification for %s", v->name);
1651 } else if (termc == ':') {
1658 *lengthPtr = tstr - input + 1;
1660 *lengthPtr = tstr - input + 1;
1664 if (v->flags & VAR_FROM_ENV) {
1665 if (rw_str == (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1667 * Returning the value unmodified, so tell the caller to free
1671 VarDestroy(v, FALSE);
1674 VarDestroy(v, TRUE);
1677 } else if (v->flags & VAR_JUNK) {
1679 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1680 * doesn't try to free a static pointer.
1687 VarDestroy(v, TRUE);
1688 rw_str = emalloc(*lengthPtr + 1);
1689 strncpy(rw_str, input, *lengthPtr);
1690 rw_str[*lengthPtr] = '\0';
1695 VarDestroy(v, TRUE);
1696 return (err ? var_Error : varNoError);
1704 VarParseShort(const char input[], GNode *ctxt, Boolean err, size_t *lengthPtr,
1708 * If it's not bounded by braces of some sort, life is much simpler.
1709 * We just need to check for the first character and return the value
1712 Var *v; /* Variable in invocation */
1718 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1720 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1722 * If substituting a local variable in a non-local
1723 * context, assume it's for dynamic source stuff. We
1724 * have to handle this specially and return the
1725 * longhand for the variable with the dollar sign
1726 * escaped so it makes it back to the caller. Only
1727 * four of the local variables are treated specially
1728 * as they are the only four that will be set when
1729 * dynamic sources are expanded.
1731 /* XXX: It looks like $% and $! are reversed here */
1736 return ("$(.TARGET)");
1738 return ("$(.ARCHIVE)");
1740 return ("$(.PREFIX)");
1742 return ("$(.MEMBER)");
1744 return (err ? var_Error : varNoError);
1749 return (err ? var_Error : varNoError);
1754 result = VarExpand(v, ctxt, err);
1756 if (v->flags & VAR_FROM_ENV) {
1757 VarDestroy(v, TRUE);
1767 *-----------------------------------------------------------------------
1769 * Given the start of a variable invocation, extract the variable
1770 * name and find its value, then modify it according to the
1774 * The (possibly-modified) value of the variable or var_Error if the
1775 * specification is invalid. The length of the specification is
1776 * placed in *lengthPtr (for invalid specifications, this is just
1777 * 2 to skip the '$' and the following letter, or 1 if '$' was the
1778 * last character in the string).
1779 * A Boolean in *freePtr telling whether the returned string should
1780 * be freed by the caller.
1786 * It is assumed that Var_Parse() is called with str[0] == '$'.
1788 *-----------------------------------------------------------------------
1791 Var_Parse(char *foo, GNode *ctxt, Boolean err, size_t *lengthPtr,
1794 const char *input = foo;
1796 if (input[1] == '\0') {
1797 /* Error, there is only a dollar sign in the input string. */
1800 return (err ? var_Error : varNoError);
1802 } else if (input[1] == OPEN_PAREN || input[1] == OPEN_BRACE) {
1803 /* multi letter variable name */
1804 return (VarParseLong(foo, ctxt, err, lengthPtr, freePtr));
1807 /* single letter variable name */
1808 return (VarParseShort(input, ctxt, err, lengthPtr, freePtr));
1813 *-----------------------------------------------------------------------
1815 * Substitute for all variables in the given string in the given context
1816 * If undefErr is TRUE, Parse_Error will be called when an undefined
1817 * variable is encountered.
1820 * The resulting string.
1823 * None. The old string must be freed by the caller
1824 *-----------------------------------------------------------------------
1827 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1829 Boolean errorReported;
1830 Buffer *buf; /* Buffer for forming things */
1833 * Set TRUE if an error has already been reported to prevent a
1834 * plethora of messages when recursing.
1836 errorReported = FALSE;
1840 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1842 * A dollar sign may be escaped either with another dollar sign.
1843 * In such a case, we skip over the escape character and store the
1844 * dollar sign into the buffer directly.
1846 Buf_AddByte(buf, (Byte)str[0]);
1849 } else if (str[0] == '$') {
1850 char *val; /* Value to substitute for a variable */
1851 size_t length; /* Length of the variable invocation */
1852 Boolean doFree; /* Set true if val should be freed */
1854 * Variable invocation.
1859 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1861 const char *p = str + 2;
1864 * Scan up to the end of the variable name.
1866 while (*p != '\0' &&
1868 *p != CLOSE_PAREN &&
1869 *p != CLOSE_BRACE &&
1875 * A variable inside the variable. We cannot expand
1876 * the external variable yet, so we try again with
1880 Buf_AppendRange(buf, str, p);
1886 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1890 * Not the variable we want to expand, scan
1891 * until the next variable
1893 while (*p != '$' && *p != '\0')
1896 Buf_AppendRange(buf, str, p);
1902 * Single letter variable name
1904 if (var[1] == '\0' && var[0] == str[1]) {
1907 Buf_AddBytes(buf, 2, (const Byte *)str);
1918 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1921 * When we come down here, val should either point to the
1922 * value of this variable, suitably modified, or be NULL.
1923 * Length should be the total length of the potential
1924 * variable invocation (from $ to end character...)
1926 if (val == var_Error || val == varNoError) {
1928 * If performing old-time variable substitution, skip over
1929 * the variable and continue with the substitution. Otherwise,
1930 * store the dollar sign and advance str so we continue with
1935 } else if (undefErr) {
1937 * If variable is undefined, complain and skip the
1938 * variable. The complaint will stop us from doing anything
1939 * when the file is parsed.
1941 if (!errorReported) {
1942 Parse_Error(PARSE_FATAL,
1943 "Undefined variable \"%.*s\"",length,str);
1946 errorReported = TRUE;
1948 Buf_AddByte(buf, (Byte)*str);
1953 * We've now got a variable structure to store in. But first,
1954 * advance the string pointer.
1959 * Copy all the characters from the variable value straight
1960 * into the new string.
1962 Buf_Append(buf, val);
1969 * Skip as many characters as possible -- either to the end of
1970 * the string or to the next dollar sign (variable invocation).
1972 const char *cp = str;
1976 } while (str[0] != '$' && str[0] != '\0');
1978 Buf_AppendRange(buf, cp, str);
1986 *-----------------------------------------------------------------------
1988 * Return the tail from each of a list of words. Used to set the
1989 * System V local variables.
1992 * The resulting string.
1997 *-----------------------------------------------------------------------
2000 Var_GetTail(char *file)
2003 return (VarModify(file, VarTail, (void *)NULL));
2007 *-----------------------------------------------------------------------
2009 * Find the leading components of a (list of) filename(s).
2010 * XXX: VarHead does not replace foo by ., as (sun) System V make
2014 * The leading components.
2019 *-----------------------------------------------------------------------
2022 Var_GetHead(char *file)
2025 return (VarModify(file, VarHead, (void *)NULL));
2029 *-----------------------------------------------------------------------
2031 * Initialize the module
2037 * The VAR_CMD and VAR_GLOBAL contexts are created
2038 *-----------------------------------------------------------------------
2044 VAR_GLOBAL = Targ_NewGN("Global");
2045 VAR_CMD = Targ_NewGN("Command");
2048 /****************** PRINT DEBUGGING INFO *****************/
2050 VarPrintVar(void *vp, void *dummy __unused)
2052 Var *v = (Var *) vp;
2054 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
2059 *-----------------------------------------------------------------------
2061 * print all variables in a context
2062 *-----------------------------------------------------------------------
2065 Var_Dump(GNode *ctxt)
2068 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);