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.168 2005/03/19 00:15:44 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 unless flags
696 * has VAR_NOSUBST set).
697 * Return the expanded string or NULL if the delimiter was missing
698 * If pattern is specified, handle escaped ampersands, and replace
699 * unescaped ampersands with the lhs of the pattern.
702 * A string of all the words modified appropriately.
703 * If length is specified, return the string length of the buffer
704 * If flags is specified and the last character of the pattern is a
705 * $ set the VAR_MATCH_END bit of flags.
709 *-----------------------------------------------------------------------
712 VarGetPattern(VarParser *vp, int delim, int *flags,
713 size_t *length, VarPattern *patt)
720 * Skim through until the matching delimiter is found; pick up
721 * variable substitutions on the way. Also allow backslashes to quote
722 * the delimiter, $, and \, but don't touch other backslashes.
724 while (*vp->ptr != '\0') {
725 if (*vp->ptr == delim) {
727 vp->ptr++; /* consume delim */
729 result = (char *)Buf_GetAll(buf, length);
730 Buf_Destroy(buf, FALSE);
733 } else if ((vp->ptr[0] == '\\') &&
734 ((vp->ptr[1] == delim) ||
735 (vp->ptr[1] == '\\') ||
736 (vp->ptr[1] == '$') ||
737 (vp->ptr[1] == '&' && patt != NULL))) {
738 vp->ptr++; /* consume backslash */
739 Buf_AddByte(buf, (Byte)vp->ptr[0]);
742 } else if (vp->ptr[0] == '$') {
743 if (vp->ptr[1] == delim) {
745 Buf_AddByte(buf, (Byte)vp->ptr[0]);
749 * Unescaped $ at end of patt =>
750 * anchor patt at end.
752 *flags |= VAR_MATCH_END;
756 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
762 * If unescaped dollar sign not
763 * before the delimiter, assume it's
764 * a variable substitution and
768 cp = Var_Parse(vp->ptr, vp->ctxt, vp->err, &len, &freeIt);
774 const char *cp = vp->ptr + 1;
776 if (*cp == OPEN_PAREN || *cp == OPEN_BRACE) {
778 * Find the end of this
779 * variable reference and
780 * suck it in without further
782 * interperated later.
785 int want = (*cp == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
788 for (++cp; *cp != '\0' && depth > 0; ++cp) {
789 if (cp[-1] != '\\') {
796 Buf_AppendRange(buf, vp->ptr, cp);
805 } else if (vp->ptr[0] == '&' && patt != NULL) {
806 Buf_AddBytes(buf, patt->leftLen, (Byte *)patt->lhs);
809 Buf_AddByte(buf, (Byte)vp->ptr[0]);
814 if (length != NULL) {
821 *-----------------------------------------------------------------------
823 * Quote shell meta-characters in the string
831 *-----------------------------------------------------------------------
834 Var_Quote(const char *str)
837 /* This should cover most shells :-( */
838 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
841 buf = Buf_Init(MAKE_BSIZE);
842 for (; *str; str++) {
843 if (strchr(meta, *str) != NULL)
844 Buf_AddByte(buf, (Byte)'\\');
845 Buf_AddByte(buf, (Byte)*str);
847 Buf_AddByte(buf, (Byte)'\0');
848 ret = Buf_GetAll(buf, NULL);
849 Buf_Destroy(buf, FALSE);
854 *-----------------------------------------------------------------------
856 * Print the error caused by a regcomp or regexec call.
862 * An error gets printed.
864 *-----------------------------------------------------------------------
867 VarREError(int err, regex_t *pat, const char *str)
872 errlen = regerror(err, pat, 0, 0);
873 errbuf = emalloc(errlen);
874 regerror(err, pat, errbuf, errlen);
875 Error("%s: %s", str, errbuf);
880 * Make sure this variable is fully expanded.
883 VarExpand(Var *v, VarParser *vp)
888 if (v->flags & VAR_IN_USE) {
889 Fatal("Variable %s is recursive.", v->name);
893 v->flags |= VAR_IN_USE;
896 * Before doing any modification, we have to make sure the
897 * value has been fully expanded. If it looks like recursion
898 * might be necessary (there's a dollar sign somewhere in the
899 * variable's value) we just call Var_Subst to do any other
900 * substitutions that are necessary. Note that the value
901 * returned by Var_Subst will have been
902 * dynamically-allocated, so it will need freeing when we
905 value = (char *)Buf_GetAll(v->val, (size_t *)NULL);
906 if (strchr(value, '$') == NULL) {
907 result = strdup(value);
911 buf = Var_Subst(NULL, value, vp->ctxt, vp->err);
912 result = Buf_GetAll(buf, NULL);
913 Buf_Destroy(buf, FALSE);
916 v->flags &= ~VAR_IN_USE;
922 * Select only those words in value that match the modifier.
925 modifier_M(VarParser *vp, const char value[], char endc)
932 modifier = vp->ptr[0];
933 vp->ptr++; /* consume 'M' or 'N' */
936 * Compress the \:'s out of the pattern, so allocate enough
937 * room to hold the uncompressed pattern and compress the
938 * pattern into that space.
940 patt = estrdup(vp->ptr);
942 while (vp->ptr[0] != '\0') {
943 if ((vp->ptr[0] == endc) || (vp->ptr[0] == ':')) {
946 if ((vp->ptr[0] == '\\') &&
947 ((vp->ptr[1] == endc) || (vp->ptr[1] == ':'))) {
948 vp->ptr++; /* consume backslash */
956 if (modifier == 'M') {
957 newValue = VarModify(value, VarMatch, patt);
959 newValue = VarModify(value, VarNoMatch, patt);
967 * Substitute the replacement string for the pattern. The substitution
968 * is applied to each word in value.
971 modifier_S(VarParser *vp, const char value[], Var *v)
974 Buffer *buf; /* Buffer for patterns */
981 vp->ptr++; /* consume 'S' */
983 delim = *vp->ptr; /* used to find end of pattern */
984 vp->ptr++; /* consume 1st delim */
987 * If pattern begins with '^', it is anchored to the start of the
988 * word -- skip over it and flag pattern.
990 if (*vp->ptr == '^') {
991 pattern.flags |= VAR_MATCH_START;
996 * Pass through the lhs looking for 1) escaped delimiters, '$'s and
997 * backslashes (place the escaped character in uninterpreted) and 2)
998 * unescaped $'s that aren't before the delimiter (expand the
999 * variable substitution). The result is left in the Buffer buf.
1001 while (vp->ptr[0] != delim) {
1002 if (vp->ptr[0] == '\0') {
1004 * LHS didn't end with the delim, complain and exit.
1006 Fatal("Unclosed substitution for %s (%c missing)",
1009 } else if ((vp->ptr[0] == '\\') &&
1010 ((vp->ptr[1] == delim) ||
1011 (vp->ptr[1] == '$') ||
1012 (vp->ptr[1] == '\\'))) {
1013 vp->ptr++; /* consume backslash */
1014 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1017 } else if (vp->ptr[0] == '$') {
1018 if (vp->ptr[1] == delim) {
1020 * Unescaped $ at end of pattern => anchor
1023 pattern.flags |= VAR_MATCH_END;
1027 * If unescaped dollar sign not before the
1028 * delimiter, assume it's a variable
1029 * substitution and recurse.
1036 cp = Var_Parse(vp->ptr, vp->ctxt, vp->err, &len, &freeIt);
1038 Buf_Append(buf, cp);
1044 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1048 vp->ptr++; /* consume 2nd delim */
1051 * Fetch pattern and destroy buffer, but preserve the data in it,
1052 * since that's our lhs.
1054 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1055 Buf_Destroy(buf, FALSE);
1058 * Now comes the replacement string. Three things need to be done
1059 * here: 1) need to compress escaped delimiters and ampersands and 2)
1060 * need to replace unescaped ampersands with the l.h.s. (since this
1061 * isn't regexp, we can do it right here) and 3) expand any variable
1066 while (vp->ptr[0] != delim) {
1067 if (vp->ptr[0] == '\0') {
1069 * Didn't end with delim character, complain
1071 Fatal("Unclosed substitution for %s (%c missing)",
1074 } else if ((vp->ptr[0] == '\\') &&
1075 ((vp->ptr[1] == delim) ||
1076 (vp->ptr[1] == '&') ||
1077 (vp->ptr[1] == '\\') ||
1078 (vp->ptr[1] == '$'))) {
1079 vp->ptr++; /* skip backslash */
1080 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1083 } else if (vp->ptr[0] == '$') {
1084 if (vp->ptr[1] == delim) {
1085 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1093 cp = Var_Parse(vp->ptr, vp->ctxt, vp->err, &len, &freeIt);
1095 Buf_Append(buf, cp);
1100 } else if (vp->ptr[0] == '&') {
1101 Buf_AddBytes(buf, pattern.leftLen, (Byte *)pattern.lhs);
1104 Buf_AddByte(buf, (Byte)vp->ptr[0]);
1108 vp->ptr++; /* consume last delim */
1110 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1111 Buf_Destroy(buf, FALSE);
1114 * Check for global substitution. If 'g' after the final delimiter,
1115 * substitution is global and is marked that way.
1117 if (vp->ptr[0] == 'g') {
1118 pattern.flags |= VAR_SUB_GLOBAL;
1123 * Global substitution of the empty string causes an infinite number
1124 * of matches, unless anchored by '^' (start of string) or '$' (end
1125 * of string). Catch the infinite substitution here. Note that flags
1126 * can only contain the 3 bits we're interested in so we don't have
1127 * to mask unrelated bits. We can test for equality.
1129 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1130 Fatal("Global substitution of the empty string");
1132 newValue = VarModify(value, VarSubstitute, &pattern);
1135 * Free the two strings.
1144 modifier_C(VarParser *vp, char value[], Var *v)
1154 vp->ptr++; /* consume 'C' */
1156 delim = *vp->ptr; /* delimiter between sections */
1158 vp->ptr++; /* consume 1st delim */
1160 re = VarGetPattern(vp, delim, NULL, NULL, NULL);
1162 Fatal("Unclosed substitution for %s (%c missing)",
1166 patt.replace = VarGetPattern(vp, delim, NULL, NULL, NULL);
1167 if (patt.replace == NULL) {
1168 Fatal("Unclosed substitution for %s (%c missing)",
1174 patt.flags |= VAR_SUB_GLOBAL;
1175 vp->ptr++; /* consume 'g' */
1178 patt.flags |= VAR_SUB_ONE;
1179 vp->ptr++; /* consume '1' */
1185 error = regcomp(&patt.re, re, REG_EXTENDED);
1187 VarREError(error, &patt.re, "RE substitution error");
1193 patt.nsub = patt.re.re_nsub + 1;
1198 patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
1200 newValue = VarModify(value, VarRESubstitute, &patt);
1211 sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
1215 * This can either be a bogus modifier or a System-V substitution
1225 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1230 * First we make a pass through the string trying to verify it is a
1231 * SYSV-make-style translation: it must be: <string1>=<string2>)
1236 while (*cp != '\0' && cnt) {
1239 /* continue looking for endc */
1240 } else if (*cp == endc)
1242 else if (*cp == startc)
1248 if (*cp == endc && eqFound) {
1250 * Now we break this sucker into the lhs and rhs.
1252 patt.lhs = VarGetPattern(vp, '=', &patt.flags, &patt.leftLen, NULL);
1253 if (patt.lhs == NULL) {
1254 Fatal("Unclosed substitution for %s (%c missing)",
1257 patt.rhs = VarGetPattern(vp, endc, NULL, &patt.rightLen, &patt);
1258 if (patt.rhs == NULL) {
1259 Fatal("Unclosed substitution for %s (%c missing)",
1263 vp->ptr--; /* put pointer back on top of endc */
1266 * SYSV modifications happen through the whole string. Note
1267 * the pattern is anchored at the end.
1269 newStr = VarModify(value, VarSYSVMatch, &patt);
1276 Error("Unknown modifier '%c'\n", *vp->ptr);
1278 while (*vp->ptr != '\0') {
1279 if (*vp->ptr == endc && *vp->ptr == ':') {
1291 * Now we need to apply any modifiers the user wants applied.
1294 * words which match the given <pattern>.
1295 * <pattern> is of the standard file
1297 * :S<d><pat1><d><pat2><d>[g]
1298 * Substitute <pat2> for <pat1> in the value
1299 * :C<d><pat1><d><pat2><d>[g]
1300 * Substitute <pat2> for regex <pat1> in the value
1301 * :H Substitute the head of each word
1302 * :T Substitute the tail of each word
1303 * :E Substitute the extension (minus '.') of
1305 * :R Substitute the root of each word
1306 * (pathname minus the suffix).
1308 * Like :S, but the rhs goes to the end of
1310 * :U Converts variable to upper-case.
1311 * :L Converts variable to lower-case.
1313 * XXXHB update this comment or remove it and point to the man page.
1316 ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
1321 value = VarExpand(v, vp);
1324 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1326 vp->ptr++; /* consume first colon */
1328 while (*vp->ptr != '\0') {
1329 char *newStr; /* New value to return */
1331 if (*vp->ptr == endc) {
1335 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
1339 newStr = modifier_M(vp, value, endc);
1342 newStr = modifier_S(vp, value, v);
1345 newStr = modifier_C(vp, value, v);
1348 if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
1350 if ((vp->ptr[0] == 's') &&
1351 (vp->ptr[1] == 'h') &&
1352 (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
1356 buf = Cmd_Exec(value, &error);
1357 newStr = Buf_GetAll(buf, NULL);
1358 Buf_Destroy(buf, FALSE);
1361 Error(error, value);
1366 newStr = sysVvarsub(vp, startc, v, value);
1371 switch (vp->ptr[0]) {
1376 buf = Buf_Init(MAKE_BSIZE);
1377 for (cp = value; *cp; cp++)
1378 Buf_AddByte(buf, (Byte)tolower(*cp));
1380 newStr = (char *)Buf_GetAll(buf, NULL);
1381 Buf_Destroy(buf, FALSE);
1387 newStr = VarSortWords(value, SortIncreasing);
1391 newStr = Var_Quote(value);
1395 newStr = VarModify(value, VarTail, NULL);
1402 buf = Buf_Init(MAKE_BSIZE);
1403 for (cp = value; *cp; cp++)
1404 Buf_AddByte(buf, (Byte)toupper(*cp));
1406 newStr = (char *)Buf_GetAll(buf, NULL);
1407 Buf_Destroy(buf, FALSE);
1413 newStr = VarModify(value, VarHead, NULL);
1417 newStr = VarModify(value, VarSuffix, NULL);
1421 newStr = VarModify(value, VarRoot, NULL);
1425 newStr = sysVvarsub(vp, startc, v, value);
1431 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1437 *freeResult = (value == var_Error) ? FALSE : TRUE;
1439 if (vp->ptr[0] == ':') {
1440 vp->ptr++; /* consume colon */
1448 ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
1455 vname = Buf_GetAll(buf, &vlen);
1457 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1459 value = ParseModifier(vp, startc, v, freeResult);
1461 if (v->flags & VAR_FROM_ENV) {
1462 VarDestroy(v, TRUE);
1467 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1468 size_t consumed = vp->ptr - vp->input + 1;
1471 * If substituting a local variable in a non-local context,
1472 * assume it's for dynamic source stuff. We have to handle
1473 * this specially and return the longhand for the variable
1474 * with the dollar sign escaped so it makes it back to the
1475 * caller. Only four of the local variables are treated
1476 * specially as they are the only four that will be set when
1477 * dynamic sources are expanded.
1480 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1481 if (strchr("!%*@", vname[0]) != NULL) {
1482 value = emalloc(consumed + 1);
1483 strncpy(value, vp->input, consumed);
1484 value[consumed] = '\0';
1491 (vname[0] == '.') &&
1492 isupper((unsigned char)vname[1])) {
1493 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1494 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1495 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1496 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1497 value = emalloc(consumed + 1);
1498 strncpy(value, vp->input, consumed);
1499 value[consumed] = '\0';
1507 * Check for D and F forms of local variables since we're in
1508 * a local context and the name is the right length.
1511 (vname[1] == 'F' || vname[1] == 'D') &&
1512 (strchr("!%*<>@", vname[0]) != NULL)) {
1518 v = VarFind(name, vp->ctxt, 0);
1520 value = ParseModifier(vp, startc, v, freeResult);
1527 * Still need to get to the end of the variable
1528 * specification, so kludge up a Var structure for the
1531 v = VarCreate(vname, NULL, VAR_JUNK);
1532 value = ParseModifier(vp, startc, v, freeResult);
1536 VarDestroy(v, TRUE);
1538 *freeResult = FALSE;
1539 return (vp->err ? var_Error : varNoError);
1543 ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
1550 vname = Buf_GetAll(buf, &vlen);
1552 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1554 value = VarExpand(v, vp);
1556 if (v->flags & VAR_FROM_ENV) {
1557 VarDestroy(v, TRUE);
1564 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1565 size_t consumed = vp->ptr - vp->input + 1;
1568 * If substituting a local variable in a non-local context,
1569 * assume it's for dynamic source stuff. We have to handle
1570 * this specially and return the longhand for the variable
1571 * with the dollar sign escaped so it makes it back to the
1572 * caller. Only four of the local variables are treated
1573 * specially as they are the only four that will be set when
1574 * dynamic sources are expanded.
1576 if (((vlen == 1)) ||
1577 ((vlen == 2) && (vname[1] == 'F' || vname[1] == 'D'))) {
1578 if (strchr("!%*@", vname[0]) != NULL) {
1579 value = emalloc(consumed + 1);
1580 strncpy(value, vp->input, consumed);
1581 value[consumed] = '\0';
1588 (vname[0] == '.') &&
1589 isupper((unsigned char)vname[1])) {
1590 if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
1591 (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
1592 (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
1593 (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
1594 value = emalloc(consumed + 1);
1595 strncpy(value, vp->input, consumed);
1596 value[consumed] = '\0';
1604 * Check for D and F forms of local variables since we're in
1605 * a local context and the name is the right length.
1608 (vname[1] == 'F' || vname[1] == 'D') &&
1609 (strchr("!%*<>@", vname[0]) != NULL)) {
1615 v = VarFind(name, vp->ctxt, 0);
1619 * No need for nested expansion or anything,
1620 * as we're the only one who sets these
1621 * things and we sure don't put nested
1622 * invocations in them...
1624 val = (char *)Buf_GetAll(v->val, NULL);
1626 if (vname[1] == 'D') {
1627 val = VarModify(val, VarHead, NULL);
1629 val = VarModify(val, VarTail, NULL);
1638 *freeResult = FALSE;
1639 return (vp->err ? var_Error : varNoError);
1643 * Parse a multi letter variable name, and return it's value.
1646 VarParseLong(VarParser *vp, Boolean *freeResult)
1653 buf = Buf_Init(MAKE_BSIZE);
1655 startc = vp->ptr[0];
1656 vp->ptr++; /* consume opening paren or brace */
1658 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
1661 * Process characters until we reach an end character or a colon,
1662 * replacing embedded variables as we go.
1664 while (*vp->ptr != '\0') {
1665 if (*vp->ptr == endc) {
1666 value = ParseRestEnd(vp, buf, freeResult);
1667 vp->ptr++; /* consume closing paren or brace */
1668 Buf_Destroy(buf, TRUE);
1671 } else if (*vp->ptr == ':') {
1672 value = ParseRestModifier(vp, startc, buf, freeResult);
1673 vp->ptr++; /* consume closing paren or brace */
1674 Buf_Destroy(buf, TRUE);
1677 } else if (*vp->ptr == '$') {
1683 rval = Var_Parse(vp->ptr, vp->ctxt, vp->err,
1685 if (rval == var_Error) {
1686 Fatal("Error expanding embedded variable.");
1688 Buf_Append(buf, rval);
1694 Buf_AddByte(buf, (Byte)*vp->ptr);
1699 /* If we did not find the end character, return var_Error */
1700 Buf_Destroy(buf, TRUE);
1701 *freeResult = FALSE;
1706 * Parse a single letter variable name, and return it's value.
1709 VarParseShort(VarParser *vp, Boolean *freeResult)
1715 vname[0] = vp->ptr[0];
1718 vp->ptr++; /* consume single letter */
1720 v = VarFind(vname, vp->ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1722 value = VarExpand(v, vp);
1724 if (v->flags & VAR_FROM_ENV) {
1725 VarDestroy(v, TRUE);
1733 * If substituting a local variable in a non-local context, assume
1734 * it's for dynamic source stuff. We have to handle this specially
1735 * and return the longhand for the variable with the dollar sign
1736 * escaped so it makes it back to the caller. Only four of the local
1737 * variables are treated specially as they are the only four that
1738 * will be set when dynamic sources are expanded.
1740 if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
1742 /* XXX: It looks like $% and $! are reversed here */
1746 return (estrdup("$(.TARGET)"));
1749 return (estrdup("$(.ARCHIVE)"));
1752 return (estrdup("$(.PREFIX)"));
1755 return (estrdup("$(.MEMBER)"));
1757 *freeResult = FALSE;
1758 return (vp->err ? var_Error : varNoError);
1762 /* Variable name was not found. */
1763 *freeResult = FALSE;
1764 return (vp->err ? var_Error : varNoError);
1768 VarParse(VarParser *vp, Boolean *freeResult)
1771 vp->ptr++; /* consume '$' or last letter of conditional */
1773 if (vp->ptr[0] == '\0') {
1774 /* Error, there is only a dollar sign in the input string. */
1775 *freeResult = FALSE;
1776 return (vp->err ? var_Error : varNoError);
1778 } else if (vp->ptr[0] == OPEN_PAREN || vp->ptr[0] == OPEN_BRACE) {
1779 /* multi letter variable name */
1780 return (VarParseLong(vp, freeResult));
1783 /* single letter variable name */
1784 return (VarParseShort(vp, freeResult));
1789 *-----------------------------------------------------------------------
1791 * Given the start of a variable invocation, extract the variable
1792 * name and find its value, then modify it according to the
1796 * The value of the variable or var_Error if the specification
1797 * is invalid. The number of characters in the specification
1798 * is placed in the variable pointed to by consumed. (for
1799 * invalid specifications, this is just 2 to skip the '$' and
1800 * the following letter, or 1 if '$' was the last character
1801 * in the string). A Boolean in *freeResult telling whether the
1802 * returned string should be freed by the caller.
1806 *-----------------------------------------------------------------------
1809 Var_Parse(const char input[], GNode *ctxt, Boolean err,
1810 size_t *consumed, Boolean *freeResult)
1820 value = VarParse(&vp, freeResult);
1821 *consumed += vp.ptr - vp.input;
1826 *-----------------------------------------------------------------------
1828 * Substitute for all variables in the given string in the given context
1829 * If undefErr is TRUE, Parse_Error will be called when an undefined
1830 * variable is encountered.
1833 * The resulting string.
1836 * None. The old string must be freed by the caller
1837 *-----------------------------------------------------------------------
1840 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1842 Boolean errorReported;
1843 Buffer *buf; /* Buffer for forming things */
1846 * Set TRUE if an error has already been reported to prevent a
1847 * plethora of messages when recursing. XXXHB this comment sounds
1850 errorReported = FALSE;
1854 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1856 * A dollar sign may be escaped either with another
1857 * dollar sign. In such a case, we skip over the
1858 * escape character and store the dollar sign into
1859 * the buffer directly.
1861 Buf_AddByte(buf, (Byte)str[0]);
1864 } else if (str[0] == '$') {
1865 char *val; /* Value to substitute for a variable */
1866 size_t length; /* Length of the variable invocation */
1867 Boolean doFree; /* Set true if val should be freed */
1870 * Variable invocation.
1875 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACE) {
1877 const char *p = str + 2;
1880 * Scan up to the end of the
1883 while (*p != '\0' &&
1885 *p != CLOSE_PAREN &&
1886 *p != CLOSE_BRACE &&
1892 * A variable inside the
1893 * variable. We cannot expand
1894 * the external variable yet,
1895 * so we try again with the
1899 Buf_AppendRange(buf, str, p);
1904 if (var[ln] == '\0' && strncmp(var, str + 2, ln) == 0) {
1909 * we want to expand,
1913 while (*p != '$' && *p != '\0')
1916 Buf_AppendRange(buf, str, p);
1922 * Single letter variable
1925 if (var[1] == '\0' && var[0] == str[1]) {
1928 Buf_AddBytes(buf, 2, (const Byte *) str);
1939 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1942 * When we come down here, val should either point to
1943 * the value of this variable, suitably modified, or
1944 * be NULL. Length should be the total length of the
1945 * potential variable invocation (from $ to end
1948 if (val == var_Error || val == varNoError) {
1950 * If performing old-time variable
1951 * substitution, skip over the variable and
1952 * continue with the substitution. Otherwise,
1953 * store the dollar sign and advance str so
1954 * we continue with the string...
1958 } else if (undefErr) {
1960 * If variable is undefined, complain
1961 * and skip the variable. The
1962 * complaint will stop us from doing
1963 * anything when the file is parsed.
1965 if (!errorReported) {
1966 Parse_Error(PARSE_FATAL,
1967 "Undefined variable \"%.*s\"", length, str);
1970 errorReported = TRUE;
1972 Buf_AddByte(buf, (Byte)*str);
1977 * We've now got a variable structure to
1978 * store in. But first, advance the string
1984 * Copy all the characters from the variable
1985 * value straight into the new string.
1987 Buf_Append(buf, val);
1994 * Skip as many characters as possible -- either to
1995 * the end of the string or to the next dollar sign
1996 * (variable invocation).
1998 const char *cp = str;
2002 } while (str[0] != '$' && str[0] != '\0');
2004 Buf_AppendRange(buf, cp, str);
2012 *-----------------------------------------------------------------------
2014 * Return the tail from each of a list of words. Used to set the
2015 * System V local variables.
2018 * The resulting string.
2023 *-----------------------------------------------------------------------
2026 Var_GetTail(char *file)
2029 return (VarModify(file, VarTail, (void *)NULL));
2033 *-----------------------------------------------------------------------
2035 * Find the leading components of a (list of) filename(s).
2036 * XXX: VarHead does not replace foo by ., as (sun) System V make
2040 * The leading components.
2045 *-----------------------------------------------------------------------
2048 Var_GetHead(char *file)
2051 return (VarModify(file, VarHead, (void *)NULL));
2055 *-----------------------------------------------------------------------
2057 * Initialize the module
2063 * The VAR_CMD and VAR_GLOBAL contexts are created
2064 *-----------------------------------------------------------------------
2070 VAR_GLOBAL = Targ_NewGN("Global");
2071 VAR_CMD = Targ_NewGN("Command");
2075 *-----------------------------------------------------------------------
2077 * print all variables in a context
2078 *-----------------------------------------------------------------------
2081 Var_Dump(const GNode *ctxt)
2086 LST_FOREACH(ln, &ctxt->context) {
2088 printf("%-16s = %s\n", v->name,
2089 (const char *)Buf_GetAll(v->val, NULL));