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.143 2005/03/12 12:00:31 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)
920 for (cur = mod + 1; *cur != '\0'; cur++) {
921 if (cur[0] == endc) {
923 } else if (cur[0] == ':') {
925 } else if ((cur[0] == '\\') &&
926 (cur[1] == ':' || cur[1] == endc)) {
933 * Compress the \:'s out of the pattern, so allocate enough
934 * room to hold the uncompressed pattern and compress the
935 * pattern into the space. (note that cur started at mod+1
936 * so cur-mod takes the null byte into account)
938 patt = emalloc(cur - mod);
940 for (cur = mod + 1; cur != end; cur++) {
941 if ((cur[0] == '\\') &&
942 (cur[1] == ':' || cur[1] == endc)) {
950 if (*mod == 'M' || *mod == 'm') {
951 newValue = VarModify(value, VarMatch, patt);
953 newValue = VarModify(value, VarNoMatch, patt);
957 *consumed += (end - mod);
960 *consumed += 1; /* include colon as part of modifier */
967 modifier_S(const char mod[], const char value[], Var *v, GNode *ctxt, Boolean err, size_t *consumed)
970 Buffer *buf; /* Buffer for patterns */
978 delim = mod[1]; /* used to find end of pattern */
981 * If pattern begins with '^', it is anchored to the start of the
982 * word -- skip over it and flag pattern.
985 pattern.flags |= VAR_MATCH_START;
992 * Pass through the lhs looking for 1) escaped delimiters, '$'s and
993 * backslashes (place the escaped character in uninterpreted) and 2)
994 * unescaped $'s that aren't before the delimiter (expand the
995 * variable substitution). The result is left in the Buffer buf.
997 while (cur[0] != delim) {
998 if (cur[0] == '\0') {
1000 * LHS didn't end with the delim, complain and exit.
1002 Fatal("Unclosed substitution for %s (%c missing)",
1005 } else if ((cur[0] == '\\') &&
1006 ((cur[1] == delim) ||
1008 (cur[1] == '\\'))) {
1009 cur++; /* skip backslash */
1010 Buf_AddByte(buf, (Byte) cur[0]);
1013 } else if (cur[0] == '$') {
1014 if (cur[1] == delim) {
1016 * Unescaped $ at end of pattern => anchor
1019 pattern.flags |= VAR_MATCH_END;
1023 * If unescaped dollar sign not before the
1024 * delimiter, assume it's a variable
1025 * substitution and recurse.
1032 cp2 = Var_Parse(cur, ctxt, err, &len, &freeIt);
1034 Buf_Append(buf, cp2);
1040 Buf_AddByte(buf, (Byte)cur[0]);
1044 cur++; /* skip over delim */
1047 * Fetch pattern and destroy buffer, but preserve the data in it,
1048 * since that's our lhs.
1050 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1051 Buf_Destroy(buf, FALSE);
1054 * Now comes the replacement string. Three things need to be done
1055 * here: 1) need to compress escaped delimiters and ampersands and 2)
1056 * need to replace unescaped ampersands with the l.h.s. (since this
1057 * isn't regexp, we can do it right here) and 3) expand any variable
1062 while (cur[0] != delim) {
1063 if (cur[0] == '\0') {
1065 * Didn't end with delim character, complain
1067 Fatal("Unclosed substitution for %s (%c missing)",
1070 } else if ((cur[0] == '\\') &&
1071 ((cur[1] == delim) ||
1075 cur++; /* skip backslash */
1076 Buf_AddByte(buf, (Byte) cur[0]);
1079 } else if (cur[0] == '$') {
1080 if (cur[1] == delim) {
1081 Buf_AddByte(buf, (Byte) cur[0]);
1089 cp2 = Var_Parse(cur, ctxt, err, &len, &freeIt);
1091 Buf_Append(buf, cp2);
1096 } else if (cur[0] == '&') {
1097 Buf_AddBytes(buf, pattern.leftLen, (Byte *)pattern.lhs);
1100 Buf_AddByte(buf, (Byte) cur[0]);
1104 cur++; /* skip over delim */
1106 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1107 Buf_Destroy(buf, FALSE);
1110 * Check for global substitution. If 'g' after the final delimiter,
1111 * substitution is global and is marked that way.
1113 if (cur[0] == 'g') {
1114 pattern.flags |= VAR_SUB_GLOBAL;
1119 * Global substitution of the empty string causes an infinite number
1120 * of matches, unless anchored by '^' (start of string) or '$' (end
1121 * of string). Catch the infinite substitution here. Note that flags
1122 * can only contain the 3 bits we're interested in so we don't have
1123 * to mask unrelated bits. We can test for equality.
1125 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1126 Fatal("Global substitution of the empty string");
1128 newValue = VarModify(value, VarSubstitute, &pattern);
1131 * Free the two strings.
1136 *consumed += (cur - mod);
1138 if (cur[0] == ':') {
1139 *consumed += 1; /* include colin as part of modifier */
1146 * Now we need to apply any modifiers the user wants applied.
1149 * words which match the given <pattern>.
1150 * <pattern> is of the standard file
1152 * :S<d><pat1><d><pat2><d>[g]
1153 * Substitute <pat2> for <pat1> in the value
1154 * :C<d><pat1><d><pat2><d>[g]
1155 * Substitute <pat2> for regex <pat1> in the value
1156 * :H Substitute the head of each word
1157 * :T Substitute the tail of each word
1158 * :E Substitute the extension (minus '.') of
1160 * :R Substitute the root of each word
1161 * (pathname minus the suffix).
1163 * Like :S, but the rhs goes to the end of
1165 * :U Converts variable to upper-case.
1166 * :L Converts variable to lower-case.
1168 * XXXHB update this comment or remove it and point to the man page.
1171 ParseModifier(const char input[], const char tstr[],
1172 char startc, char endc, Boolean dynamic, Var *v,
1173 GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
1179 value = 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, value));
1193 readonly = TRUE; /* tstr isn't modified here */
1195 newStr = modifier_M(tstr, value, endc, &consumed);
1200 readonly = TRUE; /* tstr isn't modified here */
1202 newStr = modifier_S(tstr, value, v, ctxt, err, &consumed);
1208 VarREPattern pattern;
1218 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1219 NULL, NULL)) == NULL) {
1220 *lengthPtr = cp - input + 1;
1224 Fatal("Unclosed substitution for %s (%c missing)",
1229 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1230 delim, NULL, NULL, NULL)) == NULL){
1233 /* was: goto cleanup */
1234 *lengthPtr = cp - input + 1;
1238 Fatal("Unclosed substitution for %s (%c missing)",
1246 pattern.flags |= VAR_SUB_GLOBAL;
1249 pattern.flags |= VAR_SUB_ONE;
1259 error = regcomp(&pattern.re, re, REG_EXTENDED);
1262 *lengthPtr = cp - input + 1;
1263 VarREError(error, &pattern.re, "RE substitution error");
1264 free(pattern.replace);
1268 pattern.nsub = pattern.re.re_nsub + 1;
1269 if (pattern.nsub < 1)
1271 if (pattern.nsub > 10)
1273 pattern.matches = emalloc(pattern.nsub *
1274 sizeof(regmatch_t));
1275 newStr = VarModify(value, VarRESubstitute, &pattern);
1276 regfree(&pattern.re);
1277 free(pattern.replace);
1278 free(pattern.matches);
1282 if (tstr[1] == endc || tstr[1] == ':') {
1284 buf = Buf_Init(MAKE_BSIZE);
1285 for (cp = value; *cp ; cp++)
1286 Buf_AddByte(buf, (Byte)tolower(*cp));
1288 Buf_AddByte(buf, (Byte)'\0');
1289 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1290 Buf_Destroy(buf, FALSE);
1298 if (tstr[1] == endc || tstr[1] == ':') {
1299 newStr = VarSortWords(value, SortIncreasing);
1306 if (tstr[1] == endc || tstr[1] == ':') {
1307 newStr = Var_Quote(value);
1314 if (tstr[1] == endc || tstr[1] == ':') {
1315 newStr = VarModify(value, VarTail, (void *)NULL);
1322 if (tstr[1] == endc || tstr[1] == ':') {
1324 buf = Buf_Init(MAKE_BSIZE);
1325 for (cp = value; *cp ; cp++)
1326 Buf_AddByte(buf, (Byte)toupper(*cp));
1328 Buf_AddByte(buf, (Byte)'\0');
1329 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1330 Buf_Destroy(buf, FALSE);
1338 if (tstr[1] == endc || tstr[1] == ':') {
1339 newStr = VarModify(value, VarHead, (void *)NULL);
1346 if (tstr[1] == endc || tstr[1] == ':') {
1347 newStr = VarModify(value, VarSuffix, (void *)NULL);
1354 if (tstr[1] == endc || tstr[1] == ':') {
1355 newStr = VarModify(value, VarRoot, (void *)NULL);
1363 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1367 buf = Cmd_Exec(value, &error);
1368 newStr = Buf_GetAll(buf, NULL);
1369 Buf_Destroy(buf, FALSE);
1372 Error(error, value);
1383 * This can either be a bogus modifier or a System-V
1384 * substitution command.
1393 * First we make a pass through the string trying
1394 * to verify it is a SYSV-make-style translation:
1395 * it must be: <string1>=<string2>)
1399 while (*cp != '\0' && cnt) {
1402 /* continue looking for endc */
1404 else if (*cp == endc)
1406 else if (*cp == startc)
1411 if (*cp == endc && eqFound) {
1415 * Now we break this sucker into the lhs and
1416 * rhs. We must null terminate them of course.
1421 if ((pattern.lhs = VarGetPattern(ctxt,
1422 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1424 /* was: goto cleanup */
1425 *lengthPtr = cp - input + 1;
1429 Fatal("Unclosed substitution for %s (%c missing)",
1435 if ((pattern.rhs = VarGetPattern(ctxt,
1436 err, &cp, delim, NULL, &pattern.rightLen,
1437 &pattern)) == NULL) {
1438 /* was: goto cleanup */
1439 *lengthPtr = cp - input + 1;
1443 Fatal("Unclosed substitution for %s (%c missing)",
1449 * SYSV modifications happen through the whole
1450 * string. Note the pattern is anchored at the end.
1454 newStr = VarModify(value, VarSYSVMatch, &pattern);
1463 Error("Unknown modifier '%c'\n", *tstr);
1465 *cp != ':' && *cp != endc && *cp != '\0';
1474 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1479 if (value != var_Error) {
1485 if (readonly == FALSE) {
1486 if (termc == '\0') {
1487 Error("Unclosed variable specification for %s",
1489 } else if (termc == ':') {
1497 used = tstr - input + 1;
1500 if (v->flags & VAR_FROM_ENV) {
1501 if (value == (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1502 VarDestroy(v, FALSE);
1506 VarDestroy(v, TRUE);
1509 } else if (v->flags & VAR_JUNK) {
1511 * Perform any free'ing needed and set *freePtr to
1512 * FALSE so the caller doesn't try to free a static
1521 VarDestroy(v, TRUE);
1522 result = emalloc(used + 1);
1523 strncpy(result, input, used);
1524 result[used] = '\0';
1529 VarDestroy(v, TRUE);
1532 return (err ? var_Error : varNoError);
1540 ParseRestModifier(const char input[], const char ptr[], char startc, char endc, Buffer *buf, GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
1545 Boolean dynamic; /* TRUE if the variable is local and we're
1546 * expanding it in a non-local context. This
1547 * is done to support dynamic sources. The
1548 * result is just the invocation, unaltered */
1550 vname = Buf_GetAll(buf, &vlen);
1554 v = VarFind(vname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1556 return (ParseModifier(input, ptr,
1557 startc, endc, dynamic, v,
1558 ctxt, err, lengthPtr, freePtr));
1561 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1563 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1565 * If substituting a local variable in a non-local
1566 * context, assume it's for dynamic source stuff. We
1567 * have to handle this specially and return the
1568 * longhand for the variable with the dollar sign
1569 * escaped so it makes it back to the caller. Only
1570 * four of the local variables are treated specially
1571 * as they are the only four that will be set when
1572 * dynamic sources are expanded.
1574 if (strchr("!%*@", vname[0]) != NULL) {
1579 (vname[0] == '.') &&
1580 isupper((unsigned char)vname[1])) {
1581 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1582 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1583 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1584 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1589 * Still need to get to the end of the variable
1590 * specification, so kludge up a Var structure for
1593 v = VarCreate(vname, NULL, VAR_JUNK);
1594 return (ParseModifier(input, ptr,
1595 startc, endc, dynamic, v,
1596 ctxt, err, lengthPtr, freePtr));
1599 * Check for D and F forms of local variables since we're in
1600 * a local context and the name is the right length.
1603 (vname[1] == 'F' || vname[1] == 'D') &&
1604 (strchr("!%*<>@", vname[0]) != NULL)) {
1608 * Well, it's local -- go look for it.
1613 v = VarFind(name, ctxt, 0);
1615 return (ParseModifier(input, ptr,
1616 startc, endc, dynamic, v,
1617 ctxt, err, lengthPtr, freePtr));
1622 * Still need to get to the end of the variable
1623 * specification, so kludge up a Var structure for
1626 v = VarCreate(vname, NULL, VAR_JUNK);
1627 return (ParseModifier(input, ptr,
1628 startc, endc, dynamic, v,
1629 ctxt, err, lengthPtr, freePtr));
1634 ParseRestEnd(const char input[], Buffer *buf,
1635 GNode *ctxt, Boolean err, size_t *consumed, Boolean *freePtr)
1642 vname = Buf_GetAll(buf, &vlen);
1644 v = VarFind(vname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1646 value = VarExpand(v, ctxt, err);
1648 if (v->flags & VAR_FROM_ENV) {
1649 VarDestroy(v, TRUE);
1656 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1658 * If substituting a local variable in a non-local
1659 * context, assume it's for dynamic source stuff. We
1660 * have to handle this specially and return the
1661 * longhand for the variable with the dollar sign
1662 * escaped so it makes it back to the caller. Only
1663 * four of the local variables are treated specially
1664 * as they are the only four that will be set when
1665 * dynamic sources are expanded.
1667 if (((vlen == 1)) ||
1668 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1669 if (strchr("!%*@", vname[0]) != NULL) {
1670 value = emalloc(*consumed + 1);
1671 strncpy(value, input, *consumed);
1672 value[*consumed] = '\0';
1679 (vname[0] == '.') &&
1680 isupper((unsigned char)vname[1])) {
1681 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1682 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1683 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1684 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1685 value = emalloc(*consumed + 1);
1686 strncpy(value, input, *consumed);
1687 value[*consumed] = '\0';
1695 return (err ? var_Error : varNoError);
1698 * Check for D and F forms of local variables since we're in
1699 * a local context and the name is the right length.
1702 (vname[1] == 'F' || vname[1] == 'D') &&
1703 (strchr("!%*<>@", vname[0]) != NULL)) {
1709 v = VarFind(name, ctxt, 0);
1713 * No need for nested expansion or
1714 * anything, as we're the only one
1715 * who sets these things and we sure
1716 * don't put nested invocations in
1719 val = (char *)Buf_GetAll(v->val, NULL);
1721 if (vname[1] == 'D') {
1722 val = VarModify(val, VarHead, NULL);
1724 val = VarModify(val, VarTail, NULL);
1733 return (err ? var_Error : varNoError);
1738 * Parse a multi letter variable name, and return it's value.
1741 VarParseLong(const char input[], GNode *ctxt, Boolean err,
1742 size_t *consumed, Boolean *freePtr)
1750 buf = Buf_Init(MAKE_BSIZE);
1753 * Process characters until we reach an end character or a
1754 * colon, replacing embedded variables as we go.
1757 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1759 *consumed += 1; /* consume opening paren or brace */
1763 while (*ptr != endc) {
1766 * If we did not find the end character,
1767 * return var_Error right now, setting the
1768 * length to be the distance to the end of
1769 * the string, since that's what make does.
1771 Buf_Destroy(buf, TRUE);
1775 } else if (*ptr == ':') {
1776 result = ParseRestModifier(input - 2, ptr,
1778 ctxt, err, consumed, freePtr);
1779 Buf_Destroy(buf, TRUE);
1782 } else if (*ptr == '$') {
1788 rval = Var_Parse(ptr, ctxt, err, &rlen, &rfree);
1789 if (rval == var_Error) {
1790 Fatal("Error expanding embedded variable.");
1792 Buf_Append(buf, rval);
1799 Buf_AddByte(buf, (Byte)*ptr);
1805 *consumed += 1; /* consume closing paren or brace */
1807 result = ParseRestEnd(input - 2, buf, ctxt, err, consumed, freePtr);
1809 Buf_Destroy(buf, TRUE);
1814 * Parse a single letter variable name, and return it's value.
1817 VarParseShort(const char input[], GNode *ctxt, Boolean err,
1818 size_t *consumed, Boolean *freeResult)
1824 vname[0] = input[0];
1827 *consumed += 1; /* consume single letter */
1829 v = VarFind(vname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1831 value = VarExpand(v, ctxt, err);
1833 if (v->flags & VAR_FROM_ENV) {
1834 VarDestroy(v, TRUE);
1842 * If substituting a local variable in a non-local context, assume
1843 * it's for dynamic source stuff. We have to handle this specially
1844 * and return the longhand for the variable with the dollar sign
1845 * escaped so it makes it back to the caller. Only four of the local
1846 * variables are treated specially as they are the only four that
1847 * will be set when dynamic sources are expanded.
1849 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1851 /* XXX: It looks like $% and $! are reversed here */
1855 return (estrdup("$(.TARGET)"));
1858 return (estrdup("$(.ARCHIVE)"));
1861 return (estrdup("$(.PREFIX)"));
1864 return (estrdup("$(.MEMBER)"));
1866 *freeResult = FALSE;
1867 return (err ? var_Error : varNoError);
1872 * Variable name was not found.
1874 *freeResult = FALSE;
1875 return (err ? var_Error : varNoError);
1879 *-----------------------------------------------------------------------
1881 * Given the start of a variable invocation, extract the variable
1882 * name and find its value, then modify it according to the
1886 * The value of the variable or var_Error if the specification
1887 * is invalid. The number of characters in the specification
1888 * is placed in the variable pointed to by consumed. (for
1889 * invalid specifications, this is just 2 to skip the '$' and
1890 * the following letter, or 1 if '$' was the last character
1891 * in the string). A Boolean in *freeResult telling whether the
1892 * returned string should be freed by the caller.
1898 * It is assumed that Var_Parse() is called with input[0] == '$'.
1900 *-----------------------------------------------------------------------
1903 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1904 size_t *consumed, Boolean *freeResult)
1906 /* assert(input[0] == '$'); */
1908 *consumed += 1; /* consume '$' */
1911 if (input[0] == '\0') {
1912 /* Error, there is only a dollar sign in the input string. */
1913 *freeResult = FALSE;
1914 return (err ? var_Error : varNoError);
1916 } else if (input[0] == OPEN_PAREN || input[0] == OPEN_BRACE) {
1917 /* multi letter variable name */
1918 return (VarParseLong(input, ctxt, err, consumed, freeResult));
1921 /* single letter variable name */
1922 return (VarParseShort(input, ctxt, err, consumed, freeResult));
1927 *-----------------------------------------------------------------------
1929 * Substitute for all variables in the given string in the given context
1930 * If undefErr is TRUE, Parse_Error will be called when an undefined
1931 * variable is encountered.
1934 * The resulting string.
1937 * None. The old string must be freed by the caller
1938 *-----------------------------------------------------------------------
1941 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1943 Boolean errorReported;
1944 Buffer *buf; /* Buffer for forming things */
1947 * Set TRUE if an error has already been reported to prevent a
1948 * plethora of messages when recursing.
1949 * XXXHB this comment sounds wrong.
1951 errorReported = FALSE;
1955 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1957 * A dollar sign may be escaped either with another dollar sign.
1958 * In such a case, we skip over the escape character and store the
1959 * dollar sign into the buffer directly.
1961 Buf_AddByte(buf, (Byte)str[0]);
1964 } else if (str[0] == '$') {
1965 char *val; /* Value to substitute for a variable */
1966 size_t length; /* Length of the variable invocation */
1967 Boolean doFree; /* Set true if val should be freed */
1970 * Variable invocation.
1975 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1977 const char *p = str + 2;
1980 * Scan up to the end of the variable name.
1982 while (*p != '\0' &&
1984 *p != CLOSE_PAREN &&
1985 *p != CLOSE_BRACE &&
1991 * A variable inside the variable. We cannot expand
1992 * the external variable yet, so we try again with
1996 Buf_AppendRange(buf, str, p);
2002 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
2006 * Not the variable we want to expand, scan
2007 * until the next variable
2009 while (*p != '$' && *p != '\0')
2012 Buf_AppendRange(buf, str, p);
2018 * Single letter variable name
2020 if (var[1] == '\0' && var[0] == str[1]) {
2023 Buf_AddBytes(buf, 2, (const Byte *)str);
2035 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
2038 * When we come down here, val should either point to the
2039 * value of this variable, suitably modified, or be NULL.
2040 * Length should be the total length of the potential
2041 * variable invocation (from $ to end character...)
2043 if (val == var_Error || val == varNoError) {
2045 * If performing old-time variable substitution, skip over
2046 * the variable and continue with the substitution. Otherwise,
2047 * store the dollar sign and advance str so we continue with
2052 } else if (undefErr) {
2054 * If variable is undefined, complain and skip the
2055 * variable. The complaint will stop us from doing anything
2056 * when the file is parsed.
2058 if (!errorReported) {
2059 Parse_Error(PARSE_FATAL,
2060 "Undefined variable \"%.*s\"",length,str);
2063 errorReported = TRUE;
2065 Buf_AddByte(buf, (Byte)*str);
2070 * We've now got a variable structure to store in. But first,
2071 * advance the string pointer.
2076 * Copy all the characters from the variable value straight
2077 * into the new string.
2079 Buf_Append(buf, val);
2086 * Skip as many characters as possible -- either to the end of
2087 * the string or to the next dollar sign (variable invocation).
2089 const char *cp = str;
2093 } while (str[0] != '$' && str[0] != '\0');
2095 Buf_AppendRange(buf, cp, str);
2103 *-----------------------------------------------------------------------
2105 * Return the tail from each of a list of words. Used to set the
2106 * System V local variables.
2109 * The resulting string.
2114 *-----------------------------------------------------------------------
2117 Var_GetTail(char *file)
2120 return (VarModify(file, VarTail, (void *)NULL));
2124 *-----------------------------------------------------------------------
2126 * Find the leading components of a (list of) filename(s).
2127 * XXX: VarHead does not replace foo by ., as (sun) System V make
2131 * The leading components.
2136 *-----------------------------------------------------------------------
2139 Var_GetHead(char *file)
2142 return (VarModify(file, VarHead, (void *)NULL));
2146 *-----------------------------------------------------------------------
2148 * Initialize the module
2154 * The VAR_CMD and VAR_GLOBAL contexts are created
2155 *-----------------------------------------------------------------------
2161 VAR_GLOBAL = Targ_NewGN("Global");
2162 VAR_CMD = Targ_NewGN("Command");
2166 *-----------------------------------------------------------------------
2168 * print all variables in a context
2169 *-----------------------------------------------------------------------
2172 Var_Dump(const GNode *ctxt)
2177 LST_FOREACH(ln, &ctxt->context) {
2179 printf("%-16s = %s\n", v->name,
2180 (const char *)Buf_GetAll(v->val, NULL));