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.161 2005/03/16 22:47:47 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.
105 typedef struct VarParser {
106 const char *const input; /* pointer to input string */
107 const char *ptr; /* current parser pos in input str */
111 static char *VarParse(VarParser *, Boolean *);
114 * This is a harmless return value for Var_Parse that can be used by Var_Subst
115 * to determine if there was an error in parsing -- easier than returning
116 * a flag, as things outside this module don't give a hoot.
118 char var_Error[] = "";
121 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
122 * set false. Why not just use a constant? Well, gcc likes to condense
123 * identical string instances...
125 static char varNoError[] = "";
128 * Internally, variables are contained in four different contexts.
129 * 1) the environment. They may not be changed. If an environment
130 * variable is appended-to, the result is placed in the global
132 * 2) the global context. Variables set in the Makefile are located in
133 * the global context. It is the penultimate context searched when
135 * 3) the command-line context. All variables set on the command line
136 * are placed in this context. They are UNALTERABLE once placed here.
137 * 4) the local context. Each target has associated with it a context
138 * list. On this list are located the structures describing such
139 * local variables as $(@) and $(*)
140 * The four contexts are searched in the reverse order from which they are
143 GNode *VAR_GLOBAL; /* variables from the makefile */
144 GNode *VAR_CMD; /* variables defined on the command-line */
146 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
147 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
148 #define FIND_ENV 0x4 /* look in the environment also */
150 #define OPEN_PAREN '('
151 #define CLOSE_PAREN ')'
152 #define OPEN_BRACE '{'
153 #define CLOSE_BRACE '}'
156 * Create a Var object.
158 * @param name Name of variable.
159 * @param value Value of variable.
160 * @param flags Flags set on variable.
163 VarCreate(const char name[], const char value[], int flags)
167 v = emalloc(sizeof(Var));
168 v->name = estrdup(name);
169 v->val = Buf_Init(0);
173 Buf_Append(v->val, value);
179 * Destroy a Var object.
181 * @param v Object to destroy.
182 * @param f true if internal buffer in Buffer object is to be
186 VarDestroy(Var *v, Boolean f)
189 Buf_Destroy(v->val, f);
195 *-----------------------------------------------------------------------
197 * See if the given variable matches the named one. Called from
198 * Lst_Find when searching for a variable of a given name.
201 * 0 if they match. non-zero otherwise.
205 *-----------------------------------------------------------------------
208 VarCmp(const void *v, const void *name)
211 return (strcmp(name, ((const Var *)v)->name));
215 *-----------------------------------------------------------------------
216 * VarPossiblyExpand --
217 * Expand a variable name's embedded variables in the given context.
220 * The contents of name, possibly expanded.
221 *-----------------------------------------------------------------------
224 VarPossiblyExpand(const char *name, GNode *ctxt)
231 * XXX make a temporary copy of the name because Var_Subst insists
232 * on writing into the string.
235 if (strchr(name, '$') != NULL) {
236 buf = Var_Subst(NULL, tmp, ctxt, 0);
237 str = Buf_GetAll(buf, NULL);
238 Buf_Destroy(buf, FALSE);
248 *-----------------------------------------------------------------------
250 * Find the given variable in the given context and any other contexts
254 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
255 * FIND_CMD set means to look in the VAR_CMD context too
256 * FIND_ENV set means to look in the environment
259 * A pointer to the structure describing the desired variable or
260 * NULL if the variable does not exist.
264 *-----------------------------------------------------------------------
267 VarFind(const char *name, GNode *ctxt, int flags)
269 Boolean localCheckEnvFirst;
274 * If the variable name begins with a '.', it could very well be one of
275 * the local ones. We check the name against all the local variables
276 * and substitute the short version in for 'name' if it matches one of
279 if (name[0] == '.') {
282 if (!strcmp(name, ".ALLSRC"))
284 if (!strcmp(name, ".ARCHIVE"))
288 if (!strcmp(name, ".IMPSRC"))
292 if (!strcmp(name, ".MEMBER"))
296 if (!strcmp(name, ".OODATE"))
300 if (!strcmp(name, ".PREFIX"))
304 if (!strcmp(name, ".TARGET"))
313 * Note whether this is one of the specific variables we were told
314 * through the -E flag to use environment-variable-override for.
316 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
317 localCheckEnvFirst = TRUE;
319 localCheckEnvFirst = FALSE;
323 * First look for the variable in the given context. If it's not there,
324 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
325 * in that order, depending on the FIND_* flags in 'flags'
327 var = Lst_Find(&ctxt->context, name, VarCmp);
330 return (Lst_Datum(var));
333 /* not there - try command line context */
334 if ((flags & FIND_CMD) && (ctxt != VAR_CMD)) {
335 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
337 return (Lst_Datum(var));
340 /* not there - try global context, but only if not -e/-E */
341 if ((flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
342 !checkEnvFirst && !localCheckEnvFirst) {
343 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
345 return (Lst_Datum(var));
348 if (!(flags & FIND_ENV))
349 /* we were not told to look into the environment */
352 /* look in the environment */
353 if ((env = getenv(name)) != NULL) {
354 /* craft this variable from the environment value */
355 return (VarCreate(name, env, VAR_FROM_ENV));
358 /* deferred check for the environment (in case of -e/-E) */
359 if ((checkEnvFirst || localCheckEnvFirst) &&
360 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL)) {
361 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
363 return (Lst_Datum(var));
369 *-----------------------------------------------------------------------
371 * Add a new variable of name name and value val to the given context.
377 * The new variable is placed at the front of the given context
378 * The name and val arguments are duplicated so they may
380 *-----------------------------------------------------------------------
383 VarAdd(const char *name, const char *val, GNode *ctxt)
386 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
387 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
391 *-----------------------------------------------------------------------
393 * Remove a variable from a context.
399 * The Var structure is removed and freed.
401 *-----------------------------------------------------------------------
404 Var_Delete(const char *name, GNode *ctxt)
408 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
409 ln = Lst_Find(&ctxt->context, name, VarCmp);
411 VarDestroy(Lst_Datum(ln), TRUE);
412 Lst_Remove(&ctxt->context, ln);
417 *-----------------------------------------------------------------------
419 * Set the variable name to the value val in the given context.
425 * If the variable doesn't yet exist, a new record is created for it.
426 * Else the old value is freed and the new one stuck in its place
429 * The variable is searched for only in its context before being
430 * created in that context. I.e. if the context is VAR_GLOBAL,
431 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
432 * VAR_CMD->context is searched. This is done to avoid the literally
433 * thousands of unnecessary strcmp's that used to be done to
434 * set, say, $(@) or $(<).
435 *-----------------------------------------------------------------------
438 Var_Set(const char *name, const char *val, GNode *ctxt)
444 * We only look for a variable in the given context since anything
445 * set here will override anything in a lower context, so there's not
446 * much point in searching them all just to save a bit of memory...
448 n = VarPossiblyExpand(name, ctxt);
449 v = VarFind(n, ctxt, 0);
451 VarAdd(n, val, ctxt);
454 Buf_Append(v->val, val);
456 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
459 * Any variables given on the command line are automatically exported
460 * to the environment (as per POSIX standard)
462 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
470 * Set the VAR_TO_ENV flag on a variable
473 Var_SetEnv(const char *name, GNode *ctxt)
477 v = VarFind(name, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
479 if ((v->flags & VAR_TO_ENV) == 0) {
480 v->flags |= VAR_TO_ENV;
481 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
484 Error("Cannot set environment flag on non-existant variable %s", name);
489 *-----------------------------------------------------------------------
491 * The variable of the given name has the given value appended to it in
498 * If the variable doesn't exist, it is created. Else the strings
499 * are concatenated (with a space in between).
502 * Only if the variable is being sought in the global context is the
503 * environment searched.
504 * XXX: Knows its calling circumstances in that if called with ctxt
505 * an actual target, it will only search that context since only
506 * a local variable could be being appended to. This is actually
507 * a big win and must be tolerated.
508 *-----------------------------------------------------------------------
511 Var_Append(const char *name, const char *val, GNode *ctxt)
516 n = VarPossiblyExpand(name, ctxt);
517 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
520 VarAdd(n, val, ctxt);
522 Buf_AddByte(v->val, (Byte)' ');
523 Buf_Append(v->val, val);
525 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
526 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
528 if (v->flags & VAR_FROM_ENV) {
530 * If the original variable came from the
531 * environment, we have to install it in the global
532 * context (we could place it in the environment, but
533 * then we should provide a way to export other
536 v->flags &= ~VAR_FROM_ENV;
537 Lst_AtFront(&ctxt->context, v);
544 *-----------------------------------------------------------------------
546 * See if the given variable exists.
549 * TRUE if it does, FALSE if it doesn't
554 *-----------------------------------------------------------------------
557 Var_Exists(const char *name, GNode *ctxt)
562 n = VarPossiblyExpand(name, ctxt);
563 v = VarFind(n, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
568 } else if (v->flags & VAR_FROM_ENV) {
575 *-----------------------------------------------------------------------
577 * Return the value of the named variable in the given context
580 * The value if the variable exists, NULL if it doesn't
584 *-----------------------------------------------------------------------
587 Var_Value(const char *name, GNode *ctxt, char **frp)
592 n = VarPossiblyExpand(name, ctxt);
593 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
597 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
599 if (v->flags & VAR_FROM_ENV) {
600 VarDestroy(v, FALSE);
610 *-----------------------------------------------------------------------
612 * Modify each of the words of the passed string using the given
613 * function. Used to implement all modifiers.
616 * A string of all the words modified appropriately.
619 * Uses brk_string() so it invalidates any previous call to
622 *-----------------------------------------------------------------------
625 VarModify(const char *str, VarModifyProc *modProc, void *datum)
627 char **av; /* word list [first word does not count] */
629 Buffer *buf; /* Buffer for the new string */
630 Boolean addSpace; /* TRUE if need to add a space to the buffer
631 * before adding the trimmed word */
635 av = brk_string(str, &ac, FALSE);
640 for (i = 1; i < ac; i++)
641 addSpace = (*modProc)(av[i], addSpace, buf, datum);
643 result = (char *)Buf_GetAll(buf, (size_t *)NULL);
644 Buf_Destroy(buf, FALSE);
649 *-----------------------------------------------------------------------
651 * Sort the words in the string.
654 * str String whose words should be sorted
655 * cmp A comparison function to control the ordering
658 * A string containing the words sorted
661 * Uses brk_string() so it invalidates any previous call to
664 *-----------------------------------------------------------------------
667 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
675 av = brk_string(str, &ac, FALSE);
676 qsort(av + 1, ac - 1, sizeof(char *), cmp);
679 for (i = 1; i < ac; i++) {
680 Buf_Append(buf, av[i]);
681 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
684 result = (char *)Buf_GetAll(buf, (size_t *)NULL);
685 Buf_Destroy(buf, FALSE);
690 SortIncreasing(const void *l, const void *r)
693 return (strcmp(*(const char* const*)l, *(const char* const*)r));
697 *-----------------------------------------------------------------------
699 * Pass through the tstr looking for 1) escaped delimiters,
700 * '$'s and backslashes (place the escaped character in
701 * uninterpreted) and 2) unescaped $'s that aren't before
702 * the delimiter (expand the variable substitution unless flags
703 * has VAR_NOSUBST set).
704 * Return the expanded string or NULL if the delimiter was missing
705 * If pattern is specified, handle escaped ampersands, and replace
706 * unescaped ampersands with the lhs of the pattern.
709 * A string of all the words modified appropriately.
710 * If length is specified, return the string length of the buffer
711 * If flags is specified and the last character of the pattern is a
712 * $ set the VAR_MATCH_END bit of flags.
716 *-----------------------------------------------------------------------
719 VarGetPattern(VarParser *vp, const char **tstr, int delim, int *flags,
720 size_t *length, VarPattern *pattern)
723 Buffer *buf = Buf_Init(0);
729 #define IS_A_MATCH(cp, delim) \
730 ((cp[0] == '\\') && ((cp[1] == delim) || \
731 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
734 * Skim through until the matching delimiter is found; pick up
735 * variable substitutions on the way. Also allow backslashes to quote
736 * the delimiter, $, and \, but don't touch other backslashes.
738 for (cp = *tstr; *cp && (*cp != delim); cp++) {
739 if (IS_A_MATCH(cp, delim)) {
740 Buf_AddByte(buf, (Byte)cp[1]);
742 } else if (*cp == '$') {
743 if (cp[1] == delim) {
745 Buf_AddByte(buf, (Byte)*cp);
748 * Unescaped $ at end of pattern =>
749 * anchor pattern at end.
751 *flags |= VAR_MATCH_END;
754 (*flags & VAR_NOSUBST) == 0) {
760 * If unescaped dollar sign not
761 * before the delimiter, assume it's
762 * a variable substitution and
766 cp2 = Var_Parse(cp, vp->ctxt, vp->err, &len, &freeIt);
767 Buf_Append(buf, cp2);
772 const char *cp2 = &cp[1];
774 if (*cp2 == OPEN_PAREN ||
775 *cp2 == OPEN_BRACE) {
777 * Find the end of this
778 * variable reference and
779 * suck it in without further
781 * interperated later.
784 int want = (*cp2 == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
787 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
788 if (cp2[-1] != '\\') {
795 Buf_AppendRange(buf, cp, cp2);
798 Buf_AddByte(buf, (Byte)*cp);
801 } else if (pattern && *cp == '&')
802 Buf_AddBytes(buf, pattern->leftLen, (Byte *) pattern->lhs);
804 Buf_AddByte(buf, (Byte)*cp);
807 Buf_AddByte(buf, (Byte)'\0');
816 result = (char *)Buf_GetAll(buf, length);
817 *length -= 1; /* Don't count the NULL */
818 Buf_Destroy(buf, FALSE);
824 *-----------------------------------------------------------------------
826 * Quote shell meta-characters in the string
834 *-----------------------------------------------------------------------
837 Var_Quote(const char *str)
840 /* This should cover most shells :-( */
841 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
844 buf = Buf_Init(MAKE_BSIZE);
845 for (; *str; str++) {
846 if (strchr(meta, *str) != NULL)
847 Buf_AddByte(buf, (Byte)'\\');
848 Buf_AddByte(buf, (Byte)*str);
850 Buf_AddByte(buf, (Byte)'\0');
851 ret = Buf_GetAll(buf, NULL);
852 Buf_Destroy(buf, FALSE);
857 *-----------------------------------------------------------------------
859 * Print the error caused by a regcomp or regexec call.
865 * An error gets printed.
867 *-----------------------------------------------------------------------
870 VarREError(int err, regex_t *pat, const char *str)
875 errlen = regerror(err, pat, 0, 0);
876 errbuf = emalloc(errlen);
877 regerror(err, pat, errbuf, errlen);
878 Error("%s: %s", str, errbuf);
883 * Make sure this variable is fully expanded.
886 VarExpand(Var *v, VarParser *vp)
891 if (v->flags & VAR_IN_USE) {
892 Fatal("Variable %s is recursive.", v->name);
896 v->flags |= VAR_IN_USE;
899 * Before doing any modification, we have to make sure the
900 * value has been fully expanded. If it looks like recursion
901 * might be necessary (there's a dollar sign somewhere in the
902 * variable's value) we just call Var_Subst to do any other
903 * substitutions that are necessary. Note that the value
904 * returned by Var_Subst will have been
905 * dynamically-allocated, so it will need freeing when we
908 value = (char *)Buf_GetAll(v->val, (size_t *)NULL);
909 if (strchr(value, '$') == NULL) {
910 result = strdup(value);
914 buf = Var_Subst(NULL, value, vp->ctxt, vp->err);
915 result = Buf_GetAll(buf, NULL);
916 Buf_Destroy(buf, FALSE);
919 v->flags &= ~VAR_IN_USE;
925 * Select only those words in value that match the modifier.
928 modifier_M(VarParser *vp, const char value[], char endc)
935 modifier = vp->ptr[0];
936 vp->ptr++; /* consume 'M' or 'N' */
939 * Compress the \:'s out of the pattern, so allocate enough
940 * room to hold the uncompressed pattern and compress the
941 * pattern into that space.
943 patt = estrdup(vp->ptr);
945 while (vp->ptr[0] != '\0') {
946 if ((vp->ptr[0] == endc) || (vp->ptr[0] == ':')) {
949 if ((vp->ptr[0] == '\\') &&
950 ((vp->ptr[1] == endc) || (vp->ptr[1] == ':'))) {
951 vp->ptr++; /* skip over backslash */
959 if (modifier == 'M') {
960 newValue = VarModify(value, VarMatch, patt);
962 newValue = VarModify(value, VarNoMatch, patt);
966 if (vp->ptr[0] == ':') {
967 vp->ptr++; /* include colon as part of modifier */
974 * Substitute the replacement string for the pattern. The substitution
975 * is applied to each word in value.
978 modifier_S(VarParser *vp, const char value[], Var *v)
980 const char *mod = vp->ptr;
982 Buffer *buf; /* Buffer for patterns */
990 delim = mod[1]; /* used to find end of pattern */
993 * If pattern begins with '^', it is anchored to the start of the
994 * word -- skip over it and flag pattern.
997 pattern.flags |= VAR_MATCH_START;
1004 * Pass through the lhs looking for 1) escaped delimiters, '$'s and
1005 * backslashes (place the escaped character in uninterpreted) and 2)
1006 * unescaped $'s that aren't before the delimiter (expand the
1007 * variable substitution). The result is left in the Buffer buf.
1009 while (cur[0] != delim) {
1010 if (cur[0] == '\0') {
1012 * LHS didn't end with the delim, complain and exit.
1014 Fatal("Unclosed substitution for %s (%c missing)",
1017 } else if ((cur[0] == '\\') &&
1018 ((cur[1] == delim) ||
1020 (cur[1] == '\\'))) {
1021 cur++; /* skip backslash */
1022 Buf_AddByte(buf, (Byte)cur[0]);
1025 } else if (cur[0] == '$') {
1026 if (cur[1] == delim) {
1028 * Unescaped $ at end of pattern => anchor
1031 pattern.flags |= VAR_MATCH_END;
1035 * If unescaped dollar sign not before the
1036 * delimiter, assume it's a variable
1037 * substitution and recurse.
1044 cp2 = Var_Parse(cur, vp->ctxt, vp->err, &len, &freeIt);
1046 Buf_Append(buf, cp2);
1052 Buf_AddByte(buf, (Byte)cur[0]);
1056 cur++; /* skip over delim */
1059 * Fetch pattern and destroy buffer, but preserve the data in it,
1060 * since that's our lhs.
1062 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1063 Buf_Destroy(buf, FALSE);
1066 * Now comes the replacement string. Three things need to be done
1067 * here: 1) need to compress escaped delimiters and ampersands and 2)
1068 * need to replace unescaped ampersands with the l.h.s. (since this
1069 * isn't regexp, we can do it right here) and 3) expand any variable
1074 while (cur[0] != delim) {
1075 if (cur[0] == '\0') {
1077 * Didn't end with delim character, complain
1079 Fatal("Unclosed substitution for %s (%c missing)",
1082 } else if ((cur[0] == '\\') &&
1083 ((cur[1] == delim) ||
1087 cur++; /* skip backslash */
1088 Buf_AddByte(buf, (Byte)cur[0]);
1091 } else if (cur[0] == '$') {
1092 if (cur[1] == delim) {
1093 Buf_AddByte(buf, (Byte)cur[0]);
1101 cp2 = Var_Parse(cur, vp->ctxt, vp->err, &len, &freeIt);
1103 Buf_Append(buf, cp2);
1108 } else if (cur[0] == '&') {
1109 Buf_AddBytes(buf, pattern.leftLen, (Byte *)pattern.lhs);
1112 Buf_AddByte(buf, (Byte)cur[0]);
1116 cur++; /* skip over delim */
1118 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1119 Buf_Destroy(buf, FALSE);
1122 * Check for global substitution. If 'g' after the final delimiter,
1123 * substitution is global and is marked that way.
1125 if (cur[0] == 'g') {
1126 pattern.flags |= VAR_SUB_GLOBAL;
1130 vp->ptr += (cur - mod);
1132 if (cur[0] == ':') {
1133 vp->ptr++; /* include colin as part of modifier */
1137 * Global substitution of the empty string causes an infinite number
1138 * of matches, unless anchored by '^' (start of string) or '$' (end
1139 * of string). Catch the infinite substitution here. Note that flags
1140 * can only contain the 3 bits we're interested in so we don't have
1141 * to mask unrelated bits. We can test for equality.
1143 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1144 Fatal("Global substitution of the empty string");
1146 newValue = VarModify(value, VarSubstitute, &pattern);
1149 * Free the two strings.
1158 modifier_C(VarParser *vp, char value[], Var *v)
1160 const char *mod = vp->ptr;
1170 delim = mod[1]; /* delimiter between sections */
1174 re = VarGetPattern(vp, &cur, delim, NULL, NULL, NULL);
1176 Fatal("Unclosed substitution for %s (%c missing)",
1180 patt.replace = VarGetPattern(vp, &cur, delim, NULL, NULL, NULL);
1181 if (patt.replace == NULL) {
1182 Fatal("Unclosed substitution for %s (%c missing)",
1189 patt.flags |= VAR_SUB_GLOBAL;
1192 patt.flags |= VAR_SUB_ONE;
1200 vp->ptr += (cur - mod);
1202 if (cur[0] == ':') {
1203 vp->ptr++; /* include colin as part of modifier */
1206 error = regcomp(&patt.re, re, REG_EXTENDED);
1208 VarREError(error, &patt.re, "RE substitution error");
1214 patt.nsub = patt.re.re_nsub + 1;
1219 patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1221 newValue = VarModify(value, VarRESubstitute, &patt);
1232 * Now we need to apply any modifiers the user wants applied.
1235 * words which match the given <pattern>.
1236 * <pattern> is of the standard file
1238 * :S<d><pat1><d><pat2><d>[g]
1239 * Substitute <pat2> for <pat1> in the value
1240 * :C<d><pat1><d><pat2><d>[g]
1241 * Substitute <pat2> for regex <pat1> in the value
1242 * :H Substitute the head of each word
1243 * :T Substitute the tail of each word
1244 * :E Substitute the extension (minus '.') of
1246 * :R Substitute the root of each word
1247 * (pathname minus the suffix).
1249 * Like :S, but the rhs goes to the end of
1251 * :U Converts variable to upper-case.
1252 * :L Converts variable to lower-case.
1254 * XXXHB update this comment or remove it and point to the man page.
1257 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freePtr)
1262 value = VarExpand(v, vp);
1265 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1268 while (*vp->ptr != endc) {
1269 char *newStr; /* New value to return */
1271 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1275 newStr = modifier_M(vp, value, endc);
1278 newStr = modifier_S(vp, value, v);
1281 newStr = modifier_C(vp, value, v);
1284 if (vp->ptr[1] == endc || vp->ptr[1] == ':') {
1285 switch (vp->ptr[0]) {
1290 buf = Buf_Init(MAKE_BSIZE);
1291 for (cp = value; *cp; cp++)
1292 Buf_AddByte(buf, (Byte)tolower(*cp));
1294 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1295 Buf_Destroy(buf, FALSE);
1297 vp->ptr += (vp->ptr[1] == ':') ? 2 : 1;
1301 newStr = VarSortWords(value, SortIncreasing);
1302 vp->ptr += (vp->ptr[1] == ':') ? 2 : 1;
1305 newStr = Var_Quote(value);
1306 vp->ptr += (vp->ptr[1] == ':') ? 2 : 1;
1309 newStr = VarModify(value, VarTail, (void *)NULL);
1310 vp->ptr += (vp->ptr[1] == ':') ? 2 : 1;
1316 buf = Buf_Init(MAKE_BSIZE);
1317 for (cp = value; *cp; cp++)
1318 Buf_AddByte(buf, (Byte)toupper(*cp));
1320 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1321 Buf_Destroy(buf, FALSE);
1323 vp->ptr += (vp->ptr[1] == ':') ? 2 : 1;
1327 newStr = VarModify(value, VarHead, (void *)NULL);
1328 vp->ptr += (vp->ptr[1] == ':') ? 2 : 1;
1331 newStr = VarModify(value, VarSuffix, (void *)NULL);
1332 vp->ptr += (vp->ptr[1] == ':') ? 2 : 1;
1335 newStr = VarModify(value, VarRoot, (void *)NULL);
1336 vp->ptr += (vp->ptr[1] == ':') ? 2 : 1;
1343 * This can either be a bogus modifier or a
1344 * System-V substitution command.
1353 * First we make a pass through the string
1354 * trying to verify it is a SYSV-make-style
1355 * translation: it must be:
1356 * <string1>=<string2>)
1360 while (*cp != '\0' && cnt) {
1363 /* continue looking for endc */
1364 } else if (*cp == endc)
1366 else if (*cp == startc)
1371 if (*cp == endc && eqFound) {
1373 * Now we break this sucker into the
1374 * lhs and rhs. We must null
1375 * terminate them of course.
1379 patt.lhs = VarGetPattern(vp, &cp, '=', &patt.flags, &patt.leftLen, NULL);
1380 if (patt.lhs == NULL) {
1381 Fatal("Unclosed substitution for %s (%c missing)",
1385 patt.rhs = VarGetPattern(vp, &cp, endc, NULL, &patt.rightLen, &patt);
1386 if (patt.rhs == NULL) {
1387 Fatal("Unclosed substitution for %s (%c missing)",
1391 * SYSV modifications happen through
1392 * the whole string. Note the pattern
1393 * is anchored at the end.
1396 newStr = VarModify(value, VarSYSVMatch, &patt);
1401 vp->ptr = (endc == ':') ? (cp + 1) : cp;
1405 Error("Unknown modifier '%c'\n", *vp->ptr);
1406 for (cp = vp->ptr + 1; *cp != '\0'; cp++) {
1407 if (*cp == ':' && *cp == endc) {
1411 vp->ptr = (*cp == ':') ? (cp + 1) : cp;
1420 if ((vp->ptr[0] == 's') &&
1421 (vp->ptr[1] == 'h') &&
1422 (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1426 buf = Cmd_Exec(value, &error);
1427 newStr = Buf_GetAll(buf, NULL);
1428 Buf_Destroy(buf, FALSE);
1431 Error(error, value);
1432 vp->ptr = (vp->ptr[2] == ':') ? (vp->ptr + 2 + 1) : vp->ptr + 2;
1439 * This can either be a bogus modifier or a
1440 * System-V substitution command.
1449 * First we make a pass through the string
1450 * trying to verify it is a SYSV-make-style
1451 * translation: it must be:
1452 * <string1>=<string2>)
1456 while (*cp != '\0' && cnt) {
1459 /* continue looking for endc */
1460 } else if (*cp == endc)
1462 else if (*cp == startc)
1467 if (*cp == endc && eqFound) {
1469 * Now we break this sucker into the
1470 * lhs and rhs. We must null
1471 * terminate them of course.
1475 patt.lhs = VarGetPattern(vp, &cp, '=', &patt.flags, &patt.leftLen, NULL);
1476 if (patt.lhs == NULL) {
1477 Fatal("Unclosed substitution for %s (%c missing)",
1481 patt.rhs = VarGetPattern(vp, &cp, endc, NULL, &patt.rightLen, &patt);
1482 if (patt.rhs == NULL) {
1483 Fatal("Unclosed substitution for %s (%c missing)",
1487 * SYSV modifications happen through
1488 * the whole string. Note the pattern
1489 * is anchored at the end.
1492 newStr = VarModify(value, VarSYSVMatch, &patt);
1497 vp->ptr = (endc == ':') ? (cp + 1) : cp;
1501 Error("Unknown modifier '%c'\n", *vp->ptr);
1502 for (cp = vp->ptr + 1; *cp != '\0'; cp++) {
1503 if (*cp == ':' || *cp == endc) {
1508 vp->ptr = (*cp == ':') ? (cp + 1) : cp;
1517 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1522 if (value != var_Error) {
1529 if (v->flags & VAR_FROM_ENV) {
1530 if (value == (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1531 VarDestroy(v, FALSE);
1535 VarDestroy(v, TRUE);
1544 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freePtr)
1551 vname = Buf_GetAll(buf, &vlen);
1553 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1555 return (ParseModifier(vp, startc, v, freePtr));
1558 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1561 * Still need to get to the end of the variable
1562 * specification, so kludge up a Var structure for
1565 v = VarCreate(vname, NULL, VAR_JUNK);
1566 value = ParseModifier(vp, startc, v, freePtr);
1570 VarDestroy(v, TRUE);
1572 consumed = vp->ptr - vp->input + 1;
1575 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1577 * If substituting a local variable in a non-local
1578 * context, assume it's for dynamic source stuff. We
1579 * have to handle this specially and return the
1580 * longhand for the variable with the dollar sign
1581 * escaped so it makes it back to the caller. Only
1582 * four of the local variables are treated specially
1583 * as they are the only four that will be set when
1584 * dynamic sources are expanded.
1586 if (strchr("!%*@", vname[0]) != NULL) {
1587 value = emalloc(consumed + 1);
1588 strncpy(value, vp->input, consumed);
1589 value[consumed] = '\0';
1596 (vname[0] == '.') &&
1597 isupper((unsigned char)vname[1])) {
1598 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1599 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1600 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1601 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1602 value = emalloc(consumed + 1);
1603 strncpy(value, vp->input, consumed);
1604 value[consumed] = '\0';
1612 return (vp->err ? var_Error : varNoError);
1615 * Check for D and F forms of local variables since we're in
1616 * a local context and the name is the right length.
1619 (vname[1] == 'F' || vname[1] == 'D') &&
1620 (strchr("!%*<>@", vname[0]) != NULL)) {
1624 * Well, it's local -- go look for it.
1629 v = VarFind(name, vp->ctxt, 0);
1631 return (ParseModifier(vp, startc, v, freePtr));
1636 * Still need to get to the end of the variable
1637 * specification, so kludge up a Var structure for
1640 v = VarCreate(vname, NULL, VAR_JUNK);
1641 value = ParseModifier(vp, startc, v, freePtr);
1645 VarDestroy(v, TRUE);
1648 return (vp->err ? var_Error : varNoError);
1653 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freePtr)
1659 size_t consumed = vp->ptr - vp->input;
1661 vname = Buf_GetAll(buf, &vlen);
1663 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1665 value = VarExpand(v, vp);
1667 if (v->flags & VAR_FROM_ENV) {
1668 VarDestroy(v, TRUE);
1675 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1677 * If substituting a local variable in a non-local
1678 * context, assume it's for dynamic source stuff. We
1679 * have to handle this specially and return the
1680 * longhand for the variable with the dollar sign
1681 * escaped so it makes it back to the caller. Only
1682 * four of the local variables are treated specially
1683 * as they are the only four that will be set when
1684 * dynamic sources are expanded.
1686 if (((vlen == 1)) ||
1687 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1688 if (strchr("!%*@", vname[0]) != NULL) {
1689 value = emalloc(consumed + 1);
1690 strncpy(value, vp->input, consumed);
1691 value[consumed] = '\0';
1698 (vname[0] == '.') &&
1699 isupper((unsigned char)vname[1])) {
1700 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1701 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1702 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1703 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1704 value = emalloc(consumed + 1);
1705 strncpy(value, vp->input, consumed);
1706 value[consumed] = '\0';
1714 return (vp->err ? var_Error : varNoError);
1717 * Check for D and F forms of local variables since we're in
1718 * a local context and the name is the right length.
1721 (vname[1] == 'F' || vname[1] == 'D') &&
1722 (strchr("!%*<>@", vname[0]) != NULL)) {
1728 v = VarFind(name, vp->ctxt, 0);
1732 * No need for nested expansion or
1733 * anything, as we're the only one
1734 * who sets these things and we sure
1735 * don't put nested invocations in
1738 val = (char *)Buf_GetAll(v->val, NULL);
1740 if (vname[1] == 'D') {
1741 val = VarModify(val, VarHead, NULL);
1743 val = VarModify(val, VarTail, NULL);
1752 return (vp->err ? var_Error : varNoError);
1757 * Parse a multi letter variable name, and return it's value.
1760 VarParseLong(VarParser *vp, Boolean *freePtr)
1767 buf = Buf_Init(MAKE_BSIZE);
1770 * Process characters until we reach an end character or a
1771 * colon, replacing embedded variables as we go.
1773 startc = vp->ptr[0];
1774 vp->ptr++; /* consume opening paren or brace */
1776 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1778 while (*vp->ptr != '\0') {
1779 if (*vp->ptr == endc) {
1780 vp->ptr++; /* consume closing paren or brace */
1781 result = ParseRestEnd(vp, buf, freePtr);
1782 Buf_Destroy(buf, TRUE);
1785 } else if (*vp->ptr == ':') {
1786 result = ParseRestModifier(vp, startc, buf, freePtr);
1787 vp->ptr++; /* consume closing paren or brace */
1788 Buf_Destroy(buf, TRUE);
1791 } else if (*vp->ptr == '$') {
1797 rval = Var_Parse(vp->ptr, vp->ctxt, vp->err, &rlen, &rfree);
1798 if (rval == var_Error) {
1799 Fatal("Error expanding embedded variable.");
1801 Buf_Append(buf, rval);
1807 Buf_AddByte(buf, (Byte)*vp->ptr);
1813 * If we did not find the end character,
1814 * return var_Error right now, setting the
1815 * length to be the distance to the end of
1816 * the string, since that's what make does.
1818 Buf_Destroy(buf, TRUE);
1824 * Parse a single letter variable name, and return it's value.
1827 VarParseShort(VarParser *vp, Boolean *freeResult)
1833 vname[0] = vp->ptr[0];
1836 vp->ptr++; /* consume single letter */
1838 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1840 value = VarExpand(v, vp);
1842 if (v->flags & VAR_FROM_ENV) {
1843 VarDestroy(v, TRUE);
1851 * If substituting a local variable in a non-local context, assume
1852 * it's for dynamic source stuff. We have to handle this specially
1853 * and return the longhand for the variable with the dollar sign
1854 * escaped so it makes it back to the caller. Only four of the local
1855 * variables are treated specially as they are the only four that
1856 * will be set when dynamic sources are expanded.
1858 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1860 /* XXX: It looks like $% and $! are reversed here */
1864 return (estrdup("$(.TARGET)"));
1867 return (estrdup("$(.ARCHIVE)"));
1870 return (estrdup("$(.PREFIX)"));
1873 return (estrdup("$(.MEMBER)"));
1875 *freeResult = FALSE;
1876 return (vp->err ? var_Error : varNoError);
1881 * Variable name was not found.
1883 *freeResult = FALSE;
1884 return (vp->err ? var_Error : varNoError);
1888 VarParse(VarParser *vp, Boolean *freeResult)
1891 /* assert(vp->ptr[0] == '$'); */
1893 vp->ptr++; /* consume '$' */
1895 if (vp->ptr[0] == '\0') {
1896 /* Error, there is only a dollar sign in the input string. */
1897 *freeResult = FALSE;
1898 return (vp->err ? var_Error : varNoError);
1900 } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
1901 /* multi letter variable name */
1902 return (VarParseLong(vp, freeResult));
1905 /* single letter variable name */
1906 return (VarParseShort(vp, freeResult));
1911 *-----------------------------------------------------------------------
1913 * Given the start of a variable invocation, extract the variable
1914 * name and find its value, then modify it according to the
1918 * The value of the variable or var_Error if the specification
1919 * is invalid. The number of characters in the specification
1920 * is placed in the variable pointed to by consumed. (for
1921 * invalid specifications, this is just 2 to skip the '$' and
1922 * the following letter, or 1 if '$' was the last character
1923 * in the string). A Boolean in *freeResult telling whether the
1924 * returned string should be freed by the caller.
1930 * It is assumed that Var_Parse() is called with input[0] == '$'.
1932 *-----------------------------------------------------------------------
1935 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1936 size_t *consumed, Boolean *freeResult)
1946 value = VarParse(&vp, freeResult);
1947 *consumed += vp.ptr - vp.input;
1952 *-----------------------------------------------------------------------
1954 * Substitute for all variables in the given string in the given context
1955 * If undefErr is TRUE, Parse_Error will be called when an undefined
1956 * variable is encountered.
1959 * The resulting string.
1962 * None. The old string must be freed by the caller
1963 *-----------------------------------------------------------------------
1966 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1968 Boolean errorReported;
1969 Buffer *buf; /* Buffer for forming things */
1972 * Set TRUE if an error has already been reported to prevent a
1973 * plethora of messages when recursing. XXXHB this comment sounds
1976 errorReported = FALSE;
1980 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1982 * A dollar sign may be escaped either with another
1983 * dollar sign. In such a case, we skip over the
1984 * escape character and store the dollar sign into
1985 * the buffer directly.
1987 Buf_AddByte(buf, (Byte)str[0]);
1990 } else if (str[0] == '$') {
1991 char *val; /* Value to substitute for a variable */
1992 size_t length; /* Length of the variable invocation */
1993 Boolean doFree; /* Set true if val should be freed */
1996 * Variable invocation.
2001 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
2003 const char *p = str + 2;
2006 * Scan up to the end of the
2009 while (*p != '\0' &&
2011 *p != CLOSE_PAREN &&
2012 *p != CLOSE_BRACE &&
2018 * A variable inside the
2019 * variable. We cannot expand
2020 * the external variable yet,
2021 * so we try again with the
2025 Buf_AppendRange(buf, str, p);
2030 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
2035 * we want to expand,
2039 while (*p != '$' && *p != '\0')
2042 Buf_AppendRange(buf, str, p);
2048 * Single letter variable
2051 if (var[1] == '\0' && var[0] == str[1]) {
2054 Buf_AddBytes(buf, 2, (const Byte *) str);
2065 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
2068 * When we come down here, val should either point to
2069 * the value of this variable, suitably modified, or
2070 * be NULL. Length should be the total length of the
2071 * potential variable invocation (from $ to end
2074 if (val == var_Error || val == varNoError) {
2076 * If performing old-time variable
2077 * substitution, skip over the variable and
2078 * continue with the substitution. Otherwise,
2079 * store the dollar sign and advance str so
2080 * we continue with the string...
2084 } else if (undefErr) {
2086 * If variable is undefined, complain
2087 * and skip the variable. The
2088 * complaint will stop us from doing
2089 * anything when the file is parsed.
2091 if (!errorReported) {
2092 Parse_Error(PARSE_FATAL,
2093 "Undefined variable \"%.*s\"", length, str);
2096 errorReported = TRUE;
2098 Buf_AddByte(buf, (Byte)*str);
2103 * We've now got a variable structure to
2104 * store in. But first, advance the string
2110 * Copy all the characters from the variable
2111 * value straight into the new string.
2113 Buf_Append(buf, val);
2120 * Skip as many characters as possible -- either to
2121 * the end of the string or to the next dollar sign
2122 * (variable invocation).
2124 const char *cp = str;
2128 } while (str[0] != '$' && str[0] != '\0');
2130 Buf_AppendRange(buf, cp, str);
2138 *-----------------------------------------------------------------------
2140 * Return the tail from each of a list of words. Used to set the
2141 * System V local variables.
2144 * The resulting string.
2149 *-----------------------------------------------------------------------
2152 Var_GetTail(char *file)
2155 return (VarModify(file, VarTail, (void *)NULL));
2159 *-----------------------------------------------------------------------
2161 * Find the leading components of a (list of) filename(s).
2162 * XXX: VarHead does not replace foo by ., as (sun) System V make
2166 * The leading components.
2171 *-----------------------------------------------------------------------
2174 Var_GetHead(char *file)
2177 return (VarModify(file, VarHead, (void *)NULL));
2181 *-----------------------------------------------------------------------
2183 * Initialize the module
2189 * The VAR_CMD and VAR_GLOBAL contexts are created
2190 *-----------------------------------------------------------------------
2196 VAR_GLOBAL = Targ_NewGN("Global");
2197 VAR_CMD = Targ_NewGN("Command");
2201 *-----------------------------------------------------------------------
2203 * print all variables in a context
2204 *-----------------------------------------------------------------------
2207 Var_Dump(const GNode *ctxt)
2212 LST_FOREACH(ln, &ctxt->context) {
2214 printf("%-16s = %s\n", v->name,
2215 (const char *)Buf_GetAll(v->val, NULL));