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.173 2005/03/20 12:22:46 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);
509 VarAdd(n, val, ctxt);
511 Buf_AddByte(v->val, (Byte)' ');
512 Buf_Append(v->val, val);
514 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
516 if (v->flags & VAR_FROM_ENV) {
518 * If the original variable came from the
519 * environment, we have to install it in the global
520 * context (we could place it in the environment, but
521 * then we should provide a way to export other
524 v->flags &= ~VAR_FROM_ENV;
525 Lst_AtFront(&ctxt->context, v);
532 *-----------------------------------------------------------------------
534 * See if the given variable exists.
537 * TRUE if it does, FALSE if it doesn't
542 *-----------------------------------------------------------------------
545 Var_Exists(const char *name, GNode *ctxt)
550 n = VarPossiblyExpand(name, ctxt);
551 v = VarFind(n, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
556 } else if (v->flags & VAR_FROM_ENV) {
563 *-----------------------------------------------------------------------
565 * Return the value of the named variable in the given context
568 * The value if the variable exists, NULL if it doesn't
572 *-----------------------------------------------------------------------
575 Var_Value(const char *name, GNode *ctxt, char **frp)
580 n = VarPossiblyExpand(name, ctxt);
581 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
585 char *p = Buf_Data(v->val);
587 if (v->flags & VAR_FROM_ENV) {
588 VarDestroy(v, FALSE);
598 *-----------------------------------------------------------------------
600 * Modify each of the words of the passed string using the given
601 * function. Used to implement all modifiers.
604 * A string of all the words modified appropriately.
607 * Uses brk_string() so it invalidates any previous call to
610 *-----------------------------------------------------------------------
613 VarModify(const char *str, VarModifyProc *modProc, void *datum)
615 char **av; /* word list [first word does not count] */
617 Buffer *buf; /* Buffer for the new string */
618 Boolean addSpace; /* TRUE if need to add a space to the buffer
619 * before adding the trimmed word */
622 av = brk_string(str, &ac, FALSE);
627 for (i = 1; i < ac; i++)
628 addSpace = (*modProc)(av[i], addSpace, buf, datum);
630 return (Buf_Peel(buf));
634 *-----------------------------------------------------------------------
636 * Sort the words in the string.
639 * str String whose words should be sorted
640 * cmp A comparison function to control the ordering
643 * A string containing the words sorted
646 * Uses brk_string() so it invalidates any previous call to
649 *-----------------------------------------------------------------------
652 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
659 av = brk_string(str, &ac, FALSE);
660 qsort(av + 1, ac - 1, sizeof(char *), cmp);
663 for (i = 1; i < ac; i++) {
664 Buf_Append(buf, av[i]);
665 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
668 return (Buf_Peel(buf));
672 SortIncreasing(const void *l, const void *r)
675 return (strcmp(*(const char* const*)l, *(const char* const*)r));
679 *-----------------------------------------------------------------------
681 * Pass through the tstr looking for 1) escaped delimiters,
682 * '$'s and backslashes (place the escaped character in
683 * uninterpreted) and 2) unescaped $'s that aren't before
684 * the delimiter (expand the variable substitution).
685 * Return the expanded string or NULL if the delimiter was missing
686 * If pattern is specified, handle escaped ampersands, and replace
687 * unescaped ampersands with the lhs of the pattern.
690 * A string of all the words modified appropriately.
691 * If length is specified, return the string length of the buffer
692 * If flags is specified and the last character of the pattern is a
693 * $ set the VAR_MATCH_END bit of flags.
697 *-----------------------------------------------------------------------
700 VarGetPattern(VarParser *vp, int delim, int *flags,
701 size_t *length, VarPattern *patt)
708 * Skim through until the matching delimiter is found; pick up
709 * variable substitutions on the way. Also allow backslashes to quote
710 * the delimiter, $, and \, but don't touch other backslashes.
712 while (*vp->ptr != '\0') {
713 if (*vp->ptr == delim) {
716 result = (char *)Buf_GetAll(buf, length);
717 Buf_Destroy(buf, FALSE);
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;
748 * If unescaped dollar sign not
749 * before the delimiter, assume it's
750 * a variable substitution and
754 cp = Var_Parse(vp->ptr, vp->ctxt, vp->err, &len, &freeIt);
760 } else if (vp->ptr[0] == '&' && patt != NULL) {
761 Buf_AddBytes(buf, patt->leftLen, (Byte *)patt->lhs);
764 Buf_AddByte(buf, (Byte)vp->ptr[0]);
769 if (length != NULL) {
772 Buf_Destroy(buf, TRUE);
777 *-----------------------------------------------------------------------
779 * Quote shell meta-characters in the string
787 *-----------------------------------------------------------------------
790 Var_Quote(const char *str)
793 /* This should cover most shells :-( */
794 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
796 buf = Buf_Init(MAKE_BSIZE);
797 for (; *str; str++) {
798 if (strchr(meta, *str) != NULL)
799 Buf_AddByte(buf, (Byte)'\\');
800 Buf_AddByte(buf, (Byte)*str);
803 return (Buf_Peel(buf));
807 *-----------------------------------------------------------------------
809 * Print the error caused by a regcomp or regexec call.
815 * An error gets printed.
817 *-----------------------------------------------------------------------
820 VarREError(int err, regex_t *pat, const char *str)
825 errlen = regerror(err, pat, 0, 0);
826 errbuf = emalloc(errlen);
827 regerror(err, pat, errbuf, errlen);
828 Error("%s: %s", str, errbuf);
833 * Make sure this variable is fully expanded.
836 VarExpand(Var *v, VarParser *vp)
841 if (v->flags & VAR_IN_USE) {
842 Fatal("Variable %s is recursive.", v->name);
846 v->flags |= VAR_IN_USE;
849 * Before doing any modification, we have to make sure the
850 * value has been fully expanded. If it looks like recursion
851 * might be necessary (there's a dollar sign somewhere in the
852 * variable's value) we just call Var_Subst to do any other
853 * substitutions that are necessary. Note that the value
854 * returned by Var_Subst will have been
855 * dynamically-allocated, so it will need freeing when we
858 value = Buf_Data(v->val);
859 if (strchr(value, '$') == NULL) {
860 result = strdup(value);
864 buf = Var_Subst(NULL, value, vp->ctxt, vp->err);
865 result = Buf_Peel(buf);
868 v->flags &= ~VAR_IN_USE;
874 * Select only those words in value that match the modifier.
877 modifier_M(VarParser *vp, const char value[], char endc)
884 modifier = vp->ptr[0];
885 vp->ptr++; /* consume 'M' or 'N' */
888 * Compress the \:'s out of the pattern, so allocate enough
889 * room to hold the uncompressed pattern and compress the
890 * pattern into that space.
892 patt = estrdup(vp->ptr);
894 while (vp->ptr[0] != '\0') {
895 if ((vp->ptr[0] == endc) || (vp->ptr[0] == ':')) {
898 if ((vp->ptr[0] == '\\') &&
899 ((vp->ptr[1] == endc) || (vp->ptr[1] == ':'))) {
900 vp->ptr++; /* consume backslash */
908 if (modifier == 'M') {
909 newValue = VarModify(value, VarMatch, patt);
911 newValue = VarModify(value, VarNoMatch, patt);
919 * Substitute the replacement string for the pattern. The substitution
920 * is applied to each word in value.
923 modifier_S(VarParser *vp, const char value[], Var *v)
931 vp->ptr++; /* consume 'S' */
933 delim = *vp->ptr; /* used to find end of pattern */
934 vp->ptr++; /* consume 1st delim */
937 * If pattern begins with '^', it is anchored to the start of the
938 * word -- skip over it and flag pattern.
940 if (*vp->ptr == '^') {
941 patt.flags |= VAR_MATCH_START;
945 patt.lhs = VarGetPattern(vp, delim, &patt.flags, &patt.leftLen, NULL);
946 if (patt.lhs == NULL) {
948 * LHS didn't end with the delim, complain and exit.
950 Fatal("Unclosed substitution for %s (%c missing)",
954 vp->ptr++; /* consume 2nd delim */
956 patt.rhs = VarGetPattern(vp, delim, NULL, &patt.rightLen, &patt);
957 if (patt.rhs == NULL) {
959 * RHS didn't end with the delim, complain and exit.
961 Fatal("Unclosed substitution for %s (%c missing)",
965 vp->ptr++; /* consume last delim */
968 * Check for global substitution. If 'g' after the final delimiter,
969 * substitution is global and is marked that way.
971 if (vp->ptr[0] == 'g') {
972 patt.flags |= VAR_SUB_GLOBAL;
977 * Global substitution of the empty string causes an infinite number
978 * of matches, unless anchored by '^' (start of string) or '$' (end
979 * of string). Catch the infinite substitution here. Note that flags
980 * can only contain the 3 bits we're interested in so we don't have
981 * to mask unrelated bits. We can test for equality.
983 if (patt.leftLen == 0 && patt.flags == VAR_SUB_GLOBAL)
984 Fatal("Global substitution of the empty string");
986 newValue = VarModify(value, VarSubstitute, &patt);
989 * Free the two strings.
998 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 re = VarGetPattern(vp, delim, NULL, NULL, NULL);
1016 Fatal("Unclosed substitution for %s (%c missing)",
1020 vp->ptr++; /* consume 2st delim */
1022 patt.rhs = VarGetPattern(vp, delim, NULL, 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, re, 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, &patt.leftLen, 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.rightLen, &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';
1346 (vname[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.
1431 if (((vlen == 1)) ||
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';
1443 (vname[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 == '$') {
1538 rval = Var_Parse(vp->ptr, vp->ctxt, vp->err,
1540 if (rval == var_Error) {
1541 Fatal("Error expanding embedded variable.");
1543 Buf_Append(buf, rval);
1549 Buf_AddByte(buf, (Byte)*vp->ptr);
1554 /* If we did not find the end character, return var_Error */
1555 Buf_Destroy(buf, TRUE);
1556 *freeResult = FALSE;
1561 * Parse a single letter variable name, and return it's value.
1564 VarParseShort(VarParser *vp, Boolean *freeResult)
1570 vname[0] = vp->ptr[0];
1573 vp->ptr++; /* consume single letter */
1575 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1577 value = VarExpand(v, vp);
1579 if (v->flags & VAR_FROM_ENV) {
1580 VarDestroy(v, TRUE);
1588 * If substituting a local variable in a non-local context, assume
1589 * it's for dynamic source stuff. We have to handle this specially
1590 * and return the longhand for the variable with the dollar sign
1591 * escaped so it makes it back to the caller. Only four of the local
1592 * variables are treated specially as they are the only four that
1593 * will be set when dynamic sources are expanded.
1595 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1597 /* XXX: It looks like $% and $! are reversed here */
1601 return (estrdup("$(.TARGET)"));
1604 return (estrdup("$(.ARCHIVE)"));
1607 return (estrdup("$(.PREFIX)"));
1610 return (estrdup("$(.MEMBER)"));
1612 *freeResult = FALSE;
1613 return (vp->err ? var_Error : varNoError);
1617 /* Variable name was not found. */
1618 *freeResult = FALSE;
1619 return (vp->err ? var_Error : varNoError);
1623 VarParse(VarParser *vp, Boolean *freeResult)
1626 vp->ptr++; /* consume '$' or last letter of conditional */
1628 if (vp->ptr[0] == '\0') {
1629 /* Error, there is only a dollar sign in the input string. */
1630 *freeResult = FALSE;
1631 return (vp->err ? var_Error : varNoError);
1633 } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
1634 /* multi letter variable name */
1635 return (VarParseLong(vp, freeResult));
1638 /* single letter variable name */
1639 return (VarParseShort(vp, freeResult));
1644 *-----------------------------------------------------------------------
1646 * Given the start of a variable invocation, extract the variable
1647 * name and find its value, then modify it according to the
1651 * The value of the variable or var_Error if the specification
1652 * is invalid. The number of characters in the specification
1653 * is placed in the variable pointed to by consumed. (for
1654 * invalid specifications, this is just 2 to skip the '$' and
1655 * the following letter, or 1 if '$' was the last character
1656 * in the string). A Boolean in *freeResult telling whether the
1657 * returned string should be freed by the caller.
1661 *-----------------------------------------------------------------------
1664 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1665 size_t *consumed, Boolean *freeResult)
1675 value = VarParse(&vp, freeResult);
1676 *consumed += vp.ptr - vp.input;
1681 *-----------------------------------------------------------------------
1683 * Substitute for all variables in the given string in the given context
1684 * If undefErr is TRUE, Parse_Error will be called when an undefined
1685 * variable is encountered.
1688 * The resulting string.
1691 * None. The old string must be freed by the caller
1692 *-----------------------------------------------------------------------
1695 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1697 Boolean errorReported;
1698 Buffer *buf; /* Buffer for forming things */
1701 * Set TRUE if an error has already been reported to prevent a
1702 * plethora of messages when recursing. XXXHB this comment sounds
1705 errorReported = FALSE;
1709 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1711 * A dollar sign may be escaped either with another
1712 * dollar sign. In such a case, we skip over the
1713 * escape character and store the dollar sign into
1714 * the buffer directly.
1716 Buf_AddByte(buf, (Byte)str[0]);
1719 } else if (str[0] == '$') {
1720 char *val; /* Value to substitute for a variable */
1721 size_t length; /* Length of the variable invocation */
1722 Boolean doFree; /* Set true if val should be freed */
1725 * Variable invocation.
1730 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1732 const char *p = str + 2;
1735 * Scan up to the end of the
1738 while (*p != '\0' &&
1740 *p != CLOSE_PAREN &&
1741 *p != CLOSE_BRACE &&
1747 * A variable inside the
1748 * variable. We cannot expand
1749 * the external variable yet,
1750 * so we try again with the
1754 Buf_AppendRange(buf, str, p);
1759 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1764 * we want to expand,
1768 while (*p != '$' && *p != '\0')
1771 Buf_AppendRange(buf, str, p);
1777 * Single letter variable
1780 if (var[1] == '\0' && var[0] == str[1]) {
1783 Buf_AddBytes(buf, 2, (const Byte *) str);
1794 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1797 * When we come down here, val should either point to
1798 * the value of this variable, suitably modified, or
1799 * be NULL. Length should be the total length of the
1800 * potential variable invocation (from $ to end
1803 if (val == var_Error || val == varNoError) {
1805 * If performing old-time variable
1806 * substitution, skip over the variable and
1807 * continue with the substitution. Otherwise,
1808 * store the dollar sign and advance str so
1809 * we continue with the string...
1813 } else if (undefErr) {
1815 * If variable is undefined, complain
1816 * and skip the variable. The
1817 * complaint will stop us from doing
1818 * anything when the file is parsed.
1820 if (!errorReported) {
1821 Parse_Error(PARSE_FATAL,
1822 "Undefined variable \"%.*s\"", length, str);
1825 errorReported = TRUE;
1827 Buf_AddByte(buf, (Byte)*str);
1832 * We've now got a variable structure to
1833 * store in. But first, advance the string
1839 * Copy all the characters from the variable
1840 * value straight into the new string.
1842 Buf_Append(buf, val);
1849 * Skip as many characters as possible -- either to
1850 * the end of the string or to the next dollar sign
1851 * (variable invocation).
1853 const char *cp = str;
1857 } while (str[0] != '$' && str[0] != '\0');
1859 Buf_AppendRange(buf, cp, str);
1867 *-----------------------------------------------------------------------
1869 * Return the tail from each of a list of words. Used to set the
1870 * System V local variables.
1873 * The resulting string.
1878 *-----------------------------------------------------------------------
1881 Var_GetTail(char *file)
1884 return (VarModify(file, VarTail, (void *)NULL));
1888 *-----------------------------------------------------------------------
1890 * Find the leading components of a (list of) filename(s).
1891 * XXX: VarHead does not replace foo by ., as (sun) System V make
1895 * The leading components.
1900 *-----------------------------------------------------------------------
1903 Var_GetHead(char *file)
1906 return (VarModify(file, VarHead, (void *)NULL));
1910 *-----------------------------------------------------------------------
1912 * Initialize the module
1918 * The VAR_CMD and VAR_GLOBAL contexts are created
1919 *-----------------------------------------------------------------------
1925 VAR_GLOBAL = Targ_NewGN("Global");
1926 VAR_CMD = Targ_NewGN("Command");
1930 *-----------------------------------------------------------------------
1932 * print all variables in a context
1933 *-----------------------------------------------------------------------
1936 Var_Dump(const GNode *ctxt)
1941 LST_FOREACH(ln, &ctxt->context) {
1943 printf("%-16s = %s\n", v->name, Buf_Data(v->val));