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.140 2005/03/12 11:59:03 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 ParseRestModifier(const char input[], const char ptr[], char startc, char endc, Buffer *buf, GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
1548 Boolean dynamic; /* TRUE if the variable is local and we're
1549 * expanding it in a non-local context. This
1550 * is done to support dynamic sources. The
1551 * result is just the invocation, unaltered */
1553 vname = Buf_GetAll(buf, &vlen);
1557 v = VarFind(vname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1559 return (ParseModifier(input, ptr,
1560 startc, endc, dynamic, v,
1561 ctxt, err, lengthPtr, freePtr));
1564 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1565 if (((vlen == 1)) ||
1566 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1568 * If substituting a local variable in a non-local
1569 * context, assume it's for dynamic source stuff. We
1570 * have to handle this specially and return the
1571 * longhand for the variable with the dollar sign
1572 * escaped so it makes it back to the caller. Only
1573 * four of the local variables are treated specially
1574 * as they are the only four that will be set when
1575 * dynamic sources are expanded.
1577 if (strchr("!%*@", vname[0]) != NULL) {
1582 (vname[0] == '.') &&
1583 isupper((unsigned char)vname[1])) {
1584 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1585 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1586 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1587 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1592 * Still need to get to the end of the variable
1593 * specification, so kludge up a Var structure for
1596 v = VarCreate(vname, NULL, VAR_JUNK);
1597 return (ParseModifier(input, ptr,
1598 startc, endc, dynamic, v,
1599 ctxt, err, lengthPtr, freePtr));
1602 * Check for D and F forms of local variables since we're in
1603 * a local context and the name is the right length.
1606 (vname[1] == 'F' || vname[1] == 'D') &&
1607 (strchr("!%*<>@", vname[0]) != NULL)) {
1611 * Well, it's local -- go look for it.
1616 v = VarFind(name, ctxt, 0);
1618 return (ParseModifier(input, ptr,
1619 startc, endc, dynamic, v,
1620 ctxt, err, lengthPtr, freePtr));
1625 * Still need to get to the end of the variable
1626 * specification, so kludge up a Var structure for
1629 v = VarCreate(vname, NULL, VAR_JUNK);
1630 return (ParseModifier(input, ptr,
1631 startc, endc, dynamic, v,
1632 ctxt, err, lengthPtr, freePtr));
1637 ParseRestEnd(const char input[], Buffer *buf, GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
1644 vname = Buf_GetAll(buf, &vlen);
1646 v = VarFind(vname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1648 result = VarExpand(v, ctxt, err);
1650 if (v->flags & VAR_FROM_ENV) {
1651 VarDestroy(v, TRUE);
1658 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1660 * If substituting a local variable in a non-local
1661 * context, assume it's for dynamic source stuff. We
1662 * have to handle this specially and return the
1663 * longhand for the variable with the dollar sign
1664 * escaped so it makes it back to the caller. Only
1665 * four of the local variables are treated specially
1666 * as they are the only four that will be set when
1667 * dynamic sources are expanded.
1669 if (((vlen == 1)) ||
1670 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1671 if (strchr("!%*@", vname[0]) != NULL) {
1672 result = emalloc(*lengthPtr + 1);
1673 strncpy(result, input, *lengthPtr);
1674 result[*lengthPtr] = '\0';
1681 (vname[0] == '.') &&
1682 isupper((unsigned char)vname[1])) {
1683 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1684 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1685 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1686 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1687 result = emalloc(*lengthPtr + 1);
1688 strncpy(result, input, *lengthPtr);
1689 result[*lengthPtr] = '\0';
1697 return (err ? var_Error : varNoError);
1700 * Check for D and F forms of local variables since we're in
1701 * a local context and the name is the right length.
1704 (vname[1] == 'F' || vname[1] == 'D') &&
1705 (strchr("!%*<>@", vname[0]) != NULL)) {
1711 v = VarFind(name, ctxt, 0);
1715 * No need for nested expansion or
1716 * anything, as we're the only one
1717 * who sets these things and we sure
1718 * don't put nested invocations in
1721 val = (char *)Buf_GetAll(v->val, NULL);
1723 if (vname[1] == 'D') {
1724 val = VarModify(val, VarHead, NULL);
1726 val = VarModify(val, VarTail, NULL);
1735 return (err ? var_Error : varNoError);
1740 * Parse a multi letter variable name, and return it's value.
1743 VarParseLong(const char input[], GNode *ctxt, Boolean err,
1744 size_t *consumed, Boolean *freePtr)
1747 char endc; /* Ending character when variable in parens
1749 char startc; /* Starting character when variable in parens
1754 buf = Buf_Init(MAKE_BSIZE);
1757 * Process characters until we reach an end character or a
1758 * colon, replacing embedded variables as we go.
1761 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1764 while (*ptr != endc && *ptr != ':') {
1767 * If we did not find the end character,
1768 * return var_Error right now, setting the
1769 * length to be the distance to the end of
1770 * the string, since that's what make does.
1773 *consumed += ptr - input;
1774 Buf_Destroy(buf, TRUE);
1777 } else if (*ptr == '$') {
1783 rval = Var_Parse(ptr, ctxt, err, &rlen, &rfree);
1784 if (rval == var_Error) {
1785 Fatal("Error expanding embedded variable.");
1787 Buf_Append(buf, rval);
1792 Buf_AddByte(buf, (Byte)*ptr);
1798 result = ParseRestModifier(input - 1, ptr, startc, endc, buf, ctxt, err, consumed, freePtr);
1800 *consumed = ptr - (input - 1) + 1;
1801 result = ParseRestEnd(input - 1, buf, ctxt, err, consumed, freePtr);
1804 Buf_Destroy(buf, TRUE);
1809 * Parse a single letter variable name, and return it's value.
1812 VarParseShort(const char input[], GNode *ctxt, Boolean err,
1813 size_t *consumed, Boolean *freePtr)
1821 /* consume character */
1824 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1828 result = VarExpand(v, ctxt, err);
1830 if (v->flags & VAR_FROM_ENV) {
1831 VarDestroy(v, TRUE);
1839 * If substituting a local variable in a non-local context, assume
1840 * it's for dynamic source stuff. We have to handle this specially
1841 * and return the longhand for the variable with the dollar sign
1842 * escaped so it makes it back to the caller. Only four of the local
1843 * variables are treated specially as they are the only four that
1844 * will be set when dynamic sources are expanded.
1846 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1848 /* XXX: It looks like $% and $! are reversed here */
1852 return (estrdup("$(.TARGET)"));
1855 return (estrdup("$(.ARCHIVE)"));
1858 return (estrdup("$(.PREFIX)"));
1861 return (estrdup("$(.MEMBER)"));
1864 return (err ? var_Error : varNoError);
1869 * Variable name was not found.
1872 return (err ? var_Error : varNoError);
1876 *-----------------------------------------------------------------------
1878 * Given the start of a variable invocation, extract the variable
1879 * name and find its value, then modify it according to the
1883 * The value of the variable or var_Error if the specification
1884 * is invalid. The number of characters in the specification
1885 * is placed in the variable pointed to by consumed. (for
1886 * invalid specifications, this is just 2 to skip the '$' and
1887 * the following letter, or 1 if '$' was the last character
1888 * in the string). A Boolean in *freePtr telling whether the
1889 * returned string should be freed by the caller.
1895 * It is assumed that Var_Parse() is called with input[0] == '$'.
1897 *-----------------------------------------------------------------------
1900 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1901 size_t *consumed, Boolean *freePtr)
1903 /* assert(input[0] == '$'); */
1909 if (input[0] == '\0') {
1910 /* Error, there is only a dollar sign in the input string. */
1912 return (err ? var_Error : varNoError);
1914 } else if (input[0] == OPEN_PAREN || input[0] == OPEN_BRACE) {
1915 /* multi letter variable name */
1916 return (VarParseLong(input, ctxt, err, consumed, freePtr));
1919 /* single letter variable name */
1920 return (VarParseShort(input, ctxt, err, consumed, freePtr));
1925 *-----------------------------------------------------------------------
1927 * Substitute for all variables in the given string in the given context
1928 * If undefErr is TRUE, Parse_Error will be called when an undefined
1929 * variable is encountered.
1932 * The resulting string.
1935 * None. The old string must be freed by the caller
1936 *-----------------------------------------------------------------------
1939 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1941 Boolean errorReported;
1942 Buffer *buf; /* Buffer for forming things */
1945 * Set TRUE if an error has already been reported to prevent a
1946 * plethora of messages when recursing.
1947 * XXXHB this comment sounds wrong.
1949 errorReported = FALSE;
1953 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1955 * A dollar sign may be escaped either with another dollar sign.
1956 * In such a case, we skip over the escape character and store the
1957 * dollar sign into the buffer directly.
1959 Buf_AddByte(buf, (Byte)str[0]);
1962 } else if (str[0] == '$') {
1963 char *val; /* Value to substitute for a variable */
1964 size_t length; /* Length of the variable invocation */
1965 Boolean doFree; /* Set true if val should be freed */
1968 * Variable invocation.
1973 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1975 const char *p = str + 2;
1978 * Scan up to the end of the variable name.
1980 while (*p != '\0' &&
1982 *p != CLOSE_PAREN &&
1983 *p != CLOSE_BRACE &&
1989 * A variable inside the variable. We cannot expand
1990 * the external variable yet, so we try again with
1994 Buf_AppendRange(buf, str, p);
2000 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
2004 * Not the variable we want to expand, scan
2005 * until the next variable
2007 while (*p != '$' && *p != '\0')
2010 Buf_AppendRange(buf, str, p);
2016 * Single letter variable name
2018 if (var[1] == '\0' && var[0] == str[1]) {
2021 Buf_AddBytes(buf, 2, (const Byte *)str);
2033 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
2036 * When we come down here, val should either point to the
2037 * value of this variable, suitably modified, or be NULL.
2038 * Length should be the total length of the potential
2039 * variable invocation (from $ to end character...)
2041 if (val == var_Error || val == varNoError) {
2043 * If performing old-time variable substitution, skip over
2044 * the variable and continue with the substitution. Otherwise,
2045 * store the dollar sign and advance str so we continue with
2050 } else if (undefErr) {
2052 * If variable is undefined, complain and skip the
2053 * variable. The complaint will stop us from doing anything
2054 * when the file is parsed.
2056 if (!errorReported) {
2057 Parse_Error(PARSE_FATAL,
2058 "Undefined variable \"%.*s\"",length,str);
2061 errorReported = TRUE;
2063 Buf_AddByte(buf, (Byte)*str);
2068 * We've now got a variable structure to store in. But first,
2069 * advance the string pointer.
2074 * Copy all the characters from the variable value straight
2075 * into the new string.
2077 Buf_Append(buf, val);
2084 * Skip as many characters as possible -- either to the end of
2085 * the string or to the next dollar sign (variable invocation).
2087 const char *cp = str;
2091 } while (str[0] != '$' && str[0] != '\0');
2093 Buf_AppendRange(buf, cp, str);
2101 *-----------------------------------------------------------------------
2103 * Return the tail from each of a list of words. Used to set the
2104 * System V local variables.
2107 * The resulting string.
2112 *-----------------------------------------------------------------------
2115 Var_GetTail(char *file)
2118 return (VarModify(file, VarTail, (void *)NULL));
2122 *-----------------------------------------------------------------------
2124 * Find the leading components of a (list of) filename(s).
2125 * XXX: VarHead does not replace foo by ., as (sun) System V make
2129 * The leading components.
2134 *-----------------------------------------------------------------------
2137 Var_GetHead(char *file)
2140 return (VarModify(file, VarHead, (void *)NULL));
2144 *-----------------------------------------------------------------------
2146 * Initialize the module
2152 * The VAR_CMD and VAR_GLOBAL contexts are created
2153 *-----------------------------------------------------------------------
2159 VAR_GLOBAL = Targ_NewGN("Global");
2160 VAR_CMD = Targ_NewGN("Command");
2164 *-----------------------------------------------------------------------
2166 * print all variables in a context
2167 *-----------------------------------------------------------------------
2170 Var_Dump(const GNode *ctxt)
2175 LST_FOREACH(ln, &ctxt->context) {
2177 printf("%-16s = %s\n", v->name,
2178 (const char *)Buf_GetAll(v->val, NULL));