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.58 2005/02/04 22:06:01 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 #define OPEN_PAREN '('
139 #define CLOSE_PAREN ')'
140 #define OPEN_BRACKET '{'
141 #define CLOSE_BRACKET '}'
143 static Var *VarCreate(const char [], const char [], int);
144 static void VarDestroy(Var *, Boolean);
145 static char *VarGetPattern(GNode *, int, char **, int, int *, size_t *,
147 static char *VarModify(char *,
148 Boolean (*)(const char *, Boolean, Buffer *, void *),
150 static int VarPrintVar(void *, void *);
153 *-----------------------------------------------------------------------
155 * See if the given variable matches the named one. Called from
156 * Lst_Find when searching for a variable of a given name.
159 * 0 if they match. non-zero otherwise.
163 *-----------------------------------------------------------------------
166 VarCmp(const void *v, const void *name)
169 return (strcmp(name, ((const Var *)v)->name));
173 *-----------------------------------------------------------------------
174 * VarPossiblyExpand --
175 * Expand a variable name's embedded variables in the given context.
178 * The contents of name, possibly expanded.
179 *-----------------------------------------------------------------------
182 VarPossiblyExpand(const char *name, GNode *ctxt)
184 if (strchr(name, '$') != NULL) {
188 buf = Var_Subst(NULL, name, ctxt, 0);
189 str = Buf_GetAll(buf, NULL);
190 Buf_Destroy(buf, FALSE);
194 return(estrdup(name));
199 *-----------------------------------------------------------------------
201 * Find the given variable in the given context and any other contexts
205 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
206 * FIND_CMD set means to look in the VAR_CMD context too
207 * FIND_ENV set means to look in the environment
210 * A pointer to the structure describing the desired variable or
211 * NULL if the variable does not exist.
215 *-----------------------------------------------------------------------
218 VarFind(const char *name, GNode *ctxt, int flags)
220 Boolean localCheckEnvFirst;
225 * If the variable name begins with a '.', it could very well be one of
226 * the local ones. We check the name against all the local variables
227 * and substitute the short version in for 'name' if it matches one of
230 if (name[0] == '.' && isupper((unsigned char)name[1]))
233 if (!strcmp(name, ".ALLSRC"))
235 if (!strcmp(name, ".ARCHIVE"))
239 if (!strcmp(name, ".IMPSRC"))
243 if (!strcmp(name, ".MEMBER"))
247 if (!strcmp(name, ".OODATE"))
251 if (!strcmp(name, ".PREFIX"))
255 if (!strcmp(name, ".TARGET"))
261 * Note whether this is one of the specific variables we were told through
262 * the -E flag to use environment-variable-override for.
264 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
265 localCheckEnvFirst = TRUE;
267 localCheckEnvFirst = FALSE;
271 * First look for the variable in the given context. If it's not there,
272 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
273 * depending on the FIND_* flags in 'flags'
275 var = Lst_Find(&ctxt->context, name, VarCmp);
277 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
278 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
280 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
281 !checkEnvFirst && !localCheckEnvFirst)
283 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
285 if ((var == NULL) && (flags & FIND_ENV)) {
288 if ((env = getenv(name)) != NULL) {
289 v = VarCreate(name, env, VAR_FROM_ENV);
292 } else if ((checkEnvFirst || localCheckEnvFirst) &&
293 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
295 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
299 return (Lst_Datum(var));
304 } else if (var == NULL) {
307 return (Lst_Datum(var));
312 *-----------------------------------------------------------------------
314 * Add a new variable of name name and value val to the given context.
320 * The new variable is placed at the front of the given context
321 * The name and val arguments are duplicated so they may
323 *-----------------------------------------------------------------------
326 VarAdd(const char *name, const char *val, GNode *ctxt)
328 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
330 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
334 * Create a Var object.
336 * @param name Name of variable.
337 * @param value Value of variable.
338 * @param flags Flags set on variable.
341 VarCreate(const char name[], const char value[], int flags)
345 v = emalloc(sizeof(Var));
346 v->name = estrdup(name);
347 v->val = Buf_Init(0);
351 Buf_Append(v->val, value);
357 * Destroy a Var object.
359 * @param v Object to destroy.
360 * @param f true if internal buffer in Buffer object is to be
364 VarDestroy(Var *v, Boolean f)
366 Buf_Destroy(v->val, f);
372 *-----------------------------------------------------------------------
374 * Remove a variable from a context.
380 * The Var structure is removed and freed.
382 *-----------------------------------------------------------------------
385 Var_Delete(const char *name, GNode *ctxt)
389 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
390 ln = Lst_Find(&ctxt->context, name, VarCmp);
392 VarDestroy(Lst_Datum(ln), TRUE);
393 Lst_Remove(&ctxt->context, ln);
398 *-----------------------------------------------------------------------
400 * Set the variable name to the value val in the given context.
406 * If the variable doesn't yet exist, a new record is created for it.
407 * Else the old value is freed and the new one stuck in its place
410 * The variable is searched for only in its context before being
411 * created in that context. I.e. if the context is VAR_GLOBAL,
412 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
413 * VAR_CMD->context is searched. This is done to avoid the literally
414 * thousands of unnecessary strcmp's that used to be done to
415 * set, say, $(@) or $(<).
416 *-----------------------------------------------------------------------
419 Var_Set(const char *name, const char *val, GNode *ctxt)
425 * We only look for a variable in the given context since anything set
426 * here will override anything in a lower context, so there's not much
427 * point in searching them all just to save a bit of memory...
429 n = VarPossiblyExpand(name, ctxt);
430 v = VarFind(n, ctxt, 0);
432 VarAdd(n, val, ctxt);
435 Buf_Append(v->val, val);
437 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
440 * Any variables given on the command line are automatically exported
441 * to the environment (as per POSIX standard)
443 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
451 * Set the VAR_TO_ENV flag on a variable
454 Var_SetEnv(const char *name, GNode *ctxt)
458 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
460 if ((v->flags & VAR_TO_ENV) == 0) {
461 v->flags |= VAR_TO_ENV;
462 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
465 Error("Cannot set environment flag on non-existant variable %s", name);
470 *-----------------------------------------------------------------------
472 * The variable of the given name has the given value appended to it in
479 * If the variable doesn't exist, it is created. Else the strings
480 * are concatenated (with a space in between).
483 * Only if the variable is being sought in the global context is the
484 * environment searched.
485 * XXX: Knows its calling circumstances in that if called with ctxt
486 * an actual target, it will only search that context since only
487 * a local variable could be being appended to. This is actually
488 * a big win and must be tolerated.
489 *-----------------------------------------------------------------------
492 Var_Append(const char *name, const char *val, GNode *ctxt)
497 n = VarPossiblyExpand(name, ctxt);
498 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
501 VarAdd(n, val, ctxt);
503 Buf_AddByte(v->val, (Byte)' ');
504 Buf_Append(v->val, val);
506 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
507 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
509 if (v->flags & VAR_FROM_ENV) {
511 * If the original variable came from the environment, we
512 * have to install it in the global context (we could place
513 * it in the environment, but then we should provide a way to
514 * export other variables...)
516 v->flags &= ~VAR_FROM_ENV;
517 Lst_AtFront(&ctxt->context, v);
524 *-----------------------------------------------------------------------
526 * See if the given variable exists.
529 * TRUE if it does, FALSE if it doesn't
534 *-----------------------------------------------------------------------
537 Var_Exists(const char *name, GNode *ctxt)
542 n = VarPossiblyExpand(name, ctxt);
543 v = VarFind(n, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
548 } else if (v->flags & VAR_FROM_ENV) {
555 *-----------------------------------------------------------------------
557 * Return the value of the named variable in the given context
560 * The value if the variable exists, NULL if it doesn't
564 *-----------------------------------------------------------------------
567 Var_Value(const char *name, GNode *ctxt, char **frp)
572 n = VarPossiblyExpand(name, ctxt);
573 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
577 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
579 if (v->flags & VAR_FROM_ENV) {
580 VarDestroy(v, FALSE);
590 *-----------------------------------------------------------------------
592 * Modify each of the words of the passed string using the given
593 * function. Used to implement all modifiers.
596 * A string of all the words modified appropriately.
601 *-----------------------------------------------------------------------
604 VarModify(char *str, Boolean (*modProc)(const char *, Boolean, Buffer *, void *),
607 Buffer *buf; /* Buffer for the new string */
608 Boolean addSpace; /* TRUE if need to add a space to the
609 * buffer before adding the trimmed
611 char **av; /* word list [first word does not count] */
617 av = brk_string(str, &ac, FALSE);
619 for (i = 1; i < ac; i++)
620 addSpace = (*modProc)(av[i], addSpace, buf, datum);
622 Buf_AddByte(buf, '\0');
623 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
624 Buf_Destroy(buf, FALSE);
629 *-----------------------------------------------------------------------
631 * Sort the words in the string.
634 * str String whose words should be sorted
635 * cmp A comparison function to control the ordering
638 * A string containing the words sorted
643 *-----------------------------------------------------------------------
646 VarSortWords(char *str, int (*cmp)(const void *, const void *))
653 av = brk_string(str, &ac, FALSE);
654 qsort(av + 1, ac - 1, sizeof(char *), cmp);
655 for (i = 1; i < ac; i++) {
656 Buf_Append(buf, av[i]);
657 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
659 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
660 Buf_Destroy(buf, FALSE);
665 SortIncreasing(const void *l, const void *r)
668 return (strcmp(*(const char* const*)l, *(const char* const*)r));
672 *-----------------------------------------------------------------------
674 * Pass through the tstr looking for 1) escaped delimiters,
675 * '$'s and backslashes (place the escaped character in
676 * uninterpreted) and 2) unescaped $'s that aren't before
677 * the delimiter (expand the variable substitution unless flags
678 * has VAR_NOSUBST set).
679 * Return the expanded string or NULL if the delimiter was missing
680 * If pattern is specified, handle escaped ampersands, and replace
681 * unescaped ampersands with the lhs of the pattern.
684 * A string of all the words modified appropriately.
685 * If length is specified, return the string length of the buffer
686 * If flags is specified and the last character of the pattern is a
687 * $ set the VAR_MATCH_END bit of flags.
691 *-----------------------------------------------------------------------
694 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
695 size_t *length, VarPattern *pattern)
698 Buffer *buf = Buf_Init(0);
704 #define IS_A_MATCH(cp, delim) \
705 ((cp[0] == '\\') && ((cp[1] == delim) || \
706 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
709 * Skim through until the matching delimiter is found;
710 * pick up variable substitutions on the way. Also allow
711 * backslashes to quote the delimiter, $, and \, but don't
712 * touch other backslashes.
714 for (cp = *tstr; *cp && (*cp != delim); cp++) {
715 if (IS_A_MATCH(cp, delim)) {
716 Buf_AddByte(buf, (Byte)cp[1]);
718 } else if (*cp == '$') {
719 if (cp[1] == delim) {
721 Buf_AddByte(buf, (Byte)*cp);
724 * Unescaped $ at end of pattern => anchor
727 *flags |= VAR_MATCH_END;
729 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
735 * If unescaped dollar sign not before the
736 * delimiter, assume it's a variable
737 * substitution and recurse.
739 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
740 Buf_Append(buf, cp2);
747 if (*cp2 == OPEN_PAREN || *cp2 == OPEN_BRACKET) {
749 * Find the end of this variable reference
750 * and suck it in without further ado.
751 * It will be interperated later.
754 int want = (*cp2 == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACKET;
757 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
758 if (cp2[-1] != '\\') {
765 Buf_AppendRange(buf, cp, cp2);
768 Buf_AddByte(buf, (Byte)*cp);
772 else if (pattern && *cp == '&')
773 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
775 Buf_AddByte(buf, (Byte)*cp);
778 Buf_AddByte(buf, (Byte)'\0');
786 cp = (char *)Buf_GetAll(buf, length);
787 *length -= 1; /* Don't count the NULL */
788 Buf_Destroy(buf, FALSE);
794 *-----------------------------------------------------------------------
796 * Quote shell meta-characters in the string
804 *-----------------------------------------------------------------------
807 Var_Quote(const char *str)
810 /* This should cover most shells :-( */
811 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
814 buf = Buf_Init(MAKE_BSIZE);
815 for (; *str; str++) {
816 if (strchr(meta, *str) != NULL)
817 Buf_AddByte(buf, (Byte)'\\');
818 Buf_AddByte(buf, (Byte)*str);
820 Buf_AddByte(buf, (Byte)'\0');
821 ret = Buf_GetAll(buf, NULL);
822 Buf_Destroy(buf, FALSE);
827 *-----------------------------------------------------------------------
829 * Print the error caused by a regcomp or regexec call.
835 * An error gets printed.
837 *-----------------------------------------------------------------------
840 VarREError(int err, regex_t *pat, const char *str)
845 errlen = regerror(err, pat, 0, 0);
846 errbuf = emalloc(errlen);
847 regerror(err, pat, errbuf, errlen);
848 Error("%s: %s", str, errbuf);
853 *-----------------------------------------------------------------------
855 * Given the start of a variable invocation, extract the variable
856 * name and find its value, then modify it according to the
860 * The (possibly-modified) value of the variable or var_Error if the
861 * specification is invalid. The length of the specification is
862 * placed in *lengthPtr (for invalid specifications, this is just
863 * 2 to skip the '$' and the following letter, or 1 if '$' was the
864 * last character in the string).
865 * A Boolean in *freePtr telling whether the returned string should
866 * be freed by the caller.
871 *-----------------------------------------------------------------------
874 Var_Parse(char *str, GNode *ctxt, Boolean err, size_t *lengthPtr,
877 char *tstr; /* Pointer into str */
878 Var *v; /* Variable in invocation */
879 char *cp; /* Secondary pointer into str (place marker
881 Boolean haveModifier;/* TRUE if have modifiers for the variable */
882 char endc; /* Ending character when variable in parens
884 char startc=0; /* Starting character when variable in parens
886 int cnt; /* Used to count brace pairs when variable in
887 * in parens or braces */
890 Boolean dynamic; /* TRUE if the variable is local and we're
891 * expanding it in a non-local context. This
892 * is done to support dynamic sources. The
893 * result is just the invocation, unaltered */
894 int vlen; /* length of variable name, after embedded variable
902 * It is assumed that Var_Parse() is called with str[0] == '$'
905 if (str[1] != OPEN_PAREN && str[1] != OPEN_BRACKET) {
907 * If it's not bounded by braces of some sort, life is much simpler.
908 * We just need to check for the first character and return the
909 * value if it exists.
916 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
917 if (v == (Var *)NULL) {
923 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
925 * If substituting a local variable in a non-local context,
926 * assume it's for dynamic source stuff. We have to handle
927 * this specially and return the longhand for the variable
928 * with the dollar sign escaped so it makes it back to the
929 * caller. Only four of the local variables are treated
930 * specially as they are the only four that will be set
931 * when dynamic sources are expanded.
933 /* XXX: It looks like $% and $! are reversed here */
936 return ("$(.TARGET)");
938 return ("$(.ARCHIVE)");
940 return ("$(.PREFIX)");
942 return ("$(.MEMBER)");
950 return (err ? var_Error : varNoError);
952 haveModifier = FALSE;
957 /* build up expanded variable name in this buffer */
958 Buffer *buf = Buf_Init(MAKE_BSIZE);
961 * Skip to the end character or a colon, whichever comes first,
962 * replacing embedded variables as we go.
965 endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACKET;
968 while (*tstr != '\0' && *tstr != endc && *tstr != ':') {
974 rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
975 if (rval == var_Error) {
976 Fatal("Error expanding embedded variable.");
977 } else if (rval != NULL) {
978 Buf_Append(buf, rval);
984 Buf_AddByte(buf, (Byte)*tstr);
991 * If we never did find the end character, return NULL
992 * right now, setting the length to be the distance to
993 * the end of the string, since that's what make does.
995 *lengthPtr = tstr - str;
999 haveModifier = (*tstr == ':');
1000 *tstr = '\0'; /* modify input string */
1002 Buf_AddByte(buf, (Byte)'\0');
1003 str = Buf_GetAll(buf, (size_t *)NULL);
1006 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1007 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
1008 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
1011 * Check for bogus D and F forms of local variables since we're
1012 * in a local context and the name is the right length.
1026 * Well, it's local -- go look for it.
1030 v = VarFind(vname, ctxt, 0);
1032 if (v != NULL && !haveModifier) {
1034 * No need for nested expansion or anything, as we're
1035 * the only one who sets these things and we sure don't
1036 * put nested invocations in them...
1038 val = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1040 if (str[1] == 'D') {
1041 val = VarModify(val, VarHead, (void *)NULL);
1043 val = VarModify(val, VarTail, (void *)NULL);
1046 * Resulting string is dynamically allocated, so
1047 * tell caller to free it.
1050 *lengthPtr = tstr-start+1;
1052 Buf_Destroy(buf, TRUE);
1062 if (v == (Var *)NULL) {
1064 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
1065 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1068 * If substituting a local variable in a non-local context,
1069 * assume it's for dynamic source stuff. We have to handle
1070 * this specially and return the longhand for the variable
1071 * with the dollar sign escaped so it makes it back to the
1072 * caller. Only four of the local variables are treated
1073 * specially as they are the only four that will be set
1074 * when dynamic sources are expanded.
1086 } else if ((vlen > 2) && (str[0] == '.') &&
1087 isupper((unsigned char)str[1]) &&
1088 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1093 if ((strncmp(str, ".TARGET", len) == 0) ||
1094 (strncmp(str, ".ARCHIVE", len) == 0) ||
1095 (strncmp(str, ".PREFIX", len) == 0) ||
1096 (strncmp(str, ".MEMBER", len) == 0))
1102 if (!haveModifier) {
1104 * No modifiers -- have specification length so we can return
1107 *lengthPtr = tstr - start + 1;
1110 str = emalloc(*lengthPtr + 1);
1111 strncpy(str, start, *lengthPtr);
1112 str[*lengthPtr] = '\0';
1114 Buf_Destroy(buf, TRUE);
1117 Buf_Destroy(buf, TRUE);
1118 return (err ? var_Error : varNoError);
1122 * Still need to get to the end of the variable specification,
1123 * so kludge up a Var structure for the modifications
1125 v = VarCreate(str, NULL, VAR_JUNK);
1128 Buf_Destroy(buf, TRUE);
1131 if (v->flags & VAR_IN_USE) {
1132 Fatal("Variable %s is recursive.", v->name);
1135 v->flags |= VAR_IN_USE;
1139 * Before doing any modification, we have to make sure the value
1140 * has been fully expanded. If it looks like recursion might be
1141 * necessary (there's a dollar sign somewhere in the variable's value)
1142 * we just call Var_Subst to do any other substitutions that are
1143 * necessary. Note that the value returned by Var_Subst will have
1144 * been dynamically-allocated, so it will need freeing when we
1147 str = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1148 if (strchr(str, '$') != NULL) {
1151 buf = Var_Subst(NULL, str, ctxt, err);
1152 str = Buf_GetAll(buf, NULL);
1153 Buf_Destroy(buf, FALSE);
1158 v->flags &= ~VAR_IN_USE;
1161 * Now we need to apply any modifiers the user wants applied.
1163 * :M<pattern> words which match the given <pattern>.
1164 * <pattern> is of the standard file
1166 * :S<d><pat1><d><pat2><d>[g]
1167 * Substitute <pat2> for <pat1> in the value
1168 * :C<d><pat1><d><pat2><d>[g]
1169 * Substitute <pat2> for regex <pat1> in the value
1170 * :H Substitute the head of each word
1171 * :T Substitute the tail of each word
1172 * :E Substitute the extension (minus '.') of
1174 * :R Substitute the root of each word
1175 * (pathname minus the suffix).
1176 * :lhs=rhs Like :S, but the rhs goes to the end of
1178 * :U Converts variable to upper-case.
1179 * :L Converts variable to lower-case.
1181 if ((str != NULL) && haveModifier) {
1183 * Skip initial colon while putting it back.
1186 while (*tstr != endc) {
1187 char *newStr; /* New value to return */
1188 char termc; /* Character which terminated scan */
1190 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1201 *cp != '\0' && *cp != ':' && *cp != endc;
1204 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
1213 * Need to compress the \:'s out of the pattern, so
1214 * allocate enough room to hold the uncompressed
1215 * pattern (note that cp started at tstr+1, so
1216 * cp - tstr takes the null byte into account) and
1217 * compress the pattern into the space.
1219 pattern = emalloc(cp - tstr);
1220 for (cp2 = pattern, cp = tstr + 1;
1224 if ((*cp == '\\') &&
1225 (cp[1] == ':' || cp[1] == endc)) {
1234 if (*tstr == 'M' || *tstr == 'm') {
1235 newStr = VarModify(str, VarMatch, pattern);
1237 newStr = VarModify(str, VarNoMatch, pattern);
1248 Buffer *buf; /* Buffer for patterns */
1255 * If pattern begins with '^', it is anchored to the
1256 * start of the word -- skip over it and flag pattern.
1259 pattern.flags |= VAR_MATCH_START;
1266 * Pass through the lhs looking for 1) escaped delimiters,
1267 * '$'s and backslashes (place the escaped character in
1268 * uninterpreted) and 2) unescaped $'s that aren't before
1269 * the delimiter (expand the variable substitution).
1270 * The result is left in the Buffer buf.
1272 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1273 if ((*cp == '\\') &&
1278 Buf_AddByte(buf, (Byte)cp[1]);
1280 } else if (*cp == '$') {
1283 * If unescaped dollar sign not before the
1284 * delimiter, assume it's a variable
1285 * substitution and recurse.
1291 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1292 Buf_Append(buf, cp2);
1299 * Unescaped $ at end of pattern => anchor
1302 pattern.flags |= VAR_MATCH_END;
1305 Buf_AddByte(buf, (Byte)*cp);
1309 Buf_AddByte(buf, (Byte)'\0');
1312 * If lhs didn't end with the delimiter, complain and
1316 Fatal("Unclosed substitution for %s (%c missing)",
1321 * Fetch pattern and destroy buffer, but preserve the data
1322 * in it, since that's our lhs. Note that Buf_GetAll
1323 * will return the actual number of bytes, which includes
1324 * the null byte, so we have to decrement the length by
1327 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1329 Buf_Destroy(buf, FALSE);
1332 * Now comes the replacement string. Three things need to
1333 * be done here: 1) need to compress escaped delimiters and
1334 * ampersands and 2) need to replace unescaped ampersands
1335 * with the l.h.s. (since this isn't regexp, we can do
1336 * it right here) and 3) expand any variable substitutions.
1341 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1342 if ((*cp == '\\') &&
1348 Buf_AddByte(buf, (Byte)cp[1]);
1350 } else if ((*cp == '$') && (cp[1] != del)) {
1355 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1356 Buf_Append(buf, cp2);
1361 } else if (*cp == '&') {
1362 Buf_AddBytes(buf, pattern.leftLen,
1363 (Byte *)pattern.lhs);
1365 Buf_AddByte(buf, (Byte)*cp);
1369 Buf_AddByte(buf, (Byte)'\0');
1372 * If didn't end in delimiter character, complain
1375 Fatal("Unclosed substitution for %s (%c missing)",
1379 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1381 Buf_Destroy(buf, FALSE);
1384 * Check for global substitution. If 'g' after the final
1385 * delimiter, substitution is global and is marked that
1390 pattern.flags |= VAR_SUB_GLOBAL;
1395 * Global substitution of the empty string causes an
1396 * infinite number of matches, unless anchored by '^'
1397 * (start of string) or '$' (end of string). Catch the
1398 * infinite substitution here.
1399 * Note that flags can only contain the 3 bits we're
1400 * interested in so we don't have to mask unrelated
1401 * bits. We can test for equality.
1403 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1404 Fatal("Global substitution of the empty string");
1407 newStr = VarModify(str, VarSubstitute, &pattern);
1409 * Free the two strings.
1417 VarREPattern pattern;
1427 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1428 NULL, NULL)) == NULL) {
1429 /* was: goto cleanup */
1430 *lengthPtr = cp - start + 1;
1434 Fatal("Unclosed substitution for %s (%c missing)",
1439 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1440 delim, NULL, NULL, NULL)) == NULL){
1443 /* was: goto cleanup */
1444 *lengthPtr = cp - start + 1;
1448 Fatal("Unclosed substitution for %s (%c missing)",
1456 pattern.flags |= VAR_SUB_GLOBAL;
1459 pattern.flags |= VAR_SUB_ONE;
1469 error = regcomp(&pattern.re, re, REG_EXTENDED);
1472 *lengthPtr = cp - start + 1;
1473 VarREError(error, &pattern.re, "RE substitution error");
1474 free(pattern.replace);
1478 pattern.nsub = pattern.re.re_nsub + 1;
1479 if (pattern.nsub < 1)
1481 if (pattern.nsub > 10)
1483 pattern.matches = emalloc(pattern.nsub *
1484 sizeof(regmatch_t));
1485 newStr = VarModify(str, VarRESubstitute, &pattern);
1486 regfree(&pattern.re);
1487 free(pattern.replace);
1488 free(pattern.matches);
1492 if (tstr[1] == endc || tstr[1] == ':') {
1494 buf = Buf_Init(MAKE_BSIZE);
1495 for (cp = str; *cp ; cp++)
1496 Buf_AddByte(buf, (Byte)tolower(*cp));
1498 Buf_AddByte(buf, (Byte)'\0');
1499 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1500 Buf_Destroy(buf, FALSE);
1508 if (tstr[1] == endc || tstr[1] == ':') {
1509 newStr = VarSortWords(str, SortIncreasing);
1516 if (tstr[1] == endc || tstr[1] == ':') {
1517 newStr = Var_Quote(str);
1524 if (tstr[1] == endc || tstr[1] == ':') {
1525 newStr = VarModify(str, VarTail, (void *)NULL);
1532 if (tstr[1] == endc || tstr[1] == ':') {
1534 buf = Buf_Init(MAKE_BSIZE);
1535 for (cp = str; *cp ; cp++)
1536 Buf_AddByte(buf, (Byte)toupper(*cp));
1538 Buf_AddByte(buf, (Byte)'\0');
1539 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1540 Buf_Destroy(buf, FALSE);
1548 if (tstr[1] == endc || tstr[1] == ':') {
1549 newStr = VarModify(str, VarHead, (void *)NULL);
1556 if (tstr[1] == endc || tstr[1] == ':') {
1557 newStr = VarModify(str, VarSuffix, (void *)NULL);
1564 if (tstr[1] == endc || tstr[1] == ':') {
1565 newStr = VarModify(str, VarRoot, (void *)NULL);
1573 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1576 Buffer *buf = Cmd_Exec(str, &error);
1577 newStr = Buf_GetAll(buf, NULL);
1578 Buf_Destroy(buf, FALSE);
1592 * This can either be a bogus modifier or a System-V
1593 * substitution command.
1601 * First we make a pass through the string trying
1602 * to verify it is a SYSV-make-style translation:
1603 * it must be: <string1>=<string2>)
1607 while (*cp != '\0' && cnt) {
1610 /* continue looking for endc */
1612 else if (*cp == endc)
1614 else if (*cp == startc)
1619 if (*cp == endc && eqFound) {
1622 * Now we break this sucker into the lhs and
1623 * rhs. We must null terminate them of course.
1628 if ((pattern.lhs = VarGetPattern(ctxt,
1629 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1631 /* was: goto cleanup */
1632 *lengthPtr = cp - start + 1;
1636 Fatal("Unclosed substitution for %s (%c missing)",
1642 if ((pattern.rhs = VarGetPattern(ctxt,
1643 err, &cp, delim, NULL, &pattern.rightLen,
1644 &pattern)) == NULL) {
1645 /* was: goto cleanup */
1646 *lengthPtr = cp - start + 1;
1650 Fatal("Unclosed substitution for %s (%c missing)",
1656 * SYSV modifications happen through the whole
1657 * string. Note the pattern is anchored at the end.
1661 newStr = VarModify(str, VarSYSVMatch, &pattern);
1670 Error("Unknown modifier '%c'\n", *tstr);
1672 *cp != ':' && *cp != endc && *cp != '\0';
1680 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1686 if (str != var_Error) {
1691 if (termc == '\0') {
1692 Error("Unclosed variable specification for %s", v->name);
1693 } else if (termc == ':') {
1700 *lengthPtr = tstr - start + 1;
1702 *lengthPtr = tstr - start + 1;
1706 if (v->flags & VAR_FROM_ENV) {
1707 Boolean destroy = FALSE;
1709 if (str != (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1713 * Returning the value unmodified, so tell the caller to free
1718 VarDestroy(v, destroy);
1719 } else if (v->flags & VAR_JUNK) {
1721 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1722 * doesn't try to free a static pointer.
1728 VarDestroy(v, TRUE);
1730 str = emalloc(*lengthPtr + 1);
1731 strncpy(str, start, *lengthPtr);
1732 str[*lengthPtr] = '\0';
1735 str = err ? var_Error : varNoError;
1742 *-----------------------------------------------------------------------
1744 * Substitute for all variables in the given string in the given context
1745 * If undefErr is TRUE, Parse_Error will be called when an undefined
1746 * variable is encountered.
1749 * The resulting string.
1752 * None. The old string must be freed by the caller
1753 *-----------------------------------------------------------------------
1756 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1758 Boolean errorReported;
1759 Buffer *buf; /* Buffer for forming things */
1762 * Set TRUE if an error has already been reported to prevent a
1763 * plethora of messages when recursing.
1765 errorReported = FALSE;
1769 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1771 * A dollar sign may be escaped either with another dollar sign.
1772 * In such a case, we skip over the escape character and store the
1773 * dollar sign into the buffer directly.
1775 Buf_AddByte(buf, (Byte)str[0]);
1778 } else if (str[0] == '$') {
1779 char *val; /* Value to substitute for a variable */
1780 size_t length; /* Length of the variable invocation */
1781 Boolean doFree; /* Set true if val should be freed */
1783 * Variable invocation.
1788 if (str[1] == OPEN_PAREN || str[1] == OPEN_BRACKET) {
1789 const char *p = str + 2;
1792 * Scan up to the end of the variable name.
1794 while (*p != '\0' &&
1796 *p != CLOSE_PAREN &&
1797 *p != CLOSE_BRACKET &&
1803 * A variable inside the variable. We cannot expand
1804 * the external variable yet, so we try again with
1808 Buf_AppendRange(buf, str, p);
1813 if (var[p - (str + 2)] == '\0' && strncmp(var, str + 2, p - (str + 2)) == 0) {
1817 * Not the variable we want to expand, scan
1818 * until the next variable
1820 while (*p != '$' && *p != '\0')
1823 Buf_AppendRange(buf, str, p);
1830 * Single letter variable name.
1832 if (var[1] == '\0' && str[1] == var[0]) {
1835 Buf_AddBytes(buf, 2, (const Byte *)str);
1846 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1849 * When we come down here, val should either point to the
1850 * value of this variable, suitably modified, or be NULL.
1851 * Length should be the total length of the potential
1852 * variable invocation (from $ to end character...)
1854 if (val == var_Error || val == varNoError) {
1856 * If performing old-time variable substitution, skip over
1857 * the variable and continue with the substitution. Otherwise,
1858 * store the dollar sign and advance str so we continue with
1863 } else if (undefErr) {
1865 * If variable is undefined, complain and skip the
1866 * variable. The complaint will stop us from doing anything
1867 * when the file is parsed.
1869 if (!errorReported) {
1870 Parse_Error(PARSE_FATAL,
1871 "Undefined variable \"%.*s\"",length,str);
1874 errorReported = TRUE;
1876 Buf_AddByte(buf, (Byte)*str);
1881 * We've now got a variable structure to store in. But first,
1882 * advance the string pointer.
1887 * Copy all the characters from the variable value straight
1888 * into the new string.
1890 Buf_Append(buf, val);
1898 * Skip as many characters as possible -- either to the end of
1899 * the string or to the next dollar sign (variable invocation).
1901 const char *cp = str;
1905 } while (str[0] != '$' && str[0] != '\0');
1907 Buf_AppendRange(buf, cp, str);
1915 *-----------------------------------------------------------------------
1917 * Return the tail from each of a list of words. Used to set the
1918 * System V local variables.
1921 * The resulting string.
1926 *-----------------------------------------------------------------------
1929 Var_GetTail(char *file)
1932 return (VarModify(file, VarTail, (void *)NULL));
1936 *-----------------------------------------------------------------------
1938 * Find the leading components of a (list of) filename(s).
1939 * XXX: VarHead does not replace foo by ., as (sun) System V make
1943 * The leading components.
1948 *-----------------------------------------------------------------------
1951 Var_GetHead(char *file)
1954 return (VarModify(file, VarHead, (void *)NULL));
1958 *-----------------------------------------------------------------------
1960 * Initialize the module
1966 * The VAR_CMD and VAR_GLOBAL contexts are created
1967 *-----------------------------------------------------------------------
1973 VAR_GLOBAL = Targ_NewGN("Global");
1974 VAR_CMD = Targ_NewGN("Command");
1977 /****************** PRINT DEBUGGING INFO *****************/
1979 VarPrintVar(void *vp, void *dummy __unused)
1981 Var *v = (Var *) vp;
1983 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
1988 *-----------------------------------------------------------------------
1990 * print all variables in a context
1991 *-----------------------------------------------------------------------
1994 Var_Dump(GNode *ctxt)
1997 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);