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.170 2005/03/19 00:17:07 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)
229 if (strchr(name, '$') != NULL) {
230 buf = Var_Subst(NULL, name, ctxt, 0);
231 str = Buf_GetAll(buf, NULL);
232 Buf_Destroy(buf, FALSE);
236 return estrdup(name);
241 *-----------------------------------------------------------------------
243 * Find the given variable in the given context and any other contexts
247 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
248 * FIND_CMD set means to look in the VAR_CMD context too
249 * FIND_ENV set means to look in the environment
252 * A pointer to the structure describing the desired variable or
253 * NULL if the variable does not exist.
257 *-----------------------------------------------------------------------
260 VarFind(const char *name, GNode *ctxt, int flags)
262 Boolean localCheckEnvFirst;
267 * If the variable name begins with a '.', it could very well be one of
268 * the local ones. We check the name against all the local variables
269 * and substitute the short version in for 'name' if it matches one of
272 if (name[0] == '.') {
275 if (!strcmp(name, ".ALLSRC"))
277 if (!strcmp(name, ".ARCHIVE"))
281 if (!strcmp(name, ".IMPSRC"))
285 if (!strcmp(name, ".MEMBER"))
289 if (!strcmp(name, ".OODATE"))
293 if (!strcmp(name, ".PREFIX"))
297 if (!strcmp(name, ".TARGET"))
306 * Note whether this is one of the specific variables we were told
307 * through the -E flag to use environment-variable-override for.
309 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
310 localCheckEnvFirst = TRUE;
312 localCheckEnvFirst = FALSE;
316 * First look for the variable in the given context. If it's not there,
317 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
318 * in that order, depending on the FIND_* flags in 'flags'
320 var = Lst_Find(&ctxt->context, name, VarCmp);
323 return (Lst_Datum(var));
326 /* not there - try command line context */
327 if ((flags & FIND_CMD) && (ctxt != VAR_CMD)) {
328 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
330 return (Lst_Datum(var));
333 /* not there - try global context, but only if not -e/-E */
334 if ((flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
335 !checkEnvFirst && !localCheckEnvFirst) {
336 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
338 return (Lst_Datum(var));
341 if (!(flags & FIND_ENV))
342 /* we were not told to look into the environment */
345 /* look in the environment */
346 if ((env = getenv(name)) != NULL) {
347 /* craft this variable from the environment value */
348 return (VarCreate(name, env, VAR_FROM_ENV));
351 /* deferred check for the environment (in case of -e/-E) */
352 if ((checkEnvFirst || localCheckEnvFirst) &&
353 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL)) {
354 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
356 return (Lst_Datum(var));
362 *-----------------------------------------------------------------------
364 * Add a new variable of name name and value val to the given context.
370 * The new variable is placed at the front of the given context
371 * The name and val arguments are duplicated so they may
373 *-----------------------------------------------------------------------
376 VarAdd(const char *name, const char *val, GNode *ctxt)
379 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
380 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
384 *-----------------------------------------------------------------------
386 * Remove a variable from a context.
392 * The Var structure is removed and freed.
394 *-----------------------------------------------------------------------
397 Var_Delete(const char *name, GNode *ctxt)
401 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
402 ln = Lst_Find(&ctxt->context, name, VarCmp);
404 VarDestroy(Lst_Datum(ln), TRUE);
405 Lst_Remove(&ctxt->context, ln);
410 *-----------------------------------------------------------------------
412 * Set the variable name to the value val in the given context.
418 * If the variable doesn't yet exist, a new record is created for it.
419 * Else the old value is freed and the new one stuck in its place
422 * The variable is searched for only in its context before being
423 * created in that context. I.e. if the context is VAR_GLOBAL,
424 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
425 * VAR_CMD->context is searched. This is done to avoid the literally
426 * thousands of unnecessary strcmp's that used to be done to
427 * set, say, $(@) or $(<).
428 *-----------------------------------------------------------------------
431 Var_Set(const char *name, const char *val, GNode *ctxt)
437 * We only look for a variable in the given context since anything
438 * set here will override anything in a lower context, so there's not
439 * much point in searching them all just to save a bit of memory...
441 n = VarPossiblyExpand(name, ctxt);
442 v = VarFind(n, ctxt, 0);
444 VarAdd(n, val, ctxt);
447 Buf_Append(v->val, val);
449 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
452 * Any variables given on the command line are automatically exported
453 * to the environment (as per POSIX standard)
455 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
463 * Set the VAR_TO_ENV flag on a variable
466 Var_SetEnv(const char *name, GNode *ctxt)
470 v = VarFind(name, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
472 if ((v->flags & VAR_TO_ENV) == 0) {
473 v->flags |= VAR_TO_ENV;
474 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
477 Error("Cannot set environment flag on non-existant variable %s", name);
482 *-----------------------------------------------------------------------
484 * The variable of the given name has the given value appended to it in
491 * If the variable doesn't exist, it is created. Else the strings
492 * are concatenated (with a space in between).
495 * Only if the variable is being sought in the global context is the
496 * environment searched.
497 * XXX: Knows its calling circumstances in that if called with ctxt
498 * an actual target, it will only search that context since only
499 * a local variable could be being appended to. This is actually
500 * a big win and must be tolerated.
501 *-----------------------------------------------------------------------
504 Var_Append(const char *name, const char *val, GNode *ctxt)
509 n = VarPossiblyExpand(name, ctxt);
510 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
513 VarAdd(n, val, ctxt);
515 Buf_AddByte(v->val, (Byte)' ');
516 Buf_Append(v->val, val);
518 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
519 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
521 if (v->flags & VAR_FROM_ENV) {
523 * If the original variable came from the
524 * environment, we have to install it in the global
525 * context (we could place it in the environment, but
526 * then we should provide a way to export other
529 v->flags &= ~VAR_FROM_ENV;
530 Lst_AtFront(&ctxt->context, v);
537 *-----------------------------------------------------------------------
539 * See if the given variable exists.
542 * TRUE if it does, FALSE if it doesn't
547 *-----------------------------------------------------------------------
550 Var_Exists(const char *name, GNode *ctxt)
555 n = VarPossiblyExpand(name, ctxt);
556 v = VarFind(n, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
561 } else if (v->flags & VAR_FROM_ENV) {
568 *-----------------------------------------------------------------------
570 * Return the value of the named variable in the given context
573 * The value if the variable exists, NULL if it doesn't
577 *-----------------------------------------------------------------------
580 Var_Value(const char *name, GNode *ctxt, char **frp)
585 n = VarPossiblyExpand(name, ctxt);
586 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
590 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
592 if (v->flags & VAR_FROM_ENV) {
593 VarDestroy(v, FALSE);
603 *-----------------------------------------------------------------------
605 * Modify each of the words of the passed string using the given
606 * function. Used to implement all modifiers.
609 * A string of all the words modified appropriately.
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 */
628 av = brk_string(str, &ac, FALSE);
633 for (i = 1; i < ac; i++)
634 addSpace = (*modProc)(av[i], addSpace, buf, datum);
636 result = (char *)Buf_GetAll(buf, (size_t *)NULL);
637 Buf_Destroy(buf, FALSE);
642 *-----------------------------------------------------------------------
644 * Sort the words in the string.
647 * str String whose words should be sorted
648 * cmp A comparison function to control the ordering
651 * A string containing the words sorted
654 * Uses brk_string() so it invalidates any previous call to
657 *-----------------------------------------------------------------------
660 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
668 av = brk_string(str, &ac, FALSE);
669 qsort(av + 1, ac - 1, sizeof(char *), cmp);
672 for (i = 1; i < ac; i++) {
673 Buf_Append(buf, av[i]);
674 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
677 result = (char *)Buf_GetAll(buf, (size_t *)NULL);
678 Buf_Destroy(buf, FALSE);
683 SortIncreasing(const void *l, const void *r)
686 return (strcmp(*(const char* const*)l, *(const char* const*)r));
690 *-----------------------------------------------------------------------
692 * Pass through the tstr looking for 1) escaped delimiters,
693 * '$'s and backslashes (place the escaped character in
694 * uninterpreted) and 2) unescaped $'s that aren't before
695 * the delimiter (expand the variable substitution).
696 * Return the expanded string or NULL if the delimiter was missing
697 * If pattern is specified, handle escaped ampersands, and replace
698 * unescaped ampersands with the lhs of the pattern.
701 * A string of all the words modified appropriately.
702 * If length is specified, return the string length of the buffer
703 * If flags is specified and the last character of the pattern is a
704 * $ set the VAR_MATCH_END bit of flags.
708 *-----------------------------------------------------------------------
711 VarGetPattern(VarParser *vp, int delim, int *flags,
712 size_t *length, VarPattern *patt)
719 * Skim through until the matching delimiter is found; pick up
720 * variable substitutions on the way. Also allow backslashes to quote
721 * the delimiter, $, and \, but don't touch other backslashes.
723 while (*vp->ptr != '\0') {
724 if (*vp->ptr == delim) {
727 result = (char *)Buf_GetAll(buf, length);
728 Buf_Destroy(buf, FALSE);
731 } else if ((vp->ptr[0] == '\\') &&
732 ((vp->ptr[1] == delim) ||
733 (vp->ptr[1] == '\\') ||
734 (vp->ptr[1] == '$') ||
735 (vp->ptr[1] == '&' && patt != NULL))) {
736 vp->ptr++; /* consume backslash */
737 Buf_AddByte(buf, (Byte)vp->ptr[0]);
740 } else if (vp->ptr[0] == '$') {
741 if (vp->ptr[1] == delim) {
743 Buf_AddByte(buf, (Byte)vp->ptr[0]);
747 * Unescaped $ at end of patt =>
748 * anchor patt at end.
750 *flags |= VAR_MATCH_END;
759 * If unescaped dollar sign not
760 * before the delimiter, assume it's
761 * a variable substitution and
765 cp = Var_Parse(vp->ptr, vp->ctxt, vp->err, &len, &freeIt);
771 } else if (vp->ptr[0] == '&' && patt != NULL) {
772 Buf_AddBytes(buf, patt->leftLen, (Byte *)patt->lhs);
775 Buf_AddByte(buf, (Byte)vp->ptr[0]);
780 if (length != NULL) {
783 Buf_Destroy(buf, TRUE);
788 *-----------------------------------------------------------------------
790 * Quote shell meta-characters in the string
798 *-----------------------------------------------------------------------
801 Var_Quote(const char *str)
804 /* This should cover most shells :-( */
805 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
808 buf = Buf_Init(MAKE_BSIZE);
809 for (; *str; str++) {
810 if (strchr(meta, *str) != NULL)
811 Buf_AddByte(buf, (Byte)'\\');
812 Buf_AddByte(buf, (Byte)*str);
814 Buf_AddByte(buf, (Byte)'\0');
815 ret = Buf_GetAll(buf, NULL);
816 Buf_Destroy(buf, FALSE);
821 *-----------------------------------------------------------------------
823 * Print the error caused by a regcomp or regexec call.
829 * An error gets printed.
831 *-----------------------------------------------------------------------
834 VarREError(int err, regex_t *pat, const char *str)
839 errlen = regerror(err, pat, 0, 0);
840 errbuf = emalloc(errlen);
841 regerror(err, pat, errbuf, errlen);
842 Error("%s: %s", str, errbuf);
847 * Make sure this variable is fully expanded.
850 VarExpand(Var *v, VarParser *vp)
855 if (v->flags & VAR_IN_USE) {
856 Fatal("Variable %s is recursive.", v->name);
860 v->flags |= VAR_IN_USE;
863 * Before doing any modification, we have to make sure the
864 * value has been fully expanded. If it looks like recursion
865 * might be necessary (there's a dollar sign somewhere in the
866 * variable's value) we just call Var_Subst to do any other
867 * substitutions that are necessary. Note that the value
868 * returned by Var_Subst will have been
869 * dynamically-allocated, so it will need freeing when we
872 value = (char *)Buf_GetAll(v->val, (size_t *)NULL);
873 if (strchr(value, '$') == NULL) {
874 result = strdup(value);
878 buf = Var_Subst(NULL, value, vp->ctxt, vp->err);
879 result = Buf_GetAll(buf, NULL);
880 Buf_Destroy(buf, FALSE);
883 v->flags &= ~VAR_IN_USE;
889 * Select only those words in value that match the modifier.
892 modifier_M(VarParser *vp, const char value[], char endc)
899 modifier = vp->ptr[0];
900 vp->ptr++; /* consume 'M' or 'N' */
903 * Compress the \:'s out of the pattern, so allocate enough
904 * room to hold the uncompressed pattern and compress the
905 * pattern into that space.
907 patt = estrdup(vp->ptr);
909 while (vp->ptr[0] != '\0') {
910 if ((vp->ptr[0] == endc) || (vp->ptr[0] == ':')) {
913 if ((vp->ptr[0] == '\\') &&
914 ((vp->ptr[1] == endc) || (vp->ptr[1] == ':'))) {
915 vp->ptr++; /* consume backslash */
923 if (modifier == 'M') {
924 newValue = VarModify(value, VarMatch, patt);
926 newValue = VarModify(value, VarNoMatch, patt);
934 * Substitute the replacement string for the pattern. The substitution
935 * is applied to each word in value.
938 modifier_S(VarParser *vp, const char value[], Var *v)
946 vp->ptr++; /* consume 'S' */
948 delim = *vp->ptr; /* used to find end of pattern */
949 vp->ptr++; /* consume 1st delim */
952 * If pattern begins with '^', it is anchored to the start of the
953 * word -- skip over it and flag pattern.
955 if (*vp->ptr == '^') {
956 patt.flags |= VAR_MATCH_START;
960 patt.lhs = VarGetPattern(vp, delim, &patt.flags, &patt.leftLen, NULL);
961 if (patt.lhs == NULL) {
963 * LHS didn't end with the delim, complain and exit.
965 Fatal("Unclosed substitution for %s (%c missing)",
969 vp->ptr++; /* consume 2nd delim */
971 patt.rhs = VarGetPattern(vp, delim, NULL, &patt.rightLen, &patt);
972 if (patt.rhs == NULL) {
974 * RHS didn't end with the delim, complain and exit.
976 Fatal("Unclosed substitution for %s (%c missing)",
980 vp->ptr++; /* consume last delim */
983 * Check for global substitution. If 'g' after the final delimiter,
984 * substitution is global and is marked that way.
986 if (vp->ptr[0] == 'g') {
987 patt.flags |= VAR_SUB_GLOBAL;
992 * Global substitution of the empty string causes an infinite number
993 * of matches, unless anchored by '^' (start of string) or '$' (end
994 * of string). Catch the infinite substitution here. Note that flags
995 * can only contain the 3 bits we're interested in so we don't have
996 * to mask unrelated bits. We can test for equality.
998 if (patt.leftLen == 0 && patt.flags == VAR_SUB_GLOBAL)
999 Fatal("Global substitution of the empty string");
1001 newValue = VarModify(value, VarSubstitute, &patt);
1004 * Free the two strings.
1013 modifier_C(VarParser *vp, char value[], Var *v)
1023 vp->ptr++; /* consume 'C' */
1025 delim = *vp->ptr; /* delimiter between sections */
1027 vp->ptr++; /* consume 1st delim */
1029 re = VarGetPattern(vp, delim, NULL, NULL, NULL);
1031 Fatal("Unclosed substitution for %s (%c missing)",
1035 vp->ptr++; /* consume 2st delim */
1037 patt.replace = VarGetPattern(vp, delim, NULL, NULL, NULL);
1038 if (patt.replace == NULL) {
1039 Fatal("Unclosed substitution for %s (%c missing)",
1043 vp->ptr++; /* consume last delim */
1047 patt.flags |= VAR_SUB_GLOBAL;
1048 vp->ptr++; /* consume 'g' */
1051 patt.flags |= VAR_SUB_ONE;
1052 vp->ptr++; /* consume '1' */
1058 error = regcomp(&patt.re, re, REG_EXTENDED);
1060 VarREError(error, &patt.re, "RE substitution error");
1066 patt.nsub = patt.re.re_nsub + 1;
1071 patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1073 newValue = VarModify(value, VarRESubstitute, &patt);
1084 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1088 * This can either be a bogus modifier or a System-V substitution
1098 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1103 * First we make a pass through the string trying to verify it is a
1104 * SYSV-make-style translation: it must be: <string1>=<string2>)
1109 while (*cp != '\0' && cnt) {
1112 /* continue looking for endc */
1113 } else if (*cp == endc)
1115 else if (*cp == startc)
1121 if (*cp == endc && eqFound) {
1123 * Now we break this sucker into the lhs and rhs.
1125 patt.lhs = VarGetPattern(vp, '=', &patt.flags, &patt.leftLen, NULL);
1126 if (patt.lhs == NULL) {
1127 Fatal("Unclosed substitution for %s (%c missing)",
1130 vp->ptr++; /* consume '=' */
1132 patt.rhs = VarGetPattern(vp, endc, NULL, &patt.rightLen, &patt);
1133 if (patt.rhs == NULL) {
1134 Fatal("Unclosed substitution for %s (%c missing)",
1139 * SYSV modifications happen through the whole string. Note
1140 * the pattern is anchored at the end.
1142 newStr = VarModify(value, VarSYSVMatch, &patt);
1149 Error("Unknown modifier '%c'\n", *vp->ptr);
1151 while (*vp->ptr != '\0') {
1152 if (*vp->ptr == endc && *vp->ptr == ':') {
1164 * Now we need to apply any modifiers the user wants applied.
1167 * words which match the given <pattern>.
1168 * <pattern> is of the standard file
1170 * :S<d><pat1><d><pat2><d>[g]
1171 * Substitute <pat2> for <pat1> in the value
1172 * :C<d><pat1><d><pat2><d>[g]
1173 * Substitute <pat2> for regex <pat1> in the value
1174 * :H Substitute the head of each word
1175 * :T Substitute the tail of each word
1176 * :E Substitute the extension (minus '.') of
1178 * :R Substitute the root of each word
1179 * (pathname minus the suffix).
1181 * Like :S, but the rhs goes to the end of
1183 * :U Converts variable to upper-case.
1184 * :L Converts variable to lower-case.
1186 * XXXHB update this comment or remove it and point to the man page.
1189 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1194 value = VarExpand(v, vp);
1197 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1199 vp->ptr++; /* consume first colon */
1201 while (*vp->ptr != '\0') {
1202 char *newStr; /* New value to return */
1204 if (*vp->ptr == endc) {
1208 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1212 newStr = modifier_M(vp, value, endc);
1215 newStr = modifier_S(vp, value, v);
1218 newStr = modifier_C(vp, value, v);
1221 if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1223 if ((vp->ptr[0] == 's') &&
1224 (vp->ptr[1] == 'h') &&
1225 (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1229 buf = Cmd_Exec(value, &error);
1230 newStr = Buf_GetAll(buf, NULL);
1231 Buf_Destroy(buf, FALSE);
1234 Error(error, value);
1239 newStr = sysVvarsub(vp, startc, v, value);
1244 switch (vp->ptr[0]) {
1249 buf = Buf_Init(MAKE_BSIZE);
1250 for (cp = value; *cp; cp++)
1251 Buf_AddByte(buf, (Byte)tolower(*cp));
1253 newStr = (char *)Buf_GetAll(buf, NULL);
1254 Buf_Destroy(buf, FALSE);
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 = (char *)Buf_GetAll(buf, NULL);
1280 Buf_Destroy(buf, FALSE);
1286 newStr = VarModify(value, VarHead, NULL);
1290 newStr = VarModify(value, VarSuffix, NULL);
1294 newStr = VarModify(value, VarRoot, NULL);
1298 newStr = sysVvarsub(vp, startc, v, value);
1304 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1310 *freeResult = (value == var_Error) ? FALSE : TRUE;
1312 if (vp->ptr[0] == ':') {
1313 vp->ptr++; /* consume colon */
1321 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1328 vname = Buf_GetAll(buf, &vlen);
1330 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1332 value = ParseModifier(vp, startc, v, freeResult);
1334 if (v->flags & VAR_FROM_ENV) {
1335 VarDestroy(v, TRUE);
1340 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1341 size_t consumed = vp->ptr - vp->input + 1;
1344 * If substituting a local variable in a non-local context,
1345 * assume it's for dynamic source stuff. We have to handle
1346 * this specially and return the longhand for the variable
1347 * with the dollar sign escaped so it makes it back to the
1348 * caller. Only four of the local variables are treated
1349 * specially as they are the only four that will be set when
1350 * dynamic sources are expanded.
1353 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1354 if (strchr("!%*@", vname[0]) != NULL) {
1355 value = emalloc(consumed + 1);
1356 strncpy(value, vp->input, consumed);
1357 value[consumed] = '\0';
1364 (vname[0] == '.') &&
1365 isupper((unsigned char)vname[1])) {
1366 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1367 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1368 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1369 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1370 value = emalloc(consumed + 1);
1371 strncpy(value, vp->input, consumed);
1372 value[consumed] = '\0';
1380 * Check for D and F forms of local variables since we're in
1381 * a local context and the name is the right length.
1384 (vname[1] == 'F' || vname[1] == 'D') &&
1385 (strchr("!%*<>@", vname[0]) != NULL)) {
1391 v = VarFind(name, vp->ctxt, 0);
1393 value = ParseModifier(vp, startc, v, freeResult);
1400 * Still need to get to the end of the variable
1401 * specification, so kludge up a Var structure for the
1404 v = VarCreate(vname, NULL, VAR_JUNK);
1405 value = ParseModifier(vp, startc, v, freeResult);
1409 VarDestroy(v, TRUE);
1411 *freeResult = FALSE;
1412 return (vp->err ? var_Error : varNoError);
1416 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1423 vname = Buf_GetAll(buf, &vlen);
1425 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1427 value = VarExpand(v, vp);
1429 if (v->flags & VAR_FROM_ENV) {
1430 VarDestroy(v, TRUE);
1437 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1438 size_t consumed = vp->ptr - vp->input + 1;
1441 * If substituting a local variable in a non-local context,
1442 * assume it's for dynamic source stuff. We have to handle
1443 * this specially and return the longhand for the variable
1444 * with the dollar sign escaped so it makes it back to the
1445 * caller. Only four of the local variables are treated
1446 * specially as they are the only four that will be set when
1447 * dynamic sources are expanded.
1449 if (((vlen == 1)) ||
1450 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1451 if (strchr("!%*@", vname[0]) != NULL) {
1452 value = emalloc(consumed + 1);
1453 strncpy(value, vp->input, consumed);
1454 value[consumed] = '\0';
1461 (vname[0] == '.') &&
1462 isupper((unsigned char)vname[1])) {
1463 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1464 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1465 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1466 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1467 value = emalloc(consumed + 1);
1468 strncpy(value, vp->input, consumed);
1469 value[consumed] = '\0';
1477 * Check for D and F forms of local variables since we're in
1478 * a local context and the name is the right length.
1481 (vname[1] == 'F' || vname[1] == 'D') &&
1482 (strchr("!%*<>@", vname[0]) != NULL)) {
1488 v = VarFind(name, vp->ctxt, 0);
1492 * No need for nested expansion or anything,
1493 * as we're the only one who sets these
1494 * things and we sure don't put nested
1495 * invocations in them...
1497 val = (char *)Buf_GetAll(v->val, NULL);
1499 if (vname[1] == 'D') {
1500 val = VarModify(val, VarHead, NULL);
1502 val = VarModify(val, VarTail, NULL);
1511 *freeResult = FALSE;
1512 return (vp->err ? var_Error : varNoError);
1516 * Parse a multi letter variable name, and return it's value.
1519 VarParseLong(VarParser *vp, Boolean *freeResult)
1526 buf = Buf_Init(MAKE_BSIZE);
1528 startc = vp->ptr[0];
1529 vp->ptr++; /* consume opening paren or brace */
1531 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1534 * Process characters until we reach an end character or a colon,
1535 * replacing embedded variables as we go.
1537 while (*vp->ptr != '\0') {
1538 if (*vp->ptr == endc) {
1539 value = ParseRestEnd(vp, buf, freeResult);
1540 vp->ptr++; /* consume closing paren or brace */
1541 Buf_Destroy(buf, TRUE);
1544 } else if (*vp->ptr == ':') {
1545 value = ParseRestModifier(vp, startc, buf, freeResult);
1546 vp->ptr++; /* consume closing paren or brace */
1547 Buf_Destroy(buf, TRUE);
1550 } else if (*vp->ptr == '$') {
1556 rval = Var_Parse(vp->ptr, vp->ctxt, vp->err,
1558 if (rval == var_Error) {
1559 Fatal("Error expanding embedded variable.");
1561 Buf_Append(buf, rval);
1567 Buf_AddByte(buf, (Byte)*vp->ptr);
1572 /* If we did not find the end character, return var_Error */
1573 Buf_Destroy(buf, TRUE);
1574 *freeResult = FALSE;
1579 * Parse a single letter variable name, and return it's value.
1582 VarParseShort(VarParser *vp, Boolean *freeResult)
1588 vname[0] = vp->ptr[0];
1591 vp->ptr++; /* consume single letter */
1593 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1595 value = VarExpand(v, vp);
1597 if (v->flags & VAR_FROM_ENV) {
1598 VarDestroy(v, TRUE);
1606 * If substituting a local variable in a non-local context, assume
1607 * it's for dynamic source stuff. We have to handle this specially
1608 * and return the longhand for the variable with the dollar sign
1609 * escaped so it makes it back to the caller. Only four of the local
1610 * variables are treated specially as they are the only four that
1611 * will be set when dynamic sources are expanded.
1613 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1615 /* XXX: It looks like $% and $! are reversed here */
1619 return (estrdup("$(.TARGET)"));
1622 return (estrdup("$(.ARCHIVE)"));
1625 return (estrdup("$(.PREFIX)"));
1628 return (estrdup("$(.MEMBER)"));
1630 *freeResult = FALSE;
1631 return (vp->err ? var_Error : varNoError);
1635 /* Variable name was not found. */
1636 *freeResult = FALSE;
1637 return (vp->err ? var_Error : varNoError);
1641 VarParse(VarParser *vp, Boolean *freeResult)
1644 vp->ptr++; /* consume '$' or last letter of conditional */
1646 if (vp->ptr[0] == '\0') {
1647 /* Error, there is only a dollar sign in the input string. */
1648 *freeResult = FALSE;
1649 return (vp->err ? var_Error : varNoError);
1651 } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
1652 /* multi letter variable name */
1653 return (VarParseLong(vp, freeResult));
1656 /* single letter variable name */
1657 return (VarParseShort(vp, freeResult));
1662 *-----------------------------------------------------------------------
1664 * Given the start of a variable invocation, extract the variable
1665 * name and find its value, then modify it according to the
1669 * The value of the variable or var_Error if the specification
1670 * is invalid. The number of characters in the specification
1671 * is placed in the variable pointed to by consumed. (for
1672 * invalid specifications, this is just 2 to skip the '$' and
1673 * the following letter, or 1 if '$' was the last character
1674 * in the string). A Boolean in *freeResult telling whether the
1675 * returned string should be freed by the caller.
1679 *-----------------------------------------------------------------------
1682 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1683 size_t *consumed, Boolean *freeResult)
1693 value = VarParse(&vp, freeResult);
1694 *consumed += vp.ptr - vp.input;
1699 *-----------------------------------------------------------------------
1701 * Substitute for all variables in the given string in the given context
1702 * If undefErr is TRUE, Parse_Error will be called when an undefined
1703 * variable is encountered.
1706 * The resulting string.
1709 * None. The old string must be freed by the caller
1710 *-----------------------------------------------------------------------
1713 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1715 Boolean errorReported;
1716 Buffer *buf; /* Buffer for forming things */
1719 * Set TRUE if an error has already been reported to prevent a
1720 * plethora of messages when recursing. XXXHB this comment sounds
1723 errorReported = FALSE;
1727 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1729 * A dollar sign may be escaped either with another
1730 * dollar sign. In such a case, we skip over the
1731 * escape character and store the dollar sign into
1732 * the buffer directly.
1734 Buf_AddByte(buf, (Byte)str[0]);
1737 } else if (str[0] == '$') {
1738 char *val; /* Value to substitute for a variable */
1739 size_t length; /* Length of the variable invocation */
1740 Boolean doFree; /* Set true if val should be freed */
1743 * Variable invocation.
1748 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1750 const char *p = str + 2;
1753 * Scan up to the end of the
1756 while (*p != '\0' &&
1758 *p != CLOSE_PAREN &&
1759 *p != CLOSE_BRACE &&
1765 * A variable inside the
1766 * variable. We cannot expand
1767 * the external variable yet,
1768 * so we try again with the
1772 Buf_AppendRange(buf, str, p);
1777 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1782 * we want to expand,
1786 while (*p != '$' && *p != '\0')
1789 Buf_AppendRange(buf, str, p);
1795 * Single letter variable
1798 if (var[1] == '\0' && var[0] == str[1]) {
1801 Buf_AddBytes(buf, 2, (const Byte *) str);
1812 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1815 * When we come down here, val should either point to
1816 * the value of this variable, suitably modified, or
1817 * be NULL. Length should be the total length of the
1818 * potential variable invocation (from $ to end
1821 if (val == var_Error || val == varNoError) {
1823 * If performing old-time variable
1824 * substitution, skip over the variable and
1825 * continue with the substitution. Otherwise,
1826 * store the dollar sign and advance str so
1827 * we continue with the string...
1831 } else if (undefErr) {
1833 * If variable is undefined, complain
1834 * and skip the variable. The
1835 * complaint will stop us from doing
1836 * anything when the file is parsed.
1838 if (!errorReported) {
1839 Parse_Error(PARSE_FATAL,
1840 "Undefined variable \"%.*s\"", length, str);
1843 errorReported = TRUE;
1845 Buf_AddByte(buf, (Byte)*str);
1850 * We've now got a variable structure to
1851 * store in. But first, advance the string
1857 * Copy all the characters from the variable
1858 * value straight into the new string.
1860 Buf_Append(buf, val);
1867 * Skip as many characters as possible -- either to
1868 * the end of the string or to the next dollar sign
1869 * (variable invocation).
1871 const char *cp = str;
1875 } while (str[0] != '$' && str[0] != '\0');
1877 Buf_AppendRange(buf, cp, str);
1885 *-----------------------------------------------------------------------
1887 * Return the tail from each of a list of words. Used to set the
1888 * System V local variables.
1891 * The resulting string.
1896 *-----------------------------------------------------------------------
1899 Var_GetTail(char *file)
1902 return (VarModify(file, VarTail, (void *)NULL));
1906 *-----------------------------------------------------------------------
1908 * Find the leading components of a (list of) filename(s).
1909 * XXX: VarHead does not replace foo by ., as (sun) System V make
1913 * The leading components.
1918 *-----------------------------------------------------------------------
1921 Var_GetHead(char *file)
1924 return (VarModify(file, VarHead, (void *)NULL));
1928 *-----------------------------------------------------------------------
1930 * Initialize the module
1936 * The VAR_CMD and VAR_GLOBAL contexts are created
1937 *-----------------------------------------------------------------------
1943 VAR_GLOBAL = Targ_NewGN("Global");
1944 VAR_CMD = Targ_NewGN("Command");
1948 *-----------------------------------------------------------------------
1950 * print all variables in a context
1951 *-----------------------------------------------------------------------
1954 Var_Dump(const GNode *ctxt)
1959 LST_FOREACH(ln, &ctxt->context) {
1961 printf("%-16s = %s\n", v->name,
1962 (const char *)Buf_GetAll(v->val, NULL));