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.184 2005/04/15 20:45:48 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 OPEN_PAREN '('
147 #define CLOSE_PAREN ')'
148 #define OPEN_BRACE '{'
149 #define CLOSE_BRACE '}'
152 * Create a Var object.
154 * @param name Name of variable.
155 * @param value Value of variable.
156 * @param flags Flags set on variable.
159 VarCreate(const char name[], const char value[], int flags)
163 v = emalloc(sizeof(Var));
164 v->name = estrdup(name);
165 v->val = Buf_Init(0);
169 Buf_Append(v->val, value);
175 * Destroy a Var object.
177 * @param v Object to destroy.
178 * @param f true if internal buffer in Buffer object is to be
182 VarDestroy(Var *v, Boolean f)
185 Buf_Destroy(v->val, f);
191 * Find a variable in a variable list.
194 VarLookup(Lst *vlist, const char *name)
198 LST_FOREACH(ln, vlist)
199 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0)
200 return (Lst_Datum(ln));
205 *-----------------------------------------------------------------------
206 * VarPossiblyExpand --
207 * Expand a variable name's embedded variables in the given context.
210 * The contents of name, possibly expanded.
211 *-----------------------------------------------------------------------
214 VarPossiblyExpand(const char *name, GNode *ctxt)
218 if (strchr(name, '$') != NULL) {
219 buf = Var_Subst(NULL, name, ctxt, 0);
220 return (Buf_Peel(buf));
222 return estrdup(name);
227 * If the variable name begins with a '.', it could very well be
228 * one of the local ones. We check the name against all the local
229 * variables and substitute the short version in for 'name' if it
230 * matches one of them.
233 VarLocal(const char name[])
235 if (name[0] == '.') {
238 if (!strcmp(name, ".ALLSRC"))
240 if (!strcmp(name, ".ARCHIVE"))
244 if (!strcmp(name, ".IMPSRC"))
248 if (!strcmp(name, ".MEMBER"))
252 if (!strcmp(name, ".OODATE"))
256 if (!strcmp(name, ".PREFIX"))
260 if (!strcmp(name, ".TARGET"))
271 * Find the given variable in the given context and the enviornment.
274 * A pointer to the structure describing the desired variable or
275 * NULL if the variable does not exist.
278 VarFindEnv(const char name[], GNode *ctxt)
283 name = VarLocal(name);
285 /* First look for the variable in the given context. */
286 if ((var = VarLookup(&ctxt->context, name)) != NULL)
289 /* Look for the variable in the environment. */
290 if ((env = getenv(name)) != NULL) {
291 /* craft this variable from the environment value */
292 return (VarCreate(name, env, VAR_FROM_ENV));
299 * Look for the variable in the given context.
302 VarFindOnly(const char name[], GNode *ctxt)
305 return VarLookup(&ctxt->context, VarLocal(name));
309 * Look for the variable in all contexts.
312 VarFindAny(const char name[], GNode *ctxt)
314 Boolean localCheckEnvFirst;
319 name = VarLocal(name);
322 * Note whether this is one of the specific variables we were told
323 * through the -E flag to use environment-variable-override for.
325 localCheckEnvFirst = FALSE;
326 LST_FOREACH(ln, &envFirstVars) {
327 if (strcmp(Lst_Datum(ln), name) == 0) {
328 localCheckEnvFirst = TRUE;
334 * First look for the variable in the given context. If it's not there,
335 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
336 * in that order, depending on the FIND_* flags in 'flags'
338 if ((var = VarLookup(&ctxt->context, name)) != NULL)
341 /* not there - try command line context */
342 if (ctxt != VAR_CMD) {
343 if ((var = VarLookup(&VAR_CMD->context, name)) != NULL)
347 /* not there - try global context, but only if not -e/-E */
348 if (ctxt != VAR_GLOBAL && (!checkEnvFirst && !localCheckEnvFirst)) {
349 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
353 /* look in the environment */
354 if ((env = getenv(name)) != NULL) {
355 /* craft this variable from the environment value */
356 return (VarCreate(name, env, VAR_FROM_ENV));
359 /* deferred check for the environment (in case of -e/-E) */
360 if ((ctxt != VAR_GLOBAL) && (checkEnvFirst || localCheckEnvFirst)) {
361 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
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 LST_FOREACH(ln, &ctxt->context) {
410 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0) {
411 VarDestroy(Lst_Datum(ln), TRUE);
412 Lst_Remove(&ctxt->context, ln);
419 *-----------------------------------------------------------------------
421 * Set the variable name to the value val in the given context.
427 * If the variable doesn't yet exist, a new record is created for it.
428 * Else the old value is freed and the new one stuck in its place
431 * The variable is searched for only in its context before being
432 * created in that context. I.e. if the context is VAR_GLOBAL,
433 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
434 * VAR_CMD->context is searched. This is done to avoid the literally
435 * thousands of unnecessary strcmp's that used to be done to
436 * set, say, $(@) or $(<).
437 *-----------------------------------------------------------------------
440 Var_Set(const char *name, const char *val, GNode *ctxt)
446 * We only look for a variable in the given context since anything
447 * set here will override anything in a lower context, so there's not
448 * much point in searching them all just to save a bit of memory...
450 n = VarPossiblyExpand(name, ctxt);
451 v = VarFindOnly(n, ctxt);
453 VarAdd(n, val, ctxt);
456 Buf_Append(v->val, val);
458 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
461 * Any variables given on the command line are automatically exported
462 * to the environment (as per POSIX standard)
464 if (ctxt == VAR_CMD || (v != NULL && (v->flags & VAR_TO_ENV))) {
472 * Set the VAR_TO_ENV flag on a variable
475 Var_SetEnv(const char *name, GNode *ctxt)
479 v = VarFindAny(name, ctxt);
481 Error("Cannot set environment flag on non-existant variable %s", name);
483 if ((v->flags & VAR_TO_ENV) == 0) {
484 v->flags |= VAR_TO_ENV;
485 setenv(v->name, Buf_Data(v->val), 1);
491 *-----------------------------------------------------------------------
493 * The variable of the given name has the given value appended to it in
500 * If the variable doesn't exist, it is created. Else the strings
501 * are concatenated (with a space in between).
504 * Only if the variable is being sought in the global context is the
505 * environment searched.
506 * XXX: Knows its calling circumstances in that if called with ctxt
507 * an actual target, it will only search that context since only
508 * a local variable could be being appended to. This is actually
509 * a big win and must be tolerated.
510 *-----------------------------------------------------------------------
513 Var_Append(const char *name, const char *val, GNode *ctxt)
518 n = VarPossiblyExpand(name, ctxt);
519 if (ctxt == VAR_GLOBAL) {
520 v = VarFindEnv(n, ctxt);
522 v = VarFindOnly(n, ctxt);
525 VarAdd(n, val, ctxt);
527 } else if (v->flags & VAR_FROM_ENV) {
528 Buf_AddByte(v->val, (Byte)' ');
529 Buf_Append(v->val, val);
530 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
532 * If the original variable came from the
533 * environment, we have to install it in the global
534 * context (we could place it in the environment, but
535 * then we should provide a way to export other
538 v->flags &= ~VAR_FROM_ENV;
539 Lst_AtFront(&ctxt->context, v);
542 Buf_AddByte(v->val, (Byte)' ');
543 Buf_Append(v->val, val);
544 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
550 *-----------------------------------------------------------------------
552 * See if the given variable exists.
555 * TRUE if it does, FALSE if it doesn't
560 *-----------------------------------------------------------------------
563 Var_Exists(const char *name, GNode *ctxt)
568 n = VarPossiblyExpand(name, ctxt);
569 v = VarFindAny(n, ctxt);
573 } else if (v->flags & VAR_FROM_ENV) {
584 *-----------------------------------------------------------------------
586 * Return the value of the named variable in the given context
589 * The value if the variable exists, NULL if it doesn't
593 *-----------------------------------------------------------------------
596 Var_Value(const char *name, GNode *ctxt, char **frp)
602 n = VarPossiblyExpand(name, ctxt);
603 v = VarFindAny(n, ctxt);
607 } else if (v->flags & VAR_FROM_ENV) {
608 p = Buf_Data(v->val);
610 VarDestroy(v, FALSE);
612 p = Buf_Data(v->val);
620 *-----------------------------------------------------------------------
622 * Modify each of the words of the passed string using the given
623 * function. Used to implement all modifiers.
626 * A string of all the words modified appropriately.
629 * Uses brk_string() so it invalidates any previous call to
632 *-----------------------------------------------------------------------
635 VarModify(const char *str, VarModifyProc *modProc, void *datum)
637 char **av; /* word list [first word does not count] */
639 Buffer *buf; /* Buffer for the new string */
640 Boolean addSpace; /* TRUE if need to add a space to the buffer
641 * before adding the trimmed word */
644 av = brk_string(str, &ac, FALSE);
649 for (i = 1; i < ac; i++)
650 addSpace = (*modProc)(av[i], addSpace, buf, datum);
652 return (Buf_Peel(buf));
656 *-----------------------------------------------------------------------
658 * Sort the words in the string.
661 * str String whose words should be sorted
662 * cmp A comparison function to control the ordering
665 * A string containing the words sorted
668 * Uses brk_string() so it invalidates any previous call to
671 *-----------------------------------------------------------------------
674 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
681 av = brk_string(str, &ac, FALSE);
682 qsort(av + 1, ac - 1, sizeof(char *), cmp);
685 for (i = 1; i < ac; i++) {
686 Buf_Append(buf, av[i]);
687 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
690 return (Buf_Peel(buf));
694 SortIncreasing(const void *l, const void *r)
697 return (strcmp(*(const char* const*)l, *(const char* const*)r));
701 *-----------------------------------------------------------------------
703 * Pass through the tstr looking for 1) escaped delimiters,
704 * '$'s and backslashes (place the escaped character in
705 * uninterpreted) and 2) unescaped $'s that aren't before
706 * the delimiter (expand the variable substitution).
707 * Return the expanded string or NULL if the delimiter was missing
708 * If pattern is specified, handle escaped ampersands, and replace
709 * unescaped ampersands with the lhs of the pattern.
712 * A string of all the words modified appropriately.
713 * If length is specified, return the string length of the buffer
714 * If flags is specified and the last character of the pattern is a
715 * $ set the VAR_MATCH_END bit of flags.
719 *-----------------------------------------------------------------------
722 VarGetPattern(VarParser *vp, int delim, int *flags, VarPattern *patt)
729 * Skim through until the matching delimiter is found; pick up
730 * variable substitutions on the way. Also allow backslashes to quote
731 * the delimiter, $, and \, but don't touch other backslashes.
733 while (*vp->ptr != '\0') {
734 if (*vp->ptr == delim) {
737 } else if ((vp->ptr[0] == '\\') &&
738 ((vp->ptr[1] == delim) ||
739 (vp->ptr[1] == '\\') ||
740 (vp->ptr[1] == '$') ||
741 (vp->ptr[1] == '&' && patt != NULL))) {
742 vp->ptr++; /* consume backslash */
743 Buf_AddByte(buf, (Byte)vp->ptr[0]);
746 } else if (vp->ptr[0] == '$') {
747 if (vp->ptr[1] == delim) {
749 Buf_AddByte(buf, (Byte)vp->ptr[0]);
753 * Unescaped $ at end of patt =>
754 * anchor patt at end.
756 *flags |= VAR_MATCH_END;
770 * If unescaped dollar sign not
771 * before the delimiter, assume it's
772 * a variable substitution and
775 rval = VarParse(&subvp, &rfree);
776 Buf_Append(buf, rval);
781 } else if (vp->ptr[0] == '&' && patt != NULL) {
782 Buf_AppendBuf(buf, patt->lhs);
785 Buf_AddByte(buf, (Byte)vp->ptr[0]);
790 Buf_Destroy(buf, TRUE);
795 *-----------------------------------------------------------------------
797 * Quote shell meta-characters in the string
805 *-----------------------------------------------------------------------
808 Var_Quote(const char *str)
811 /* This should cover most shells :-( */
812 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
814 buf = Buf_Init(MAKE_BSIZE);
815 for (; *str; str++) {
816 if (strchr(meta, *str) != NULL)
817 Buf_AddByte(buf, (Byte)'\\');
818 Buf_AddByte(buf, (Byte)*str);
821 return (Buf_Peel(buf));
825 *-----------------------------------------------------------------------
827 * Print the error caused by a regcomp or regexec call.
833 * An error gets printed.
835 *-----------------------------------------------------------------------
838 VarREError(int err, regex_t *pat, const char *str)
843 errlen = regerror(err, pat, 0, 0);
844 errbuf = emalloc(errlen);
845 regerror(err, pat, errbuf, errlen);
846 Error("%s: %s", str, errbuf);
851 * Make sure this variable is fully expanded.
854 VarExpand(Var *v, VarParser *vp)
859 if (v->flags & VAR_IN_USE) {
860 Fatal("Variable %s is recursive.", v->name);
864 v->flags |= VAR_IN_USE;
867 * Before doing any modification, we have to make sure the
868 * value has been fully expanded. If it looks like recursion
869 * might be necessary (there's a dollar sign somewhere in the
870 * variable's value) we just call Var_Subst to do any other
871 * substitutions that are necessary. Note that the value
872 * returned by Var_Subst will have been
873 * dynamically-allocated, so it will need freeing when we
876 value = Buf_Data(v->val);
877 if (strchr(value, '$') == NULL) {
878 result = strdup(value);
882 buf = Var_Subst(NULL, value, vp->ctxt, vp->err);
883 result = Buf_Peel(buf);
886 v->flags &= ~VAR_IN_USE;
892 * Select only those words in value that match the modifier.
895 modifier_M(VarParser *vp, const char value[], char endc)
902 modifier = vp->ptr[0];
903 vp->ptr++; /* consume 'M' or 'N' */
906 * Compress the \:'s out of the pattern, so allocate enough
907 * room to hold the uncompressed pattern and compress the
908 * pattern into that space.
910 patt = estrdup(vp->ptr);
912 while (vp->ptr[0] != '\0') {
913 if (vp->ptr[0] == endc || vp->ptr[0] == ':') {
916 if (vp->ptr[0] == '\\' &&
917 (vp->ptr[1] == endc || vp->ptr[1] == ':')) {
918 vp->ptr++; /* consume backslash */
926 if (modifier == 'M') {
927 newValue = VarModify(value, VarMatch, patt);
929 newValue = VarModify(value, VarNoMatch, patt);
937 * Substitute the replacement string for the pattern. The substitution
938 * is applied to each word in value.
941 modifier_S(VarParser *vp, const char value[], Var *v)
949 vp->ptr++; /* consume 'S' */
951 delim = *vp->ptr; /* used to find end of pattern */
952 vp->ptr++; /* consume 1st delim */
955 * If pattern begins with '^', it is anchored to the start of the
956 * word -- skip over it and flag pattern.
958 if (*vp->ptr == '^') {
959 patt.flags |= VAR_MATCH_START;
963 patt.lhs = VarGetPattern(vp, delim, &patt.flags, NULL);
964 if (patt.lhs == NULL) {
966 * LHS didn't end with the delim, complain and exit.
968 Fatal("Unclosed substitution for %s (%c missing)",
972 vp->ptr++; /* consume 2nd delim */
974 patt.rhs = VarGetPattern(vp, delim, NULL, &patt);
975 if (patt.rhs == NULL) {
977 * RHS didn't end with the delim, complain and exit.
979 Fatal("Unclosed substitution for %s (%c missing)",
983 vp->ptr++; /* consume last delim */
986 * Check for global substitution. If 'g' after the final delimiter,
987 * substitution is global and is marked that way.
989 if (vp->ptr[0] == 'g') {
990 patt.flags |= VAR_SUB_GLOBAL;
995 * Global substitution of the empty string causes an infinite number
996 * of matches, unless anchored by '^' (start of string) or '$' (end
997 * of string). Catch the infinite substitution here. Note that flags
998 * can only contain the 3 bits we're interested in so we don't have
999 * to mask unrelated bits. We can test for equality.
1001 if (Buf_Size(patt.lhs) == 0 && patt.flags == VAR_SUB_GLOBAL)
1002 Fatal("Global substitution of the empty string");
1004 newValue = VarModify(value, VarSubstitute, &patt);
1007 * Free the two strings.
1016 modifier_C(VarParser *vp, char value[], Var *v)
1025 vp->ptr++; /* consume 'C' */
1027 delim = *vp->ptr; /* delimiter between sections */
1029 vp->ptr++; /* consume 1st delim */
1031 patt.lhs = VarGetPattern(vp, delim, NULL, NULL);
1032 if (patt.lhs == NULL) {
1033 Fatal("Unclosed substitution for %s (%c missing)",
1037 vp->ptr++; /* consume 2st delim */
1039 patt.rhs = VarGetPattern(vp, delim, NULL, NULL);
1040 if (patt.rhs == NULL) {
1041 Fatal("Unclosed substitution for %s (%c missing)",
1045 vp->ptr++; /* consume last delim */
1049 patt.flags |= VAR_SUB_GLOBAL;
1050 vp->ptr++; /* consume 'g' */
1053 patt.flags |= VAR_SUB_ONE;
1054 vp->ptr++; /* consume '1' */
1060 error = regcomp(&patt.re, Buf_Data(patt.lhs), REG_EXTENDED);
1062 VarREError(error, &patt.re, "RE substitution error");
1068 patt.nsub = patt.re.re_nsub + 1;
1073 patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1075 newValue = VarModify(value, VarRESubstitute, &patt);
1086 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1090 * This can either be a bogus modifier or a System-V substitution
1100 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1105 * First we make a pass through the string trying to verify it is a
1106 * SYSV-make-style translation: it must be: <string1>=<string2>)
1111 while (*cp != '\0' && cnt) {
1114 /* continue looking for endc */
1115 } else if (*cp == endc)
1117 else if (*cp == startc)
1123 if (*cp == endc && eqFound) {
1125 * Now we break this sucker into the lhs and rhs.
1127 patt.lhs = VarGetPattern(vp, '=', &patt.flags, NULL);
1128 if (patt.lhs == NULL) {
1129 Fatal("Unclosed substitution for %s (%c missing)",
1132 vp->ptr++; /* consume '=' */
1134 patt.rhs = VarGetPattern(vp, endc, NULL, &patt);
1135 if (patt.rhs == NULL) {
1136 Fatal("Unclosed substitution for %s (%c missing)",
1141 * SYSV modifications happen through the whole string. Note
1142 * the pattern is anchored at the end.
1144 newStr = VarModify(value, VarSYSVMatch, &patt);
1151 Error("Unknown modifier '%c'\n", *vp->ptr);
1153 while (*vp->ptr != '\0') {
1154 if (*vp->ptr == endc && *vp->ptr == ':') {
1166 * Now we need to apply any modifiers the user wants applied.
1169 * words which match the given <pattern>.
1170 * <pattern> is of the standard file
1172 * :S<d><pat1><d><pat2><d>[g]
1173 * Substitute <pat2> for <pat1> in the value
1174 * :C<d><pat1><d><pat2><d>[g]
1175 * Substitute <pat2> for regex <pat1> in the value
1176 * :H Substitute the head of each word
1177 * :T Substitute the tail of each word
1178 * :E Substitute the extension (minus '.') of
1180 * :R Substitute the root of each word
1181 * (pathname minus the suffix).
1183 * Like :S, but the rhs goes to the end of
1185 * :U Converts variable to upper-case.
1186 * :L Converts variable to lower-case.
1188 * XXXHB update this comment or remove it and point to the man page.
1191 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1196 value = VarExpand(v, vp);
1199 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1201 vp->ptr++; /* consume first colon */
1203 while (*vp->ptr != '\0') {
1204 char *newStr; /* New value to return */
1206 if (*vp->ptr == endc) {
1210 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1214 newStr = modifier_M(vp, value, endc);
1217 newStr = modifier_S(vp, value, v);
1220 newStr = modifier_C(vp, value, v);
1223 if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1225 if ((vp->ptr[0] == 's') &&
1226 (vp->ptr[1] == 'h') &&
1227 (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1231 buf = Cmd_Exec(value, &error);
1232 newStr = Buf_Peel(buf);
1235 Error(error, value);
1240 newStr = sysVvarsub(vp, startc, v, value);
1245 switch (vp->ptr[0]) {
1250 buf = Buf_Init(MAKE_BSIZE);
1251 for (cp = value; *cp; cp++)
1252 Buf_AddByte(buf, (Byte)tolower(*cp));
1254 newStr = Buf_Peel(buf);
1260 newStr = VarSortWords(value, SortIncreasing);
1264 newStr = Var_Quote(value);
1268 newStr = VarModify(value, VarTail, NULL);
1275 buf = Buf_Init(MAKE_BSIZE);
1276 for (cp = value; *cp; cp++)
1277 Buf_AddByte(buf, (Byte)toupper(*cp));
1279 newStr = Buf_Peel(buf);
1285 newStr = VarModify(value, VarHead, NULL);
1289 newStr = VarModify(value, VarSuffix, NULL);
1293 newStr = VarModify(value, VarRoot, NULL);
1297 newStr = sysVvarsub(vp, startc, v, value);
1303 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1309 *freeResult = (value == var_Error) ? FALSE : TRUE;
1311 if (vp->ptr[0] == ':') {
1312 vp->ptr++; /* consume colon */
1320 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1327 vname = Buf_GetAll(buf, &vlen);
1329 v = VarFindAny(vname, vp->ctxt);
1331 value = ParseModifier(vp, startc, v, freeResult);
1333 if (v->flags & VAR_FROM_ENV) {
1334 VarDestroy(v, TRUE);
1339 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1342 * Still need to get to the end of the variable
1343 * specification, so kludge up a Var structure for the
1346 v = VarCreate(vname, NULL, VAR_JUNK);
1347 value = ParseModifier(vp, startc, v, freeResult);
1351 VarDestroy(v, TRUE);
1353 consumed = vp->ptr - vp->input + 1;
1355 * If substituting a local variable in a non-local context,
1356 * assume it's for dynamic source stuff. We have to handle
1357 * this specially and return the longhand for the variable
1358 * with the dollar sign escaped so it makes it back to the
1359 * caller. Only four of the local variables are treated
1360 * specially as they are the only four that will be set when
1361 * dynamic sources are expanded.
1364 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1365 if (strchr("!%*@", vname[0]) != NULL) {
1366 value = emalloc(consumed + 1);
1367 strncpy(value, vp->input, consumed);
1368 value[consumed] = '\0';
1376 isupper((unsigned char)vname[1])) {
1377 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1378 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1379 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1380 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1381 value = emalloc(consumed + 1);
1382 strncpy(value, vp->input, consumed);
1383 value[consumed] = '\0';
1390 *freeResult = FALSE;
1391 return (vp->err ? var_Error : varNoError);
1394 * Check for D and F forms of local variables since we're in
1395 * a local context and the name is the right length.
1398 (vname[1] == 'F' || vname[1] == 'D') &&
1399 (strchr("!%*<>@", vname[0]) != NULL)) {
1405 v = VarFindOnly(name, vp->ctxt);
1407 value = ParseModifier(vp, startc, v, freeResult);
1413 * Still need to get to the end of the variable
1414 * specification, so kludge up a Var structure for the
1417 v = VarCreate(vname, NULL, VAR_JUNK);
1418 value = ParseModifier(vp, startc, v, freeResult);
1422 VarDestroy(v, TRUE);
1424 *freeResult = FALSE;
1425 return (vp->err ? var_Error : varNoError);
1430 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1437 vname = Buf_GetAll(buf, &vlen);
1439 v = VarFindAny(vname, vp->ctxt);
1441 value = VarExpand(v, vp);
1443 if (v->flags & VAR_FROM_ENV) {
1444 VarDestroy(v, TRUE);
1451 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1452 size_t consumed = vp->ptr - vp->input + 1;
1455 * If substituting a local variable in a non-local context,
1456 * assume it's for dynamic source stuff. We have to handle
1457 * this specially and return the longhand for the variable
1458 * with the dollar sign escaped so it makes it back to the
1459 * caller. Only four of the local variables are treated
1460 * specially as they are the only four that will be set when
1461 * dynamic sources are expanded.
1464 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1465 if (strchr("!%*@", vname[0]) != NULL) {
1466 value = emalloc(consumed + 1);
1467 strncpy(value, vp->input, consumed);
1468 value[consumed] = '\0';
1476 isupper((unsigned char)vname[1])) {
1477 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1478 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1479 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1480 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1481 value = emalloc(consumed + 1);
1482 strncpy(value, vp->input, consumed);
1483 value[consumed] = '\0';
1491 * Check for D and F forms of local variables since we're in
1492 * a local context and the name is the right length.
1495 (vname[1] == 'F' || vname[1] == 'D') &&
1496 (strchr("!%*<>@", vname[0]) != NULL)) {
1502 v = VarFindOnly(name, vp->ctxt);
1506 * No need for nested expansion or anything,
1507 * as we're the only one who sets these
1508 * things and we sure don't put nested
1509 * invocations in them...
1511 val = Buf_Data(v->val);
1513 if (vname[1] == 'D') {
1514 val = VarModify(val, VarHead, NULL);
1516 val = VarModify(val, VarTail, NULL);
1525 *freeResult = FALSE;
1526 return (vp->err ? var_Error : varNoError);
1530 * Parse a multi letter variable name, and return it's value.
1533 VarParseLong(VarParser *vp, Boolean *freeResult)
1540 buf = Buf_Init(MAKE_BSIZE);
1542 startc = vp->ptr[0];
1543 vp->ptr++; /* consume opening paren or brace */
1545 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1548 * Process characters until we reach an end character or a colon,
1549 * replacing embedded variables as we go.
1551 while (*vp->ptr != '\0') {
1552 if (*vp->ptr == endc) {
1553 value = ParseRestEnd(vp, buf, freeResult);
1554 vp->ptr++; /* consume closing paren or brace */
1555 Buf_Destroy(buf, TRUE);
1558 } else if (*vp->ptr == ':') {
1559 value = ParseRestModifier(vp, startc, buf, freeResult);
1560 vp->ptr++; /* consume closing paren or brace */
1561 Buf_Destroy(buf, TRUE);
1564 } else if (*vp->ptr == '$') {
1574 rval = VarParse(&subvp, &rfree);
1575 if (rval == var_Error) {
1576 Fatal("Error expanding embedded variable.");
1578 Buf_Append(buf, rval);
1581 vp->ptr = subvp.ptr;
1583 Buf_AddByte(buf, (Byte)*vp->ptr);
1588 /* If we did not find the end character, return var_Error */
1589 Buf_Destroy(buf, TRUE);
1590 *freeResult = FALSE;
1595 * Parse a single letter variable name, and return it's value.
1598 VarParseShort(VarParser *vp, Boolean *freeResult)
1604 vname[0] = vp->ptr[0];
1607 vp->ptr++; /* consume single letter */
1609 v = VarFindAny(vname, vp->ctxt);
1611 value = VarExpand(v, vp);
1613 if (v->flags & VAR_FROM_ENV) {
1614 VarDestroy(v, TRUE);
1622 * If substituting a local variable in a non-local context, assume
1623 * it's for dynamic source stuff. We have to handle this specially
1624 * and return the longhand for the variable with the dollar sign
1625 * escaped so it makes it back to the caller. Only four of the local
1626 * variables are treated specially as they are the only four that
1627 * will be set when dynamic sources are expanded.
1629 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1631 /* XXX: It looks like $% and $! are reversed here */
1635 return (estrdup("$(.TARGET)"));
1638 return (estrdup("$(.ARCHIVE)"));
1641 return (estrdup("$(.PREFIX)"));
1644 return (estrdup("$(.MEMBER)"));
1646 *freeResult = FALSE;
1647 return (vp->err ? var_Error : varNoError);
1651 /* Variable name was not found. */
1652 *freeResult = FALSE;
1653 return (vp->err ? var_Error : varNoError);
1657 VarParse(VarParser *vp, Boolean *freeResult)
1660 vp->ptr++; /* consume '$' or last letter of conditional */
1662 if (vp->ptr[0] == '\0') {
1663 /* Error, there is only a dollar sign in the input string. */
1664 *freeResult = FALSE;
1665 return (vp->err ? var_Error : varNoError);
1667 } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
1668 /* multi letter variable name */
1669 return (VarParseLong(vp, freeResult));
1672 /* single letter variable name */
1673 return (VarParseShort(vp, freeResult));
1678 *-----------------------------------------------------------------------
1680 * Given the start of a variable invocation, extract the variable
1681 * name and find its value, then modify it according to the
1685 * The value of the variable or var_Error if the specification
1686 * is invalid. The number of characters in the specification
1687 * is placed in the variable pointed to by consumed. (for
1688 * invalid specifications, this is just 2 to skip the '$' and
1689 * the following letter, or 1 if '$' was the last character
1690 * in the string). A Boolean in *freeResult telling whether the
1691 * returned string should be freed by the caller.
1695 *-----------------------------------------------------------------------
1698 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1699 size_t *consumed, Boolean *freeResult)
1709 value = VarParse(&vp, freeResult);
1710 *consumed += vp.ptr - vp.input;
1715 *-----------------------------------------------------------------------
1717 * Substitute for all variables in the given string in the given context
1718 * If err is TRUE, Parse_Error will be called when an undefined
1719 * variable is encountered.
1722 * The resulting string.
1725 * None. The old string must be freed by the caller
1726 *-----------------------------------------------------------------------
1729 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean err)
1731 Boolean errorReported;
1732 Buffer *buf; /* Buffer for forming things */
1735 * Set TRUE if an error has already been reported to prevent a
1736 * plethora of messages when recursing. XXXHB this comment sounds
1739 errorReported = FALSE;
1743 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1745 * A dollar sign may be escaped either with another
1746 * dollar sign. In such a case, we skip over the
1747 * escape character and store the dollar sign into
1748 * the buffer directly.
1750 Buf_AddByte(buf, (Byte)str[0]);
1753 } else if (str[0] == '$') {
1755 * Variable invocation.
1760 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1762 const char *p = str + 2;
1765 * Scan up to the end of the
1768 while (*p != '\0' &&
1770 *p != CLOSE_PAREN &&
1771 *p != CLOSE_BRACE &&
1777 * A variable inside the
1778 * variable. We cannot expand
1779 * the external variable yet,
1780 * so we try again with the
1784 Buf_AppendRange(buf, str, p);
1789 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1794 * we want to expand,
1798 while (*p != '$' && *p != '\0')
1801 Buf_AppendRange(buf, str, p);
1807 * Single letter variable
1810 if (var[1] == '\0' && var[0] == str[1]) {
1813 Buf_AddBytes(buf, 2, (const Byte *) str);
1833 rval = VarParse(&subvp, &rfree);
1836 * When we come down here, val should either point to
1837 * the value of this variable, suitably modified, or
1838 * be NULL. Length should be the total length of the
1839 * potential variable invocation (from $ to end
1842 if (rval == var_Error || rval == varNoError) {
1844 * If performing old-time variable
1845 * substitution, skip over the variable and
1846 * continue with the substitution. Otherwise,
1847 * store the dollar sign and advance str so
1848 * we continue with the string...
1854 * If variable is undefined, complain
1855 * and skip the variable. The
1856 * complaint will stop us from doing
1857 * anything when the file is parsed.
1859 if (!errorReported) {
1860 Parse_Error(PARSE_FATAL,
1861 "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
1864 errorReported = TRUE;
1866 Buf_AddByte(buf, (Byte)*str);
1871 * We've now got a variable structure to
1872 * store in. But first, advance the string
1878 * Copy all the characters from the variable
1879 * value straight into the new string.
1881 Buf_Append(buf, rval);
1889 * Skip as many characters as possible -- either to
1890 * the end of the string or to the next dollar sign
1891 * (variable invocation).
1893 const char *cp = str;
1897 } while (str[0] != '$' && str[0] != '\0');
1899 Buf_AppendRange(buf, cp, str);
1907 *-----------------------------------------------------------------------
1909 * Return the tail from each of a list of words. Used to set the
1910 * System V local variables.
1913 * The resulting string.
1918 *-----------------------------------------------------------------------
1921 Var_GetTail(char *file)
1924 return (VarModify(file, VarTail, (void *)NULL));
1928 *-----------------------------------------------------------------------
1930 * Find the leading components of a (list of) filename(s).
1931 * XXX: VarHead does not replace foo by ., as (sun) System V make
1935 * The leading components.
1940 *-----------------------------------------------------------------------
1943 Var_GetHead(char *file)
1946 return (VarModify(file, VarHead, (void *)NULL));
1950 *-----------------------------------------------------------------------
1952 * Initialize the module
1958 * The VAR_CMD and VAR_GLOBAL contexts are created
1959 *-----------------------------------------------------------------------
1965 VAR_GLOBAL = Targ_NewGN("Global");
1966 VAR_CMD = Targ_NewGN("Command");
1970 *-----------------------------------------------------------------------
1972 * print all variables in a context
1973 *-----------------------------------------------------------------------
1976 Var_Dump(const GNode *ctxt)
1981 LST_FOREACH(ln, &ctxt->context) {
1983 printf("%-16s = %s\n", v->name, Buf_Data(v->val));