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.132 2005/03/04 23:50:28 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 '}'
144 static char *VarGetPattern(GNode *, int, char **, int, int *, size_t *,
146 static int VarPrintVar(void *, void *);
149 * Create a Var object.
151 * @param name Name of variable.
152 * @param value Value of variable.
153 * @param flags Flags set on variable.
156 VarCreate(const char name[], const char value[], int flags)
160 v = emalloc(sizeof(Var));
161 v->name = estrdup(name);
162 v->val = Buf_Init(0);
166 Buf_Append(v->val, value);
172 * Destroy a Var object.
174 * @param v Object to destroy.
175 * @param f true if internal buffer in Buffer object is to be
179 VarDestroy(Var *v, Boolean f)
182 Buf_Destroy(v->val, f);
188 *-----------------------------------------------------------------------
190 * See if the given variable matches the named one. Called from
191 * Lst_Find when searching for a variable of a given name.
194 * 0 if they match. non-zero otherwise.
198 *-----------------------------------------------------------------------
201 VarCmp(const void *v, const void *name)
204 return (strcmp(name, ((const Var *)v)->name));
208 *-----------------------------------------------------------------------
209 * VarPossiblyExpand --
210 * Expand a variable name's embedded variables in the given context.
213 * The contents of name, possibly expanded.
214 *-----------------------------------------------------------------------
217 VarPossiblyExpand(const char *name, GNode *ctxt)
224 * XXX make a temporary copy of the name because Var_Subst insists
225 * on writing into the string.
228 if (strchr(name, '$') != NULL) {
229 buf = Var_Subst(NULL, tmp, ctxt, 0);
230 str = Buf_GetAll(buf, NULL);
231 Buf_Destroy(buf, FALSE);
241 *-----------------------------------------------------------------------
243 * Find the given variable in the given context and any other contexts
247 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
248 * FIND_CMD set means to look in the VAR_CMD context too
249 * FIND_ENV set means to look in the environment
252 * A pointer to the structure describing the desired variable or
253 * NULL if the variable does not exist.
257 *-----------------------------------------------------------------------
260 VarFind(const char *name, GNode *ctxt, int flags)
262 Boolean localCheckEnvFirst;
267 * If the variable name begins with a '.', it could very well be one of
268 * the local ones. We check the name against all the local variables
269 * and substitute the short version in for 'name' if it matches one of
272 if (name[0] == '.') {
275 if (!strcmp(name, ".ALLSRC"))
277 if (!strcmp(name, ".ARCHIVE"))
281 if (!strcmp(name, ".IMPSRC"))
285 if (!strcmp(name, ".MEMBER"))
289 if (!strcmp(name, ".OODATE"))
293 if (!strcmp(name, ".PREFIX"))
297 if (!strcmp(name, ".TARGET"))
306 * Note whether this is one of the specific variables we were told
307 * through the -E flag to use environment-variable-override for.
309 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
310 localCheckEnvFirst = TRUE;
312 localCheckEnvFirst = FALSE;
316 * First look for the variable in the given context. If it's not there,
317 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
318 * in that order, depending on the FIND_* flags in 'flags'
320 var = Lst_Find(&ctxt->context, name, VarCmp);
323 return (Lst_Datum(var));
326 /* not there - try command line context */
327 if ((flags & FIND_CMD) && (ctxt != VAR_CMD)) {
328 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
330 return (Lst_Datum(var));
333 /* not there - try global context, but only if not -e/-E */
334 if ((flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
335 !checkEnvFirst && !localCheckEnvFirst) {
336 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
338 return (Lst_Datum(var));
341 if (!(flags & FIND_ENV))
342 /* we were not told to look into the environment */
345 /* look in the environment */
346 if ((env = getenv(name)) != NULL) {
347 /* craft this variable from the environment value */
348 return (VarCreate(name, env, VAR_FROM_ENV));
351 /* deferred check for the environment (in case of -e/-E) */
352 if ((checkEnvFirst || localCheckEnvFirst) &&
353 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL)) {
354 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
356 return (Lst_Datum(var));
362 *-----------------------------------------------------------------------
364 * Add a new variable of name name and value val to the given context.
370 * The new variable is placed at the front of the given context
371 * The name and val arguments are duplicated so they may
373 *-----------------------------------------------------------------------
376 VarAdd(const char *name, const char *val, GNode *ctxt)
379 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
381 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
385 *-----------------------------------------------------------------------
387 * Remove a variable from a context.
393 * The Var structure is removed and freed.
395 *-----------------------------------------------------------------------
398 Var_Delete(const char *name, GNode *ctxt)
402 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
403 ln = Lst_Find(&ctxt->context, name, VarCmp);
405 VarDestroy(Lst_Datum(ln), TRUE);
406 Lst_Remove(&ctxt->context, ln);
411 *-----------------------------------------------------------------------
413 * Set the variable name to the value val in the given context.
419 * If the variable doesn't yet exist, a new record is created for it.
420 * Else the old value is freed and the new one stuck in its place
423 * The variable is searched for only in its context before being
424 * created in that context. I.e. if the context is VAR_GLOBAL,
425 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
426 * VAR_CMD->context is searched. This is done to avoid the literally
427 * thousands of unnecessary strcmp's that used to be done to
428 * set, say, $(@) or $(<).
429 *-----------------------------------------------------------------------
432 Var_Set(const char *name, const char *val, GNode *ctxt)
438 * We only look for a variable in the given context since anything set
439 * here will override anything in a lower context, so there's not much
440 * point in searching them all just to save a bit of memory...
442 n = VarPossiblyExpand(name, ctxt);
443 v = VarFind(n, ctxt, 0);
445 VarAdd(n, val, ctxt);
448 Buf_Append(v->val, val);
450 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
453 * Any variables given on the command line are automatically exported
454 * to the environment (as per POSIX standard)
456 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
464 * Set the VAR_TO_ENV flag on a variable
467 Var_SetEnv(const char *name, GNode *ctxt)
471 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
473 if ((v->flags & VAR_TO_ENV) == 0) {
474 v->flags |= VAR_TO_ENV;
475 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
478 Error("Cannot set environment flag on non-existant variable %s", name);
483 *-----------------------------------------------------------------------
485 * The variable of the given name has the given value appended to it in
492 * If the variable doesn't exist, it is created. Else the strings
493 * are concatenated (with a space in between).
496 * Only if the variable is being sought in the global context is the
497 * environment searched.
498 * XXX: Knows its calling circumstances in that if called with ctxt
499 * an actual target, it will only search that context since only
500 * a local variable could be being appended to. This is actually
501 * a big win and must be tolerated.
502 *-----------------------------------------------------------------------
505 Var_Append(const char *name, const char *val, GNode *ctxt)
510 n = VarPossiblyExpand(name, ctxt);
511 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
514 VarAdd(n, val, ctxt);
516 Buf_AddByte(v->val, (Byte)' ');
517 Buf_Append(v->val, val);
519 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
520 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
522 if (v->flags & VAR_FROM_ENV) {
524 * If the original variable came from the environment, we
525 * have to install it in the global context (we could place
526 * it in the environment, but then we should provide a way to
527 * export other variables...)
529 v->flags &= ~VAR_FROM_ENV;
530 Lst_AtFront(&ctxt->context, v);
537 *-----------------------------------------------------------------------
539 * See if the given variable exists.
542 * TRUE if it does, FALSE if it doesn't
547 *-----------------------------------------------------------------------
550 Var_Exists(const char *name, GNode *ctxt)
555 n = VarPossiblyExpand(name, ctxt);
556 v = VarFind(n, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
561 } else if (v->flags & VAR_FROM_ENV) {
568 *-----------------------------------------------------------------------
570 * Return the value of the named variable in the given context
573 * The value if the variable exists, NULL if it doesn't
577 *-----------------------------------------------------------------------
580 Var_Value(const char *name, GNode *ctxt, char **frp)
585 n = VarPossiblyExpand(name, ctxt);
586 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
590 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
592 if (v->flags & VAR_FROM_ENV) {
593 VarDestroy(v, FALSE);
603 *-----------------------------------------------------------------------
605 * Modify each of the words of the passed string using the given
606 * function. Used to implement all modifiers.
609 * A string of all the words modified appropriately.
612 * Uses brk_string() so it invalidates any previous call to
615 *-----------------------------------------------------------------------
618 VarModify(const char *str, VarModifyProc *modProc, void *datum)
620 char **av; /* word list [first word does not count] */
622 Buffer *buf; /* Buffer for the new string */
623 Boolean addSpace; /* TRUE if need to add a space to the buffer
624 * before adding the trimmed word */
628 av = brk_string(str, &ac, FALSE);
633 for (i = 1; i < ac; i++)
634 addSpace = (*modProc) (av[i], addSpace, buf, datum);
636 result = (char *)Buf_GetAll(buf, (size_t *) NULL);
637 Buf_Destroy(buf, FALSE);
643 *-----------------------------------------------------------------------
645 * Sort the words in the string.
648 * str String whose words should be sorted
649 * cmp A comparison function to control the ordering
652 * A string containing the words sorted
655 * Uses brk_string() so it invalidates any previous call to
658 *-----------------------------------------------------------------------
661 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
669 av = brk_string(str, &ac, FALSE);
670 qsort(av + 1, ac - 1, sizeof(char *), cmp);
673 for (i = 1; i < ac; i++) {
674 Buf_Append(buf, av[i]);
675 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
678 result = (char *)Buf_GetAll(buf, (size_t *)NULL);
679 Buf_Destroy(buf, FALSE);
684 SortIncreasing(const void *l, const void *r)
687 return (strcmp(*(const char* const*)l, *(const char* const*)r));
691 *-----------------------------------------------------------------------
693 * Pass through the tstr looking for 1) escaped delimiters,
694 * '$'s and backslashes (place the escaped character in
695 * uninterpreted) and 2) unescaped $'s that aren't before
696 * the delimiter (expand the variable substitution unless flags
697 * has VAR_NOSUBST set).
698 * Return the expanded string or NULL if the delimiter was missing
699 * If pattern is specified, handle escaped ampersands, and replace
700 * unescaped ampersands with the lhs of the pattern.
703 * A string of all the words modified appropriately.
704 * If length is specified, return the string length of the buffer
705 * If flags is specified and the last character of the pattern is a
706 * $ set the VAR_MATCH_END bit of flags.
710 *-----------------------------------------------------------------------
713 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
714 size_t *length, VarPattern *pattern)
717 Buffer *buf = Buf_Init(0);
723 #define IS_A_MATCH(cp, delim) \
724 ((cp[0] == '\\') && ((cp[1] == delim) || \
725 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
728 * Skim through until the matching delimiter is found;
729 * pick up variable substitutions on the way. Also allow
730 * backslashes to quote the delimiter, $, and \, but don't
731 * touch other backslashes.
733 for (cp = *tstr; *cp && (*cp != delim); cp++) {
734 if (IS_A_MATCH(cp, delim)) {
735 Buf_AddByte(buf, (Byte)cp[1]);
737 } else if (*cp == '$') {
738 if (cp[1] == delim) {
740 Buf_AddByte(buf, (Byte)*cp);
743 * Unescaped $ at end of pattern => anchor
746 *flags |= VAR_MATCH_END;
748 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
754 * If unescaped dollar sign not before the
755 * delimiter, assume it's a variable
756 * substitution and recurse.
759 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
760 Buf_Append(buf, cp2);
767 if (*cp2 == OPEN_PAREN || *cp2 == OPEN_BRACE) {
769 * Find the end of this variable reference
770 * and suck it in without further ado.
771 * It will be interperated later.
774 int want = (*cp2 == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
777 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
778 if (cp2[-1] != '\\') {
785 Buf_AppendRange(buf, cp, cp2);
788 Buf_AddByte(buf, (Byte)*cp);
792 else if (pattern && *cp == '&')
793 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
795 Buf_AddByte(buf, (Byte)*cp);
798 Buf_AddByte(buf, (Byte)'\0');
806 cp = (char *)Buf_GetAll(buf, length);
807 *length -= 1; /* Don't count the NULL */
808 Buf_Destroy(buf, FALSE);
814 *-----------------------------------------------------------------------
816 * Quote shell meta-characters in the string
824 *-----------------------------------------------------------------------
827 Var_Quote(const char *str)
830 /* This should cover most shells :-( */
831 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
834 buf = Buf_Init(MAKE_BSIZE);
835 for (; *str; str++) {
836 if (strchr(meta, *str) != NULL)
837 Buf_AddByte(buf, (Byte)'\\');
838 Buf_AddByte(buf, (Byte)*str);
840 Buf_AddByte(buf, (Byte)'\0');
841 ret = Buf_GetAll(buf, NULL);
842 Buf_Destroy(buf, FALSE);
847 *-----------------------------------------------------------------------
849 * Print the error caused by a regcomp or regexec call.
855 * An error gets printed.
857 *-----------------------------------------------------------------------
860 VarREError(int err, regex_t *pat, const char *str)
865 errlen = regerror(err, pat, 0, 0);
866 errbuf = emalloc(errlen);
867 regerror(err, pat, errbuf, errlen);
868 Error("%s: %s", str, errbuf);
873 * Make sure this variable is fully expanded.
876 VarExpand(Var *v, GNode *ctxt, Boolean err)
881 if (v->flags & VAR_IN_USE) {
882 Fatal("Variable %s is recursive.", v->name);
886 v->flags |= VAR_IN_USE;
889 * Before doing any modification, we have to make sure the
890 * value has been fully expanded. If it looks like recursion
891 * might be necessary (there's a dollar sign somewhere in the
892 * variable's value) we just call Var_Subst to do any other
893 * substitutions that are necessary. Note that the value
894 * returned by Var_Subst will have been
895 * dynamically-allocated, so it will need freeing when we
898 value = (char *)Buf_GetAll(v->val, (size_t *)NULL);
899 if (strchr(value, '$') == NULL) {
900 result = strdup(value);
904 buf = Var_Subst(NULL, value, ctxt, err);
905 result = Buf_GetAll(buf, NULL);
906 Buf_Destroy(buf, FALSE);
909 v->flags &= ~VAR_IN_USE;
915 * Select only those words that match the modifier.
918 modifier_M(const char mod[], const char value[], char endc, size_t *consumed)
926 for (cur = mod + 1; *cur != '\0'; cur++) {
927 if (cur[0] == endc) {
929 } else if (cur[0] == ':') {
931 } else if ((cur[0] == '\\') &&
932 (cur[1] == ':' || cur[1] == endc)) {
939 * Compress the \:'s out of the pattern, so allocate enough
940 * room to hold the uncompressed pattern and compress the
941 * pattern into the space. (note that cur started at mod+1
942 * so cur-mod takes the null byte into account)
944 patt = emalloc(cur - mod);
946 for (cur = mod + 1; cur != end; cur++) {
947 if ((cur[0] == '\\') &&
948 (cur[1] == ':' || cur[1] == endc)) {
956 if (*mod == 'M' || *mod == 'm') {
957 newValue = VarModify(value, VarMatch, patt);
959 newValue = VarModify(value, VarNoMatch, patt);
963 *consumed += (end - mod);
966 *consumed += 1; /* include colin as part of modifier */
973 modifier_S(const char mod[], const char value[], Var *v, GNode *ctxt, Boolean err, size_t *consumed)
976 Buffer *buf; /* Buffer for patterns */
984 delim = mod[1]; /* used to find end of pattern */
987 * If pattern begins with '^', it is anchored to the start of the
988 * word -- skip over it and flag pattern.
991 pattern.flags |= VAR_MATCH_START;
998 * Pass through the lhs looking for 1) escaped delimiters, '$'s and
999 * backslashes (place the escaped character in uninterpreted) and 2)
1000 * unescaped $'s that aren't before the delimiter (expand the
1001 * variable substitution). The result is left in the Buffer buf.
1003 while (cur[0] != delim) {
1004 if (cur[0] == '\0') {
1006 * LHS didn't end with the delim, complain and exit.
1008 Fatal("Unclosed substitution for %s (%c missing)",
1011 } else if ((cur[0] == '\\') &&
1012 ((cur[1] == delim) ||
1014 (cur[1] == '\\'))) {
1015 cur++; /* skip backslash */
1016 Buf_AddByte(buf, (Byte) cur[0]);
1019 } else if (cur[0] == '$') {
1020 if (cur[1] == delim) {
1022 * Unescaped $ at end of pattern => anchor
1025 pattern.flags |= VAR_MATCH_END;
1029 * If unescaped dollar sign not before the
1030 * delimiter, assume it's a variable
1031 * substitution and recurse.
1038 cp2 = Var_Parse(cur, ctxt, err, &len, &freeIt);
1040 Buf_Append(buf, cp2);
1046 Buf_AddByte(buf, (Byte)cur[0]);
1050 cur++; /* skip over delim */
1053 * Fetch pattern and destroy buffer, but preserve the data in it,
1054 * since that's our lhs.
1056 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1057 Buf_Destroy(buf, FALSE);
1060 * Now comes the replacement string. Three things need to be done
1061 * here: 1) need to compress escaped delimiters and ampersands and 2)
1062 * need to replace unescaped ampersands with the l.h.s. (since this
1063 * isn't regexp, we can do it right here) and 3) expand any variable
1068 while (cur[0] != delim) {
1069 if (cur[0] == '\0') {
1071 * Didn't end with delim character, complain
1073 Fatal("Unclosed substitution for %s (%c missing)",
1076 } else if ((cur[0] == '\\') &&
1077 ((cur[1] == delim) ||
1081 cur++; /* skip backslash */
1082 Buf_AddByte(buf, (Byte) cur[0]);
1085 } else if (cur[0] == '$') {
1086 if (cur[1] == delim) {
1087 Buf_AddByte(buf, (Byte) cur[0]);
1095 cp2 = Var_Parse(cur, ctxt, err, &len, &freeIt);
1097 Buf_Append(buf, cp2);
1102 } else if (cur[0] == '&') {
1103 Buf_AddBytes(buf, pattern.leftLen, (Byte *)pattern.lhs);
1106 Buf_AddByte(buf, (Byte) cur[0]);
1110 cur++; /* skip over delim */
1112 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1113 Buf_Destroy(buf, FALSE);
1116 * Check for global substitution. If 'g' after the final delimiter,
1117 * substitution is global and is marked that way.
1119 if (cur[0] == 'g') {
1120 pattern.flags |= VAR_SUB_GLOBAL;
1125 * Global substitution of the empty string causes an infinite number
1126 * of matches, unless anchored by '^' (start of string) or '$' (end
1127 * of string). Catch the infinite substitution here. Note that flags
1128 * can only contain the 3 bits we're interested in so we don't have
1129 * to mask unrelated bits. We can test for equality.
1131 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1132 Fatal("Global substitution of the empty string");
1134 newValue = VarModify(value, VarSubstitute, &pattern);
1137 * Free the two strings.
1142 *consumed += (cur - mod);
1144 if (cur[0] == ':') {
1145 *consumed += 1; /* include colin as part of modifier */
1152 * Now we need to apply any modifiers the user wants applied.
1155 * words which match the given <pattern>.
1156 * <pattern> is of the standard file
1158 * :S<d><pat1><d><pat2><d>[g]
1159 * Substitute <pat2> for <pat1> in the value
1160 * :C<d><pat1><d><pat2><d>[g]
1161 * Substitute <pat2> for regex <pat1> in the value
1162 * :H Substitute the head of each word
1163 * :T Substitute the tail of each word
1164 * :E Substitute the extension (minus '.') of
1166 * :R Substitute the root of each word
1167 * (pathname minus the suffix).
1169 * Like :S, but the rhs goes to the end of
1171 * :U Converts variable to upper-case.
1172 * :L Converts variable to lower-case.
1174 * XXXHB update this comment or remove it and point to the man page.
1177 ParseModifier(const char input[], char tstr[],
1178 char startc, char endc, Boolean dynamic, Var *v,
1179 GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
1184 rw_str = VarExpand(v, ctxt, err);
1188 while (*tstr != endc) {
1189 char *newStr; /* New value to return */
1190 char termc; /* Character which terminated scan */
1191 Boolean readonly = FALSE;
1192 size_t consumed = 0;
1194 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, rw_str));
1198 readonly = TRUE; /* tstr isn't modified here */
1200 newStr = modifier_M(tstr, rw_str, endc, &consumed);
1205 readonly = TRUE; /* tstr isn't modified here */
1207 newStr = modifier_S(tstr, rw_str, v, ctxt, err, &consumed);
1213 VarREPattern pattern;
1223 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1224 NULL, NULL)) == NULL) {
1225 /* was: goto cleanup */
1226 *lengthPtr = cp - input + 1;
1230 Fatal("Unclosed substitution for %s (%c missing)",
1235 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1236 delim, NULL, NULL, NULL)) == NULL){
1239 /* was: goto cleanup */
1240 *lengthPtr = cp - input + 1;
1244 Fatal("Unclosed substitution for %s (%c missing)",
1252 pattern.flags |= VAR_SUB_GLOBAL;
1255 pattern.flags |= VAR_SUB_ONE;
1265 error = regcomp(&pattern.re, re, REG_EXTENDED);
1268 *lengthPtr = cp - input + 1;
1269 VarREError(error, &pattern.re, "RE substitution error");
1270 free(pattern.replace);
1274 pattern.nsub = pattern.re.re_nsub + 1;
1275 if (pattern.nsub < 1)
1277 if (pattern.nsub > 10)
1279 pattern.matches = emalloc(pattern.nsub *
1280 sizeof(regmatch_t));
1281 newStr = VarModify(rw_str, VarRESubstitute, &pattern);
1282 regfree(&pattern.re);
1283 free(pattern.replace);
1284 free(pattern.matches);
1288 if (tstr[1] == endc || tstr[1] == ':') {
1290 buf = Buf_Init(MAKE_BSIZE);
1291 for (cp = rw_str; *cp ; cp++)
1292 Buf_AddByte(buf, (Byte)tolower(*cp));
1294 Buf_AddByte(buf, (Byte)'\0');
1295 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1296 Buf_Destroy(buf, FALSE);
1304 if (tstr[1] == endc || tstr[1] == ':') {
1305 newStr = VarSortWords(rw_str, SortIncreasing);
1312 if (tstr[1] == endc || tstr[1] == ':') {
1313 newStr = Var_Quote(rw_str);
1320 if (tstr[1] == endc || tstr[1] == ':') {
1321 newStr = VarModify(rw_str, VarTail, (void *)NULL);
1328 if (tstr[1] == endc || tstr[1] == ':') {
1330 buf = Buf_Init(MAKE_BSIZE);
1331 for (cp = rw_str; *cp ; cp++)
1332 Buf_AddByte(buf, (Byte)toupper(*cp));
1334 Buf_AddByte(buf, (Byte)'\0');
1335 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1336 Buf_Destroy(buf, FALSE);
1344 if (tstr[1] == endc || tstr[1] == ':') {
1345 newStr = VarModify(rw_str, VarHead, (void *)NULL);
1352 if (tstr[1] == endc || tstr[1] == ':') {
1353 newStr = VarModify(rw_str, VarSuffix, (void *)NULL);
1360 if (tstr[1] == endc || tstr[1] == ':') {
1361 newStr = VarModify(rw_str, VarRoot, (void *)NULL);
1369 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1373 buf = Cmd_Exec(rw_str, &error);
1374 newStr = Buf_GetAll(buf, NULL);
1375 Buf_Destroy(buf, FALSE);
1378 Error(error, rw_str);
1389 * This can either be a bogus modifier or a System-V
1390 * substitution command.
1399 * First we make a pass through the string trying
1400 * to verify it is a SYSV-make-style translation:
1401 * it must be: <string1>=<string2>)
1405 while (*cp != '\0' && cnt) {
1408 /* continue looking for endc */
1410 else if (*cp == endc)
1412 else if (*cp == startc)
1417 if (*cp == endc && eqFound) {
1421 * Now we break this sucker into the lhs and
1422 * rhs. We must null terminate them of course.
1427 if ((pattern.lhs = VarGetPattern(ctxt,
1428 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1430 /* was: goto cleanup */
1431 *lengthPtr = cp - input + 1;
1435 Fatal("Unclosed substitution for %s (%c missing)",
1441 if ((pattern.rhs = VarGetPattern(ctxt,
1442 err, &cp, delim, NULL, &pattern.rightLen,
1443 &pattern)) == NULL) {
1444 /* was: goto cleanup */
1445 *lengthPtr = cp - input + 1;
1449 Fatal("Unclosed substitution for %s (%c missing)",
1455 * SYSV modifications happen through the whole
1456 * string. Note the pattern is anchored at the end.
1460 newStr = VarModify(rw_str, VarSYSVMatch, &pattern);
1469 Error("Unknown modifier '%c'\n", *tstr);
1471 *cp != ':' && *cp != endc && *cp != '\0';
1480 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1485 if (rw_str != var_Error) {
1491 if (readonly == FALSE) {
1492 if (termc == '\0') {
1493 Error("Unclosed variable specification for %s",
1495 } else if (termc == ':') {
1505 if (v->flags & VAR_FROM_ENV) {
1506 if (rw_str == (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1508 * Returning the value unmodified, so tell the caller to free
1512 *lengthPtr = tstr - input + 1;
1513 VarDestroy(v, FALSE);
1516 *lengthPtr = tstr - input + 1;
1517 VarDestroy(v, TRUE);
1520 } else if (v->flags & VAR_JUNK) {
1522 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1523 * doesn't try to free a static pointer.
1530 *lengthPtr = tstr - input + 1;
1531 VarDestroy(v, TRUE);
1532 rw_str = emalloc(*lengthPtr + 1);
1533 strncpy(rw_str, input, *lengthPtr);
1534 rw_str[*lengthPtr] = '\0';
1539 *lengthPtr = tstr - input + 1;
1540 VarDestroy(v, TRUE);
1541 return (err ? var_Error : varNoError);
1544 *lengthPtr = tstr - input + 1;
1550 * Check if brackets contain a variable name.
1553 VarParseLong(char foo[], GNode *ctxt, Boolean err, size_t *lengthPtr,
1556 const char *input = foo;
1559 char endc; /* Ending character when variable in parens
1561 char startc; /* Starting character when variable in parens
1564 size_t vlen; /* length of variable name, after embedded
1565 * variable expansion */
1567 /* build up expanded variable name in this buffer */
1568 Buffer *buf = Buf_Init(MAKE_BSIZE);
1571 * Skip to the end character or a colon, whichever comes first,
1572 * replacing embedded variables as we go.
1575 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1578 while (*ptr != endc && *ptr != ':') {
1581 * If we did not find the end character,
1582 * return var_Error right now, setting the
1583 * length to be the distance to the end of
1584 * the string, since that's what make does.
1587 *lengthPtr = ptr - input;
1588 Buf_Destroy(buf, TRUE);
1591 } else if (*ptr == '$') {
1597 rval = Var_Parse(ptr, ctxt, err, &rlen, &rfree);
1598 if (rval == var_Error) {
1599 Fatal("Error expanding embedded variable.");
1601 Buf_Append(buf, rval);
1606 Buf_AddByte(buf, (Byte)*ptr);
1611 vname = Buf_GetAll(buf, (size_t *)NULL); /* REPLACE str */
1612 vlen = strlen(vname);
1615 char *const tstr = ptr;
1616 size_t consumed = tstr - input + 1;
1618 Var *v; /* Variable in invocation */
1619 Boolean haveModifier; /* TRUE if have modifiers for the variable */
1620 Boolean dynamic; /* TRUE if the variable is local and we're
1621 * expanding it in a non-local context. This
1622 * is done to support dynamic sources. The
1623 * result is just the invocation, unaltered */
1625 haveModifier = (*tstr == ':');
1628 v = VarFind(vname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1630 Buf_Destroy(buf, TRUE);
1633 return (ParseModifier(input, tstr,
1634 startc, endc, dynamic, v,
1635 ctxt, err, lengthPtr, freePtr));
1639 result = VarExpand(v, ctxt, err);
1641 if (v->flags & VAR_FROM_ENV) {
1642 VarDestroy(v, TRUE);
1646 *lengthPtr = consumed;
1651 if ((ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL)) {
1653 * Check for D and F forms of local variables since we're in
1654 * a local context and the name is the right length.
1657 (vname[1] == 'F' || vname[1] == 'D') &&
1658 (strchr("!%*<>@", vname[0]) != NULL)) {
1663 * Well, it's local -- go look for it.
1668 v = VarFind(name, ctxt, 0);
1671 Buf_Destroy(buf, TRUE);
1672 return (ParseModifier(input, tstr,
1673 startc, endc, dynamic, v,
1674 ctxt, err, lengthPtr, freePtr));
1677 * No need for nested expansion or
1678 * anything, as we're the only one
1679 * who sets these things and we sure
1680 * don't put nested invocations in
1683 val = (char *)Buf_GetAll(v->val, (size_t *) NULL);
1685 if (vname[1] == 'D') {
1686 val = VarModify(val, VarHead, (void *)NULL);
1688 val = VarModify(val, VarTail, (void *)NULL);
1691 * Resulting string is dynamically
1692 * allocated, so tell caller to free
1696 *lengthPtr = consumed;
1697 Buf_Destroy(buf, TRUE);
1703 if (((vlen == 1)) ||
1704 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1706 * If substituting a local variable in a non-local
1707 * context, assume it's for dynamic source stuff. We
1708 * have to handle this specially and return the
1709 * longhand for the variable with the dollar sign
1710 * escaped so it makes it back to the caller. Only
1711 * four of the local variables are treated specially
1712 * as they are the only four that will be set when
1713 * dynamic sources are expanded.
1715 if (strchr("!%*@", vname[0]) != NULL) {
1720 (vname[0] == '.') &&
1721 isupper((unsigned char)vname[1])) {
1722 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1723 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1724 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1725 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1733 * Still need to get to the end of the variable
1734 * specification, so kludge up a Var structure for
1737 v = VarCreate(vname, NULL, VAR_JUNK);
1739 Buf_Destroy(buf, TRUE);
1740 return (ParseModifier(input, tstr,
1741 startc, endc, dynamic, v,
1742 ctxt, err, lengthPtr, freePtr));
1745 * No modifiers -- have specification length so we
1751 result = emalloc(consumed + 1);
1752 strncpy(result, input, consumed);
1753 result[consumed] = '\0';
1756 *lengthPtr = consumed;
1758 Buf_Destroy(buf, TRUE);
1762 *lengthPtr = consumed;
1764 Buf_Destroy(buf, TRUE);
1765 return (err ? var_Error : varNoError);
1772 * If it's not bounded by braces of some sort, life is much simpler.
1773 * We just need to check for the first character and return the value
1777 VarParseShort(const char input[], GNode *ctxt, Boolean err,
1778 size_t *lengthPtr, Boolean *freePtr)
1786 /* consume character */
1789 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1793 result = VarExpand(v, ctxt, err);
1795 if (v->flags & VAR_FROM_ENV) {
1796 VarDestroy(v, TRUE);
1804 * If substituting a local variable in a non-local context, assume
1805 * it's for dynamic source stuff. We have to handle this specially
1806 * and return the longhand for the variable with the dollar sign
1807 * escaped so it makes it back to the caller. Only four of the local
1808 * variables are treated specially as they are the only four that
1809 * will be set when dynamic sources are expanded.
1811 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1813 /* XXX: It looks like $% and $! are reversed here */
1817 return (estrdup("$(.TARGET)"));
1820 return (estrdup("$(.ARCHIVE)"));
1823 return (estrdup("$(.PREFIX)"));
1826 return (estrdup("$(.MEMBER)"));
1829 return (err ? var_Error : varNoError);
1834 return (err ? var_Error : varNoError);
1838 *-----------------------------------------------------------------------
1840 * Given the start of a variable invocation, extract the variable
1841 * name and find its value, then modify it according to the
1845 * The (possibly-modified) value of the variable or var_Error if the
1846 * specification is invalid. The length of the specification is
1847 * placed in *lengthPtr (for invalid specifications, this is just
1848 * 2 to skip the '$' and the following letter, or 1 if '$' was the
1849 * last character in the string).
1850 * A Boolean in *freePtr telling whether the returned string should
1851 * be freed by the caller.
1857 * It is assumed that Var_Parse() is called with str[0] == '$'.
1859 *-----------------------------------------------------------------------
1862 Var_Parse(char *foo, GNode *ctxt, Boolean err,
1863 size_t *lengthPtr, Boolean *freePtr)
1865 const char *input = foo;
1867 /* assert(input[0] == '$'); */
1873 if (input[0] == '\0') {
1874 /* Error, there is only a dollar sign in the input string. */
1876 return (err ? var_Error : varNoError);
1878 } else if (input[0] == OPEN_PAREN || input[0] == OPEN_BRACE) {
1879 /* multi letter variable name */
1880 return (VarParseLong(foo, ctxt, err, lengthPtr, freePtr));
1883 /* single letter variable name */
1884 return (VarParseShort(input, ctxt, err, lengthPtr, freePtr));
1889 *-----------------------------------------------------------------------
1891 * Substitute for all variables in the given string in the given context
1892 * If undefErr is TRUE, Parse_Error will be called when an undefined
1893 * variable is encountered.
1896 * The resulting string.
1899 * None. The old string must be freed by the caller
1900 *-----------------------------------------------------------------------
1903 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1905 Boolean errorReported;
1906 Buffer *buf; /* Buffer for forming things */
1909 * Set TRUE if an error has already been reported to prevent a
1910 * plethora of messages when recursing.
1911 * XXXHB this comment sounds wrong.
1913 errorReported = FALSE;
1917 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1919 * A dollar sign may be escaped either with another dollar sign.
1920 * In such a case, we skip over the escape character and store the
1921 * dollar sign into the buffer directly.
1923 Buf_AddByte(buf, (Byte)str[0]);
1926 } else if (str[0] == '$') {
1927 char *val; /* Value to substitute for a variable */
1928 size_t length; /* Length of the variable invocation */
1929 Boolean doFree; /* Set true if val should be freed */
1932 * Variable invocation.
1937 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1939 const char *p = str + 2;
1942 * Scan up to the end of the variable name.
1944 while (*p != '\0' &&
1946 *p != CLOSE_PAREN &&
1947 *p != CLOSE_BRACE &&
1953 * A variable inside the variable. We cannot expand
1954 * the external variable yet, so we try again with
1958 Buf_AppendRange(buf, str, p);
1964 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1968 * Not the variable we want to expand, scan
1969 * until the next variable
1971 while (*p != '$' && *p != '\0')
1974 Buf_AppendRange(buf, str, p);
1980 * Single letter variable name
1982 if (var[1] == '\0' && var[0] == str[1]) {
1985 Buf_AddBytes(buf, 2, (const Byte *)str);
1997 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
2000 * When we come down here, val should either point to the
2001 * value of this variable, suitably modified, or be NULL.
2002 * Length should be the total length of the potential
2003 * variable invocation (from $ to end character...)
2005 if (val == var_Error || val == varNoError) {
2007 * If performing old-time variable substitution, skip over
2008 * the variable and continue with the substitution. Otherwise,
2009 * store the dollar sign and advance str so we continue with
2014 } else if (undefErr) {
2016 * If variable is undefined, complain and skip the
2017 * variable. The complaint will stop us from doing anything
2018 * when the file is parsed.
2020 if (!errorReported) {
2021 Parse_Error(PARSE_FATAL,
2022 "Undefined variable \"%.*s\"",length,str);
2025 errorReported = TRUE;
2027 Buf_AddByte(buf, (Byte)*str);
2032 * We've now got a variable structure to store in. But first,
2033 * advance the string pointer.
2038 * Copy all the characters from the variable value straight
2039 * into the new string.
2041 Buf_Append(buf, val);
2048 * Skip as many characters as possible -- either to the end of
2049 * the string or to the next dollar sign (variable invocation).
2051 const char *cp = str;
2055 } while (str[0] != '$' && str[0] != '\0');
2057 Buf_AppendRange(buf, cp, str);
2065 *-----------------------------------------------------------------------
2067 * Return the tail from each of a list of words. Used to set the
2068 * System V local variables.
2071 * The resulting string.
2076 *-----------------------------------------------------------------------
2079 Var_GetTail(char *file)
2082 return (VarModify(file, VarTail, (void *)NULL));
2086 *-----------------------------------------------------------------------
2088 * Find the leading components of a (list of) filename(s).
2089 * XXX: VarHead does not replace foo by ., as (sun) System V make
2093 * The leading components.
2098 *-----------------------------------------------------------------------
2101 Var_GetHead(char *file)
2104 return (VarModify(file, VarHead, (void *)NULL));
2108 *-----------------------------------------------------------------------
2110 * Initialize the module
2116 * The VAR_CMD and VAR_GLOBAL contexts are created
2117 *-----------------------------------------------------------------------
2123 VAR_GLOBAL = Targ_NewGN("Global");
2124 VAR_CMD = Targ_NewGN("Command");
2127 /****************** PRINT DEBUGGING INFO *****************/
2129 VarPrintVar(void *vp, void *dummy __unused)
2131 Var *v = (Var *) vp;
2133 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
2138 *-----------------------------------------------------------------------
2140 * print all variables in a context
2141 *-----------------------------------------------------------------------
2144 Var_Dump(GNode *ctxt)
2147 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);