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.129 2005/03/04 23:48:53 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.
614 *-----------------------------------------------------------------------
617 VarModify(char *str, VarModifyProc *modProc, void *datum)
619 Buffer *buf; /* Buffer for the new string */
620 Boolean addSpace; /* TRUE if need to add a space to the
621 * buffer before adding the trimmed
623 char **av; /* word list [first word does not count] */
629 av = brk_string(str, &ac, FALSE);
631 for (i = 1; i < ac; i++)
632 addSpace = (*modProc)(av[i], addSpace, buf, datum);
634 Buf_AddByte(buf, '\0');
635 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
636 Buf_Destroy(buf, FALSE);
641 *-----------------------------------------------------------------------
643 * Sort the words in the string.
646 * str String whose words should be sorted
647 * cmp A comparison function to control the ordering
650 * A string containing the words sorted
655 *-----------------------------------------------------------------------
658 VarSortWords(char *str, int (*cmp)(const void *, const void *))
665 av = brk_string(str, &ac, FALSE);
666 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'));
671 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
672 Buf_Destroy(buf, FALSE);
677 SortIncreasing(const void *l, const void *r)
680 return (strcmp(*(const char* const*)l, *(const char* const*)r));
684 *-----------------------------------------------------------------------
686 * Pass through the tstr looking for 1) escaped delimiters,
687 * '$'s and backslashes (place the escaped character in
688 * uninterpreted) and 2) unescaped $'s that aren't before
689 * the delimiter (expand the variable substitution unless flags
690 * has VAR_NOSUBST set).
691 * Return the expanded string or NULL if the delimiter was missing
692 * If pattern is specified, handle escaped ampersands, and replace
693 * unescaped ampersands with the lhs of the pattern.
696 * A string of all the words modified appropriately.
697 * If length is specified, return the string length of the buffer
698 * If flags is specified and the last character of the pattern is a
699 * $ set the VAR_MATCH_END bit of flags.
703 *-----------------------------------------------------------------------
706 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
707 size_t *length, VarPattern *pattern)
710 Buffer *buf = Buf_Init(0);
716 #define IS_A_MATCH(cp, delim) \
717 ((cp[0] == '\\') && ((cp[1] == delim) || \
718 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
721 * Skim through until the matching delimiter is found;
722 * pick up variable substitutions on the way. Also allow
723 * backslashes to quote the delimiter, $, and \, but don't
724 * touch other backslashes.
726 for (cp = *tstr; *cp && (*cp != delim); cp++) {
727 if (IS_A_MATCH(cp, delim)) {
728 Buf_AddByte(buf, (Byte)cp[1]);
730 } else if (*cp == '$') {
731 if (cp[1] == delim) {
733 Buf_AddByte(buf, (Byte)*cp);
736 * Unescaped $ at end of pattern => anchor
739 *flags |= VAR_MATCH_END;
741 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
747 * If unescaped dollar sign not before the
748 * delimiter, assume it's a variable
749 * substitution and recurse.
752 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
753 Buf_Append(buf, cp2);
760 if (*cp2 == OPEN_PAREN || *cp2 == OPEN_BRACE) {
762 * Find the end of this variable reference
763 * and suck it in without further ado.
764 * It will be interperated later.
767 int want = (*cp2 == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
770 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
771 if (cp2[-1] != '\\') {
778 Buf_AppendRange(buf, cp, cp2);
781 Buf_AddByte(buf, (Byte)*cp);
785 else if (pattern && *cp == '&')
786 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
788 Buf_AddByte(buf, (Byte)*cp);
791 Buf_AddByte(buf, (Byte)'\0');
799 cp = (char *)Buf_GetAll(buf, length);
800 *length -= 1; /* Don't count the NULL */
801 Buf_Destroy(buf, FALSE);
807 *-----------------------------------------------------------------------
809 * Quote shell meta-characters in the string
817 *-----------------------------------------------------------------------
820 Var_Quote(const char *str)
823 /* This should cover most shells :-( */
824 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
827 buf = Buf_Init(MAKE_BSIZE);
828 for (; *str; str++) {
829 if (strchr(meta, *str) != NULL)
830 Buf_AddByte(buf, (Byte)'\\');
831 Buf_AddByte(buf, (Byte)*str);
833 Buf_AddByte(buf, (Byte)'\0');
834 ret = Buf_GetAll(buf, NULL);
835 Buf_Destroy(buf, FALSE);
840 *-----------------------------------------------------------------------
842 * Print the error caused by a regcomp or regexec call.
848 * An error gets printed.
850 *-----------------------------------------------------------------------
853 VarREError(int err, regex_t *pat, const char *str)
858 errlen = regerror(err, pat, 0, 0);
859 errbuf = emalloc(errlen);
860 regerror(err, pat, errbuf, errlen);
861 Error("%s: %s", str, errbuf);
866 * Make sure this variable is fully expanded.
869 VarExpand(Var *v, GNode *ctxt, Boolean err)
874 if (v->flags & VAR_IN_USE) {
875 Fatal("Variable %s is recursive.", v->name);
879 v->flags |= VAR_IN_USE;
882 * Before doing any modification, we have to make sure the
883 * value has been fully expanded. If it looks like recursion
884 * might be necessary (there's a dollar sign somewhere in the
885 * variable's value) we just call Var_Subst to do any other
886 * substitutions that are necessary. Note that the value
887 * returned by Var_Subst will have been
888 * dynamically-allocated, so it will need freeing when we
891 value = (char *)Buf_GetAll(v->val, (size_t *)NULL);
892 if (strchr(value, '$') == NULL) {
893 result = strdup(value);
897 buf = Var_Subst(NULL, value, ctxt, err);
898 result = Buf_GetAll(buf, NULL);
899 Buf_Destroy(buf, FALSE);
902 v->flags &= ~VAR_IN_USE;
908 * Select only those words that match the modifier.
911 modifier_M(const char mod[], const char value[], char endc, size_t *consumed)
919 for (cur = mod + 1; *cur != '\0'; cur++) {
920 if (cur[0] == endc) {
922 } else if (cur[0] == ':') {
924 } else if ((cur[0] == '\\') &&
925 (cur[1] == ':' || cur[1] == endc)) {
932 * Compress the \:'s out of the pattern, so allocate enough
933 * room to hold the uncompressed pattern and compress the
934 * pattern into the space. (note that cur started at mod+1
935 * so cur-mod takes the null byte into account)
937 patt = emalloc(cur - mod);
939 for (cur = mod + 1; cur != end; cur++) {
940 if ((cur[0] == '\\') &&
941 (cur[1] == ':' || cur[1] == endc)) {
949 if (*mod == 'M' || *mod == 'm') {
950 newValue = VarModify(value, VarMatch, patt);
952 newValue = VarModify(value, VarNoMatch, patt);
956 *consumed += (end - mod);
959 *consumed += 1; /* include colin as part of modifier */
966 modifier_S(char tstr[], char *rw_str, Var *v, GNode *ctxt, Boolean err, size_t *consumed)
969 Buffer *buf; /* Buffer for patterns */
977 delim = tstr[1]; /* used to find end of pattern */
980 * If pattern begins with '^', it is anchored to the start of the
981 * word -- skip over it and flag pattern.
983 if (tstr[2] == '^') {
984 pattern.flags |= VAR_MATCH_START;
991 * Pass through the lhs looking for 1) escaped delimiters, '$'s and
992 * backslashes (place the escaped character in uninterpreted) and 2)
993 * unescaped $'s that aren't before the delimiter (expand the
994 * variable substitution). The result is left in the Buffer buf.
996 while (cur[0] != delim) {
997 if (cur[0] == '\0') {
999 * LHS didn't end with the delim, complain and exit.
1001 Fatal("Unclosed substitution for %s (%c missing)",
1004 } else if ((cur[0] == '\\') &&
1005 ((cur[1] == delim) ||
1007 (cur[1] == '\\'))) {
1008 cur++; /* skip backslash */
1009 Buf_AddByte(buf, (Byte) cur[0]);
1012 } else if (cur[0] == '$') {
1013 if (cur[1] == delim) {
1015 * Unescaped $ at end of pattern => anchor
1018 pattern.flags |= VAR_MATCH_END;
1022 * If unescaped dollar sign not before the
1023 * delimiter, assume it's a variable
1024 * substitution and recurse.
1031 cp2 = Var_Parse(cur, ctxt, err, &len, &freeIt);
1033 Buf_Append(buf, cp2);
1039 Buf_AddByte(buf, (Byte)cur[0]);
1043 cur++; /* skip over delim */
1046 * Fetch pattern and destroy buffer, but preserve the data in it,
1047 * since that's our lhs.
1049 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1050 Buf_Destroy(buf, FALSE);
1053 * Now comes the replacement string. Three things need to be done
1054 * here: 1) need to compress escaped delimiters and ampersands and 2)
1055 * need to replace unescaped ampersands with the l.h.s. (since this
1056 * isn't regexp, we can do it right here) and 3) expand any variable
1061 while (cur[0] != delim) {
1062 if (cur[0] == '\0') {
1064 * Didn't end with delim character, complain
1066 Fatal("Unclosed substitution for %s (%c missing)",
1069 } else if ((cur[0] == '\\') &&
1070 ((cur[1] == delim) ||
1074 cur++; /* skip backslash */
1075 Buf_AddByte(buf, (Byte) cur[0]);
1078 } else if (cur[0] == '$') {
1079 if (cur[1] == delim) {
1080 Buf_AddByte(buf, (Byte) cur[0]);
1088 cp2 = Var_Parse(cur, ctxt, err, &len, &freeIt);
1090 Buf_Append(buf, cp2);
1095 } else if (cur[0] == '&') {
1096 Buf_AddBytes(buf, pattern.leftLen, (Byte *)pattern.lhs);
1099 Buf_AddByte(buf, (Byte) cur[0]);
1103 cur++; /* skip over delim */
1105 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1106 Buf_Destroy(buf, FALSE);
1109 * Check for global substitution. If 'g' after the final delimiter,
1110 * substitution is global and is marked that way.
1112 if (cur[0] == 'g') {
1113 pattern.flags |= VAR_SUB_GLOBAL;
1118 * Global substitution of the empty string causes an infinite number
1119 * of matches, unless anchored by '^' (start of string) or '$' (end
1120 * of string). Catch the infinite substitution here. Note that flags
1121 * can only contain the 3 bits we're interested in so we don't have
1122 * to mask unrelated bits. We can test for equality.
1124 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1125 Fatal("Global substitution of the empty string");
1127 newStr = VarModify(rw_str, VarSubstitute, &pattern);
1130 * Free the two strings.
1135 *consumed += (cur - tstr);
1137 if (cur[0] == ':') {
1138 *consumed += 1; /* include colin as part of modifier */
1145 * Now we need to apply any modifiers the user wants applied.
1148 * words which match the given <pattern>.
1149 * <pattern> is of the standard file
1151 * :S<d><pat1><d><pat2><d>[g]
1152 * Substitute <pat2> for <pat1> in the value
1153 * :C<d><pat1><d><pat2><d>[g]
1154 * Substitute <pat2> for regex <pat1> in the value
1155 * :H Substitute the head of each word
1156 * :T Substitute the tail of each word
1157 * :E Substitute the extension (minus '.') of
1159 * :R Substitute the root of each word
1160 * (pathname minus the suffix).
1162 * Like :S, but the rhs goes to the end of
1164 * :U Converts variable to upper-case.
1165 * :L Converts variable to lower-case.
1167 * XXXHB update this comment or remove it and point to the man page.
1170 ParseModifier(const char input[], char tstr[],
1171 char startc, char endc, Boolean dynamic, Var *v,
1172 GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
1177 rw_str = VarExpand(v, ctxt, err);
1181 while (*tstr != endc) {
1182 char *newStr; /* New value to return */
1183 char termc; /* Character which terminated scan */
1184 Boolean readonly = FALSE;
1185 size_t consumed = 0;
1187 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, rw_str));
1191 readonly = TRUE; /* tstr isn't modified here */
1193 newStr = modifier_M(tstr, rw_str, endc, &consumed);
1198 readonly = TRUE; /* tstr isn't modified here */
1200 newStr = modifier_S(tstr, rw_str, v, ctxt, err, &consumed);
1206 VarREPattern pattern;
1216 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1217 NULL, NULL)) == NULL) {
1218 /* was: goto cleanup */
1219 *lengthPtr = cp - input + 1;
1223 Fatal("Unclosed substitution for %s (%c missing)",
1228 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1229 delim, NULL, NULL, NULL)) == NULL){
1232 /* was: goto cleanup */
1233 *lengthPtr = cp - input + 1;
1237 Fatal("Unclosed substitution for %s (%c missing)",
1245 pattern.flags |= VAR_SUB_GLOBAL;
1248 pattern.flags |= VAR_SUB_ONE;
1258 error = regcomp(&pattern.re, re, REG_EXTENDED);
1261 *lengthPtr = cp - input + 1;
1262 VarREError(error, &pattern.re, "RE substitution error");
1263 free(pattern.replace);
1267 pattern.nsub = pattern.re.re_nsub + 1;
1268 if (pattern.nsub < 1)
1270 if (pattern.nsub > 10)
1272 pattern.matches = emalloc(pattern.nsub *
1273 sizeof(regmatch_t));
1274 newStr = VarModify(rw_str, VarRESubstitute, &pattern);
1275 regfree(&pattern.re);
1276 free(pattern.replace);
1277 free(pattern.matches);
1281 if (tstr[1] == endc || tstr[1] == ':') {
1283 buf = Buf_Init(MAKE_BSIZE);
1284 for (cp = rw_str; *cp ; cp++)
1285 Buf_AddByte(buf, (Byte)tolower(*cp));
1287 Buf_AddByte(buf, (Byte)'\0');
1288 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1289 Buf_Destroy(buf, FALSE);
1297 if (tstr[1] == endc || tstr[1] == ':') {
1298 newStr = VarSortWords(rw_str, SortIncreasing);
1305 if (tstr[1] == endc || tstr[1] == ':') {
1306 newStr = Var_Quote(rw_str);
1313 if (tstr[1] == endc || tstr[1] == ':') {
1314 newStr = VarModify(rw_str, VarTail, (void *)NULL);
1321 if (tstr[1] == endc || tstr[1] == ':') {
1323 buf = Buf_Init(MAKE_BSIZE);
1324 for (cp = rw_str; *cp ; cp++)
1325 Buf_AddByte(buf, (Byte)toupper(*cp));
1327 Buf_AddByte(buf, (Byte)'\0');
1328 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1329 Buf_Destroy(buf, FALSE);
1337 if (tstr[1] == endc || tstr[1] == ':') {
1338 newStr = VarModify(rw_str, VarHead, (void *)NULL);
1345 if (tstr[1] == endc || tstr[1] == ':') {
1346 newStr = VarModify(rw_str, VarSuffix, (void *)NULL);
1353 if (tstr[1] == endc || tstr[1] == ':') {
1354 newStr = VarModify(rw_str, VarRoot, (void *)NULL);
1362 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1366 buf = Cmd_Exec(rw_str, &error);
1367 newStr = Buf_GetAll(buf, NULL);
1368 Buf_Destroy(buf, FALSE);
1371 Error(error, rw_str);
1382 * This can either be a bogus modifier or a System-V
1383 * substitution command.
1392 * First we make a pass through the string trying
1393 * to verify it is a SYSV-make-style translation:
1394 * it must be: <string1>=<string2>)
1398 while (*cp != '\0' && cnt) {
1401 /* continue looking for endc */
1403 else if (*cp == endc)
1405 else if (*cp == startc)
1410 if (*cp == endc && eqFound) {
1414 * Now we break this sucker into the lhs and
1415 * rhs. We must null terminate them of course.
1420 if ((pattern.lhs = VarGetPattern(ctxt,
1421 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1423 /* was: goto cleanup */
1424 *lengthPtr = cp - input + 1;
1428 Fatal("Unclosed substitution for %s (%c missing)",
1434 if ((pattern.rhs = VarGetPattern(ctxt,
1435 err, &cp, delim, NULL, &pattern.rightLen,
1436 &pattern)) == NULL) {
1437 /* was: goto cleanup */
1438 *lengthPtr = cp - input + 1;
1442 Fatal("Unclosed substitution for %s (%c missing)",
1448 * SYSV modifications happen through the whole
1449 * string. Note the pattern is anchored at the end.
1453 newStr = VarModify(rw_str, VarSYSVMatch, &pattern);
1462 Error("Unknown modifier '%c'\n", *tstr);
1464 *cp != ':' && *cp != endc && *cp != '\0';
1473 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1478 if (rw_str != var_Error) {
1484 if (readonly == FALSE) {
1485 if (termc == '\0') {
1486 Error("Unclosed variable specification for %s",
1488 } 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 * Check if brackets contain a variable name.
1546 VarParseLong(char foo[], GNode *ctxt, Boolean err, size_t *lengthPtr,
1549 const char *input = foo;
1552 char endc; /* Ending character when variable in parens
1554 char startc; /* Starting character when variable in parens
1557 size_t vlen; /* length of variable name, after embedded
1558 * variable expansion */
1560 /* build up expanded variable name in this buffer */
1561 Buffer *buf = Buf_Init(MAKE_BSIZE);
1564 * Skip to the end character or a colon, whichever comes first,
1565 * replacing embedded variables as we go.
1568 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1571 while (*ptr != endc && *ptr != ':') {
1574 * If we did not find the end character,
1575 * return var_Error right now, setting the
1576 * length to be the distance to the end of
1577 * the string, since that's what make does.
1580 *lengthPtr = ptr - input;
1581 Buf_Destroy(buf, TRUE);
1584 } else if (*ptr == '$') {
1590 rval = Var_Parse(ptr, ctxt, err, &rlen, &rfree);
1591 if (rval == var_Error) {
1592 Fatal("Error expanding embedded variable.");
1594 Buf_Append(buf, rval);
1599 Buf_AddByte(buf, (Byte)*ptr);
1604 vname = Buf_GetAll(buf, (size_t *)NULL); /* REPLACE str */
1605 vlen = strlen(vname);
1608 char *const tstr = ptr;
1609 size_t consumed = tstr - input + 1;
1611 Var *v; /* Variable in invocation */
1612 Boolean haveModifier; /* TRUE if have modifiers for the variable */
1613 Boolean dynamic; /* TRUE if the variable is local and we're
1614 * expanding it in a non-local context. This
1615 * is done to support dynamic sources. The
1616 * result is just the invocation, unaltered */
1618 haveModifier = (*tstr == ':');
1621 v = VarFind(vname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1623 Buf_Destroy(buf, TRUE);
1626 return (ParseModifier(input, tstr,
1627 startc, endc, dynamic, v,
1628 ctxt, err, lengthPtr, freePtr));
1632 result = VarExpand(v, ctxt, err);
1634 if (v->flags & VAR_FROM_ENV) {
1635 VarDestroy(v, TRUE);
1639 *lengthPtr = consumed;
1644 if ((ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL)) {
1646 * Check for D and F forms of local variables since we're in
1647 * a local context and the name is the right length.
1650 (vname[1] == 'F' || vname[1] == 'D') &&
1651 (strchr("!%*<>@", vname[0]) != NULL)) {
1656 * Well, it's local -- go look for it.
1661 v = VarFind(name, ctxt, 0);
1664 Buf_Destroy(buf, TRUE);
1665 return (ParseModifier(input, tstr,
1666 startc, endc, dynamic, v,
1667 ctxt, err, lengthPtr, freePtr));
1670 * No need for nested expansion or
1671 * anything, as we're the only one
1672 * who sets these things and we sure
1673 * don't put nested invocations in
1676 val = (char *)Buf_GetAll(v->val, (size_t *) NULL);
1678 if (vname[1] == 'D') {
1679 val = VarModify(val, VarHead, (void *)NULL);
1681 val = VarModify(val, VarTail, (void *)NULL);
1684 * Resulting string is dynamically
1685 * allocated, so tell caller to free
1689 *lengthPtr = consumed;
1690 Buf_Destroy(buf, TRUE);
1696 if (((vlen == 1)) ||
1697 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1699 * If substituting a local variable in a non-local
1700 * context, assume it's for dynamic source stuff. We
1701 * have to handle this specially and return the
1702 * longhand for the variable with the dollar sign
1703 * escaped so it makes it back to the caller. Only
1704 * four of the local variables are treated specially
1705 * as they are the only four that will be set when
1706 * dynamic sources are expanded.
1708 if (strchr("!%*@", vname[0]) != NULL) {
1713 (vname[0] == '.') &&
1714 isupper((unsigned char)vname[1])) {
1715 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1716 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1717 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1718 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1726 * Still need to get to the end of the variable
1727 * specification, so kludge up a Var structure for
1730 v = VarCreate(vname, NULL, VAR_JUNK);
1732 Buf_Destroy(buf, TRUE);
1733 return (ParseModifier(input, tstr,
1734 startc, endc, dynamic, v,
1735 ctxt, err, lengthPtr, freePtr));
1738 * No modifiers -- have specification length so we
1744 result = emalloc(consumed + 1);
1745 strncpy(result, input, consumed);
1746 result[consumed] = '\0';
1749 *lengthPtr = consumed;
1751 Buf_Destroy(buf, TRUE);
1755 *lengthPtr = consumed;
1757 Buf_Destroy(buf, TRUE);
1758 return (err ? var_Error : varNoError);
1765 * If it's not bounded by braces of some sort, life is much simpler.
1766 * We just need to check for the first character and return the value
1770 VarParseShort(const char input[], GNode *ctxt, Boolean err,
1771 size_t *lengthPtr, Boolean *freePtr)
1779 /* consume character */
1782 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1786 result = VarExpand(v, ctxt, err);
1788 if (v->flags & VAR_FROM_ENV) {
1789 VarDestroy(v, TRUE);
1797 * If substituting a local variable in a non-local context, assume
1798 * it's for dynamic source stuff. We have to handle this specially
1799 * and return the longhand for the variable with the dollar sign
1800 * escaped so it makes it back to the caller. Only four of the local
1801 * variables are treated specially as they are the only four that
1802 * will be set when dynamic sources are expanded.
1804 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1806 /* XXX: It looks like $% and $! are reversed here */
1810 return (estrdup("$(.TARGET)"));
1813 return (estrdup("$(.ARCHIVE)"));
1816 return (estrdup("$(.PREFIX)"));
1819 return (estrdup("$(.MEMBER)"));
1822 return (err ? var_Error : varNoError);
1827 return (err ? var_Error : varNoError);
1831 *-----------------------------------------------------------------------
1833 * Given the start of a variable invocation, extract the variable
1834 * name and find its value, then modify it according to the
1838 * The (possibly-modified) value of the variable or var_Error if the
1839 * specification is invalid. The length of the specification is
1840 * placed in *lengthPtr (for invalid specifications, this is just
1841 * 2 to skip the '$' and the following letter, or 1 if '$' was the
1842 * last character in the string).
1843 * A Boolean in *freePtr telling whether the returned string should
1844 * be freed by the caller.
1850 * It is assumed that Var_Parse() is called with str[0] == '$'.
1852 *-----------------------------------------------------------------------
1855 Var_Parse(char *foo, GNode *ctxt, Boolean err,
1856 size_t *lengthPtr, Boolean *freePtr)
1858 const char *input = foo;
1860 /* assert(input[0] == '$'); */
1866 if (input[0] == '\0') {
1867 /* Error, there is only a dollar sign in the input string. */
1869 return (err ? var_Error : varNoError);
1871 } else if (input[0] == OPEN_PAREN || input[0] == OPEN_BRACE) {
1872 /* multi letter variable name */
1873 return (VarParseLong(foo, ctxt, err, lengthPtr, freePtr));
1876 /* single letter variable name */
1877 return (VarParseShort(input, ctxt, err, lengthPtr, freePtr));
1882 *-----------------------------------------------------------------------
1884 * Substitute for all variables in the given string in the given context
1885 * If undefErr is TRUE, Parse_Error will be called when an undefined
1886 * variable is encountered.
1889 * The resulting string.
1892 * None. The old string must be freed by the caller
1893 *-----------------------------------------------------------------------
1896 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1898 Boolean errorReported;
1899 Buffer *buf; /* Buffer for forming things */
1902 * Set TRUE if an error has already been reported to prevent a
1903 * plethora of messages when recursing.
1904 * XXXHB this comment sounds wrong.
1906 errorReported = FALSE;
1910 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1912 * A dollar sign may be escaped either with another dollar sign.
1913 * In such a case, we skip over the escape character and store the
1914 * dollar sign into the buffer directly.
1916 Buf_AddByte(buf, (Byte)str[0]);
1919 } else if (str[0] == '$') {
1920 char *val; /* Value to substitute for a variable */
1921 size_t length; /* Length of the variable invocation */
1922 Boolean doFree; /* Set true if val should be freed */
1925 * Variable invocation.
1930 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1932 const char *p = str + 2;
1935 * Scan up to the end of the variable name.
1937 while (*p != '\0' &&
1939 *p != CLOSE_PAREN &&
1940 *p != CLOSE_BRACE &&
1946 * A variable inside the variable. We cannot expand
1947 * the external variable yet, so we try again with
1951 Buf_AppendRange(buf, str, p);
1957 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1961 * Not the variable we want to expand, scan
1962 * until the next variable
1964 while (*p != '$' && *p != '\0')
1967 Buf_AppendRange(buf, str, p);
1973 * Single letter variable name
1975 if (var[1] == '\0' && var[0] == str[1]) {
1978 Buf_AddBytes(buf, 2, (const Byte *)str);
1990 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1993 * When we come down here, val should either point to the
1994 * value of this variable, suitably modified, or be NULL.
1995 * Length should be the total length of the potential
1996 * variable invocation (from $ to end character...)
1998 if (val == var_Error || val == varNoError) {
2000 * If performing old-time variable substitution, skip over
2001 * the variable and continue with the substitution. Otherwise,
2002 * store the dollar sign and advance str so we continue with
2007 } else if (undefErr) {
2009 * If variable is undefined, complain and skip the
2010 * variable. The complaint will stop us from doing anything
2011 * when the file is parsed.
2013 if (!errorReported) {
2014 Parse_Error(PARSE_FATAL,
2015 "Undefined variable \"%.*s\"",length,str);
2018 errorReported = TRUE;
2020 Buf_AddByte(buf, (Byte)*str);
2025 * We've now got a variable structure to store in. But first,
2026 * advance the string pointer.
2031 * Copy all the characters from the variable value straight
2032 * into the new string.
2034 Buf_Append(buf, val);
2041 * Skip as many characters as possible -- either to the end of
2042 * the string or to the next dollar sign (variable invocation).
2044 const char *cp = str;
2048 } while (str[0] != '$' && str[0] != '\0');
2050 Buf_AppendRange(buf, cp, str);
2058 *-----------------------------------------------------------------------
2060 * Return the tail from each of a list of words. Used to set the
2061 * System V local variables.
2064 * The resulting string.
2069 *-----------------------------------------------------------------------
2072 Var_GetTail(char *file)
2075 return (VarModify(file, VarTail, (void *)NULL));
2079 *-----------------------------------------------------------------------
2081 * Find the leading components of a (list of) filename(s).
2082 * XXX: VarHead does not replace foo by ., as (sun) System V make
2086 * The leading components.
2091 *-----------------------------------------------------------------------
2094 Var_GetHead(char *file)
2097 return (VarModify(file, VarHead, (void *)NULL));
2101 *-----------------------------------------------------------------------
2103 * Initialize the module
2109 * The VAR_CMD and VAR_GLOBAL contexts are created
2110 *-----------------------------------------------------------------------
2116 VAR_GLOBAL = Targ_NewGN("Global");
2117 VAR_CMD = Targ_NewGN("Command");
2120 /****************** PRINT DEBUGGING INFO *****************/
2122 VarPrintVar(void *vp, void *dummy __unused)
2124 Var *v = (Var *) vp;
2126 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
2131 *-----------------------------------------------------------------------
2133 * print all variables in a context
2134 *-----------------------------------------------------------------------
2137 Var_Dump(GNode *ctxt)
2140 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);