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.126 2005/03/04 23:44:37 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 */
967 * Now we need to apply any modifiers the user wants applied.
970 * words which match the given <pattern>.
971 * <pattern> is of the standard file
973 * :S<d><pat1><d><pat2><d>[g]
974 * Substitute <pat2> for <pat1> in the value
975 * :C<d><pat1><d><pat2><d>[g]
976 * Substitute <pat2> for regex <pat1> in the value
977 * :H Substitute the head of each word
978 * :T Substitute the tail of each word
979 * :E Substitute the extension (minus '.') of
981 * :R Substitute the root of each word
982 * (pathname minus the suffix).
984 * Like :S, but the rhs goes to the end of
986 * :U Converts variable to upper-case.
987 * :L Converts variable to lower-case.
989 * XXXHB update this comment or remove it and point to the man page.
992 ParseModifier(const char input[], char tstr[],
993 char startc, char endc, Boolean dynamic, Var *v,
994 GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
999 rw_str = VarExpand(v, ctxt, err);
1003 while (*tstr != endc) {
1004 char *newStr; /* New value to return */
1005 char termc; /* Character which terminated scan */
1006 Boolean readonly = FALSE;
1008 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, rw_str));
1013 size_t consumed = 0;
1015 readonly = TRUE; /* tstr isn't modified here */
1017 newStr = modifier_M(tstr, rw_str, endc, &consumed);
1025 Buffer *buf; /* Buffer for patterns */
1032 * If pattern begins with '^', it is anchored to the start of the
1033 * word -- skip over it and flag pattern.
1036 pattern.flags |= VAR_MATCH_START;
1042 * Pass through the lhs looking for 1) escaped delimiters, '$'s and
1043 * backslashes (place the escaped character in uninterpreted) and 2)
1044 * unescaped $'s that aren't before the delimiter (expand the
1045 * variable substitution). The result is left in the Buffer buf.
1047 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1048 if ((*cp == '\\') &&
1052 Buf_AddByte(buf, (Byte) cp[1]);
1054 } else if (*cp == '$') {
1057 * If unescaped dollar sign not before the
1058 * delimiter, assume it's a variable
1059 * substitution and recurse.
1066 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1067 Buf_Append(buf, cp2);
1074 * Unescaped $ at end of pattern => anchor
1077 pattern.flags |= VAR_MATCH_END;
1080 Buf_AddByte(buf, (Byte) * cp);
1084 Buf_AddByte(buf, (Byte) '\0');
1087 * If lhs didn't end with the delimiter, complain and exit.
1090 Fatal("Unclosed substitution for %s (%c missing)",
1094 * Fetch pattern and destroy buffer, but preserve the data in it,
1095 * since that's our lhs. Note that Buf_GetAll will return the actual
1096 * number of bytes, which includes the null byte, so we have to
1097 * decrement the length by one.
1099 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1101 Buf_Destroy(buf, FALSE);
1104 * Now comes the replacement string. Three things need to be done
1105 * here: 1) need to compress escaped delimiters and ampersands and 2)
1106 * need to replace unescaped ampersands with the l.h.s. (since this
1107 * isn't regexp, we can do it right here) and 3) expand any variable
1113 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1114 if ((*cp == '\\') &&
1119 Buf_AddByte(buf, (Byte) cp[1]);
1121 } else if ((*cp == '$') && (cp[1] != del)) {
1127 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1128 Buf_Append(buf, cp2);
1133 } else if (*cp == '&') {
1134 Buf_AddBytes(buf, pattern.leftLen,
1135 (Byte *) pattern.lhs);
1137 Buf_AddByte(buf, (Byte) * cp);
1141 Buf_AddByte(buf, (Byte) '\0');
1144 * If didn't end in delimiter character, complain
1147 Fatal("Unclosed substitution for %s (%c missing)",
1150 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1152 Buf_Destroy(buf, FALSE);
1155 * Check for global substitution. If 'g' after the final delimiter,
1156 * substitution is global and is marked that way.
1160 pattern.flags |= VAR_SUB_GLOBAL;
1164 * Global substitution of the empty string causes an infinite number
1165 * of matches, unless anchored by '^' (start of string) or '$' (end
1166 * of string). Catch the infinite substitution here. Note that flags
1167 * can only contain the 3 bits we're interested in so we don't have
1168 * to mask unrelated bits. We can test for equality.
1170 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1171 Fatal("Global substitution of the empty string");
1174 newStr = VarModify(rw_str, VarSubstitute, &pattern);
1176 * Free the two strings.
1185 VarREPattern pattern;
1195 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1196 NULL, NULL)) == NULL) {
1197 /* was: goto cleanup */
1198 *lengthPtr = cp - input + 1;
1202 Fatal("Unclosed substitution for %s (%c missing)",
1207 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1208 delim, NULL, NULL, NULL)) == NULL){
1211 /* was: goto cleanup */
1212 *lengthPtr = cp - input + 1;
1216 Fatal("Unclosed substitution for %s (%c missing)",
1224 pattern.flags |= VAR_SUB_GLOBAL;
1227 pattern.flags |= VAR_SUB_ONE;
1237 error = regcomp(&pattern.re, re, REG_EXTENDED);
1240 *lengthPtr = cp - input + 1;
1241 VarREError(error, &pattern.re, "RE substitution error");
1242 free(pattern.replace);
1246 pattern.nsub = pattern.re.re_nsub + 1;
1247 if (pattern.nsub < 1)
1249 if (pattern.nsub > 10)
1251 pattern.matches = emalloc(pattern.nsub *
1252 sizeof(regmatch_t));
1253 newStr = VarModify(rw_str, VarRESubstitute, &pattern);
1254 regfree(&pattern.re);
1255 free(pattern.replace);
1256 free(pattern.matches);
1260 if (tstr[1] == endc || tstr[1] == ':') {
1262 buf = Buf_Init(MAKE_BSIZE);
1263 for (cp = rw_str; *cp ; cp++)
1264 Buf_AddByte(buf, (Byte)tolower(*cp));
1266 Buf_AddByte(buf, (Byte)'\0');
1267 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1268 Buf_Destroy(buf, FALSE);
1276 if (tstr[1] == endc || tstr[1] == ':') {
1277 newStr = VarSortWords(rw_str, SortIncreasing);
1284 if (tstr[1] == endc || tstr[1] == ':') {
1285 newStr = Var_Quote(rw_str);
1292 if (tstr[1] == endc || tstr[1] == ':') {
1293 newStr = VarModify(rw_str, VarTail, (void *)NULL);
1300 if (tstr[1] == endc || tstr[1] == ':') {
1302 buf = Buf_Init(MAKE_BSIZE);
1303 for (cp = rw_str; *cp ; cp++)
1304 Buf_AddByte(buf, (Byte)toupper(*cp));
1306 Buf_AddByte(buf, (Byte)'\0');
1307 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1308 Buf_Destroy(buf, FALSE);
1316 if (tstr[1] == endc || tstr[1] == ':') {
1317 newStr = VarModify(rw_str, VarHead, (void *)NULL);
1324 if (tstr[1] == endc || tstr[1] == ':') {
1325 newStr = VarModify(rw_str, VarSuffix, (void *)NULL);
1332 if (tstr[1] == endc || tstr[1] == ':') {
1333 newStr = VarModify(rw_str, VarRoot, (void *)NULL);
1341 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1345 buf = Cmd_Exec(rw_str, &error);
1346 newStr = Buf_GetAll(buf, NULL);
1347 Buf_Destroy(buf, FALSE);
1350 Error(error, rw_str);
1361 * This can either be a bogus modifier or a System-V
1362 * substitution command.
1371 * First we make a pass through the string trying
1372 * to verify it is a SYSV-make-style translation:
1373 * it must be: <string1>=<string2>)
1377 while (*cp != '\0' && cnt) {
1380 /* continue looking for endc */
1382 else if (*cp == endc)
1384 else if (*cp == startc)
1389 if (*cp == endc && eqFound) {
1393 * Now we break this sucker into the lhs and
1394 * rhs. We must null terminate them of course.
1399 if ((pattern.lhs = VarGetPattern(ctxt,
1400 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1402 /* was: goto cleanup */
1403 *lengthPtr = cp - input + 1;
1407 Fatal("Unclosed substitution for %s (%c missing)",
1413 if ((pattern.rhs = VarGetPattern(ctxt,
1414 err, &cp, delim, NULL, &pattern.rightLen,
1415 &pattern)) == NULL) {
1416 /* was: goto cleanup */
1417 *lengthPtr = cp - input + 1;
1421 Fatal("Unclosed substitution for %s (%c missing)",
1427 * SYSV modifications happen through the whole
1428 * string. Note the pattern is anchored at the end.
1432 newStr = VarModify(rw_str, VarSYSVMatch, &pattern);
1441 Error("Unknown modifier '%c'\n", *tstr);
1443 *cp != ':' && *cp != endc && *cp != '\0';
1452 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1457 if (rw_str != var_Error) {
1463 if (readonly == FALSE) {
1464 if (termc == '\0') {
1465 Error("Unclosed variable specification for %s",
1467 } else if (termc == ':') {
1477 if (v->flags & VAR_FROM_ENV) {
1478 if (rw_str == (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1480 * Returning the value unmodified, so tell the caller to free
1484 *lengthPtr = tstr - input + 1;
1485 VarDestroy(v, FALSE);
1488 *lengthPtr = tstr - input + 1;
1489 VarDestroy(v, TRUE);
1492 } else if (v->flags & VAR_JUNK) {
1494 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1495 * doesn't try to free a static pointer.
1502 *lengthPtr = tstr - input + 1;
1503 VarDestroy(v, TRUE);
1504 rw_str = emalloc(*lengthPtr + 1);
1505 strncpy(rw_str, input, *lengthPtr);
1506 rw_str[*lengthPtr] = '\0';
1511 *lengthPtr = tstr - input + 1;
1512 VarDestroy(v, TRUE);
1513 return (err ? var_Error : varNoError);
1516 *lengthPtr = tstr - input + 1;
1522 * Check if brackets contain a variable name.
1525 VarParseLong(char foo[], GNode *ctxt, Boolean err, size_t *lengthPtr,
1528 const char *input = foo;
1531 char endc; /* Ending character when variable in parens
1533 char startc; /* Starting character when variable in parens
1536 size_t vlen; /* length of variable name, after embedded
1537 * variable expansion */
1539 /* build up expanded variable name in this buffer */
1540 Buffer *buf = Buf_Init(MAKE_BSIZE);
1543 * Skip to the end character or a colon, whichever comes first,
1544 * replacing embedded variables as we go.
1547 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1550 while (*ptr != endc && *ptr != ':') {
1553 * If we did not find the end character,
1554 * return var_Error right now, setting the
1555 * length to be the distance to the end of
1556 * the string, since that's what make does.
1559 *lengthPtr = ptr - input;
1560 Buf_Destroy(buf, TRUE);
1563 } else if (*ptr == '$') {
1569 rval = Var_Parse(ptr, ctxt, err, &rlen, &rfree);
1570 if (rval == var_Error) {
1571 Fatal("Error expanding embedded variable.");
1573 Buf_Append(buf, rval);
1578 Buf_AddByte(buf, (Byte)*ptr);
1583 vname = Buf_GetAll(buf, (size_t *)NULL); /* REPLACE str */
1584 vlen = strlen(vname);
1587 char *const tstr = ptr;
1588 size_t consumed = tstr - input + 1;
1590 Var *v; /* Variable in invocation */
1591 Boolean haveModifier; /* TRUE if have modifiers for the variable */
1592 Boolean dynamic; /* TRUE if the variable is local and we're
1593 * expanding it in a non-local context. This
1594 * is done to support dynamic sources. The
1595 * result is just the invocation, unaltered */
1597 haveModifier = (*tstr == ':');
1600 v = VarFind(vname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1602 Buf_Destroy(buf, TRUE);
1605 return (ParseModifier(input, tstr,
1606 startc, endc, dynamic, v,
1607 ctxt, err, lengthPtr, freePtr));
1611 result = VarExpand(v, ctxt, err);
1613 if (v->flags & VAR_FROM_ENV) {
1614 VarDestroy(v, TRUE);
1618 *lengthPtr = consumed;
1623 if ((ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL)) {
1625 * Check for D and F forms of local variables since we're in
1626 * a local context and the name is the right length.
1629 (vname[1] == 'F' || vname[1] == 'D') &&
1630 (strchr("!%*<>@", vname[0]) != NULL)) {
1635 * Well, it's local -- go look for it.
1640 v = VarFind(name, ctxt, 0);
1643 Buf_Destroy(buf, TRUE);
1644 return (ParseModifier(input, tstr,
1645 startc, endc, dynamic, v,
1646 ctxt, err, lengthPtr, freePtr));
1649 * No need for nested expansion or
1650 * anything, as we're the only one
1651 * who sets these things and we sure
1652 * don't put nested invocations in
1655 val = (char *)Buf_GetAll(v->val, (size_t *) NULL);
1657 if (vname[1] == 'D') {
1658 val = VarModify(val, VarHead, (void *)NULL);
1660 val = VarModify(val, VarTail, (void *)NULL);
1663 * Resulting string is dynamically
1664 * allocated, so tell caller to free
1668 *lengthPtr = consumed;
1669 Buf_Destroy(buf, TRUE);
1675 if (((vlen == 1)) ||
1676 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1678 * If substituting a local variable in a non-local
1679 * context, assume it's for dynamic source stuff. We
1680 * have to handle this specially and return the
1681 * longhand for the variable with the dollar sign
1682 * escaped so it makes it back to the caller. Only
1683 * four of the local variables are treated specially
1684 * as they are the only four that will be set when
1685 * dynamic sources are expanded.
1687 if (strchr("!%*@", vname[0]) != NULL) {
1692 (vname[0] == '.') &&
1693 isupper((unsigned char)vname[1])) {
1694 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1695 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1696 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1697 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1705 * Still need to get to the end of the variable
1706 * specification, so kludge up a Var structure for
1709 v = VarCreate(vname, NULL, VAR_JUNK);
1711 Buf_Destroy(buf, TRUE);
1712 return (ParseModifier(input, tstr,
1713 startc, endc, dynamic, v,
1714 ctxt, err, lengthPtr, freePtr));
1717 * No modifiers -- have specification length so we
1723 result = emalloc(consumed + 1);
1724 strncpy(result, input, consumed);
1725 result[consumed] = '\0';
1728 *lengthPtr = consumed;
1730 Buf_Destroy(buf, TRUE);
1734 *lengthPtr = consumed;
1736 Buf_Destroy(buf, TRUE);
1737 return (err ? var_Error : varNoError);
1744 * If it's not bounded by braces of some sort, life is much simpler.
1745 * We just need to check for the first character and return the value
1749 VarParseShort(const char input[], GNode *ctxt, Boolean err,
1750 size_t *lengthPtr, Boolean *freePtr)
1758 /* consume character */
1761 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1765 result = VarExpand(v, ctxt, err);
1767 if (v->flags & VAR_FROM_ENV) {
1768 VarDestroy(v, TRUE);
1776 * If substituting a local variable in a non-local context, assume
1777 * it's for dynamic source stuff. We have to handle this specially
1778 * and return the longhand for the variable with the dollar sign
1779 * escaped so it makes it back to the caller. Only four of the local
1780 * variables are treated specially as they are the only four that
1781 * will be set when dynamic sources are expanded.
1783 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
1785 /* XXX: It looks like $% and $! are reversed here */
1789 return (estrdup("$(.TARGET)"));
1792 return (estrdup("$(.ARCHIVE)"));
1795 return (estrdup("$(.PREFIX)"));
1798 return (estrdup("$(.MEMBER)"));
1801 return (err ? var_Error : varNoError);
1806 return (err ? var_Error : varNoError);
1810 *-----------------------------------------------------------------------
1812 * Given the start of a variable invocation, extract the variable
1813 * name and find its value, then modify it according to the
1817 * The (possibly-modified) value of the variable or var_Error if the
1818 * specification is invalid. The length of the specification is
1819 * placed in *lengthPtr (for invalid specifications, this is just
1820 * 2 to skip the '$' and the following letter, or 1 if '$' was the
1821 * last character in the string).
1822 * A Boolean in *freePtr telling whether the returned string should
1823 * be freed by the caller.
1829 * It is assumed that Var_Parse() is called with str[0] == '$'.
1831 *-----------------------------------------------------------------------
1834 Var_Parse(char *foo, GNode *ctxt, Boolean err,
1835 size_t *lengthPtr, Boolean *freePtr)
1837 const char *input = foo;
1839 /* assert(input[0] == '$'); */
1845 if (input[0] == '\0') {
1846 /* Error, there is only a dollar sign in the input string. */
1848 return (err ? var_Error : varNoError);
1850 } else if (input[0] == OPEN_PAREN || input[0] == OPEN_BRACE) {
1851 /* multi letter variable name */
1852 return (VarParseLong(foo, ctxt, err, lengthPtr, freePtr));
1855 /* single letter variable name */
1856 return (VarParseShort(input, ctxt, err, lengthPtr, freePtr));
1861 *-----------------------------------------------------------------------
1863 * Substitute for all variables in the given string in the given context
1864 * If undefErr is TRUE, Parse_Error will be called when an undefined
1865 * variable is encountered.
1868 * The resulting string.
1871 * None. The old string must be freed by the caller
1872 *-----------------------------------------------------------------------
1875 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1877 Boolean errorReported;
1878 Buffer *buf; /* Buffer for forming things */
1881 * Set TRUE if an error has already been reported to prevent a
1882 * plethora of messages when recursing.
1883 * XXXHB this comment sounds wrong.
1885 errorReported = FALSE;
1889 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1891 * A dollar sign may be escaped either with another dollar sign.
1892 * In such a case, we skip over the escape character and store the
1893 * dollar sign into the buffer directly.
1895 Buf_AddByte(buf, (Byte)str[0]);
1898 } else if (str[0] == '$') {
1899 char *val; /* Value to substitute for a variable */
1900 size_t length; /* Length of the variable invocation */
1901 Boolean doFree; /* Set true if val should be freed */
1904 * Variable invocation.
1909 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1911 const char *p = str + 2;
1914 * Scan up to the end of the variable name.
1916 while (*p != '\0' &&
1918 *p != CLOSE_PAREN &&
1919 *p != CLOSE_BRACE &&
1925 * A variable inside the variable. We cannot expand
1926 * the external variable yet, so we try again with
1930 Buf_AppendRange(buf, str, p);
1936 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1940 * Not the variable we want to expand, scan
1941 * until the next variable
1943 while (*p != '$' && *p != '\0')
1946 Buf_AppendRange(buf, str, p);
1952 * Single letter variable name
1954 if (var[1] == '\0' && var[0] == str[1]) {
1957 Buf_AddBytes(buf, 2, (const Byte *)str);
1969 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1972 * When we come down here, val should either point to the
1973 * value of this variable, suitably modified, or be NULL.
1974 * Length should be the total length of the potential
1975 * variable invocation (from $ to end character...)
1977 if (val == var_Error || val == varNoError) {
1979 * If performing old-time variable substitution, skip over
1980 * the variable and continue with the substitution. Otherwise,
1981 * store the dollar sign and advance str so we continue with
1986 } else if (undefErr) {
1988 * If variable is undefined, complain and skip the
1989 * variable. The complaint will stop us from doing anything
1990 * when the file is parsed.
1992 if (!errorReported) {
1993 Parse_Error(PARSE_FATAL,
1994 "Undefined variable \"%.*s\"",length,str);
1997 errorReported = TRUE;
1999 Buf_AddByte(buf, (Byte)*str);
2004 * We've now got a variable structure to store in. But first,
2005 * advance the string pointer.
2010 * Copy all the characters from the variable value straight
2011 * into the new string.
2013 Buf_Append(buf, val);
2020 * Skip as many characters as possible -- either to the end of
2021 * the string or to the next dollar sign (variable invocation).
2023 const char *cp = str;
2027 } while (str[0] != '$' && str[0] != '\0');
2029 Buf_AppendRange(buf, cp, str);
2037 *-----------------------------------------------------------------------
2039 * Return the tail from each of a list of words. Used to set the
2040 * System V local variables.
2043 * The resulting string.
2048 *-----------------------------------------------------------------------
2051 Var_GetTail(char *file)
2054 return (VarModify(file, VarTail, (void *)NULL));
2058 *-----------------------------------------------------------------------
2060 * Find the leading components of a (list of) filename(s).
2061 * XXX: VarHead does not replace foo by ., as (sun) System V make
2065 * The leading components.
2070 *-----------------------------------------------------------------------
2073 Var_GetHead(char *file)
2076 return (VarModify(file, VarHead, (void *)NULL));
2080 *-----------------------------------------------------------------------
2082 * Initialize the module
2088 * The VAR_CMD and VAR_GLOBAL contexts are created
2089 *-----------------------------------------------------------------------
2095 VAR_GLOBAL = Targ_NewGN("Global");
2096 VAR_CMD = Targ_NewGN("Command");
2099 /****************** PRINT DEBUGGING INFO *****************/
2101 VarPrintVar(void *vp, void *dummy __unused)
2103 Var *v = (Var *) vp;
2105 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
2110 *-----------------------------------------------------------------------
2112 * print all variables in a context
2113 *-----------------------------------------------------------------------
2116 Var_Dump(GNode *ctxt)
2119 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);