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.139 2005/03/12 11:58:21 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.
103 * This is a harmless return value for Var_Parse that can be used by Var_Subst
104 * to determine if there was an error in parsing -- easier than returning
105 * a flag, as things outside this module don't give a hoot.
107 char var_Error[] = "";
110 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
111 * set false. Why not just use a constant? Well, gcc likes to condense
112 * identical string instances...
114 static char varNoError[] = "";
117 * Internally, variables are contained in four different contexts.
118 * 1) the environment. They may not be changed. If an environment
119 * variable is appended-to, the result is placed in the global
121 * 2) the global context. Variables set in the Makefile are located in
122 * the global context. It is the penultimate context searched when
124 * 3) the command-line context. All variables set on the command line
125 * are placed in this context. They are UNALTERABLE once placed here.
126 * 4) the local context. Each target has associated with it a context
127 * list. On this list are located the structures describing such
128 * local variables as $(@) and $(*)
129 * The four contexts are searched in the reverse order from which they are
132 GNode *VAR_GLOBAL; /* variables from the makefile */
133 GNode *VAR_CMD; /* variables defined on the command-line */
135 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
136 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
137 #define FIND_ENV 0x4 /* look in the environment also */
139 #define OPEN_PAREN '('
140 #define CLOSE_PAREN ')'
141 #define OPEN_BRACE '{'
142 #define CLOSE_BRACE '}'
145 * Create a Var object.
147 * @param name Name of variable.
148 * @param value Value of variable.
149 * @param flags Flags set on variable.
152 VarCreate(const char name[], const char value[], int flags)
156 v = emalloc(sizeof(Var));
157 v->name = estrdup(name);
158 v->val = Buf_Init(0);
162 Buf_Append(v->val, value);
168 * Destroy a Var object.
170 * @param v Object to destroy.
171 * @param f true if internal buffer in Buffer object is to be
175 VarDestroy(Var *v, Boolean f)
178 Buf_Destroy(v->val, f);
184 *-----------------------------------------------------------------------
186 * See if the given variable matches the named one. Called from
187 * Lst_Find when searching for a variable of a given name.
190 * 0 if they match. non-zero otherwise.
194 *-----------------------------------------------------------------------
197 VarCmp(const void *v, const void *name)
200 return (strcmp(name, ((const Var *)v)->name));
204 *-----------------------------------------------------------------------
205 * VarPossiblyExpand --
206 * Expand a variable name's embedded variables in the given context.
209 * The contents of name, possibly expanded.
210 *-----------------------------------------------------------------------
213 VarPossiblyExpand(const char *name, GNode *ctxt)
220 * XXX make a temporary copy of the name because Var_Subst insists
221 * on writing into the string.
224 if (strchr(name, '$') != NULL) {
225 buf = Var_Subst(NULL, tmp, ctxt, 0);
226 str = Buf_GetAll(buf, NULL);
227 Buf_Destroy(buf, FALSE);
237 *-----------------------------------------------------------------------
239 * Find the given variable in the given context and any other contexts
243 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
244 * FIND_CMD set means to look in the VAR_CMD context too
245 * FIND_ENV set means to look in the environment
248 * A pointer to the structure describing the desired variable or
249 * NULL if the variable does not exist.
253 *-----------------------------------------------------------------------
256 VarFind(const char *name, GNode *ctxt, int flags)
258 Boolean localCheckEnvFirst;
263 * If the variable name begins with a '.', it could very well be one of
264 * the local ones. We check the name against all the local variables
265 * and substitute the short version in for 'name' if it matches one of
268 if (name[0] == '.') {
271 if (!strcmp(name, ".ALLSRC"))
273 if (!strcmp(name, ".ARCHIVE"))
277 if (!strcmp(name, ".IMPSRC"))
281 if (!strcmp(name, ".MEMBER"))
285 if (!strcmp(name, ".OODATE"))
289 if (!strcmp(name, ".PREFIX"))
293 if (!strcmp(name, ".TARGET"))
302 * Note whether this is one of the specific variables we were told
303 * through the -E flag to use environment-variable-override for.
305 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
306 localCheckEnvFirst = TRUE;
308 localCheckEnvFirst = FALSE;
312 * First look for the variable in the given context. If it's not there,
313 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
314 * in that order, depending on the FIND_* flags in 'flags'
316 var = Lst_Find(&ctxt->context, name, VarCmp);
319 return (Lst_Datum(var));
322 /* not there - try command line context */
323 if ((flags & FIND_CMD) && (ctxt != VAR_CMD)) {
324 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
326 return (Lst_Datum(var));
329 /* not there - try global context, but only if not -e/-E */
330 if ((flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
331 !checkEnvFirst && !localCheckEnvFirst) {
332 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
334 return (Lst_Datum(var));
337 if (!(flags & FIND_ENV))
338 /* we were not told to look into the environment */
341 /* look in the environment */
342 if ((env = getenv(name)) != NULL) {
343 /* craft this variable from the environment value */
344 return (VarCreate(name, env, VAR_FROM_ENV));
347 /* deferred check for the environment (in case of -e/-E) */
348 if ((checkEnvFirst || localCheckEnvFirst) &&
349 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL)) {
350 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
352 return (Lst_Datum(var));
358 *-----------------------------------------------------------------------
360 * Add a new variable of name name and value val to the given context.
366 * The new variable is placed at the front of the given context
367 * The name and val arguments are duplicated so they may
369 *-----------------------------------------------------------------------
372 VarAdd(const char *name, const char *val, GNode *ctxt)
375 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
376 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
380 *-----------------------------------------------------------------------
382 * Remove a variable from a context.
388 * The Var structure is removed and freed.
390 *-----------------------------------------------------------------------
393 Var_Delete(const char *name, GNode *ctxt)
397 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
398 ln = Lst_Find(&ctxt->context, name, VarCmp);
400 VarDestroy(Lst_Datum(ln), TRUE);
401 Lst_Remove(&ctxt->context, ln);
406 *-----------------------------------------------------------------------
408 * Set the variable name to the value val in the given context.
414 * If the variable doesn't yet exist, a new record is created for it.
415 * Else the old value is freed and the new one stuck in its place
418 * The variable is searched for only in its context before being
419 * created in that context. I.e. if the context is VAR_GLOBAL,
420 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
421 * VAR_CMD->context is searched. This is done to avoid the literally
422 * thousands of unnecessary strcmp's that used to be done to
423 * set, say, $(@) or $(<).
424 *-----------------------------------------------------------------------
427 Var_Set(const char *name, const char *val, GNode *ctxt)
433 * We only look for a variable in the given context since anything set
434 * here will override anything in a lower context, so there's not much
435 * point in searching them all just to save a bit of memory...
437 n = VarPossiblyExpand(name, ctxt);
438 v = VarFind(n, ctxt, 0);
440 VarAdd(n, val, ctxt);
443 Buf_Append(v->val, val);
445 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
448 * Any variables given on the command line are automatically exported
449 * to the environment (as per POSIX standard)
451 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
459 * Set the VAR_TO_ENV flag on a variable
462 Var_SetEnv(const char *name, GNode *ctxt)
466 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
468 if ((v->flags & VAR_TO_ENV) == 0) {
469 v->flags |= VAR_TO_ENV;
470 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
473 Error("Cannot set environment flag on non-existant variable %s", name);
478 *-----------------------------------------------------------------------
480 * The variable of the given name has the given value appended to it in
487 * If the variable doesn't exist, it is created. Else the strings
488 * are concatenated (with a space in between).
491 * Only if the variable is being sought in the global context is the
492 * environment searched.
493 * XXX: Knows its calling circumstances in that if called with ctxt
494 * an actual target, it will only search that context since only
495 * a local variable could be being appended to. This is actually
496 * a big win and must be tolerated.
497 *-----------------------------------------------------------------------
500 Var_Append(const char *name, const char *val, GNode *ctxt)
505 n = VarPossiblyExpand(name, ctxt);
506 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
509 VarAdd(n, val, ctxt);
511 Buf_AddByte(v->val, (Byte)' ');
512 Buf_Append(v->val, val);
514 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
515 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
517 if (v->flags & VAR_FROM_ENV) {
519 * If the original variable came from the environment, we
520 * have to install it in the global context (we could place
521 * it in the environment, but then we should provide a way to
522 * export other variables...)
524 v->flags &= ~VAR_FROM_ENV;
525 Lst_AtFront(&ctxt->context, v);
532 *-----------------------------------------------------------------------
534 * See if the given variable exists.
537 * TRUE if it does, FALSE if it doesn't
542 *-----------------------------------------------------------------------
545 Var_Exists(const char *name, GNode *ctxt)
550 n = VarPossiblyExpand(name, ctxt);
551 v = VarFind(n, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
556 } else if (v->flags & VAR_FROM_ENV) {
563 *-----------------------------------------------------------------------
565 * Return the value of the named variable in the given context
568 * The value if the variable exists, NULL if it doesn't
572 *-----------------------------------------------------------------------
575 Var_Value(const char *name, GNode *ctxt, char **frp)
580 n = VarPossiblyExpand(name, ctxt);
581 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
585 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
587 if (v->flags & VAR_FROM_ENV) {
588 VarDestroy(v, FALSE);
598 *-----------------------------------------------------------------------
600 * Modify each of the words of the passed string using the given
601 * function. Used to implement all modifiers.
604 * A string of all the words modified appropriately.
607 * Uses brk_string() so it invalidates any previous call to
610 *-----------------------------------------------------------------------
613 VarModify(const char *str, VarModifyProc *modProc, void *datum)
615 char **av; /* word list [first word does not count] */
617 Buffer *buf; /* Buffer for the new string */
618 Boolean addSpace; /* TRUE if need to add a space to the buffer
619 * before adding the trimmed word */
623 av = brk_string(str, &ac, FALSE);
628 for (i = 1; i < ac; i++)
629 addSpace = (*modProc)(av[i], addSpace, buf, datum);
631 result = (char *)Buf_GetAll(buf, (size_t *)NULL);
632 Buf_Destroy(buf, FALSE);
637 *-----------------------------------------------------------------------
639 * Sort the words in the string.
642 * str String whose words should be sorted
643 * cmp A comparison function to control the ordering
646 * A string containing the words sorted
649 * Uses brk_string() so it invalidates any previous call to
652 *-----------------------------------------------------------------------
655 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
663 av = brk_string(str, &ac, FALSE);
664 qsort(av + 1, ac - 1, sizeof(char *), cmp);
667 for (i = 1; i < ac; i++) {
668 Buf_Append(buf, av[i]);
669 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
672 result = (char *)Buf_GetAll(buf, (size_t *)NULL);
673 Buf_Destroy(buf, FALSE);
678 SortIncreasing(const void *l, const void *r)
681 return (strcmp(*(const char* const*)l, *(const char* const*)r));
685 *-----------------------------------------------------------------------
687 * Pass through the tstr looking for 1) escaped delimiters,
688 * '$'s and backslashes (place the escaped character in
689 * uninterpreted) and 2) unescaped $'s that aren't before
690 * the delimiter (expand the variable substitution unless flags
691 * has VAR_NOSUBST set).
692 * Return the expanded string or NULL if the delimiter was missing
693 * If pattern is specified, handle escaped ampersands, and replace
694 * unescaped ampersands with the lhs of the pattern.
697 * A string of all the words modified appropriately.
698 * If length is specified, return the string length of the buffer
699 * If flags is specified and the last character of the pattern is a
700 * $ set the VAR_MATCH_END bit of flags.
704 *-----------------------------------------------------------------------
707 VarGetPattern(GNode *ctxt, int err, const char **tstr, int delim, int *flags,
708 size_t *length, VarPattern *pattern)
711 Buffer *buf = Buf_Init(0);
717 #define IS_A_MATCH(cp, delim) \
718 ((cp[0] == '\\') && ((cp[1] == delim) || \
719 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
722 * Skim through until the matching delimiter is found;
723 * pick up variable substitutions on the way. Also allow
724 * backslashes to quote the delimiter, $, and \, but don't
725 * touch other backslashes.
727 for (cp = *tstr; *cp && (*cp != delim); cp++) {
728 if (IS_A_MATCH(cp, delim)) {
729 Buf_AddByte(buf, (Byte)cp[1]);
731 } else if (*cp == '$') {
732 if (cp[1] == delim) {
734 Buf_AddByte(buf, (Byte)*cp);
737 * Unescaped $ at end of pattern => anchor
740 *flags |= VAR_MATCH_END;
742 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
748 * If unescaped dollar sign not before the
749 * delimiter, assume it's a variable
750 * substitution and recurse.
753 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
754 Buf_Append(buf, cp2);
759 const char *cp2 = &cp[1];
761 if (*cp2 == OPEN_PAREN || *cp2 == OPEN_BRACE) {
763 * Find the end of this variable reference
764 * and suck it in without further ado.
765 * It will be interperated later.
768 int want = (*cp2 == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
771 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
772 if (cp2[-1] != '\\') {
779 Buf_AppendRange(buf, cp, cp2);
782 Buf_AddByte(buf, (Byte)*cp);
786 else if (pattern && *cp == '&')
787 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
789 Buf_AddByte(buf, (Byte)*cp);
792 Buf_AddByte(buf, (Byte)'\0');
801 result = (char *)Buf_GetAll(buf, length);
802 *length -= 1; /* Don't count the NULL */
803 Buf_Destroy(buf, FALSE);
809 *-----------------------------------------------------------------------
811 * Quote shell meta-characters in the string
819 *-----------------------------------------------------------------------
822 Var_Quote(const char *str)
825 /* This should cover most shells :-( */
826 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
829 buf = Buf_Init(MAKE_BSIZE);
830 for (; *str; str++) {
831 if (strchr(meta, *str) != NULL)
832 Buf_AddByte(buf, (Byte)'\\');
833 Buf_AddByte(buf, (Byte)*str);
835 Buf_AddByte(buf, (Byte)'\0');
836 ret = Buf_GetAll(buf, NULL);
837 Buf_Destroy(buf, FALSE);
842 *-----------------------------------------------------------------------
844 * Print the error caused by a regcomp or regexec call.
850 * An error gets printed.
852 *-----------------------------------------------------------------------
855 VarREError(int err, regex_t *pat, const char *str)
860 errlen = regerror(err, pat, 0, 0);
861 errbuf = emalloc(errlen);
862 regerror(err, pat, errbuf, errlen);
863 Error("%s: %s", str, errbuf);
868 * Make sure this variable is fully expanded.
871 VarExpand(Var *v, GNode *ctxt, Boolean err)
876 if (v->flags & VAR_IN_USE) {
877 Fatal("Variable %s is recursive.", v->name);
881 v->flags |= VAR_IN_USE;
884 * Before doing any modification, we have to make sure the
885 * value has been fully expanded. If it looks like recursion
886 * might be necessary (there's a dollar sign somewhere in the
887 * variable's value) we just call Var_Subst to do any other
888 * substitutions that are necessary. Note that the value
889 * returned by Var_Subst will have been
890 * dynamically-allocated, so it will need freeing when we
893 value = (char *)Buf_GetAll(v->val, (size_t *)NULL);
894 if (strchr(value, '$') == NULL) {
895 result = strdup(value);
899 buf = Var_Subst(NULL, value, ctxt, err);
900 result = Buf_GetAll(buf, NULL);
901 Buf_Destroy(buf, FALSE);
904 v->flags &= ~VAR_IN_USE;
910 * Select only those words that match the modifier.
913 modifier_M(const char mod[], const char value[], char endc, size_t *consumed)
921 for (cur = mod + 1; *cur != '\0'; cur++) {
922 if (cur[0] == endc) {
924 } else if (cur[0] == ':') {
926 } else if ((cur[0] == '\\') &&
927 (cur[1] == ':' || cur[1] == endc)) {
934 * Compress the \:'s out of the pattern, so allocate enough
935 * room to hold the uncompressed pattern and compress the
936 * pattern into the space. (note that cur started at mod+1
937 * so cur-mod takes the null byte into account)
939 patt = emalloc(cur - mod);
941 for (cur = mod + 1; cur != end; cur++) {
942 if ((cur[0] == '\\') &&
943 (cur[1] == ':' || cur[1] == endc)) {
951 if (*mod == 'M' || *mod == 'm') {
952 newValue = VarModify(value, VarMatch, patt);
954 newValue = VarModify(value, VarNoMatch, patt);
958 *consumed += (end - mod);
961 *consumed += 1; /* include colon as part of modifier */
968 modifier_S(const char mod[], const char value[], Var *v, GNode *ctxt, Boolean err, size_t *consumed)
971 Buffer *buf; /* Buffer for patterns */
979 delim = mod[1]; /* used to find end of pattern */
982 * If pattern begins with '^', it is anchored to the start of the
983 * word -- skip over it and flag pattern.
986 pattern.flags |= VAR_MATCH_START;
993 * Pass through the lhs looking for 1) escaped delimiters, '$'s and
994 * backslashes (place the escaped character in uninterpreted) and 2)
995 * unescaped $'s that aren't before the delimiter (expand the
996 * variable substitution). The result is left in the Buffer buf.
998 while (cur[0] != delim) {
999 if (cur[0] == '\0') {
1001 * LHS didn't end with the delim, complain and exit.
1003 Fatal("Unclosed substitution for %s (%c missing)",
1006 } else if ((cur[0] == '\\') &&
1007 ((cur[1] == delim) ||
1009 (cur[1] == '\\'))) {
1010 cur++; /* skip backslash */
1011 Buf_AddByte(buf, (Byte) cur[0]);
1014 } else if (cur[0] == '$') {
1015 if (cur[1] == delim) {
1017 * Unescaped $ at end of pattern => anchor
1020 pattern.flags |= VAR_MATCH_END;
1024 * If unescaped dollar sign not before the
1025 * delimiter, assume it's a variable
1026 * substitution and recurse.
1033 cp2 = Var_Parse(cur, ctxt, err, &len, &freeIt);
1035 Buf_Append(buf, cp2);
1041 Buf_AddByte(buf, (Byte)cur[0]);
1045 cur++; /* skip over delim */
1048 * Fetch pattern and destroy buffer, but preserve the data in it,
1049 * since that's our lhs.
1051 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1052 Buf_Destroy(buf, FALSE);
1055 * Now comes the replacement string. Three things need to be done
1056 * here: 1) need to compress escaped delimiters and ampersands and 2)
1057 * need to replace unescaped ampersands with the l.h.s. (since this
1058 * isn't regexp, we can do it right here) and 3) expand any variable
1063 while (cur[0] != delim) {
1064 if (cur[0] == '\0') {
1066 * Didn't end with delim character, complain
1068 Fatal("Unclosed substitution for %s (%c missing)",
1071 } else if ((cur[0] == '\\') &&
1072 ((cur[1] == delim) ||
1076 cur++; /* skip backslash */
1077 Buf_AddByte(buf, (Byte) cur[0]);
1080 } else if (cur[0] == '$') {
1081 if (cur[1] == delim) {
1082 Buf_AddByte(buf, (Byte) cur[0]);
1090 cp2 = Var_Parse(cur, ctxt, err, &len, &freeIt);
1092 Buf_Append(buf, cp2);
1097 } else if (cur[0] == '&') {
1098 Buf_AddBytes(buf, pattern.leftLen, (Byte *)pattern.lhs);
1101 Buf_AddByte(buf, (Byte) cur[0]);
1105 cur++; /* skip over delim */
1107 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1108 Buf_Destroy(buf, FALSE);
1111 * Check for global substitution. If 'g' after the final delimiter,
1112 * substitution is global and is marked that way.
1114 if (cur[0] == 'g') {
1115 pattern.flags |= VAR_SUB_GLOBAL;
1120 * Global substitution of the empty string causes an infinite number
1121 * of matches, unless anchored by '^' (start of string) or '$' (end
1122 * of string). Catch the infinite substitution here. Note that flags
1123 * can only contain the 3 bits we're interested in so we don't have
1124 * to mask unrelated bits. We can test for equality.
1126 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1127 Fatal("Global substitution of the empty string");
1129 newValue = VarModify(value, VarSubstitute, &pattern);
1132 * Free the two strings.
1137 *consumed += (cur - mod);
1139 if (cur[0] == ':') {
1140 *consumed += 1; /* include colin as part of modifier */
1147 * Now we need to apply any modifiers the user wants applied.
1150 * words which match the given <pattern>.
1151 * <pattern> is of the standard file
1153 * :S<d><pat1><d><pat2><d>[g]
1154 * Substitute <pat2> for <pat1> in the value
1155 * :C<d><pat1><d><pat2><d>[g]
1156 * Substitute <pat2> for regex <pat1> in the value
1157 * :H Substitute the head of each word
1158 * :T Substitute the tail of each word
1159 * :E Substitute the extension (minus '.') of
1161 * :R Substitute the root of each word
1162 * (pathname minus the suffix).
1164 * Like :S, but the rhs goes to the end of
1166 * :U Converts variable to upper-case.
1167 * :L Converts variable to lower-case.
1169 * XXXHB update this comment or remove it and point to the man page.
1172 ParseModifier(const char input[], const char tstr[],
1173 char startc, char endc, Boolean dynamic, Var *v,
1174 GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
1179 rw_str = VarExpand(v, ctxt, err);
1183 while (*tstr != endc) {
1184 char *newStr; /* New value to return */
1185 char termc; /* Character which terminated scan */
1186 Boolean readonly = FALSE;
1187 size_t consumed = 0;
1189 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, rw_str));
1193 readonly = TRUE; /* tstr isn't modified here */
1195 newStr = modifier_M(tstr, rw_str, endc, &consumed);
1200 readonly = TRUE; /* tstr isn't modified here */
1202 newStr = modifier_S(tstr, rw_str, v, ctxt, err, &consumed);
1208 VarREPattern pattern;
1218 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1219 NULL, NULL)) == NULL) {
1220 /* was: goto cleanup */
1221 *lengthPtr = cp - input + 1;
1225 Fatal("Unclosed substitution for %s (%c missing)",
1230 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1231 delim, NULL, NULL, NULL)) == NULL){
1234 /* was: goto cleanup */
1235 *lengthPtr = cp - input + 1;
1239 Fatal("Unclosed substitution for %s (%c missing)",
1247 pattern.flags |= VAR_SUB_GLOBAL;
1250 pattern.flags |= VAR_SUB_ONE;
1260 error = regcomp(&pattern.re, re, REG_EXTENDED);
1263 *lengthPtr = cp - input + 1;
1264 VarREError(error, &pattern.re, "RE substitution error");
1265 free(pattern.replace);
1269 pattern.nsub = pattern.re.re_nsub + 1;
1270 if (pattern.nsub < 1)
1272 if (pattern.nsub > 10)
1274 pattern.matches = emalloc(pattern.nsub *
1275 sizeof(regmatch_t));
1276 newStr = VarModify(rw_str, VarRESubstitute, &pattern);
1277 regfree(&pattern.re);
1278 free(pattern.replace);
1279 free(pattern.matches);
1283 if (tstr[1] == endc || tstr[1] == ':') {
1285 buf = Buf_Init(MAKE_BSIZE);
1286 for (cp = rw_str; *cp ; cp++)
1287 Buf_AddByte(buf, (Byte)tolower(*cp));
1289 Buf_AddByte(buf, (Byte)'\0');
1290 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1291 Buf_Destroy(buf, FALSE);
1299 if (tstr[1] == endc || tstr[1] == ':') {
1300 newStr = VarSortWords(rw_str, SortIncreasing);
1307 if (tstr[1] == endc || tstr[1] == ':') {
1308 newStr = Var_Quote(rw_str);
1315 if (tstr[1] == endc || tstr[1] == ':') {
1316 newStr = VarModify(rw_str, VarTail, (void *)NULL);
1323 if (tstr[1] == endc || tstr[1] == ':') {
1325 buf = Buf_Init(MAKE_BSIZE);
1326 for (cp = rw_str; *cp ; cp++)
1327 Buf_AddByte(buf, (Byte)toupper(*cp));
1329 Buf_AddByte(buf, (Byte)'\0');
1330 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1331 Buf_Destroy(buf, FALSE);
1339 if (tstr[1] == endc || tstr[1] == ':') {
1340 newStr = VarModify(rw_str, VarHead, (void *)NULL);
1347 if (tstr[1] == endc || tstr[1] == ':') {
1348 newStr = VarModify(rw_str, VarSuffix, (void *)NULL);
1355 if (tstr[1] == endc || tstr[1] == ':') {
1356 newStr = VarModify(rw_str, VarRoot, (void *)NULL);
1364 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1368 buf = Cmd_Exec(rw_str, &error);
1369 newStr = Buf_GetAll(buf, NULL);
1370 Buf_Destroy(buf, FALSE);
1373 Error(error, rw_str);
1384 * This can either be a bogus modifier or a System-V
1385 * substitution command.
1394 * First we make a pass through the string trying
1395 * to verify it is a SYSV-make-style translation:
1396 * it must be: <string1>=<string2>)
1400 while (*cp != '\0' && cnt) {
1403 /* continue looking for endc */
1405 else if (*cp == endc)
1407 else if (*cp == startc)
1412 if (*cp == endc && eqFound) {
1416 * Now we break this sucker into the lhs and
1417 * rhs. We must null terminate them of course.
1422 if ((pattern.lhs = VarGetPattern(ctxt,
1423 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1425 /* was: goto cleanup */
1426 *lengthPtr = cp - input + 1;
1430 Fatal("Unclosed substitution for %s (%c missing)",
1436 if ((pattern.rhs = VarGetPattern(ctxt,
1437 err, &cp, delim, NULL, &pattern.rightLen,
1438 &pattern)) == NULL) {
1439 /* was: goto cleanup */
1440 *lengthPtr = cp - input + 1;
1444 Fatal("Unclosed substitution for %s (%c missing)",
1450 * SYSV modifications happen through the whole
1451 * string. Note the pattern is anchored at the end.
1455 newStr = VarModify(rw_str, VarSYSVMatch, &pattern);
1464 Error("Unknown modifier '%c'\n", *tstr);
1466 *cp != ':' && *cp != endc && *cp != '\0';
1475 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1480 if (rw_str != var_Error) {
1486 if (readonly == FALSE) {
1487 if (termc == '\0') {
1488 Error("Unclosed variable specification for %s",
1490 } else if (termc == ':') {
1498 if (v->flags & VAR_FROM_ENV) {
1499 if (rw_str == (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1501 * Returning the value unmodified, so tell the caller to free
1505 *lengthPtr = tstr - input + 1;
1506 VarDestroy(v, FALSE);
1509 *lengthPtr = tstr - input + 1;
1510 VarDestroy(v, TRUE);
1513 } else if (v->flags & VAR_JUNK) {
1515 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1516 * doesn't try to free a static pointer.
1523 *lengthPtr = tstr - input + 1;
1524 VarDestroy(v, TRUE);
1525 rw_str = emalloc(*lengthPtr + 1);
1526 strncpy(rw_str, input, *lengthPtr);
1527 rw_str[*lengthPtr] = '\0';
1532 *lengthPtr = tstr - input + 1;
1533 VarDestroy(v, TRUE);
1534 return (err ? var_Error : varNoError);
1537 *lengthPtr = tstr - input + 1;
1543 ParseRest(const char input[], const char ptr[], char startc, char endc, Buffer *buf, GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
1545 const char *const tstr = ptr;
1546 size_t consumed = tstr - (input - 1) + 1;
1551 Boolean haveModifier;
1552 Boolean dynamic; /* TRUE if the variable is local and we're
1553 * expanding it in a non-local context. This
1554 * is done to support dynamic sources. The
1555 * result is just the invocation, unaltered */
1557 vname = Buf_GetAll(buf, &vlen);
1560 haveModifier = (*tstr == ':');
1563 v = VarFind(vname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1566 return (ParseModifier(input, tstr,
1567 startc, endc, dynamic, v,
1568 ctxt, err, lengthPtr, freePtr));
1572 result = VarExpand(v, ctxt, err);
1574 if (v->flags & VAR_FROM_ENV) {
1575 VarDestroy(v, TRUE);
1579 *lengthPtr = consumed;
1584 if ((ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL)) {
1586 * Check for D and F forms of local variables since we're in
1587 * a local context and the name is the right length.
1590 (vname[1] == 'F' || vname[1] == 'D') &&
1591 (strchr("!%*<>@", vname[0]) != NULL)) {
1596 * Well, it's local -- go look for it.
1601 v = VarFind(name, ctxt, 0);
1604 return (ParseModifier(input, tstr,
1605 startc, endc, dynamic, v,
1606 ctxt, err, lengthPtr, freePtr));
1609 * No need for nested expansion or
1610 * anything, as we're the only one
1611 * who sets these things and we sure
1612 * don't put nested invocations in
1615 val = (char *)Buf_GetAll(v->val, (size_t *) NULL);
1617 if (vname[1] == 'D') {
1618 val = VarModify(val, VarHead, (void *)NULL);
1620 val = VarModify(val, VarTail, (void *)NULL);
1623 * Resulting string is dynamically
1624 * allocated, so tell caller to free
1628 *lengthPtr = consumed;
1634 if (((vlen == 1)) ||
1635 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1637 * If substituting a local variable in a non-local
1638 * context, assume it's for dynamic source stuff. We
1639 * have to handle this specially and return the
1640 * longhand for the variable with the dollar sign
1641 * escaped so it makes it back to the caller. Only
1642 * four of the local variables are treated specially
1643 * as they are the only four that will be set when
1644 * dynamic sources are expanded.
1646 if (strchr("!%*@", vname[0]) != NULL) {
1651 (vname[0] == '.') &&
1652 isupper((unsigned char)vname[1])) {
1653 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1654 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1655 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1656 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1664 * Still need to get to the end of the variable
1665 * specification, so kludge up a Var structure for
1668 v = VarCreate(vname, NULL, VAR_JUNK);
1670 return (ParseModifier(input, tstr,
1671 startc, endc, dynamic, v,
1672 ctxt, err, lengthPtr, freePtr));
1675 * No modifiers -- have specification length so we
1681 result = emalloc(consumed + 1);
1682 strncpy(result, input, consumed);
1683 result[consumed] = '\0';
1686 *lengthPtr = consumed;
1691 *lengthPtr = consumed;
1693 return (err ? var_Error : varNoError);
1699 * Parse a multi letter variable name, and return it's value.
1702 VarParseLong(const char input[], GNode *ctxt, Boolean err,
1703 size_t *consumed, Boolean *freePtr)
1706 char endc; /* Ending character when variable in parens
1708 char startc; /* Starting character when variable in parens
1713 buf = Buf_Init(MAKE_BSIZE);
1716 * Process characters until we reach an end character or a
1717 * colon, replacing embedded variables as we go.
1720 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1723 while (*ptr != endc && *ptr != ':') {
1726 * If we did not find the end character,
1727 * return var_Error right now, setting the
1728 * length to be the distance to the end of
1729 * the string, since that's what make does.
1732 *consumed += ptr - input;
1733 Buf_Destroy(buf, TRUE);
1736 } else if (*ptr == '$') {
1742 rval = Var_Parse(ptr, ctxt, err, &rlen, &rfree);
1743 if (rval == var_Error) {
1744 Fatal("Error expanding embedded variable.");
1746 Buf_Append(buf, rval);
1751 Buf_AddByte(buf, (Byte)*ptr);
1756 result = ParseRest(input, ptr, startc, endc, buf, ctxt, err, consumed, freePtr);
1758 Buf_Destroy(buf, TRUE);
1763 * Parse a single letter variable name, and return it's value.
1766 VarParseShort(const char input[], GNode *ctxt, Boolean err,
1767 size_t *consumed, Boolean *freePtr)
1775 /* consume character */
1778 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1782 result = VarExpand(v, ctxt, err);
1784 if (v->flags & VAR_FROM_ENV) {
1785 VarDestroy(v, TRUE);
1793 * If substituting a local variable in a non-local context, assume
1794 * it's for dynamic source stuff. We have to handle this specially
1795 * and return the longhand for the variable with the dollar sign
1796 * escaped so it makes it back to the caller. Only four of the local
1797 * variables are treated specially as they are the only four that
1798 * will be set when dynamic sources are expanded.
1800 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1802 /* XXX: It looks like $% and $! are reversed here */
1806 return (estrdup("$(.TARGET)"));
1809 return (estrdup("$(.ARCHIVE)"));
1812 return (estrdup("$(.PREFIX)"));
1815 return (estrdup("$(.MEMBER)"));
1818 return (err ? var_Error : varNoError);
1823 * Variable name was not found.
1826 return (err ? var_Error : varNoError);
1830 *-----------------------------------------------------------------------
1832 * Given the start of a variable invocation, extract the variable
1833 * name and find its value, then modify it according to the
1837 * The value of the variable or var_Error if the specification
1838 * is invalid. The number of characters in the specification
1839 * is placed in the variable pointed to by consumed. (for
1840 * invalid specifications, this is just 2 to skip the '$' and
1841 * the following letter, or 1 if '$' was the last character
1842 * in the string). A Boolean in *freePtr telling whether the
1843 * returned string should be freed by the caller.
1849 * It is assumed that Var_Parse() is called with input[0] == '$'.
1851 *-----------------------------------------------------------------------
1854 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1855 size_t *consumed, Boolean *freePtr)
1857 /* assert(input[0] == '$'); */
1863 if (input[0] == '\0') {
1864 /* Error, there is only a dollar sign in the input string. */
1866 return (err ? var_Error : varNoError);
1868 } else if (input[0] == OPEN_PAREN || input[0] == OPEN_BRACE) {
1869 /* multi letter variable name */
1870 return (VarParseLong(input, ctxt, err, consumed, freePtr));
1873 /* single letter variable name */
1874 return (VarParseShort(input, ctxt, err, consumed, freePtr));
1879 *-----------------------------------------------------------------------
1881 * Substitute for all variables in the given string in the given context
1882 * If undefErr is TRUE, Parse_Error will be called when an undefined
1883 * variable is encountered.
1886 * The resulting string.
1889 * None. The old string must be freed by the caller
1890 *-----------------------------------------------------------------------
1893 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1895 Boolean errorReported;
1896 Buffer *buf; /* Buffer for forming things */
1899 * Set TRUE if an error has already been reported to prevent a
1900 * plethora of messages when recursing.
1901 * XXXHB this comment sounds wrong.
1903 errorReported = FALSE;
1907 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1909 * A dollar sign may be escaped either with another dollar sign.
1910 * In such a case, we skip over the escape character and store the
1911 * dollar sign into the buffer directly.
1913 Buf_AddByte(buf, (Byte)str[0]);
1916 } else if (str[0] == '$') {
1917 char *val; /* Value to substitute for a variable */
1918 size_t length; /* Length of the variable invocation */
1919 Boolean doFree; /* Set true if val should be freed */
1922 * Variable invocation.
1927 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1929 const char *p = str + 2;
1932 * Scan up to the end of the variable name.
1934 while (*p != '\0' &&
1936 *p != CLOSE_PAREN &&
1937 *p != CLOSE_BRACE &&
1943 * A variable inside the variable. We cannot expand
1944 * the external variable yet, so we try again with
1948 Buf_AppendRange(buf, str, p);
1954 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1958 * Not the variable we want to expand, scan
1959 * until the next variable
1961 while (*p != '$' && *p != '\0')
1964 Buf_AppendRange(buf, str, p);
1970 * Single letter variable name
1972 if (var[1] == '\0' && var[0] == str[1]) {
1975 Buf_AddBytes(buf, 2, (const Byte *)str);
1987 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1990 * When we come down here, val should either point to the
1991 * value of this variable, suitably modified, or be NULL.
1992 * Length should be the total length of the potential
1993 * variable invocation (from $ to end character...)
1995 if (val == var_Error || val == varNoError) {
1997 * If performing old-time variable substitution, skip over
1998 * the variable and continue with the substitution. Otherwise,
1999 * store the dollar sign and advance str so we continue with
2004 } else if (undefErr) {
2006 * If variable is undefined, complain and skip the
2007 * variable. The complaint will stop us from doing anything
2008 * when the file is parsed.
2010 if (!errorReported) {
2011 Parse_Error(PARSE_FATAL,
2012 "Undefined variable \"%.*s\"",length,str);
2015 errorReported = TRUE;
2017 Buf_AddByte(buf, (Byte)*str);
2022 * We've now got a variable structure to store in. But first,
2023 * advance the string pointer.
2028 * Copy all the characters from the variable value straight
2029 * into the new string.
2031 Buf_Append(buf, val);
2038 * Skip as many characters as possible -- either to the end of
2039 * the string or to the next dollar sign (variable invocation).
2041 const char *cp = str;
2045 } while (str[0] != '$' && str[0] != '\0');
2047 Buf_AppendRange(buf, cp, str);
2055 *-----------------------------------------------------------------------
2057 * Return the tail from each of a list of words. Used to set the
2058 * System V local variables.
2061 * The resulting string.
2066 *-----------------------------------------------------------------------
2069 Var_GetTail(char *file)
2072 return (VarModify(file, VarTail, (void *)NULL));
2076 *-----------------------------------------------------------------------
2078 * Find the leading components of a (list of) filename(s).
2079 * XXX: VarHead does not replace foo by ., as (sun) System V make
2083 * The leading components.
2088 *-----------------------------------------------------------------------
2091 Var_GetHead(char *file)
2094 return (VarModify(file, VarHead, (void *)NULL));
2098 *-----------------------------------------------------------------------
2100 * Initialize the module
2106 * The VAR_CMD and VAR_GLOBAL contexts are created
2107 *-----------------------------------------------------------------------
2113 VAR_GLOBAL = Targ_NewGN("Global");
2114 VAR_CMD = Targ_NewGN("Command");
2118 *-----------------------------------------------------------------------
2120 * print all variables in a context
2121 *-----------------------------------------------------------------------
2124 Var_Dump(const GNode *ctxt)
2129 LST_FOREACH(ln, &ctxt->context) {
2131 printf("%-16s = %s\n", v->name,
2132 (const char *)Buf_GetAll(v->val, NULL));