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.185 2005/04/15 21:06:34 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_ENV; /* variables from the environment */
144 GNode *VAR_GLOBAL; /* variables from the makefile */
145 GNode *VAR_CMD; /* variables defined on the command-line */
147 #define OPEN_PAREN '('
148 #define CLOSE_PAREN ')'
149 #define OPEN_BRACE '{'
150 #define CLOSE_BRACE '}'
153 * Create a Var object.
155 * @param name Name of variable.
156 * @param value Value of variable.
157 * @param flags Flags set on variable.
160 VarCreate(const char name[], const char value[], int flags)
164 v = emalloc(sizeof(Var));
165 v->name = estrdup(name);
166 v->val = Buf_Init(0);
170 Buf_Append(v->val, value);
176 * Destroy a Var object.
178 * @param v Object to destroy.
179 * @param f true if internal buffer in Buffer object is to be
183 VarDestroy(Var *v, Boolean f)
186 Buf_Destroy(v->val, f);
192 * Find a variable in a variable list.
195 VarLookup(Lst *vlist, const char *name)
199 LST_FOREACH(ln, vlist)
200 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0)
201 return (Lst_Datum(ln));
206 *-----------------------------------------------------------------------
207 * VarPossiblyExpand --
208 * Expand a variable name's embedded variables in the given context.
211 * The contents of name, possibly expanded.
212 *-----------------------------------------------------------------------
215 VarPossiblyExpand(const char *name, GNode *ctxt)
219 if (strchr(name, '$') != NULL) {
220 buf = Var_Subst(NULL, name, ctxt, 0);
221 return (Buf_Peel(buf));
223 return estrdup(name);
228 * If the variable name begins with a '.', it could very well be
229 * one of the local ones. We check the name against all the local
230 * variables and substitute the short version in for 'name' if it
231 * matches one of them.
234 VarLocal(const char name[])
236 if (name[0] == '.') {
239 if (!strcmp(name, ".ALLSRC"))
241 if (!strcmp(name, ".ARCHIVE"))
245 if (!strcmp(name, ".IMPSRC"))
249 if (!strcmp(name, ".MEMBER"))
253 if (!strcmp(name, ".OODATE"))
257 if (!strcmp(name, ".PREFIX"))
261 if (!strcmp(name, ".TARGET"))
272 * Find the given variable in the given context and the enviornment.
275 * A pointer to the structure describing the desired variable or
276 * NULL if the variable does not exist.
279 VarFindEnv(const char name[], GNode *ctxt)
283 name = VarLocal(name);
285 if ((var = VarLookup(&ctxt->context, name)) != NULL)
288 if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
295 * Look for the variable in the given context.
298 VarFindOnly(const char name[], GNode *ctxt)
301 return VarLookup(&ctxt->context, VarLocal(name));
305 * Look for the variable in all contexts.
308 VarFindAny(const char name[], GNode *ctxt)
310 Boolean localCheckEnvFirst;
314 name = VarLocal(name);
317 * Note whether this is one of the specific variables we were told
318 * through the -E flag to use environment-variable-override for.
320 localCheckEnvFirst = FALSE;
321 LST_FOREACH(ln, &envFirstVars) {
322 if (strcmp(Lst_Datum(ln), name) == 0) {
323 localCheckEnvFirst = TRUE;
329 * First look for the variable in the given context. If it's not there,
330 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
331 * in that order, depending on the FIND_* flags in 'flags'
333 if ((var = VarLookup(&ctxt->context, name)) != NULL)
336 /* not there - try command line context */
337 if (ctxt != VAR_CMD) {
338 if ((var = VarLookup(&VAR_CMD->context, name)) != NULL)
342 /* not there - try global context, but only if not -e/-E */
343 if (ctxt != VAR_GLOBAL && (!checkEnvFirst && !localCheckEnvFirst)) {
344 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
348 if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
351 /* deferred check for the environment (in case of -e/-E) */
352 if ((ctxt != VAR_GLOBAL) && (checkEnvFirst || localCheckEnvFirst)) {
353 if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
361 * Add a new variable of name name and value val to the given context.
367 * The new variable is placed at the front of the given context
368 * The name and val arguments are duplicated so they may
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 LST_FOREACH(ln, &ctxt->context) {
399 if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0) {
400 VarDestroy(Lst_Datum(ln), TRUE);
401 Lst_Remove(&ctxt->context, ln);
408 *-----------------------------------------------------------------------
410 * Set the variable name to the value val in the given context.
416 * If the variable doesn't yet exist, a new record is created for it.
417 * Else the old value is freed and the new one stuck in its place
420 * The variable is searched for only in its context before being
421 * created in that context. I.e. if the context is VAR_GLOBAL,
422 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
423 * VAR_CMD->context is searched. This is done to avoid the literally
424 * thousands of unnecessary strcmp's that used to be done to
425 * set, say, $(@) or $(<).
426 *-----------------------------------------------------------------------
429 Var_Set(const char *name, const char *val, GNode *ctxt)
435 * We only look for a variable in the given context since anything
436 * set here will override anything in a lower context, so there's not
437 * much point in searching them all just to save a bit of memory...
439 n = VarPossiblyExpand(name, ctxt);
440 v = VarFindOnly(n, ctxt);
442 VarAdd(n, val, ctxt);
443 if (ctxt == VAR_CMD) {
445 * Any variables given on the command line
446 * are automatically exported to the
447 * environment (as per POSIX standard)
453 Buf_Append(v->val, val);
455 if (ctxt == VAR_CMD || (v->flags & VAR_TO_ENV)) {
457 * Any variables given on the command line
458 * are automatically exported to the
459 * environment (as per POSIX standard)
466 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
472 * Set the VAR_TO_ENV flag on a variable
475 Var_SetEnv(const char *name, GNode *ctxt)
479 v = VarFindOnly(name, VAR_CMD);
482 * Do not allow .EXPORT: to be set on variables
483 * from the comand line or MAKEFLAGS.
486 "Warning: Did not set .EXPORT: on %s because it "
487 "is from the comand line or MAKEFLAGS", name);
491 v = VarFindAny(name, ctxt);
493 Lst_AtFront(&VAR_ENV->context,
494 VarCreate(name, NULL, VAR_TO_ENV));
496 Error("Warning: .EXPORT: set on undefined variable %s", name);
498 if ((v->flags & VAR_TO_ENV) == 0) {
499 v->flags |= VAR_TO_ENV;
500 setenv(v->name, Buf_Data(v->val), 1);
506 *-----------------------------------------------------------------------
508 * The variable of the given name has the given value appended to it in
515 * If the variable doesn't exist, it is created. Else the strings
516 * are concatenated (with a space in between).
519 * Only if the variable is being sought in the global context is the
520 * environment searched.
521 * XXX: Knows its calling circumstances in that if called with ctxt
522 * an actual target, it will only search that context since only
523 * a local variable could be being appended to. This is actually
524 * a big win and must be tolerated.
525 *-----------------------------------------------------------------------
528 Var_Append(const char *name, const char *val, GNode *ctxt)
533 n = VarPossiblyExpand(name, ctxt);
534 if (ctxt == VAR_GLOBAL) {
535 v = VarFindEnv(n, ctxt);
537 v = VarFindOnly(n, ctxt);
540 VarAdd(n, val, ctxt);
542 Buf_AddByte(v->val, (Byte)' ');
543 Buf_Append(v->val, val);
544 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
550 *-----------------------------------------------------------------------
552 * See if the given variable exists.
555 * TRUE if it does, FALSE if it doesn't
560 *-----------------------------------------------------------------------
563 Var_Exists(const char *name, GNode *ctxt)
568 n = VarPossiblyExpand(name, ctxt);
569 v = VarFindAny(n, ctxt);
580 *-----------------------------------------------------------------------
582 * Return the value of the named variable in the given context
585 * The value if the variable exists, NULL if it doesn't
589 *-----------------------------------------------------------------------
592 Var_Value(const char *name, GNode *ctxt, char **frp)
598 n = VarPossiblyExpand(name, ctxt);
599 v = VarFindAny(n, ctxt);
604 p = Buf_Data(v->val);
612 *-----------------------------------------------------------------------
614 * Modify each of the words of the passed string using the given
615 * function. Used to implement all modifiers.
618 * A string of all the words modified appropriately.
621 * Uses brk_string() so it invalidates any previous call to
624 *-----------------------------------------------------------------------
627 VarModify(const char *str, VarModifyProc *modProc, void *datum)
629 char **av; /* word list [first word does not count] */
631 Buffer *buf; /* Buffer for the new string */
632 Boolean addSpace; /* TRUE if need to add a space to the buffer
633 * before adding the trimmed word */
636 av = brk_string(str, &ac, FALSE);
641 for (i = 1; i < ac; i++)
642 addSpace = (*modProc)(av[i], addSpace, buf, datum);
644 return (Buf_Peel(buf));
648 *-----------------------------------------------------------------------
650 * Sort the words in the string.
653 * str String whose words should be sorted
654 * cmp A comparison function to control the ordering
657 * A string containing the words sorted
660 * Uses brk_string() so it invalidates any previous call to
663 *-----------------------------------------------------------------------
666 VarSortWords(const char *str, int (*cmp)(const void *, const void *))
673 av = brk_string(str, &ac, FALSE);
674 qsort(av + 1, ac - 1, sizeof(char *), cmp);
677 for (i = 1; i < ac; i++) {
678 Buf_Append(buf, av[i]);
679 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
682 return (Buf_Peel(buf));
686 SortIncreasing(const void *l, const void *r)
689 return (strcmp(*(const char* const*)l, *(const char* const*)r));
693 *-----------------------------------------------------------------------
695 * Pass through the tstr looking for 1) escaped delimiters,
696 * '$'s and backslashes (place the escaped character in
697 * uninterpreted) and 2) unescaped $'s that aren't before
698 * the delimiter (expand the variable substitution).
699 * Return the expanded string or NULL if the delimiter was missing
700 * If pattern is specified, handle escaped ampersands, and replace
701 * unescaped ampersands with the lhs of the pattern.
704 * A string of all the words modified appropriately.
705 * If length is specified, return the string length of the buffer
706 * If flags is specified and the last character of the pattern is a
707 * $ set the VAR_MATCH_END bit of flags.
711 *-----------------------------------------------------------------------
714 VarGetPattern(VarParser *vp, int delim, int *flags, VarPattern *patt)
721 * Skim through until the matching delimiter is found; pick up
722 * variable substitutions on the way. Also allow backslashes to quote
723 * the delimiter, $, and \, but don't touch other backslashes.
725 while (*vp->ptr != '\0') {
726 if (*vp->ptr == delim) {
729 } else if ((vp->ptr[0] == '\\') &&
730 ((vp->ptr[1] == delim) ||
731 (vp->ptr[1] == '\\') ||
732 (vp->ptr[1] == '$') ||
733 (vp->ptr[1] == '&' && patt != NULL))) {
734 vp->ptr++; /* consume backslash */
735 Buf_AddByte(buf, (Byte)vp->ptr[0]);
738 } else if (vp->ptr[0] == '$') {
739 if (vp->ptr[1] == delim) {
741 Buf_AddByte(buf, (Byte)vp->ptr[0]);
745 * Unescaped $ at end of patt =>
746 * anchor patt at end.
748 *flags |= VAR_MATCH_END;
762 * If unescaped dollar sign not
763 * before the delimiter, assume it's
764 * a variable substitution and
767 rval = VarParse(&subvp, &rfree);
768 Buf_Append(buf, rval);
773 } else if (vp->ptr[0] == '&' && patt != NULL) {
774 Buf_AppendBuf(buf, patt->lhs);
777 Buf_AddByte(buf, (Byte)vp->ptr[0]);
782 Buf_Destroy(buf, TRUE);
787 *-----------------------------------------------------------------------
789 * Quote shell meta-characters in the string
797 *-----------------------------------------------------------------------
800 Var_Quote(const char *str)
803 /* This should cover most shells :-( */
804 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
806 buf = Buf_Init(MAKE_BSIZE);
807 for (; *str; str++) {
808 if (strchr(meta, *str) != NULL)
809 Buf_AddByte(buf, (Byte)'\\');
810 Buf_AddByte(buf, (Byte)*str);
813 return (Buf_Peel(buf));
817 *-----------------------------------------------------------------------
819 * Print the error caused by a regcomp or regexec call.
825 * An error gets printed.
827 *-----------------------------------------------------------------------
830 VarREError(int err, regex_t *pat, const char *str)
835 errlen = regerror(err, pat, 0, 0);
836 errbuf = emalloc(errlen);
837 regerror(err, pat, errbuf, errlen);
838 Error("%s: %s", str, errbuf);
843 * Make sure this variable is fully expanded.
846 VarExpand(Var *v, VarParser *vp)
851 if (v->flags & VAR_IN_USE) {
852 Fatal("Variable %s is recursive.", v->name);
856 v->flags |= VAR_IN_USE;
859 * Before doing any modification, we have to make sure the
860 * value has been fully expanded. If it looks like recursion
861 * might be necessary (there's a dollar sign somewhere in the
862 * variable's value) we just call Var_Subst to do any other
863 * substitutions that are necessary. Note that the value
864 * returned by Var_Subst will have been
865 * dynamically-allocated, so it will need freeing when we
868 value = Buf_Data(v->val);
869 if (strchr(value, '$') == NULL) {
870 result = strdup(value);
874 buf = Var_Subst(NULL, value, vp->ctxt, vp->err);
875 result = Buf_Peel(buf);
878 v->flags &= ~VAR_IN_USE;
884 * Select only those words in value that match the modifier.
887 modifier_M(VarParser *vp, const char value[], char endc)
894 modifier = vp->ptr[0];
895 vp->ptr++; /* consume 'M' or 'N' */
898 * Compress the \:'s out of the pattern, so allocate enough
899 * room to hold the uncompressed pattern and compress the
900 * pattern into that space.
902 patt = estrdup(vp->ptr);
904 while (vp->ptr[0] != '\0') {
905 if (vp->ptr[0] == endc || vp->ptr[0] == ':') {
908 if (vp->ptr[0] == '\\' &&
909 (vp->ptr[1] == endc || vp->ptr[1] == ':')) {
910 vp->ptr++; /* consume backslash */
918 if (modifier == 'M') {
919 newValue = VarModify(value, VarMatch, patt);
921 newValue = VarModify(value, VarNoMatch, patt);
929 * Substitute the replacement string for the pattern. The substitution
930 * is applied to each word in value.
933 modifier_S(VarParser *vp, const char value[], Var *v)
941 vp->ptr++; /* consume 'S' */
943 delim = *vp->ptr; /* used to find end of pattern */
944 vp->ptr++; /* consume 1st delim */
947 * If pattern begins with '^', it is anchored to the start of the
948 * word -- skip over it and flag pattern.
950 if (*vp->ptr == '^') {
951 patt.flags |= VAR_MATCH_START;
955 patt.lhs = VarGetPattern(vp, delim, &patt.flags, NULL);
956 if (patt.lhs == NULL) {
958 * LHS didn't end with the delim, complain and exit.
960 Fatal("Unclosed substitution for %s (%c missing)",
964 vp->ptr++; /* consume 2nd delim */
966 patt.rhs = VarGetPattern(vp, delim, NULL, &patt);
967 if (patt.rhs == NULL) {
969 * RHS didn't end with the delim, complain and exit.
971 Fatal("Unclosed substitution for %s (%c missing)",
975 vp->ptr++; /* consume last delim */
978 * Check for global substitution. If 'g' after the final delimiter,
979 * substitution is global and is marked that way.
981 if (vp->ptr[0] == 'g') {
982 patt.flags |= VAR_SUB_GLOBAL;
987 * Global substitution of the empty string causes an infinite number
988 * of matches, unless anchored by '^' (start of string) or '$' (end
989 * of string). Catch the infinite substitution here. Note that flags
990 * can only contain the 3 bits we're interested in so we don't have
991 * to mask unrelated bits. We can test for equality.
993 if (Buf_Size(patt.lhs) == 0 && patt.flags == VAR_SUB_GLOBAL)
994 Fatal("Global substitution of the empty string");
996 newValue = VarModify(value, VarSubstitute, &patt);
999 * Free the two strings.
1008 modifier_C(VarParser *vp, char value[], Var *v)
1017 vp->ptr++; /* consume 'C' */
1019 delim = *vp->ptr; /* delimiter between sections */
1021 vp->ptr++; /* consume 1st delim */
1023 patt.lhs = VarGetPattern(vp, delim, NULL, NULL);
1024 if (patt.lhs == NULL) {
1025 Fatal("Unclosed substitution for %s (%c missing)",
1029 vp->ptr++; /* consume 2st delim */
1031 patt.rhs = VarGetPattern(vp, delim, NULL, NULL);
1032 if (patt.rhs == NULL) {
1033 Fatal("Unclosed substitution for %s (%c missing)",
1037 vp->ptr++; /* consume last delim */
1041 patt.flags |= VAR_SUB_GLOBAL;
1042 vp->ptr++; /* consume 'g' */
1045 patt.flags |= VAR_SUB_ONE;
1046 vp->ptr++; /* consume '1' */
1052 error = regcomp(&patt.re, Buf_Data(patt.lhs), REG_EXTENDED);
1054 VarREError(error, &patt.re, "RE substitution error");
1060 patt.nsub = patt.re.re_nsub + 1;
1065 patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1067 newValue = VarModify(value, VarRESubstitute, &patt);
1078 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1082 * This can either be a bogus modifier or a System-V substitution
1092 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1097 * First we make a pass through the string trying to verify it is a
1098 * SYSV-make-style translation: it must be: <string1>=<string2>)
1103 while (*cp != '\0' && cnt) {
1106 /* continue looking for endc */
1107 } else if (*cp == endc)
1109 else if (*cp == startc)
1115 if (*cp == endc && eqFound) {
1117 * Now we break this sucker into the lhs and rhs.
1119 patt.lhs = VarGetPattern(vp, '=', &patt.flags, NULL);
1120 if (patt.lhs == NULL) {
1121 Fatal("Unclosed substitution for %s (%c missing)",
1124 vp->ptr++; /* consume '=' */
1126 patt.rhs = VarGetPattern(vp, endc, NULL, &patt);
1127 if (patt.rhs == NULL) {
1128 Fatal("Unclosed substitution for %s (%c missing)",
1133 * SYSV modifications happen through the whole string. Note
1134 * the pattern is anchored at the end.
1136 newStr = VarModify(value, VarSYSVMatch, &patt);
1143 Error("Unknown modifier '%c'\n", *vp->ptr);
1145 while (*vp->ptr != '\0') {
1146 if (*vp->ptr == endc && *vp->ptr == ':') {
1158 * Now we need to apply any modifiers the user wants applied.
1161 * words which match the given <pattern>.
1162 * <pattern> is of the standard file
1164 * :S<d><pat1><d><pat2><d>[g]
1165 * Substitute <pat2> for <pat1> in the value
1166 * :C<d><pat1><d><pat2><d>[g]
1167 * Substitute <pat2> for regex <pat1> in the value
1168 * :H Substitute the head of each word
1169 * :T Substitute the tail of each word
1170 * :E Substitute the extension (minus '.') of
1172 * :R Substitute the root of each word
1173 * (pathname minus the suffix).
1175 * Like :S, but the rhs goes to the end of
1177 * :U Converts variable to upper-case.
1178 * :L Converts variable to lower-case.
1180 * XXXHB update this comment or remove it and point to the man page.
1183 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1188 value = VarExpand(v, vp);
1191 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1193 vp->ptr++; /* consume first colon */
1195 while (*vp->ptr != '\0') {
1196 char *newStr; /* New value to return */
1198 if (*vp->ptr == endc) {
1202 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1206 newStr = modifier_M(vp, value, endc);
1209 newStr = modifier_S(vp, value, v);
1212 newStr = modifier_C(vp, value, v);
1215 if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1217 if ((vp->ptr[0] == 's') &&
1218 (vp->ptr[1] == 'h') &&
1219 (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1223 buf = Cmd_Exec(value, &error);
1224 newStr = Buf_Peel(buf);
1227 Error(error, value);
1232 newStr = sysVvarsub(vp, startc, v, value);
1237 switch (vp->ptr[0]) {
1242 buf = Buf_Init(MAKE_BSIZE);
1243 for (cp = value; *cp; cp++)
1244 Buf_AddByte(buf, (Byte)tolower(*cp));
1246 newStr = Buf_Peel(buf);
1252 newStr = VarSortWords(value, SortIncreasing);
1256 newStr = Var_Quote(value);
1260 newStr = VarModify(value, VarTail, NULL);
1267 buf = Buf_Init(MAKE_BSIZE);
1268 for (cp = value; *cp; cp++)
1269 Buf_AddByte(buf, (Byte)toupper(*cp));
1271 newStr = Buf_Peel(buf);
1277 newStr = VarModify(value, VarHead, NULL);
1281 newStr = VarModify(value, VarSuffix, NULL);
1285 newStr = VarModify(value, VarRoot, NULL);
1289 newStr = sysVvarsub(vp, startc, v, value);
1295 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1301 *freeResult = (value == var_Error) ? FALSE : TRUE;
1303 if (vp->ptr[0] == ':') {
1304 vp->ptr++; /* consume colon */
1312 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1319 vname = Buf_GetAll(buf, &vlen);
1321 v = VarFindAny(vname, vp->ctxt);
1323 value = ParseModifier(vp, startc, v, freeResult);
1327 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1330 * Still need to get to the end of the variable
1331 * specification, so kludge up a Var structure for the
1334 v = VarCreate(vname, NULL, VAR_JUNK);
1335 value = ParseModifier(vp, startc, v, freeResult);
1339 VarDestroy(v, TRUE);
1341 consumed = vp->ptr - vp->input + 1;
1343 * If substituting a local variable in a non-local context,
1344 * assume it's for dynamic source stuff. We have to handle
1345 * this specially and return the longhand for the variable
1346 * with the dollar sign escaped so it makes it back to the
1347 * caller. Only four of the local variables are treated
1348 * specially as they are the only four that will be set when
1349 * dynamic sources are expanded.
1352 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1353 if (strchr("!%*@", vname[0]) != NULL) {
1354 value = emalloc(consumed + 1);
1355 strncpy(value, vp->input, consumed);
1356 value[consumed] = '\0';
1364 isupper((unsigned char)vname[1])) {
1365 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1366 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1367 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1368 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1369 value = emalloc(consumed + 1);
1370 strncpy(value, vp->input, consumed);
1371 value[consumed] = '\0';
1378 *freeResult = FALSE;
1379 return (vp->err ? var_Error : varNoError);
1382 * Check for D and F forms of local variables since we're in
1383 * a local context and the name is the right length.
1386 (vname[1] == 'F' || vname[1] == 'D') &&
1387 (strchr("!%*<>@", vname[0]) != NULL)) {
1393 v = VarFindOnly(name, vp->ctxt);
1395 value = ParseModifier(vp, startc, v, freeResult);
1401 * Still need to get to the end of the variable
1402 * specification, so kludge up a Var structure for the
1405 v = VarCreate(vname, NULL, VAR_JUNK);
1406 value = ParseModifier(vp, startc, v, freeResult);
1410 VarDestroy(v, TRUE);
1412 *freeResult = FALSE;
1413 return (vp->err ? var_Error : varNoError);
1418 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1425 vname = Buf_GetAll(buf, &vlen);
1427 v = VarFindAny(vname, vp->ctxt);
1429 value = VarExpand(v, vp);
1434 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1435 size_t consumed = vp->ptr - vp->input + 1;
1438 * If substituting a local variable in a non-local context,
1439 * assume it's for dynamic source stuff. We have to handle
1440 * this specially and return the longhand for the variable
1441 * with the dollar sign escaped so it makes it back to the
1442 * caller. Only four of the local variables are treated
1443 * specially as they are the only four that will be set when
1444 * dynamic sources are expanded.
1447 (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
1448 if (strchr("!%*@", vname[0]) != NULL) {
1449 value = emalloc(consumed + 1);
1450 strncpy(value, vp->input, consumed);
1451 value[consumed] = '\0';
1459 isupper((unsigned char)vname[1])) {
1460 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1461 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1462 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1463 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1464 value = emalloc(consumed + 1);
1465 strncpy(value, vp->input, consumed);
1466 value[consumed] = '\0';
1474 * Check for D and F forms of local variables since we're in
1475 * a local context and the name is the right length.
1478 (vname[1] == 'F' || vname[1] == 'D') &&
1479 (strchr("!%*<>@", vname[0]) != NULL)) {
1485 v = VarFindOnly(name, vp->ctxt);
1489 * No need for nested expansion or anything,
1490 * as we're the only one who sets these
1491 * things and we sure don't put nested
1492 * invocations in them...
1494 val = Buf_Data(v->val);
1496 if (vname[1] == 'D') {
1497 val = VarModify(val, VarHead, NULL);
1499 val = VarModify(val, VarTail, NULL);
1508 *freeResult = FALSE;
1509 return (vp->err ? var_Error : varNoError);
1513 * Parse a multi letter variable name, and return it's value.
1516 VarParseLong(VarParser *vp, Boolean *freeResult)
1523 buf = Buf_Init(MAKE_BSIZE);
1525 startc = vp->ptr[0];
1526 vp->ptr++; /* consume opening paren or brace */
1528 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1531 * Process characters until we reach an end character or a colon,
1532 * replacing embedded variables as we go.
1534 while (*vp->ptr != '\0') {
1535 if (*vp->ptr == endc) {
1536 value = ParseRestEnd(vp, buf, freeResult);
1537 vp->ptr++; /* consume closing paren or brace */
1538 Buf_Destroy(buf, TRUE);
1541 } else if (*vp->ptr == ':') {
1542 value = ParseRestModifier(vp, startc, buf, freeResult);
1543 vp->ptr++; /* consume closing paren or brace */
1544 Buf_Destroy(buf, TRUE);
1547 } else if (*vp->ptr == '$') {
1557 rval = VarParse(&subvp, &rfree);
1558 if (rval == var_Error) {
1559 Fatal("Error expanding embedded variable.");
1561 Buf_Append(buf, rval);
1564 vp->ptr = subvp.ptr;
1566 Buf_AddByte(buf, (Byte)*vp->ptr);
1571 /* If we did not find the end character, return var_Error */
1572 Buf_Destroy(buf, TRUE);
1573 *freeResult = FALSE;
1578 * Parse a single letter variable name, and return it's value.
1581 VarParseShort(VarParser *vp, Boolean *freeResult)
1587 vname[0] = vp->ptr[0];
1590 vp->ptr++; /* consume single letter */
1592 v = VarFindAny(vname, vp->ctxt);
1594 value = VarExpand(v, vp);
1600 * If substituting a local variable in a non-local context, assume
1601 * it's for dynamic source stuff. We have to handle this specially
1602 * and return the longhand for the variable with the dollar sign
1603 * escaped so it makes it back to the caller. Only four of the local
1604 * variables are treated specially as they are the only four that
1605 * will be set when dynamic sources are expanded.
1607 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1609 /* XXX: It looks like $% and $! are reversed here */
1613 return (estrdup("$(.TARGET)"));
1616 return (estrdup("$(.ARCHIVE)"));
1619 return (estrdup("$(.PREFIX)"));
1622 return (estrdup("$(.MEMBER)"));
1624 *freeResult = FALSE;
1625 return (vp->err ? var_Error : varNoError);
1629 /* Variable name was not found. */
1630 *freeResult = FALSE;
1631 return (vp->err ? var_Error : varNoError);
1635 VarParse(VarParser *vp, Boolean *freeResult)
1638 vp->ptr++; /* consume '$' or last letter of conditional */
1640 if (vp->ptr[0] == '\0') {
1641 /* Error, there is only a dollar sign in the input string. */
1642 *freeResult = FALSE;
1643 return (vp->err ? var_Error : varNoError);
1645 } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
1646 /* multi letter variable name */
1647 return (VarParseLong(vp, freeResult));
1650 /* single letter variable name */
1651 return (VarParseShort(vp, freeResult));
1656 *-----------------------------------------------------------------------
1658 * Given the start of a variable invocation, extract the variable
1659 * name and find its value, then modify it according to the
1663 * The value of the variable or var_Error if the specification
1664 * is invalid. The number of characters in the specification
1665 * is placed in the variable pointed to by consumed. (for
1666 * invalid specifications, this is just 2 to skip the '$' and
1667 * the following letter, or 1 if '$' was the last character
1668 * in the string). A Boolean in *freeResult telling whether the
1669 * returned string should be freed by the caller.
1673 *-----------------------------------------------------------------------
1676 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1677 size_t *consumed, Boolean *freeResult)
1687 value = VarParse(&vp, freeResult);
1688 *consumed += vp.ptr - vp.input;
1693 *-----------------------------------------------------------------------
1695 * Substitute for all variables in the given string in the given context
1696 * If err is TRUE, Parse_Error will be called when an undefined
1697 * variable is encountered.
1700 * The resulting string.
1703 * None. The old string must be freed by the caller
1704 *-----------------------------------------------------------------------
1707 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean err)
1709 Boolean errorReported;
1710 Buffer *buf; /* Buffer for forming things */
1713 * Set TRUE if an error has already been reported to prevent a
1714 * plethora of messages when recursing. XXXHB this comment sounds
1717 errorReported = FALSE;
1721 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1723 * A dollar sign may be escaped either with another
1724 * dollar sign. In such a case, we skip over the
1725 * escape character and store the dollar sign into
1726 * the buffer directly.
1728 Buf_AddByte(buf, (Byte)str[0]);
1731 } else if (str[0] == '$') {
1733 * Variable invocation.
1738 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1740 const char *p = str + 2;
1743 * Scan up to the end of the
1746 while (*p != '\0' &&
1748 *p != CLOSE_PAREN &&
1749 *p != CLOSE_BRACE &&
1755 * A variable inside the
1756 * variable. We cannot expand
1757 * the external variable yet,
1758 * so we try again with the
1762 Buf_AppendRange(buf, str, p);
1767 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1772 * we want to expand,
1776 while (*p != '$' && *p != '\0')
1779 Buf_AppendRange(buf, str, p);
1785 * Single letter variable
1788 if (var[1] == '\0' && var[0] == str[1]) {
1791 Buf_AddBytes(buf, 2, (const Byte *) str);
1811 rval = VarParse(&subvp, &rfree);
1814 * When we come down here, val should either point to
1815 * the value of this variable, suitably modified, or
1816 * be NULL. Length should be the total length of the
1817 * potential variable invocation (from $ to end
1820 if (rval == var_Error || rval == varNoError) {
1822 * If performing old-time variable
1823 * substitution, skip over the variable and
1824 * continue with the substitution. Otherwise,
1825 * store the dollar sign and advance str so
1826 * we continue with the string...
1832 * If variable is undefined, complain
1833 * and skip the variable. The
1834 * complaint will stop us from doing
1835 * anything when the file is parsed.
1837 if (!errorReported) {
1838 Parse_Error(PARSE_FATAL,
1839 "Undefined variable \"%.*s\"", subvp.ptr - subvp.input, str);
1842 errorReported = TRUE;
1844 Buf_AddByte(buf, (Byte)*str);
1849 * We've now got a variable structure to
1850 * store in. But first, advance the string
1856 * Copy all the characters from the variable
1857 * value straight into the new string.
1859 Buf_Append(buf, rval);
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 *-----------------------------------------------------------------------
1940 Var_Init(char **env)
1944 VAR_CMD = Targ_NewGN("Command");
1945 VAR_ENV = Targ_NewGN("Environment");
1946 VAR_GLOBAL = Targ_NewGN("Global");
1949 * Copy user environment variables into ENV context.
1951 for (ptr = env; *ptr != NULL; ++ptr) {
1952 char *tmp = estrdup(*ptr);
1953 const char *name = tmp;
1954 char *sep = strchr(name, '=');
1955 const char *value = sep + 1;
1959 VarAdd(name, value, VAR_ENV);
1966 *-----------------------------------------------------------------------
1968 * print all variables in a context
1969 *-----------------------------------------------------------------------
1972 Var_Dump(const GNode *ctxt)
1977 LST_FOREACH(ln, &ctxt->context) {
1979 printf("%-16s = %s\n", v->name, Buf_Data(v->val));