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.180 2005/03/23 05:02: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.
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)
228 if (strchr(name, '$') != NULL) {
229 buf = Var_Subst(NULL, name, ctxt, 0);
230 return (Buf_Peel(buf));
232 return estrdup(name);
237 *-----------------------------------------------------------------------
239 * Find the given variable in the given context and any other contexts
243 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
244 * FIND_CMD set means to look in the VAR_CMD context too
245 * FIND_ENV set means to look in the environment
248 * A pointer to the structure describing the desired variable or
249 * NULL if the variable does not exist.
253 *-----------------------------------------------------------------------
256 VarFind(const char *name, GNode *ctxt, int flags)
258 Boolean localCheckEnvFirst;
263 * If the variable name begins with a '.', it could very well be one of
264 * the local ones. We check the name against all the local variables
265 * and substitute the short version in for 'name' if it matches one of
268 if (name[0] == '.') {
271 if (!strcmp(name, ".ALLSRC"))
273 if (!strcmp(name, ".ARCHIVE"))
277 if (!strcmp(name, ".IMPSRC"))
281 if (!strcmp(name, ".MEMBER"))
285 if (!strcmp(name, ".OODATE"))
289 if (!strcmp(name, ".PREFIX"))
293 if (!strcmp(name, ".TARGET"))
302 * Note whether this is one of the specific variables we were told
303 * through the -E flag to use environment-variable-override for.
305 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
306 localCheckEnvFirst = TRUE;
308 localCheckEnvFirst = FALSE;
312 * First look for the variable in the given context. If it's not there,
313 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
314 * in that order, depending on the FIND_* flags in 'flags'
316 var = Lst_Find(&ctxt->context, name, VarCmp);
319 return (Lst_Datum(var));
322 /* not there - try command line context */
323 if ((flags & FIND_CMD) && (ctxt != VAR_CMD)) {
324 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
326 return (Lst_Datum(var));
329 /* not there - try global context, but only if not -e/-E */
330 if ((flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
331 !checkEnvFirst && !localCheckEnvFirst) {
332 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
334 return (Lst_Datum(var));
337 if (!(flags & FIND_ENV))
338 /* we were not told to look into the environment */
341 /* look in the environment */
342 if ((env = getenv(name)) != NULL) {
343 /* craft this variable from the environment value */
344 return (VarCreate(name, env, VAR_FROM_ENV));
347 /* deferred check for the environment (in case of -e/-E) */
348 if ((checkEnvFirst || localCheckEnvFirst) &&
349 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL)) {
350 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
352 return (Lst_Datum(var));
358 *-----------------------------------------------------------------------
360 * Add a new variable of name name and value val to the given context.
366 * The new variable is placed at the front of the given context
367 * The name and val arguments are duplicated so they may
369 *-----------------------------------------------------------------------
372 VarAdd(const char *name, const char *val, GNode *ctxt)
375 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
376 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
380 *-----------------------------------------------------------------------
382 * Remove a variable from a context.
388 * The Var structure is removed and freed.
390 *-----------------------------------------------------------------------
393 Var_Delete(const char *name, GNode *ctxt)
397 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
398 ln = Lst_Find(&ctxt->context, name, VarCmp);
400 VarDestroy(Lst_Datum(ln), TRUE);
401 Lst_Remove(&ctxt->context, ln);
406 *-----------------------------------------------------------------------
408 * Set the variable name to the value val in the given context.
414 * If the variable doesn't yet exist, a new record is created for it.
415 * Else the old value is freed and the new one stuck in its place
418 * The variable is searched for only in its context before being
419 * created in that context. I.e. if the context is VAR_GLOBAL,
420 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
421 * VAR_CMD->context is searched. This is done to avoid the literally
422 * thousands of unnecessary strcmp's that used to be done to
423 * set, say, $(@) or $(<).
424 *-----------------------------------------------------------------------
427 Var_Set(const char *name, const char *val, GNode *ctxt)
433 * We only look for a variable in the given context since anything
434 * set here will override anything in a lower context, so there's not
435 * much point in searching them all just to save a bit of memory...
437 n = VarPossiblyExpand(name, ctxt);
438 v = VarFind(n, ctxt, 0);
440 VarAdd(n, val, ctxt);
443 Buf_Append(v->val, val);
445 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
448 * Any variables given on the command line are automatically exported
449 * to the environment (as per POSIX standard)
451 if (ctxt == VAR_CMD || (v != NULL && (v->flags & VAR_TO_ENV))) {
459 * Set the VAR_TO_ENV flag on a variable
462 Var_SetEnv(const char *name, GNode *ctxt)
466 v = VarFind(name, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
468 Error("Cannot set environment flag on non-existant variable %s", name);
470 if ((v->flags & VAR_TO_ENV) == 0) {
471 v->flags |= VAR_TO_ENV;
472 setenv(v->name, Buf_Data(v->val), 1);
478 *-----------------------------------------------------------------------
480 * The variable of the given name has the given value appended to it in
487 * If the variable doesn't exist, it is created. Else the strings
488 * are concatenated (with a space in between).
491 * Only if the variable is being sought in the global context is the
492 * environment searched.
493 * XXX: Knows its calling circumstances in that if called with ctxt
494 * an actual target, it will only search that context since only
495 * a local variable could be being appended to. This is actually
496 * a big win and must be tolerated.
497 *-----------------------------------------------------------------------
500 Var_Append(const char *name, const char *val, GNode *ctxt)
505 n = VarPossiblyExpand(name, ctxt);
506 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
508 VarAdd(n, val, ctxt);
510 } else if (v->flags & VAR_FROM_ENV) {
511 Buf_AddByte(v->val, (Byte)' ');
512 Buf_Append(v->val, val);
513 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
515 * If the original variable came from the
516 * environment, we have to install it in the global
517 * context (we could place it in the environment, but
518 * then we should provide a way to export other
521 v->flags &= ~VAR_FROM_ENV;
522 Lst_AtFront(&ctxt->context, v);
525 Buf_AddByte(v->val, (Byte)' ');
526 Buf_Append(v->val, val);
527 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
533 *-----------------------------------------------------------------------
535 * See if the given variable exists.
538 * TRUE if it does, FALSE if it doesn't
543 *-----------------------------------------------------------------------
546 Var_Exists(const char *name, GNode *ctxt)
551 n = VarPossiblyExpand(name, ctxt);
552 v = VarFind(n, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
556 } else if (v->flags & VAR_FROM_ENV) {
567 *-----------------------------------------------------------------------
569 * Return the value of the named variable in the given context
572 * The value if the variable exists, NULL if it doesn't
576 *-----------------------------------------------------------------------
579 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 } else if (v->flags & VAR_FROM_ENV) {
591 p = estrdup(Buf_Data(v->val));
593 VarDestroy(v, FALSE);
595 p = Buf_Data(v->val);
603 *-----------------------------------------------------------------------
605 * Modify each of the words of the passed string using the given
606 * function. Used to implement all modifiers.
609 * A string of all the words modified appropriately.
612 * Uses brk_string() so it invalidates any previous call to
615 *-----------------------------------------------------------------------
618 VarModify(const char *str, VarModifyProc *modProc, void *datum)
620 char **av; /* word list [first word does not count] */
622 Buffer *buf; /* Buffer for the new string */
623 Boolean addSpace; /* TRUE if need to add a space to the buffer
624 * before adding the trimmed word */
627 av = brk_string(str, &ac, FALSE);
632 for (i = 1; i < ac; i++)
633 addSpace = (*modProc)(av[i], addSpace, buf, datum);
635 return (Buf_Peel(buf));
639 *-----------------------------------------------------------------------
641 * Sort the words in the string.
644 * str String whose words should be sorted
645 * cmp A comparison function to control the ordering
648 * A string containing the words sorted
651 * Uses brk_string() so it invalidates any previous call to
654 *-----------------------------------------------------------------------
657 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
664 av = brk_string(str, &ac, FALSE);
665 qsort(av + 1, ac - 1, sizeof(char *), cmp);
668 for (i = 1; i < ac; i++) {
669 Buf_Append(buf, av[i]);
670 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
673 return (Buf_Peel(buf));
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).
690 * Return the expanded string or NULL if the delimiter was missing
691 * If pattern is specified, handle escaped ampersands, and replace
692 * unescaped ampersands with the lhs of the pattern.
695 * A string of all the words modified appropriately.
696 * If length is specified, return the string length of the buffer
697 * If flags is specified and the last character of the pattern is a
698 * $ set the VAR_MATCH_END bit of flags.
702 *-----------------------------------------------------------------------
705 VarGetPattern(VarParser *vp, int delim, int *flags, VarPattern *patt)
712 * Skim through until the matching delimiter is found; pick up
713 * variable substitutions on the way. Also allow backslashes to quote
714 * the delimiter, $, and \, but don't touch other backslashes.
716 while (*vp->ptr != '\0') {
717 if (*vp->ptr == delim) {
720 } else if ((vp->ptr[0] == '\\') &&
721 ((vp->ptr[1] == delim) ||
722 (vp->ptr[1] == '\\') ||
723 (vp->ptr[1] == '$') ||
724 (vp->ptr[1] == '&' && patt != NULL))) {
725 vp->ptr++; /* consume backslash */
726 Buf_AddByte(buf, (Byte)vp->ptr[0]);
729 } else if (vp->ptr[0] == '$') {
730 if (vp->ptr[1] == delim) {
732 Buf_AddByte(buf, (Byte)vp->ptr[0]);
736 * Unescaped $ at end of patt =>
737 * anchor patt at end.
739 *flags |= VAR_MATCH_END;
753 * If unescaped dollar sign not
754 * before the delimiter, assume it's
755 * a variable substitution and
758 rval = VarParse(&subvp, &rfree);
759 Buf_Append(buf, rval);
764 } else if (vp->ptr[0] == '&' && patt != NULL) {
765 Buf_AppendBuf(buf, patt->lhs);
768 Buf_AddByte(buf, (Byte)vp->ptr[0]);
773 Buf_Destroy(buf, TRUE);
778 *-----------------------------------------------------------------------
780 * Quote shell meta-characters in the string
788 *-----------------------------------------------------------------------
791 Var_Quote(const char *str)
794 /* This should cover most shells :-( */
795 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
797 buf = Buf_Init(MAKE_BSIZE);
798 for (; *str; str++) {
799 if (strchr(meta, *str) != NULL)
800 Buf_AddByte(buf, (Byte)'\\');
801 Buf_AddByte(buf, (Byte)*str);
804 return (Buf_Peel(buf));
808 *-----------------------------------------------------------------------
810 * Print the error caused by a regcomp or regexec call.
816 * An error gets printed.
818 *-----------------------------------------------------------------------
821 VarREError(int err, regex_t *pat, const char *str)
826 errlen = regerror(err, pat, 0, 0);
827 errbuf = emalloc(errlen);
828 regerror(err, pat, errbuf, errlen);
829 Error("%s: %s", str, errbuf);
834 * Make sure this variable is fully expanded.
837 VarExpand(Var *v, VarParser *vp)
842 if (v->flags & VAR_IN_USE) {
843 Fatal("Variable %s is recursive.", v->name);
847 v->flags |= VAR_IN_USE;
850 * Before doing any modification, we have to make sure the
851 * value has been fully expanded. If it looks like recursion
852 * might be necessary (there's a dollar sign somewhere in the
853 * variable's value) we just call Var_Subst to do any other
854 * substitutions that are necessary. Note that the value
855 * returned by Var_Subst will have been
856 * dynamically-allocated, so it will need freeing when we
859 value = Buf_Data(v->val);
860 if (strchr(value, '$') == NULL) {
861 result = strdup(value);
865 buf = Var_Subst(NULL, value, vp->ctxt, vp->err);
866 result = Buf_Peel(buf);
869 v->flags &= ~VAR_IN_USE;
875 * Select only those words in value that match the modifier.
878 modifier_M(VarParser *vp, const char value[], char endc)
885 modifier = vp->ptr[0];
886 vp->ptr++; /* consume 'M' or 'N' */
889 * Compress the \:'s out of the pattern, so allocate enough
890 * room to hold the uncompressed pattern and compress the
891 * pattern into that space.
893 patt = estrdup(vp->ptr);
895 while (vp->ptr[0] != '\0') {
896 if (vp->ptr[0] == endc || vp->ptr[0] == ':') {
899 if (vp->ptr[0] == '\\' &&
900 (vp->ptr[1] == endc || vp->ptr[1] == ':')) {
901 vp->ptr++; /* consume backslash */
909 if (modifier == 'M') {
910 newValue = VarModify(value, VarMatch, patt);
912 newValue = VarModify(value, VarNoMatch, patt);
920 * Substitute the replacement string for the pattern. The substitution
921 * is applied to each word in value.
924 modifier_S(VarParser *vp, const char value[], Var *v)
932 vp->ptr++; /* consume 'S' */
934 delim = *vp->ptr; /* used to find end of pattern */
935 vp->ptr++; /* consume 1st delim */
938 * If pattern begins with '^', it is anchored to the start of the
939 * word -- skip over it and flag pattern.
941 if (*vp->ptr == '^') {
942 patt.flags |= VAR_MATCH_START;
946 patt.lhs = VarGetPattern(vp, delim, &patt.flags, NULL);
947 if (patt.lhs == NULL) {
949 * LHS didn't end with the delim, complain and exit.
951 Fatal("Unclosed substitution for %s (%c missing)",
955 vp->ptr++; /* consume 2nd delim */
957 patt.rhs = VarGetPattern(vp, delim, NULL, &patt);
958 if (patt.rhs == NULL) {
960 * RHS didn't end with the delim, complain and exit.
962 Fatal("Unclosed substitution for %s (%c missing)",
966 vp->ptr++; /* consume last delim */
969 * Check for global substitution. If 'g' after the final delimiter,
970 * substitution is global and is marked that way.
972 if (vp->ptr[0] == 'g') {
973 patt.flags |= VAR_SUB_GLOBAL;
978 * Global substitution of the empty string causes an infinite number
979 * of matches, unless anchored by '^' (start of string) or '$' (end
980 * of string). Catch the infinite substitution here. Note that flags
981 * can only contain the 3 bits we're interested in so we don't have
982 * to mask unrelated bits. We can test for equality.
984 if (Buf_Size(patt.lhs) == 0 && patt.flags == VAR_SUB_GLOBAL)
985 Fatal("Global substitution of the empty string");
987 newValue = VarModify(value, VarSubstitute, &patt);
990 * Free the two strings.
999 modifier_C(VarParser *vp, char value[], Var *v)
1008 vp->ptr++; /* consume 'C' */
1010 delim = *vp->ptr; /* delimiter between sections */
1012 vp->ptr++; /* consume 1st delim */
1014 patt.lhs = VarGetPattern(vp, delim, NULL, NULL);
1015 if (patt.lhs == NULL) {
1016 Fatal("Unclosed substitution for %s (%c missing)",
1020 vp->ptr++; /* consume 2st delim */
1022 patt.rhs = VarGetPattern(vp, delim, NULL, NULL);
1023 if (patt.rhs == NULL) {
1024 Fatal("Unclosed substitution for %s (%c missing)",
1028 vp->ptr++; /* consume last delim */
1032 patt.flags |= VAR_SUB_GLOBAL;
1033 vp->ptr++; /* consume 'g' */
1036 patt.flags |= VAR_SUB_ONE;
1037 vp->ptr++; /* consume '1' */
1043 error = regcomp(&patt.re, Buf_Data(patt.lhs), REG_EXTENDED);
1045 VarREError(error, &patt.re, "RE substitution error");
1051 patt.nsub = patt.re.re_nsub + 1;
1056 patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1058 newValue = VarModify(value, VarRESubstitute, &patt);
1069 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1073 * This can either be a bogus modifier or a System-V substitution
1083 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1088 * First we make a pass through the string trying to verify it is a
1089 * SYSV-make-style translation: it must be: <string1>=<string2>)
1094 while (*cp != '\0' && cnt) {
1097 /* continue looking for endc */
1098 } else if (*cp == endc)
1100 else if (*cp == startc)
1106 if (*cp == endc && eqFound) {
1108 * Now we break this sucker into the lhs and rhs.
1110 patt.lhs = VarGetPattern(vp, '=', &patt.flags, NULL);
1111 if (patt.lhs == NULL) {
1112 Fatal("Unclosed substitution for %s (%c missing)",
1115 vp->ptr++; /* consume '=' */
1117 patt.rhs = VarGetPattern(vp, endc, NULL, &patt);
1118 if (patt.rhs == NULL) {
1119 Fatal("Unclosed substitution for %s (%c missing)",
1124 * SYSV modifications happen through the whole string. Note
1125 * the pattern is anchored at the end.
1127 newStr = VarModify(value, VarSYSVMatch, &patt);
1134 Error("Unknown modifier '%c'\n", *vp->ptr);
1136 while (*vp->ptr != '\0') {
1137 if (*vp->ptr == endc && *vp->ptr == ':') {
1149 * Now we need to apply any modifiers the user wants applied.
1152 * words which match the given <pattern>.
1153 * <pattern> is of the standard file
1155 * :S<d><pat1><d><pat2><d>[g]
1156 * Substitute <pat2> for <pat1> in the value
1157 * :C<d><pat1><d><pat2><d>[g]
1158 * Substitute <pat2> for regex <pat1> in the value
1159 * :H Substitute the head of each word
1160 * :T Substitute the tail of each word
1161 * :E Substitute the extension (minus '.') of
1163 * :R Substitute the root of each word
1164 * (pathname minus the suffix).
1166 * Like :S, but the rhs goes to the end of
1168 * :U Converts variable to upper-case.
1169 * :L Converts variable to lower-case.
1171 * XXXHB update this comment or remove it and point to the man page.
1174 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1179 value = VarExpand(v, vp);
1182 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1184 vp->ptr++; /* consume first colon */
1186 while (*vp->ptr != '\0') {
1187 char *newStr; /* New value to return */
1189 if (*vp->ptr == endc) {
1193 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1197 newStr = modifier_M(vp, value, endc);
1200 newStr = modifier_S(vp, value, v);
1203 newStr = modifier_C(vp, value, v);
1206 if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1208 if ((vp->ptr[0] == 's') &&
1209 (vp->ptr[1] == 'h') &&
1210 (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1214 buf = Cmd_Exec(value, &error);
1215 newStr = Buf_Peel(buf);
1218 Error(error, value);
1223 newStr = sysVvarsub(vp, startc, v, value);
1228 switch (vp->ptr[0]) {
1233 buf = Buf_Init(MAKE_BSIZE);
1234 for (cp = value; *cp; cp++)
1235 Buf_AddByte(buf, (Byte)tolower(*cp));
1237 newStr = Buf_Peel(buf);
1243 newStr = VarSortWords(value, SortIncreasing);
1247 newStr = Var_Quote(value);
1251 newStr = VarModify(value, VarTail, NULL);
1258 buf = Buf_Init(MAKE_BSIZE);
1259 for (cp = value; *cp; cp++)
1260 Buf_AddByte(buf, (Byte)toupper(*cp));
1262 newStr = Buf_Peel(buf);
1268 newStr = VarModify(value, VarHead, NULL);
1272 newStr = VarModify(value, VarSuffix, NULL);
1276 newStr = VarModify(value, VarRoot, NULL);
1280 newStr = sysVvarsub(vp, startc, v, value);
1286 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1292 *freeResult = (value == var_Error) ? FALSE : TRUE;
1294 if (vp->ptr[0] == ':') {
1295 vp->ptr++; /* consume colon */
1303 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1310 vname = Buf_GetAll(buf, &vlen);
1312 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1314 value = ParseModifier(vp, startc, v, freeResult);
1316 if (v->flags & VAR_FROM_ENV) {
1317 VarDestroy(v, TRUE);
1322 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1323 size_t consumed = vp->ptr - vp->input + 1;
1326 * If substituting a local variable in a non-local context,
1327 * assume it's for dynamic source stuff. We have to handle
1328 * this specially and return the longhand for the variable
1329 * with the dollar sign escaped so it makes it back to the
1330 * caller. Only four of the local variables are treated
1331 * specially as they are the only four that will be set when
1332 * dynamic sources are expanded.
1335 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1336 if (strchr("!%*@", vname[0]) != NULL) {
1337 value = emalloc(consumed + 1);
1338 strncpy(value, vp->input, consumed);
1339 value[consumed] = '\0';
1347 isupper((unsigned char)vname[1])) {
1348 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1349 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1350 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1351 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1352 value = emalloc(consumed + 1);
1353 strncpy(value, vp->input, consumed);
1354 value[consumed] = '\0';
1362 * Check for D and F forms of local variables since we're in
1363 * a local context and the name is the right length.
1366 (vname[1] == 'F' || vname[1] == 'D') &&
1367 (strchr("!%*<>@", vname[0]) != NULL)) {
1373 v = VarFind(name, vp->ctxt, 0);
1375 value = ParseModifier(vp, startc, v, freeResult);
1382 * Still need to get to the end of the variable
1383 * specification, so kludge up a Var structure for the
1386 v = VarCreate(vname, NULL, VAR_JUNK);
1387 value = ParseModifier(vp, startc, v, freeResult);
1391 VarDestroy(v, TRUE);
1393 *freeResult = FALSE;
1394 return (vp->err ? var_Error : varNoError);
1398 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1405 vname = Buf_GetAll(buf, &vlen);
1407 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1409 value = VarExpand(v, vp);
1411 if (v->flags & VAR_FROM_ENV) {
1412 VarDestroy(v, TRUE);
1419 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1420 size_t consumed = vp->ptr - vp->input + 1;
1423 * If substituting a local variable in a non-local context,
1424 * assume it's for dynamic source stuff. We have to handle
1425 * this specially and return the longhand for the variable
1426 * with the dollar sign escaped so it makes it back to the
1427 * caller. Only four of the local variables are treated
1428 * specially as they are the only four that will be set when
1429 * dynamic sources are expanded.
1432 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1433 if (strchr("!%*@", vname[0]) != NULL) {
1434 value = emalloc(consumed + 1);
1435 strncpy(value, vp->input, consumed);
1436 value[consumed] = '\0';
1444 isupper((unsigned char)vname[1])) {
1445 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1446 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1447 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1448 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1449 value = emalloc(consumed + 1);
1450 strncpy(value, vp->input, consumed);
1451 value[consumed] = '\0';
1459 * Check for D and F forms of local variables since we're in
1460 * a local context and the name is the right length.
1463 (vname[1] == 'F' || vname[1] == 'D') &&
1464 (strchr("!%*<>@", vname[0]) != NULL)) {
1470 v = VarFind(name, vp->ctxt, 0);
1474 * No need for nested expansion or anything,
1475 * as we're the only one who sets these
1476 * things and we sure don't put nested
1477 * invocations in them...
1479 val = Buf_Data(v->val);
1481 if (vname[1] == 'D') {
1482 val = VarModify(val, VarHead, NULL);
1484 val = VarModify(val, VarTail, NULL);
1493 *freeResult = FALSE;
1494 return (vp->err ? var_Error : varNoError);
1498 * Parse a multi letter variable name, and return it's value.
1501 VarParseLong(VarParser *vp, Boolean *freeResult)
1508 buf = Buf_Init(MAKE_BSIZE);
1510 startc = vp->ptr[0];
1511 vp->ptr++; /* consume opening paren or brace */
1513 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1516 * Process characters until we reach an end character or a colon,
1517 * replacing embedded variables as we go.
1519 while (*vp->ptr != '\0') {
1520 if (*vp->ptr == endc) {
1521 value = ParseRestEnd(vp, buf, freeResult);
1522 vp->ptr++; /* consume closing paren or brace */
1523 Buf_Destroy(buf, TRUE);
1526 } else if (*vp->ptr == ':') {
1527 value = ParseRestModifier(vp, startc, buf, freeResult);
1528 vp->ptr++; /* consume closing paren or brace */
1529 Buf_Destroy(buf, TRUE);
1532 } else if (*vp->ptr == '$') {
1542 rval = VarParse(&subvp, &rfree);
1543 if (rval == var_Error) {
1544 Fatal("Error expanding embedded variable.");
1546 Buf_Append(buf, rval);
1549 vp->ptr = subvp.ptr;
1551 Buf_AddByte(buf, (Byte)*vp->ptr);
1556 /* If we did not find the end character, return var_Error */
1557 Buf_Destroy(buf, TRUE);
1558 *freeResult = FALSE;
1563 * Parse a single letter variable name, and return it's value.
1566 VarParseShort(VarParser *vp, Boolean *freeResult)
1572 vname[0] = vp->ptr[0];
1575 vp->ptr++; /* consume single letter */
1577 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1579 value = VarExpand(v, vp);
1581 if (v->flags & VAR_FROM_ENV) {
1582 VarDestroy(v, TRUE);
1590 * If substituting a local variable in a non-local context, assume
1591 * it's for dynamic source stuff. We have to handle this specially
1592 * and return the longhand for the variable with the dollar sign
1593 * escaped so it makes it back to the caller. Only four of the local
1594 * variables are treated specially as they are the only four that
1595 * will be set when dynamic sources are expanded.
1597 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1599 /* XXX: It looks like $% and $! are reversed here */
1603 return (estrdup("$(.TARGET)"));
1606 return (estrdup("$(.ARCHIVE)"));
1609 return (estrdup("$(.PREFIX)"));
1612 return (estrdup("$(.MEMBER)"));
1614 *freeResult = FALSE;
1615 return (vp->err ? var_Error : varNoError);
1619 /* Variable name was not found. */
1620 *freeResult = FALSE;
1621 return (vp->err ? var_Error : varNoError);
1625 VarParse(VarParser *vp, Boolean *freeResult)
1628 vp->ptr++; /* consume '$' or last letter of conditional */
1630 if (vp->ptr[0] == '\0') {
1631 /* Error, there is only a dollar sign in the input string. */
1632 *freeResult = FALSE;
1633 return (vp->err ? var_Error : varNoError);
1635 } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
1636 /* multi letter variable name */
1637 return (VarParseLong(vp, freeResult));
1640 /* single letter variable name */
1641 return (VarParseShort(vp, freeResult));
1646 *-----------------------------------------------------------------------
1648 * Given the start of a variable invocation, extract the variable
1649 * name and find its value, then modify it according to the
1653 * The value of the variable or var_Error if the specification
1654 * is invalid. The number of characters in the specification
1655 * is placed in the variable pointed to by consumed. (for
1656 * invalid specifications, this is just 2 to skip the '$' and
1657 * the following letter, or 1 if '$' was the last character
1658 * in the string). A Boolean in *freeResult telling whether the
1659 * returned string should be freed by the caller.
1663 *-----------------------------------------------------------------------
1666 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1667 size_t *consumed, Boolean *freeResult)
1677 value = VarParse(&vp, freeResult);
1678 *consumed += vp.ptr - vp.input;
1683 *-----------------------------------------------------------------------
1685 * Substitute for all variables in the given string in the given context
1686 * If err is TRUE, Parse_Error will be called when an undefined
1687 * variable is encountered.
1690 * The resulting string.
1693 * None. The old string must be freed by the caller
1694 *-----------------------------------------------------------------------
1697 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean err)
1699 Boolean errorReported;
1700 Buffer *buf; /* Buffer for forming things */
1703 * Set TRUE if an error has already been reported to prevent a
1704 * plethora of messages when recursing. XXXHB this comment sounds
1707 errorReported = FALSE;
1711 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1713 * A dollar sign may be escaped either with another
1714 * dollar sign. In such a case, we skip over the
1715 * escape character and store the dollar sign into
1716 * the buffer directly.
1718 Buf_AddByte(buf, (Byte)str[0]);
1721 } else if (str[0] == '$') {
1723 * Variable invocation.
1728 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1730 const char *p = str + 2;
1733 * Scan up to the end of the
1736 while (*p != '\0' &&
1738 *p != CLOSE_PAREN &&
1739 *p != CLOSE_BRACE &&
1745 * A variable inside the
1746 * variable. We cannot expand
1747 * the external variable yet,
1748 * so we try again with the
1752 Buf_AppendRange(buf, str, p);
1757 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1762 * we want to expand,
1766 while (*p != '$' && *p != '\0')
1769 Buf_AppendRange(buf, str, p);
1775 * Single letter variable
1778 if (var[1] == '\0' && var[0] == str[1]) {
1781 Buf_AddBytes(buf, 2, (const Byte *) str);
1801 rval = VarParse(&subvp, &rfree);
1804 * When we come down here, val should either point to
1805 * the value of this variable, suitably modified, or
1806 * be NULL. Length should be the total length of the
1807 * potential variable invocation (from $ to end
1810 if (rval == var_Error || rval == varNoError) {
1812 * If performing old-time variable
1813 * substitution, skip over the variable and
1814 * continue with the substitution. Otherwise,
1815 * store the dollar sign and advance str so
1816 * we continue with the string...
1822 * If variable is undefined, complain
1823 * and skip the variable. The
1824 * complaint will stop us from doing
1825 * anything when the file is parsed.
1827 if (!errorReported) {
1828 Parse_Error(PARSE_FATAL,
1829 "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
1832 errorReported = TRUE;
1834 Buf_AddByte(buf, (Byte)*str);
1839 * We've now got a variable structure to
1840 * store in. But first, advance the string
1846 * Copy all the characters from the variable
1847 * value straight into the new string.
1849 Buf_Append(buf, rval);
1857 * Skip as many characters as possible -- either to
1858 * the end of the string or to the next dollar sign
1859 * (variable invocation).
1861 const char *cp = str;
1865 } while (str[0] != '$' && str[0] != '\0');
1867 Buf_AppendRange(buf, cp, str);
1875 *-----------------------------------------------------------------------
1877 * Return the tail from each of a list of words. Used to set the
1878 * System V local variables.
1881 * The resulting string.
1886 *-----------------------------------------------------------------------
1889 Var_GetTail(char *file)
1892 return (VarModify(file, VarTail, (void *)NULL));
1896 *-----------------------------------------------------------------------
1898 * Find the leading components of a (list of) filename(s).
1899 * XXX: VarHead does not replace foo by ., as (sun) System V make
1903 * The leading components.
1908 *-----------------------------------------------------------------------
1911 Var_GetHead(char *file)
1914 return (VarModify(file, VarHead, (void *)NULL));
1918 *-----------------------------------------------------------------------
1920 * Initialize the module
1926 * The VAR_CMD and VAR_GLOBAL contexts are created
1927 *-----------------------------------------------------------------------
1933 VAR_GLOBAL = Targ_NewGN("Global");
1934 VAR_CMD = Targ_NewGN("Command");
1938 *-----------------------------------------------------------------------
1940 * print all variables in a context
1941 *-----------------------------------------------------------------------
1944 Var_Dump(const GNode *ctxt)
1949 LST_FOREACH(ln, &ctxt->context) {
1951 printf("%-16s = %s\n", v->name, Buf_Data(v->val));