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.16.2.3 2002/02/27 14:18:57 cjc Exp $
40 * $DragonFly: src/usr.bin/make/var.c,v 1.47 2005/01/27 10:25:19 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.
102 * This is a harmless return value for Var_Parse that can be used by Var_Subst
103 * to determine if there was an error in parsing -- easier than returning
104 * a flag, as things outside this module don't give a hoot.
106 char var_Error[] = "";
109 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
110 * set false. Why not just use a constant? Well, gcc likes to condense
111 * identical string instances...
113 static char varNoError[] = "";
116 * Internally, variables are contained in four different contexts.
117 * 1) the environment. They may not be changed. If an environment
118 * variable is appended-to, the result is placed in the global
120 * 2) the global context. Variables set in the Makefile are located in
121 * the global context. It is the penultimate context searched when
123 * 3) the command-line context. All variables set on the command line
124 * are placed in this context. They are UNALTERABLE once placed here.
125 * 4) the local context. Each target has associated with it a context
126 * list. On this list are located the structures describing such
127 * local variables as $(@) and $(*)
128 * The four contexts are searched in the reverse order from which they are
131 GNode *VAR_GLOBAL; /* variables from the makefile */
132 GNode *VAR_CMD; /* variables defined on the command-line */
134 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
135 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
136 #define FIND_ENV 0x4 /* look in the environment also */
138 static char *VarPossiblyExpand(const char *, GNode *);
139 static Var *VarFind(const char *, GNode *, int);
140 static void VarAdd(const char *, const char *, GNode *);
141 static void VarDelete(void *);
142 static char *VarGetPattern(GNode *, int, char **, int, int *, size_t *,
144 static char *VarModify(char *,
145 Boolean (*)(const char *, Boolean, Buffer *, void *),
147 static int VarPrintVar(void *, void *);
150 *-----------------------------------------------------------------------
152 * See if the given variable matches the named one. Called from
153 * Lst_Find when searching for a variable of a given name.
156 * 0 if they match. non-zero otherwise.
160 *-----------------------------------------------------------------------
163 VarCmp(const void *v, const void *name)
165 return (strcmp(name, ((const Var *)v)->name));
169 *-----------------------------------------------------------------------
170 * VarPossiblyExpand --
171 * Expand a variable name's embedded variables in the given context.
174 * The contents of name, possibly expanded.
177 * The caller must free the new contents or old contents of name.
178 *-----------------------------------------------------------------------
181 VarPossiblyExpand(const char *name, GNode *ctxt)
183 if (strchr(name, '$') != NULL)
184 return Var_Subst(NULL, name, ctxt, 0);
186 return estrdup(name);
190 *-----------------------------------------------------------------------
192 * Find the given variable in the given context and any other contexts
196 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
197 * FIND_CMD set means to look in the VAR_CMD context too
198 * FIND_ENV set means to look in the environment
201 * A pointer to the structure describing the desired variable or
202 * NULL if the variable does not exist.
206 *-----------------------------------------------------------------------
209 VarFind(const char *name, GNode *ctxt, int flags)
211 Boolean localCheckEnvFirst;
216 * If the variable name begins with a '.', it could very well be one of
217 * the local ones. We check the name against all the local variables
218 * and substitute the short version in for 'name' if it matches one of
221 if (*name == '.' && isupper((unsigned char)name[1]))
224 if (!strcmp(name, ".ALLSRC"))
226 if (!strcmp(name, ".ARCHIVE"))
230 if (!strcmp(name, ".IMPSRC"))
234 if (!strcmp(name, ".MEMBER"))
238 if (!strcmp(name, ".OODATE"))
242 if (!strcmp(name, ".PREFIX"))
246 if (!strcmp(name, ".TARGET"))
252 * Note whether this is one of the specific variables we were told through
253 * the -E flag to use environment-variable-override for.
255 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
256 localCheckEnvFirst = TRUE;
258 localCheckEnvFirst = FALSE;
262 * First look for the variable in the given context. If it's not there,
263 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
264 * depending on the FIND_* flags in 'flags'
266 var = Lst_Find(&ctxt->context, name, VarCmp);
268 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
269 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
271 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
272 !checkEnvFirst && !localCheckEnvFirst)
274 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
276 if ((var == NULL) && (flags & FIND_ENV)) {
279 if ((env = getenv(name)) != NULL) {
280 v = emalloc(sizeof(Var));
281 v->name = estrdup(name);
282 v->val = Buf_Init(0);
283 v->flags = VAR_FROM_ENV;
285 Buf_Append(v->val, env);
288 } else if ((checkEnvFirst || localCheckEnvFirst) &&
289 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
291 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
295 return (Lst_Datum(var));
300 } else if (var == NULL) {
303 return (Lst_Datum(var));
308 *-----------------------------------------------------------------------
310 * Add a new variable of name name and value val to the given context.
316 * The new variable is placed at the front of the given context
317 * The name and val arguments are duplicated so they may
319 *-----------------------------------------------------------------------
322 VarAdd(const char *name, const char *val, GNode *ctxt)
326 v = emalloc(sizeof(Var));
327 v->name = estrdup(name);
328 v->val = Buf_Init(0);
332 Buf_Append(v->val, val);
335 Lst_AtFront(&ctxt->context, v);
336 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
340 *-----------------------------------------------------------------------
342 * Delete a variable and all the space associated with it.
349 *-----------------------------------------------------------------------
357 Buf_Destroy(v->val, TRUE);
362 *-----------------------------------------------------------------------
364 * Remove a variable from a context.
370 * The Var structure is removed and freed.
372 *-----------------------------------------------------------------------
375 Var_Delete(char *name, GNode *ctxt)
379 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
380 ln = Lst_Find(&ctxt->context, name, VarCmp);
382 VarDelete(Lst_Datum(ln));
383 Lst_Remove(&ctxt->context, ln);
388 *-----------------------------------------------------------------------
390 * Set the variable name to the value val in the given context.
396 * If the variable doesn't yet exist, a new record is created for it.
397 * Else the old value is freed and the new one stuck in its place
400 * The variable is searched for only in its context before being
401 * created in that context. I.e. if the context is VAR_GLOBAL,
402 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
403 * VAR_CMD->context is searched. This is done to avoid the literally
404 * thousands of unnecessary strcmp's that used to be done to
405 * set, say, $(@) or $(<).
406 *-----------------------------------------------------------------------
409 Var_Set(const char *name, const char *val, GNode *ctxt)
415 * We only look for a variable in the given context since anything set
416 * here will override anything in a lower context, so there's not much
417 * point in searching them all just to save a bit of memory...
419 n = VarPossiblyExpand(name, ctxt);
420 v = VarFind(n, ctxt, 0);
422 VarAdd(n, val, ctxt);
425 Buf_Append(v->val, val);
427 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
430 * Any variables given on the command line are automatically exported
431 * to the environment (as per POSIX standard)
433 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
441 * Set the VAR_TO_ENV flag on a variable
444 Var_SetEnv(const char *name, GNode *ctxt)
448 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
450 if ((v->flags & VAR_TO_ENV) == 0) {
451 v->flags |= VAR_TO_ENV;
452 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
455 Error("Cannot set environment flag on non-existant variable %s", name);
460 *-----------------------------------------------------------------------
462 * The variable of the given name has the given value appended to it in
469 * If the variable doesn't exist, it is created. Else the strings
470 * are concatenated (with a space in between).
473 * Only if the variable is being sought in the global context is the
474 * environment searched.
475 * XXX: Knows its calling circumstances in that if called with ctxt
476 * an actual target, it will only search that context since only
477 * a local variable could be being appended to. This is actually
478 * a big win and must be tolerated.
479 *-----------------------------------------------------------------------
482 Var_Append(const char *name, const char *val, GNode *ctxt)
487 n = VarPossiblyExpand(name, ctxt);
488 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
490 VarAdd(n, val, ctxt);
492 Buf_AddByte(v->val, (Byte)' ');
493 Buf_Append(v->val, val);
495 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
496 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
498 if (v->flags & VAR_FROM_ENV) {
500 * If the original variable came from the environment, we
501 * have to install it in the global context (we could place
502 * it in the environment, but then we should provide a way to
503 * export other variables...)
505 v->flags &= ~VAR_FROM_ENV;
506 Lst_AtFront(&ctxt->context, v);
513 *-----------------------------------------------------------------------
515 * See if the given variable exists.
518 * TRUE if it does, FALSE if it doesn't
523 *-----------------------------------------------------------------------
526 Var_Exists(const char *name, GNode *ctxt)
531 n = VarPossiblyExpand(name, ctxt);
532 v = VarFind(n, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
537 } else if (v->flags & VAR_FROM_ENV) {
539 Buf_Destroy(v->val, TRUE);
546 *-----------------------------------------------------------------------
548 * Return the value of the named variable in the given context
551 * The value if the variable exists, NULL if it doesn't
555 *-----------------------------------------------------------------------
558 Var_Value(const char *name, GNode *ctxt, char **frp)
563 n = VarPossiblyExpand(name, ctxt);
564 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
568 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
570 if (v->flags & VAR_FROM_ENV) {
571 Buf_Destroy(v->val, FALSE);
583 *-----------------------------------------------------------------------
585 * Modify each of the words of the passed string using the given
586 * function. Used to implement all modifiers.
589 * A string of all the words modified appropriately.
594 *-----------------------------------------------------------------------
597 VarModify(char *str, Boolean (*modProc)(const char *, Boolean, Buffer *, void *), void *datum)
599 Buffer *buf; /* Buffer for the new string */
600 Boolean addSpace; /* TRUE if need to add a space to the
601 * buffer before adding the trimmed
603 char **av; /* word list [first word does not count] */
609 av = brk_string(str, &ac, FALSE);
611 for (i = 1; i < ac; i++)
612 addSpace = (*modProc)(av[i], addSpace, buf, datum);
614 Buf_AddByte(buf, '\0');
615 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
616 Buf_Destroy(buf, FALSE);
621 *-----------------------------------------------------------------------
623 * Sort the words in the string.
626 * str String whose words should be sorted
627 * cmp A comparison function to control the ordering
630 * A string containing the words sorted
635 *-----------------------------------------------------------------------
638 VarSortWords(char *str, int (*cmp)(const void *, const void *))
645 av = brk_string(str, &ac, FALSE);
646 qsort(av + 1, ac - 1, sizeof(char *), cmp);
647 for (i = 1; i < ac; i++) {
648 Buf_Append(buf, av[i]);
649 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
651 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
652 Buf_Destroy(buf, FALSE);
657 SortIncreasing(const void *l, const void *r)
659 return (strcmp(*(const char* const*)l, *(const char* const*)r));
663 *-----------------------------------------------------------------------
665 * Pass through the tstr looking for 1) escaped delimiters,
666 * '$'s and backslashes (place the escaped character in
667 * uninterpreted) and 2) unescaped $'s that aren't before
668 * the delimiter (expand the variable substitution unless flags
669 * has VAR_NOSUBST set).
670 * Return the expanded string or NULL if the delimiter was missing
671 * If pattern is specified, handle escaped ampersands, and replace
672 * unescaped ampersands with the lhs of the pattern.
675 * A string of all the words modified appropriately.
676 * If length is specified, return the string length of the buffer
677 * If flags is specified and the last character of the pattern is a
678 * $ set the VAR_MATCH_END bit of flags.
682 *-----------------------------------------------------------------------
685 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
686 size_t *length, VarPattern *pattern)
689 Buffer *buf = Buf_Init(0);
695 #define IS_A_MATCH(cp, delim) \
696 ((cp[0] == '\\') && ((cp[1] == delim) || \
697 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
700 * Skim through until the matching delimiter is found;
701 * pick up variable substitutions on the way. Also allow
702 * backslashes to quote the delimiter, $, and \, but don't
703 * touch other backslashes.
705 for (cp = *tstr; *cp && (*cp != delim); cp++) {
706 if (IS_A_MATCH(cp, delim)) {
707 Buf_AddByte(buf, (Byte)cp[1]);
709 } else if (*cp == '$') {
710 if (cp[1] == delim) {
712 Buf_AddByte(buf, (Byte)*cp);
715 * Unescaped $ at end of pattern => anchor
718 *flags |= VAR_MATCH_END;
720 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
726 * If unescaped dollar sign not before the
727 * delimiter, assume it's a variable
728 * substitution and recurse.
730 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
731 Buf_Append(buf, cp2);
738 if (*cp2 == '(' || *cp2 == '{') {
740 * Find the end of this variable reference
741 * and suck it in without further ado.
742 * It will be interperated later.
745 int want = (*cp2 == '(') ? ')' : '}';
748 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
749 if (cp2[-1] != '\\') {
756 Buf_AppendRange(buf, cp, cp2);
759 Buf_AddByte(buf, (Byte)*cp);
763 else if (pattern && *cp == '&')
764 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
766 Buf_AddByte(buf, (Byte)*cp);
769 Buf_AddByte(buf, (Byte)'\0');
777 cp = (char *)Buf_GetAll(buf, length);
778 *length -= 1; /* Don't count the NULL */
779 Buf_Destroy(buf, FALSE);
785 *-----------------------------------------------------------------------
787 * Quote shell meta-characters in the string
795 *-----------------------------------------------------------------------
798 Var_Quote(const char *str)
801 /* This should cover most shells :-( */
802 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
805 buf = Buf_Init(MAKE_BSIZE);
806 for (; *str; str++) {
807 if (strchr(meta, *str) != NULL)
808 Buf_AddByte(buf, (Byte)'\\');
809 Buf_AddByte(buf, (Byte)*str);
811 Buf_AddByte(buf, (Byte)'\0');
812 ret = Buf_GetAll(buf, NULL);
813 Buf_Destroy(buf, FALSE);
818 *-----------------------------------------------------------------------
820 * Print the error caused by a regcomp or regexec call.
826 * An error gets printed.
828 *-----------------------------------------------------------------------
831 VarREError(int err, regex_t *pat, const char *str)
836 errlen = regerror(err, pat, 0, 0);
837 errbuf = emalloc(errlen);
838 regerror(err, pat, errbuf, errlen);
839 Error("%s: %s", str, errbuf);
844 *-----------------------------------------------------------------------
846 * Given the start of a variable invocation, extract the variable
847 * name and find its value, then modify it according to the
851 * The (possibly-modified) value of the variable or var_Error if the
852 * specification is invalid. The length of the specification is
853 * placed in *lengthPtr (for invalid specifications, this is just
854 * 2 to skip the '$' and the following letter, or 1 if '$' was the
855 * last character in the string).
856 * A Boolean in *freePtr telling whether the returned string should
857 * be freed by the caller.
862 *-----------------------------------------------------------------------
865 Var_Parse(char *str, GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
867 char *tstr; /* Pointer into str */
868 Var *v; /* Variable in invocation */
869 char *cp; /* Secondary pointer into str (place marker
871 Boolean haveModifier;/* TRUE if have modifiers for the variable */
872 char endc; /* Ending character when variable in parens
874 char startc=0; /* Starting character when variable in parens
876 int cnt; /* Used to count brace pairs when variable in
877 * in parens or braces */
880 Boolean dynamic; /* TRUE if the variable is local and we're
881 * expanding it in a non-local context. This
882 * is done to support dynamic sources. The
883 * result is just the invocation, unaltered */
884 int vlen; /* length of variable name, after embedded variable
891 if (str[1] != '(' && str[1] != '{') {
893 * If it's not bounded by braces of some sort, life is much simpler.
894 * We just need to check for the first character and return the
895 * value if it exists.
902 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
903 if (v == (Var *)NULL) {
909 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
911 * If substituting a local variable in a non-local context,
912 * assume it's for dynamic source stuff. We have to handle
913 * this specially and return the longhand for the variable
914 * with the dollar sign escaped so it makes it back to the
915 * caller. Only four of the local variables are treated
916 * specially as they are the only four that will be set
917 * when dynamic sources are expanded.
919 /* XXX: It looks like $% and $! are reversed here */
922 return ("$(.TARGET)");
924 return ("$(.ARCHIVE)");
926 return ("$(.PREFIX)");
928 return ("$(.MEMBER)");
936 return (err ? var_Error : varNoError);
938 haveModifier = FALSE;
943 /* build up expanded variable name in this buffer */
944 Buffer *buf = Buf_Init(MAKE_BSIZE);
947 endc = startc == '(' ? ')' : '}';
950 * Skip to the end character or a colon, whichever comes first,
951 * replacing embedded variables as we go.
953 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
957 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
959 if (rval == var_Error) {
960 Fatal("Error expanding embedded variable.");
961 } else if (rval != NULL) {
962 Buf_Append(buf, rval);
968 Buf_AddByte(buf, (Byte)*tstr);
972 * If we never did find the end character, return NULL
973 * right now, setting the length to be the distance to
974 * the end of the string, since that's what make does.
976 *lengthPtr = tstr - str;
980 haveModifier = (*tstr == ':');
983 Buf_AddByte(buf, (Byte)'\0');
984 str = Buf_GetAll(buf, (size_t *)NULL);
987 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
988 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
989 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
992 * Check for bogus D and F forms of local variables since we're
993 * in a local context and the name is the right length.
1007 * Well, it's local -- go look for it.
1011 v = VarFind(vname, ctxt, 0);
1013 if (v != NULL && !haveModifier) {
1015 * No need for nested expansion or anything, as we're
1016 * the only one who sets these things and we sure don't
1017 * put nested invocations in them...
1019 val = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1021 if (str[1] == 'D') {
1022 val = VarModify(val, VarHead, (void *)NULL);
1024 val = VarModify(val, VarTail, (void *)NULL);
1027 * Resulting string is dynamically allocated, so
1028 * tell caller to free it.
1031 *lengthPtr = tstr-start+1;
1033 Buf_Destroy(buf, TRUE);
1043 if (v == (Var *)NULL) {
1045 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
1046 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1049 * If substituting a local variable in a non-local context,
1050 * assume it's for dynamic source stuff. We have to handle
1051 * this specially and return the longhand for the variable
1052 * with the dollar sign escaped so it makes it back to the
1053 * caller. Only four of the local variables are treated
1054 * specially as they are the only four that will be set
1055 * when dynamic sources are expanded.
1067 } else if ((vlen > 2) && (str[0] == '.') &&
1068 isupper((unsigned char)str[1]) &&
1069 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1074 if ((strncmp(str, ".TARGET", len) == 0) ||
1075 (strncmp(str, ".ARCHIVE", len) == 0) ||
1076 (strncmp(str, ".PREFIX", len) == 0) ||
1077 (strncmp(str, ".MEMBER", len) == 0))
1083 if (!haveModifier) {
1085 * No modifiers -- have specification length so we can return
1088 *lengthPtr = tstr - start + 1;
1091 str = emalloc(*lengthPtr + 1);
1092 strncpy(str, start, *lengthPtr);
1093 str[*lengthPtr] = '\0';
1095 Buf_Destroy(buf, TRUE);
1098 Buf_Destroy(buf, TRUE);
1099 return (err ? var_Error : varNoError);
1103 * Still need to get to the end of the variable specification,
1104 * so kludge up a Var structure for the modifications
1106 v = emalloc(sizeof(Var));
1107 v->name = estrdup(str);
1108 v->val = Buf_Init(1);
1109 v->flags = VAR_JUNK;
1112 Buf_Destroy(buf, TRUE);
1115 if (v->flags & VAR_IN_USE) {
1116 Fatal("Variable %s is recursive.", v->name);
1119 v->flags |= VAR_IN_USE;
1122 * Before doing any modification, we have to make sure the value
1123 * has been fully expanded. If it looks like recursion might be
1124 * necessary (there's a dollar sign somewhere in the variable's value)
1125 * we just call Var_Subst to do any other substitutions that are
1126 * necessary. Note that the value returned by Var_Subst will have
1127 * been dynamically-allocated, so it will need freeing when we
1130 str = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1131 if (strchr(str, '$') != (char *)NULL) {
1132 str = Var_Subst(NULL, str, ctxt, err);
1136 v->flags &= ~VAR_IN_USE;
1139 * Now we need to apply any modifiers the user wants applied.
1141 * :M<pattern> words which match the given <pattern>.
1142 * <pattern> is of the standard file
1144 * :S<d><pat1><d><pat2><d>[g]
1145 * Substitute <pat2> for <pat1> in the value
1146 * :C<d><pat1><d><pat2><d>[g]
1147 * Substitute <pat2> for regex <pat1> in the value
1148 * :H Substitute the head of each word
1149 * :T Substitute the tail of each word
1150 * :E Substitute the extension (minus '.') of
1152 * :R Substitute the root of each word
1153 * (pathname minus the suffix).
1154 * :lhs=rhs Like :S, but the rhs goes to the end of
1156 * :U Converts variable to upper-case.
1157 * :L Converts variable to lower-case.
1159 if ((str != NULL) && haveModifier) {
1161 * Skip initial colon while putting it back.
1164 while (*tstr != endc) {
1165 char *newStr; /* New value to return */
1166 char termc; /* Character which terminated scan */
1168 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1179 *cp != '\0' && *cp != ':' && *cp != endc;
1182 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
1191 * Need to compress the \:'s out of the pattern, so
1192 * allocate enough room to hold the uncompressed
1193 * pattern (note that cp started at tstr+1, so
1194 * cp - tstr takes the null byte into account) and
1195 * compress the pattern into the space.
1197 pattern = emalloc(cp - tstr);
1198 for (cp2 = pattern, cp = tstr + 1;
1202 if ((*cp == '\\') &&
1203 (cp[1] == ':' || cp[1] == endc)) {
1212 if (*tstr == 'M' || *tstr == 'm') {
1213 newStr = VarModify(str, VarMatch, pattern);
1215 newStr = VarModify(str, VarNoMatch, pattern);
1226 Buffer *buf; /* Buffer for patterns */
1233 * If pattern begins with '^', it is anchored to the
1234 * start of the word -- skip over it and flag pattern.
1237 pattern.flags |= VAR_MATCH_START;
1244 * Pass through the lhs looking for 1) escaped delimiters,
1245 * '$'s and backslashes (place the escaped character in
1246 * uninterpreted) and 2) unescaped $'s that aren't before
1247 * the delimiter (expand the variable substitution).
1248 * The result is left in the Buffer buf.
1250 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1251 if ((*cp == '\\') &&
1256 Buf_AddByte(buf, (Byte)cp[1]);
1258 } else if (*cp == '$') {
1261 * If unescaped dollar sign not before the
1262 * delimiter, assume it's a variable
1263 * substitution and recurse.
1269 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1270 Buf_Append(buf, cp2);
1277 * Unescaped $ at end of pattern => anchor
1280 pattern.flags |= VAR_MATCH_END;
1283 Buf_AddByte(buf, (Byte)*cp);
1287 Buf_AddByte(buf, (Byte)'\0');
1290 * If lhs didn't end with the delimiter, complain and
1294 Fatal("Unclosed substitution for %s (%c missing)",
1299 * Fetch pattern and destroy buffer, but preserve the data
1300 * in it, since that's our lhs. Note that Buf_GetAll
1301 * will return the actual number of bytes, which includes
1302 * the null byte, so we have to decrement the length by
1305 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1307 Buf_Destroy(buf, FALSE);
1310 * Now comes the replacement string. Three things need to
1311 * be done here: 1) need to compress escaped delimiters and
1312 * ampersands and 2) need to replace unescaped ampersands
1313 * with the l.h.s. (since this isn't regexp, we can do
1314 * it right here) and 3) expand any variable substitutions.
1319 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1320 if ((*cp == '\\') &&
1326 Buf_AddByte(buf, (Byte)cp[1]);
1328 } else if ((*cp == '$') && (cp[1] != del)) {
1333 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1334 Buf_Append(buf, cp2);
1339 } else if (*cp == '&') {
1340 Buf_AddBytes(buf, pattern.leftLen,
1341 (Byte *)pattern.lhs);
1343 Buf_AddByte(buf, (Byte)*cp);
1347 Buf_AddByte(buf, (Byte)'\0');
1350 * If didn't end in delimiter character, complain
1353 Fatal("Unclosed substitution for %s (%c missing)",
1357 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1359 Buf_Destroy(buf, FALSE);
1362 * Check for global substitution. If 'g' after the final
1363 * delimiter, substitution is global and is marked that
1368 pattern.flags |= VAR_SUB_GLOBAL;
1373 * Global substitution of the empty string causes an
1374 * infinite number of matches, unless anchored by '^'
1375 * (start of string) or '$' (end of string). Catch the
1376 * infinite substitution here.
1377 * Note that flags can only contain the 3 bits we're
1378 * interested in so we don't have to mask unrelated
1379 * bits. We can test for equality.
1381 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1382 Fatal("Global substitution of the empty string");
1385 newStr = VarModify(str, VarSubstitute, &pattern);
1387 * Free the two strings.
1395 VarREPattern pattern;
1405 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1406 NULL, NULL)) == NULL) {
1407 /* was: goto cleanup */
1408 *lengthPtr = cp - start + 1;
1412 Fatal("Unclosed substitution for %s (%c missing)",
1417 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1418 delim, NULL, NULL, NULL)) == NULL){
1421 /* was: goto cleanup */
1422 *lengthPtr = cp - start + 1;
1426 Fatal("Unclosed substitution for %s (%c missing)",
1434 pattern.flags |= VAR_SUB_GLOBAL;
1437 pattern.flags |= VAR_SUB_ONE;
1447 error = regcomp(&pattern.re, re, REG_EXTENDED);
1450 *lengthPtr = cp - start + 1;
1451 VarREError(error, &pattern.re, "RE substitution error");
1452 free(pattern.replace);
1456 pattern.nsub = pattern.re.re_nsub + 1;
1457 if (pattern.nsub < 1)
1459 if (pattern.nsub > 10)
1461 pattern.matches = emalloc(pattern.nsub *
1462 sizeof(regmatch_t));
1463 newStr = VarModify(str, VarRESubstitute, &pattern);
1464 regfree(&pattern.re);
1465 free(pattern.replace);
1466 free(pattern.matches);
1470 if (tstr[1] == endc || tstr[1] == ':') {
1472 buf = Buf_Init(MAKE_BSIZE);
1473 for (cp = str; *cp ; cp++)
1474 Buf_AddByte(buf, (Byte)tolower(*cp));
1476 Buf_AddByte(buf, (Byte)'\0');
1477 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1478 Buf_Destroy(buf, FALSE);
1486 if (tstr[1] == endc || tstr[1] == ':') {
1487 newStr = VarSortWords(str, SortIncreasing);
1494 if (tstr[1] == endc || tstr[1] == ':') {
1495 newStr = Var_Quote(str);
1502 if (tstr[1] == endc || tstr[1] == ':') {
1503 newStr = VarModify(str, VarTail, (void *)NULL);
1510 if (tstr[1] == endc || tstr[1] == ':') {
1512 buf = Buf_Init(MAKE_BSIZE);
1513 for (cp = str; *cp ; cp++)
1514 Buf_AddByte(buf, (Byte)toupper(*cp));
1516 Buf_AddByte(buf, (Byte)'\0');
1517 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1518 Buf_Destroy(buf, FALSE);
1526 if (tstr[1] == endc || tstr[1] == ':') {
1527 newStr = VarModify(str, VarHead, (void *)NULL);
1534 if (tstr[1] == endc || tstr[1] == ':') {
1535 newStr = VarModify(str, VarSuffix, (void *)NULL);
1542 if (tstr[1] == endc || tstr[1] == ':') {
1543 newStr = VarModify(str, VarRoot, (void *)NULL);
1551 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1554 Buffer *buf = Cmd_Exec(str, &error);
1555 newStr = Buf_GetAll(buf, NULL);
1556 Buf_Destroy(buf, FALSE);
1570 * This can either be a bogus modifier or a System-V
1571 * substitution command.
1579 * First we make a pass through the string trying
1580 * to verify it is a SYSV-make-style translation:
1581 * it must be: <string1>=<string2>)
1585 while (*cp != '\0' && cnt) {
1588 /* continue looking for endc */
1590 else if (*cp == endc)
1592 else if (*cp == startc)
1597 if (*cp == endc && eqFound) {
1600 * Now we break this sucker into the lhs and
1601 * rhs. We must null terminate them of course.
1606 if ((pattern.lhs = VarGetPattern(ctxt,
1607 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1609 /* was: goto cleanup */
1610 *lengthPtr = cp - start + 1;
1614 Fatal("Unclosed substitution for %s (%c missing)",
1620 if ((pattern.rhs = VarGetPattern(ctxt,
1621 err, &cp, delim, NULL, &pattern.rightLen,
1622 &pattern)) == NULL) {
1623 /* was: goto cleanup */
1624 *lengthPtr = cp - start + 1;
1628 Fatal("Unclosed substitution for %s (%c missing)",
1634 * SYSV modifications happen through the whole
1635 * string. Note the pattern is anchored at the end.
1639 newStr = VarModify(str, VarSYSVMatch, &pattern);
1648 Error("Unknown modifier '%c'\n", *tstr);
1650 *cp != ':' && *cp != endc && *cp != '\0';
1658 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1664 if (str != var_Error) {
1669 if (termc == '\0') {
1670 Error("Unclosed variable specification for %s", v->name);
1671 } else if (termc == ':') {
1678 *lengthPtr = tstr - start + 1;
1680 *lengthPtr = tstr - start + 1;
1684 if (v->flags & VAR_FROM_ENV) {
1685 Boolean destroy = FALSE;
1687 if (str != (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1691 * Returning the value unmodified, so tell the caller to free
1697 Buf_Destroy(v->val, destroy);
1699 } else if (v->flags & VAR_JUNK) {
1701 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1702 * doesn't try to free a static pointer.
1709 Buf_Destroy(v->val, TRUE);
1712 str = emalloc(*lengthPtr + 1);
1713 strncpy(str, start, *lengthPtr);
1714 str[*lengthPtr] = '\0';
1717 str = err ? var_Error : varNoError;
1724 *-----------------------------------------------------------------------
1726 * Substitute for all variables in the given string in the given context
1727 * If undefErr is TRUE, Parse_Error will be called when an undefined
1728 * variable is encountered.
1731 * The resulting string.
1734 * None. The old string must be freed by the caller
1735 *-----------------------------------------------------------------------
1738 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1740 Buffer *buf; /* Buffer for forming things */
1741 char *val; /* Value to substitute for a variable */
1742 size_t length; /* Length of the variable invocation */
1743 Boolean doFree; /* Set true if val should be freed */
1745 static Boolean errorReported;/* Set true if an error has already
1746 * been reported to prevent a plethora
1747 * of messages when recursing */
1749 buf = Buf_Init(MAKE_BSIZE);
1750 errorReported = FALSE;
1753 if (var == NULL && (*str == '$') && (str[1] == '$')) {
1755 * A dollar sign may be escaped either with another dollar sign.
1756 * In such a case, we skip over the escape character and store the
1757 * dollar sign into the buffer directly.
1760 Buf_AddByte(buf, (Byte)*str);
1762 } else if (*str != '$') {
1764 * Skip as many characters as possible -- either to the end of
1765 * the string or to the next dollar sign (variable invocation).
1769 for (cp = str++; *str != '$' && *str != '\0'; str++)
1771 Buf_AppendRange(buf, cp, str);
1776 if (str[1] != '(' && str[1] != '{') {
1777 if (str[1] != *var || var[1] != '\0') {
1778 Buf_AddBytes(buf, 2, (const Byte *)str);
1789 * Scan up to the end of the variable name.
1791 for (p = &str[2]; *p &&
1792 *p != ':' && *p != ')' && *p != '}'; p++)
1796 * A variable inside the variable. We cannot expand
1797 * the external variable yet, so we try again with
1801 Buf_AppendRange(buf, str, p);
1806 if (strncmp(var, str + 2, p - str - 2) != 0 ||
1807 var[p - str - 2] != '\0') {
1809 * Not the variable we want to expand, scan
1810 * until the next variable
1812 for (;*p != '$' && *p != '\0'; p++)
1814 Buf_AppendRange(buf, str, p);
1827 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1830 * When we come down here, val should either point to the
1831 * value of this variable, suitably modified, or be NULL.
1832 * Length should be the total length of the potential
1833 * variable invocation (from $ to end character...)
1835 if (val == var_Error || val == varNoError) {
1837 * If performing old-time variable substitution, skip over
1838 * the variable and continue with the substitution. Otherwise,
1839 * store the dollar sign and advance str so we continue with
1844 } else if (undefErr) {
1846 * If variable is undefined, complain and skip the
1847 * variable. The complaint will stop us from doing anything
1848 * when the file is parsed.
1850 if (!errorReported) {
1851 Parse_Error(PARSE_FATAL,
1852 "Undefined variable \"%.*s\"",length,str);
1855 errorReported = TRUE;
1857 Buf_AddByte(buf, (Byte)*str);
1862 * We've now got a variable structure to store in. But first,
1863 * advance the string pointer.
1868 * Copy all the characters from the variable value straight
1869 * into the new string.
1871 Buf_Append(buf, val);
1879 Buf_AddByte(buf, '\0');
1880 result = (char *)Buf_GetAll(buf, (size_t *)NULL);
1881 Buf_Destroy(buf, FALSE);
1886 *-----------------------------------------------------------------------
1888 * Return the tail from each of a list of words. Used to set the
1889 * System V local variables.
1892 * The resulting string.
1897 *-----------------------------------------------------------------------
1900 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 *-----------------------------------------------------------------------
1942 VAR_GLOBAL = Targ_NewGN("Global");
1943 VAR_CMD = Targ_NewGN("Command");
1946 /****************** PRINT DEBUGGING INFO *****************/
1948 VarPrintVar(void *vp, void *dummy __unused)
1950 Var *v = (Var *) vp;
1952 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
1957 *-----------------------------------------------------------------------
1959 * print all variables in a context
1960 *-----------------------------------------------------------------------
1963 Var_Dump(GNode *ctxt)
1965 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);