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.17 2004/12/01 01:29:31 joerg 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.
86 #include <sys/types.h>
94 * This is a harmless return value for Var_Parse that can be used by Var_Subst
95 * to determine if there was an error in parsing -- easier than returning
96 * a flag, as things outside this module don't give a hoot.
98 char var_Error[] = "";
101 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
102 * set false. Why not just use a constant? Well, gcc likes to condense
103 * identical string instances...
105 static char varNoError[] = "";
108 * Internally, variables are contained in four different contexts.
109 * 1) the environment. They may not be changed. If an environment
110 * variable is appended-to, the result is placed in the global
112 * 2) the global context. Variables set in the Makefile are located in
113 * the global context. It is the penultimate context searched when
115 * 3) the command-line context. All variables set on the command line
116 * are placed in this context. They are UNALTERABLE once placed here.
117 * 4) the local context. Each target has associated with it a context
118 * list. On this list are located the structures describing such
119 * local variables as $(@) and $(*)
120 * The four contexts are searched in the reverse order from which they are
123 GNode *VAR_GLOBAL; /* variables from the makefile */
124 GNode *VAR_CMD; /* variables defined on the command-line */
126 static Lst allVars; /* List of all variables */
128 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
129 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
130 #define FIND_ENV 0x4 /* look in the environment also */
132 static int VarCmp(void *, void *);
133 static void VarPossiblyExpand(char **, GNode *);
134 static Var *VarFind(char *, GNode *, int);
135 static void VarAdd(char *, char *, GNode *);
136 static void VarDelete(void *);
137 static char *VarGetPattern(GNode *, int, char **, int, int *, int *,
139 static char *VarModify(char *, Boolean (*)(const char *, Boolean, Buffer, void *),
141 static int VarPrintVar(void *, void *);
144 *-----------------------------------------------------------------------
146 * See if the given variable matches the named one. Called from
147 * Lst_Find when searching for a variable of a given name.
150 * 0 if they match. non-zero otherwise.
154 *-----------------------------------------------------------------------
157 VarCmp (void *v, void *name)
159 return (strcmp ((char *) name, ((Var *) v)->name));
163 *-----------------------------------------------------------------------
164 * VarPossiblyExpand --
165 * Expand a variable name's embedded variables in the given context.
168 * The contents of name, possibly expanded.
171 * The caller must free the new contents or old contents of name.
172 *-----------------------------------------------------------------------
175 VarPossiblyExpand(char **name, GNode *ctxt)
177 if (strchr(*name, '$') != NULL)
178 *name = Var_Subst(NULL, *name, ctxt, 0);
180 *name = estrdup(*name);
184 *-----------------------------------------------------------------------
186 * Find the given variable in the given context and any other contexts
190 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
191 * FIND_CMD set means to look in the VAR_CMD context too
192 * FIND_ENV set means to look in the environment
195 * A pointer to the structure describing the desired variable or
196 * NULL if the variable does not exist.
200 *-----------------------------------------------------------------------
203 VarFind (char *name, GNode *ctxt, int flags)
205 Boolean localCheckEnvFirst;
210 * If the variable name begins with a '.', it could very well be one of
211 * the local ones. We check the name against all the local variables
212 * and substitute the short version in for 'name' if it matches one of
215 if (*name == '.' && isupper((unsigned char) name[1]))
218 if (!strcmp(name, ".ALLSRC"))
220 if (!strcmp(name, ".ARCHIVE"))
224 if (!strcmp(name, ".IMPSRC"))
228 if (!strcmp(name, ".MEMBER"))
232 if (!strcmp(name, ".OODATE"))
236 if (!strcmp(name, ".PREFIX"))
240 if (!strcmp(name, ".TARGET"))
246 * Note whether this is one of the specific variables we were told through
247 * the -E flag to use environment-variable-override for.
249 if (Lst_Find (envFirstVars, (void *)name,
250 (int (*)(void *, void *)) strcmp) != NULL)
252 localCheckEnvFirst = TRUE;
254 localCheckEnvFirst = FALSE;
258 * First look for the variable in the given context. If it's not there,
259 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
260 * depending on the FIND_* flags in 'flags'
262 var = Lst_Find (ctxt->context, (void *)name, VarCmp);
264 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
265 var = Lst_Find (VAR_CMD->context, (void *)name, VarCmp);
267 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
268 !checkEnvFirst && !localCheckEnvFirst)
270 var = Lst_Find (VAR_GLOBAL->context, (void *)name, VarCmp);
272 if ((var == NULL) && (flags & FIND_ENV)) {
275 if ((env = getenv (name)) != NULL) {
278 v = (Var *) emalloc(sizeof(Var));
279 v->name = estrdup(name);
283 v->val = Buf_Init(len);
284 Buf_AddBytes(v->val, len, (Byte *)env);
286 v->flags = VAR_FROM_ENV;
288 } else if ((checkEnvFirst || localCheckEnvFirst) &&
289 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
291 var = Lst_Find (VAR_GLOBAL->context, (void *)name, VarCmp);
293 return ((Var *) NULL);
295 return ((Var *)Lst_Datum(var));
300 } else if (var == NULL) {
301 return ((Var *) NULL);
303 return ((Var *) 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 (char *name, char *val, GNode *ctxt)
327 v = (Var *) emalloc (sizeof (Var));
329 v->name = estrdup (name);
331 len = val ? strlen(val) : 0;
332 v->val = Buf_Init(len+1);
333 Buf_AddBytes(v->val, len, (Byte *)val);
337 (void) Lst_AtFront (ctxt->context, (void *)v);
338 (void) Lst_AtEnd (allVars, (void *) v);
339 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
344 *-----------------------------------------------------------------------
346 * Delete a variable and all the space associated with it.
353 *-----------------------------------------------------------------------
360 Buf_Destroy(v->val, TRUE);
367 *-----------------------------------------------------------------------
369 * Remove a variable from a context.
375 * The Var structure is removed and freed.
377 *-----------------------------------------------------------------------
380 Var_Delete(char *name, GNode *ctxt)
384 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
385 ln = Lst_Find(ctxt->context, (void *)name, VarCmp);
389 v = (Var *)Lst_Datum(ln);
390 Lst_Remove(ctxt->context, ln);
391 ln = Lst_Member(allVars, v);
392 Lst_Remove(allVars, ln);
393 VarDelete((void *) v);
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 (char *name, char *val, GNode *ctxt)
424 * We only look for a variable in the given context since anything set
425 * here will override anything in a lower context, so there's not much
426 * point in searching them all just to save a bit of memory...
428 VarPossiblyExpand(&name, ctxt);
429 v = VarFind (name, ctxt, 0);
430 if (v == (Var *) NULL) {
431 VarAdd (name, val, ctxt);
433 Buf_Discard(v->val, Buf_Size(v->val));
434 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
436 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
439 * Any variables given on the command line are automatically exported
440 * to the environment (as per POSIX standard)
442 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
443 setenv(name, val, 1);
450 * Set the VAR_TO_ENV flag on a variable
453 Var_SetEnv (char *name, GNode *ctxt)
457 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
459 if ((v->flags & VAR_TO_ENV) == 0) {
460 v->flags |= VAR_TO_ENV;
461 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
464 Error("Cannot set environment flag on non-existant variable %s", name);
469 *-----------------------------------------------------------------------
471 * The variable of the given name has the given value appended to it in
478 * If the variable doesn't exist, it is created. Else the strings
479 * are concatenated (with a space in between).
482 * Only if the variable is being sought in the global context is the
483 * environment searched.
484 * XXX: Knows its calling circumstances in that if called with ctxt
485 * an actual target, it will only search that context since only
486 * a local variable could be being appended to. This is actually
487 * a big win and must be tolerated.
488 *-----------------------------------------------------------------------
491 Var_Append (char *name, char *val, GNode *ctxt)
495 VarPossiblyExpand(&name, ctxt);
496 v = VarFind (name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
498 if (v == (Var *) NULL) {
499 VarAdd (name, val, ctxt);
501 Buf_AddByte(v->val, (Byte)' ');
502 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
504 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name,
505 (char *) Buf_GetAll(v->val, (int *)NULL)));
507 if (v->flags & VAR_FROM_ENV) {
509 * If the original variable came from the environment, we
510 * have to install it in the global context (we could place
511 * it in the environment, but then we should provide a way to
512 * export other variables...)
514 v->flags &= ~VAR_FROM_ENV;
515 Lst_AtFront(ctxt->context, (void *)v);
522 *-----------------------------------------------------------------------
524 * See if the given variable exists.
527 * TRUE if it does, FALSE if it doesn't
532 *-----------------------------------------------------------------------
535 Var_Exists(char *name, GNode *ctxt)
539 VarPossiblyExpand(&name, ctxt);
540 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
543 if (v == (Var *)NULL) {
545 } else if (v->flags & VAR_FROM_ENV) {
547 Buf_Destroy(v->val, TRUE);
554 *-----------------------------------------------------------------------
556 * Return the value of the named variable in the given context
559 * The value if the variable exists, NULL if it doesn't
563 *-----------------------------------------------------------------------
566 Var_Value (char *name, GNode *ctxt, char **frp)
570 VarPossiblyExpand(&name, ctxt);
571 v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
574 if (v != (Var *) NULL) {
575 char *p = ((char *)Buf_GetAll(v->val, (int *)NULL));
576 if (v->flags & VAR_FROM_ENV) {
577 Buf_Destroy(v->val, FALSE);
583 return ((char *) NULL);
588 *-----------------------------------------------------------------------
590 * Print the error caused by a regcomp or regexec call.
596 * An error gets printed.
598 *-----------------------------------------------------------------------
601 VarREError(int err, regex_t *pat, const char *str)
606 errlen = regerror(err, pat, 0, 0);
607 errbuf = emalloc(errlen);
608 regerror(err, pat, errbuf, errlen);
609 Error("%s: %s", str, errbuf);
614 *-----------------------------------------------------------------------
616 * Modify each of the words of the passed string using the given
617 * function. Used to implement all modifiers.
620 * A string of all the words modified appropriately.
625 *-----------------------------------------------------------------------
628 VarModify (char *str, Boolean (*modProc)(const char *, Boolean, Buffer, void *),
631 Buffer buf; /* Buffer for the new string */
632 Boolean addSpace; /* TRUE if need to add a space to the
633 * buffer before adding the trimmed
635 char **av; /* word list [first word does not count] */
641 av = brk_string(str, &ac, FALSE);
643 for (i = 1; i < ac; i++)
644 addSpace = (*modProc)(av[i], addSpace, buf, datum);
646 Buf_AddByte (buf, '\0');
647 str = (char *)Buf_GetAll (buf, (int *)NULL);
648 Buf_Destroy (buf, FALSE);
653 *-----------------------------------------------------------------------
655 * Pass through the tstr looking for 1) escaped delimiters,
656 * '$'s and backslashes (place the escaped character in
657 * uninterpreted) and 2) unescaped $'s that aren't before
658 * the delimiter (expand the variable substitution unless flags
659 * has VAR_NOSUBST set).
660 * Return the expanded string or NULL if the delimiter was missing
661 * If pattern is specified, handle escaped ampersands, and replace
662 * unescaped ampersands with the lhs of the pattern.
665 * A string of all the words modified appropriately.
666 * If length is specified, return the string length of the buffer
667 * If flags is specified and the last character of the pattern is a
668 * $ set the VAR_MATCH_END bit of flags.
672 *-----------------------------------------------------------------------
675 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
676 int *length, VarPattern *pattern)
679 Buffer buf = Buf_Init(0);
684 #define IS_A_MATCH(cp, delim) \
685 ((cp[0] == '\\') && ((cp[1] == delim) || \
686 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
689 * Skim through until the matching delimiter is found;
690 * pick up variable substitutions on the way. Also allow
691 * backslashes to quote the delimiter, $, and \, but don't
692 * touch other backslashes.
694 for (cp = *tstr; *cp && (*cp != delim); cp++) {
695 if (IS_A_MATCH(cp, delim)) {
696 Buf_AddByte(buf, (Byte) cp[1]);
698 } else if (*cp == '$') {
699 if (cp[1] == delim) {
701 Buf_AddByte(buf, (Byte) *cp);
704 * Unescaped $ at end of pattern => anchor
707 *flags |= VAR_MATCH_END;
709 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
715 * If unescaped dollar sign not before the
716 * delimiter, assume it's a variable
717 * substitution and recurse.
719 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
720 Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
727 if (*cp2 == '(' || *cp2 == '{') {
729 * Find the end of this variable reference
730 * and suck it in without further ado.
731 * It will be interperated later.
734 int want = (*cp2 == '(') ? ')' : '}';
737 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
738 if (cp2[-1] != '\\') {
745 Buf_AddBytes(buf, cp2 - cp, (Byte *)cp);
748 Buf_AddByte(buf, (Byte) *cp);
752 else if (pattern && *cp == '&')
753 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
755 Buf_AddByte(buf, (Byte) *cp);
758 Buf_AddByte(buf, (Byte) '\0');
767 cp = (char *) Buf_GetAll(buf, length);
768 *length -= 1; /* Don't count the NULL */
769 Buf_Destroy(buf, FALSE);
775 *-----------------------------------------------------------------------
777 * Quote shell meta-characters in the string
785 *-----------------------------------------------------------------------
788 Var_Quote(const char *str)
792 /* This should cover most shells :-( */
793 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
795 buf = Buf_Init (MAKE_BSIZE);
796 for (; *str; str++) {
797 if (strchr(meta, *str) != NULL)
798 Buf_AddByte(buf, (Byte)'\\');
799 Buf_AddByte(buf, (Byte)*str);
801 Buf_AddByte(buf, (Byte) '\0');
802 retstr = Buf_GetAll (buf, (int *)NULL);
803 Buf_Destroy (buf, FALSE);
808 *-----------------------------------------------------------------------
810 * Given the start of a variable invocation, extract the variable
811 * name and find its value, then modify it according to the
815 * The (possibly-modified) value of the variable or var_Error if the
816 * specification is invalid. The length of the specification is
817 * placed in *lengthPtr (for invalid specifications, this is just
818 * 2 to skip the '$' and the following letter, or 1 if '$' was the
819 * last character in the string).
820 * A Boolean in *freePtr telling whether the returned string should
821 * be freed by the caller.
826 *-----------------------------------------------------------------------
829 Var_Parse(char *str, GNode *ctxt, Boolean err, int *lengthPtr, Boolean *freePtr)
831 char *tstr; /* Pointer into str */
832 Var *v; /* Variable in invocation */
833 char *cp; /* Secondary pointer into str (place marker
835 Boolean haveModifier;/* TRUE if have modifiers for the variable */
836 char endc; /* Ending character when variable in parens
838 char startc=0; /* Starting character when variable in parens
840 int cnt; /* Used to count brace pairs when variable in
841 * in parens or braces */
844 Boolean dynamic; /* TRUE if the variable is local and we're
845 * expanding it in a non-local context. This
846 * is done to support dynamic sources. The
847 * result is just the invocation, unaltered */
848 int vlen; /* length of variable name, after embedded variable
855 if (str[1] != '(' && str[1] != '{') {
857 * If it's not bounded by braces of some sort, life is much simpler.
858 * We just need to check for the first character and return the
859 * value if it exists.
866 v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
867 if (v == (Var *)NULL) {
873 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
875 * If substituting a local variable in a non-local context,
876 * assume it's for dynamic source stuff. We have to handle
877 * this specially and return the longhand for the variable
878 * with the dollar sign escaped so it makes it back to the
879 * caller. Only four of the local variables are treated
880 * specially as they are the only four that will be set
881 * when dynamic sources are expanded.
883 /* XXX: It looks like $% and $! are reversed here */
886 return("$(.TARGET)");
888 return("$(.ARCHIVE)");
890 return("$(.PREFIX)");
892 return("$(.MEMBER)");
900 return (err ? var_Error : varNoError);
902 haveModifier = FALSE;
907 /* build up expanded variable name in this buffer */
908 Buffer buf = Buf_Init(MAKE_BSIZE);
911 endc = startc == '(' ? ')' : '}';
914 * Skip to the end character or a colon, whichever comes first,
915 * replacing embedded variables as we go.
917 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
921 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
923 if (rval == var_Error) {
924 Fatal("Error expanding embedded variable.");
925 } else if (rval != NULL) {
926 Buf_AddBytes(buf, strlen(rval), (Byte *) rval);
932 Buf_AddByte(buf, (Byte) *tstr);
936 * If we never did find the end character, return NULL
937 * right now, setting the length to be the distance to
938 * the end of the string, since that's what make does.
940 *lengthPtr = tstr - str;
944 haveModifier = (*tstr == ':');
947 Buf_AddByte(buf, (Byte) '\0');
948 str = Buf_GetAll(buf, NULL);
951 v = VarFind (str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
952 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
953 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
956 * Check for bogus D and F forms of local variables since we're
957 * in a local context and the name is the right length.
971 * Well, it's local -- go look for it.
975 v = VarFind(vname, ctxt, 0);
977 if (v != (Var *)NULL && !haveModifier) {
979 * No need for nested expansion or anything, as we're
980 * the only one who sets these things and we sure don't
981 * put nested invocations in them...
983 val = (char *)Buf_GetAll(v->val, (int *)NULL);
986 val = VarModify(val, VarHead, (void *)0);
988 val = VarModify(val, VarTail, (void *)0);
991 * Resulting string is dynamically allocated, so
992 * tell caller to free it.
995 *lengthPtr = tstr-start+1;
997 Buf_Destroy(buf, TRUE);
1007 if (v == (Var *)NULL) {
1009 (((vlen == 2) && (str[1] == 'F' ||
1010 str[1] == 'D')))) &&
1011 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1014 * If substituting a local variable in a non-local context,
1015 * assume it's for dynamic source stuff. We have to handle
1016 * this specially and return the longhand for the variable
1017 * with the dollar sign escaped so it makes it back to the
1018 * caller. Only four of the local variables are treated
1019 * specially as they are the only four that will be set
1020 * when dynamic sources are expanded.
1032 } else if ((vlen > 2) && (str[0] == '.') &&
1033 isupper((unsigned char) str[1]) &&
1034 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1039 if ((strncmp(str, ".TARGET", len) == 0) ||
1040 (strncmp(str, ".ARCHIVE", len) == 0) ||
1041 (strncmp(str, ".PREFIX", len) == 0) ||
1042 (strncmp(str, ".MEMBER", len) == 0))
1048 if (!haveModifier) {
1050 * No modifiers -- have specification length so we can return
1053 *lengthPtr = tstr - start + 1;
1056 str = emalloc(*lengthPtr + 1);
1057 strncpy(str, start, *lengthPtr);
1058 str[*lengthPtr] = '\0';
1060 Buf_Destroy(buf, TRUE);
1063 Buf_Destroy(buf, TRUE);
1064 return (err ? var_Error : varNoError);
1068 * Still need to get to the end of the variable specification,
1069 * so kludge up a Var structure for the modifications
1071 v = (Var *) emalloc(sizeof(Var));
1072 v->name = estrdup(str);
1073 v->val = Buf_Init(1);
1074 v->flags = VAR_JUNK;
1077 Buf_Destroy(buf, TRUE);
1080 if (v->flags & VAR_IN_USE) {
1081 Fatal("Variable %s is recursive.", v->name);
1084 v->flags |= VAR_IN_USE;
1087 * Before doing any modification, we have to make sure the value
1088 * has been fully expanded. If it looks like recursion might be
1089 * necessary (there's a dollar sign somewhere in the variable's value)
1090 * we just call Var_Subst to do any other substitutions that are
1091 * necessary. Note that the value returned by Var_Subst will have
1092 * been dynamically-allocated, so it will need freeing when we
1095 str = (char *)Buf_GetAll(v->val, (int *)NULL);
1096 if (strchr (str, '$') != (char *)NULL) {
1097 str = Var_Subst(NULL, str, ctxt, err);
1101 v->flags &= ~VAR_IN_USE;
1104 * Now we need to apply any modifiers the user wants applied.
1106 * :M<pattern> words which match the given <pattern>.
1107 * <pattern> is of the standard file
1109 * :S<d><pat1><d><pat2><d>[g]
1110 * Substitute <pat2> for <pat1> in the value
1111 * :C<d><pat1><d><pat2><d>[g]
1112 * Substitute <pat2> for regex <pat1> in the value
1113 * :H Substitute the head of each word
1114 * :T Substitute the tail of each word
1115 * :E Substitute the extension (minus '.') of
1117 * :R Substitute the root of each word
1118 * (pathname minus the suffix).
1119 * :lhs=rhs Like :S, but the rhs goes to the end of
1121 * :U Converts variable to upper-case.
1122 * :L Converts variable to lower-case.
1124 if ((str != (char *)NULL) && haveModifier) {
1126 * Skip initial colon while putting it back.
1129 while (*tstr != endc) {
1130 char *newStr; /* New value to return */
1131 char termc; /* Character which terminated scan */
1133 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1136 if (tstr[1] == endc || tstr[1] == ':') {
1138 buf = Buf_Init(MAKE_BSIZE);
1139 for (cp = str; *cp ; cp++)
1140 Buf_AddByte(buf, (Byte) toupper(*cp));
1142 Buf_AddByte(buf, (Byte) '\0');
1143 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1144 Buf_Destroy(buf, FALSE);
1152 if (tstr[1] == endc || tstr[1] == ':') {
1154 buf = Buf_Init(MAKE_BSIZE);
1155 for (cp = str; *cp ; cp++)
1156 Buf_AddByte(buf, (Byte) tolower(*cp));
1158 Buf_AddByte(buf, (Byte) '\0');
1159 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1160 Buf_Destroy(buf, FALSE);
1176 *cp != '\0' && *cp != ':' && *cp != endc;
1179 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)){
1188 * Need to compress the \:'s out of the pattern, so
1189 * allocate enough room to hold the uncompressed
1190 * pattern (note that cp started at tstr+1, so
1191 * cp - tstr takes the null byte into account) and
1192 * compress the pattern into the space.
1194 pattern = emalloc(cp - tstr);
1195 for (cp2 = pattern, cp = tstr + 1;
1199 if ((*cp == '\\') &&
1200 (cp[1] == ':' || cp[1] == endc)) {
1209 if (*tstr == 'M' || *tstr == 'm') {
1210 newStr = VarModify(str, VarMatch, (void *)pattern);
1212 newStr = VarModify(str, VarNoMatch,
1224 Buffer buf; /* Buffer for patterns */
1231 * If pattern begins with '^', it is anchored to the
1232 * start of the word -- skip over it and flag pattern.
1235 pattern.flags |= VAR_MATCH_START;
1242 * Pass through the lhs looking for 1) escaped delimiters,
1243 * '$'s and backslashes (place the escaped character in
1244 * uninterpreted) and 2) unescaped $'s that aren't before
1245 * the delimiter (expand the variable substitution).
1246 * The result is left in the Buffer buf.
1248 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1249 if ((*cp == '\\') &&
1254 Buf_AddByte(buf, (Byte)cp[1]);
1256 } else if (*cp == '$') {
1259 * If unescaped dollar sign not before the
1260 * delimiter, assume it's a variable
1261 * substitution and recurse.
1267 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1268 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1275 * Unescaped $ at end of pattern => anchor
1278 pattern.flags |= VAR_MATCH_END;
1281 Buf_AddByte(buf, (Byte)*cp);
1285 Buf_AddByte(buf, (Byte)'\0');
1288 * If lhs didn't end with the delimiter, complain and
1292 Fatal("Unclosed substitution for %s (%c missing)",
1297 * Fetch pattern and destroy buffer, but preserve the data
1298 * in it, since that's our lhs. Note that Buf_GetAll
1299 * will return the actual number of bytes, which includes
1300 * the null byte, so we have to decrement the length by
1303 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1305 Buf_Destroy(buf, FALSE);
1308 * Now comes the replacement string. Three things need to
1309 * be done here: 1) need to compress escaped delimiters and
1310 * ampersands and 2) need to replace unescaped ampersands
1311 * with the l.h.s. (since this isn't regexp, we can do
1312 * it right here) and 3) expand any variable substitutions.
1317 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1318 if ((*cp == '\\') &&
1324 Buf_AddByte(buf, (Byte)cp[1]);
1326 } else if ((*cp == '$') && (cp[1] != del)) {
1331 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1332 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1337 } else if (*cp == '&') {
1338 Buf_AddBytes(buf, pattern.leftLen,
1339 (Byte *)pattern.lhs);
1341 Buf_AddByte(buf, (Byte)*cp);
1345 Buf_AddByte(buf, (Byte)'\0');
1348 * If didn't end in delimiter character, complain
1351 Fatal("Unclosed substitution for %s (%c missing)",
1355 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1357 Buf_Destroy(buf, FALSE);
1360 * Check for global substitution. If 'g' after the final
1361 * delimiter, substitution is global and is marked that
1366 pattern.flags |= VAR_SUB_GLOBAL;
1371 * Global substitution of the empty string causes an
1372 * infinite number of matches, unless anchored by '^'
1373 * (start of string) or '$' (end of string). Catch the
1374 * infinite substitution here.
1375 * Note that flags can only contain the 3 bits we're
1376 * interested in so we don't have to mask unrelated
1377 * bits. We can test for equality.
1379 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1380 Fatal("Global substitution of the empty string");
1383 newStr = VarModify(str, VarSubstitute,
1386 * Free the two strings.
1394 VarREPattern pattern;
1404 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1405 NULL, NULL)) == NULL) {
1406 /* was: goto cleanup */
1407 *lengthPtr = cp - start + 1;
1411 Fatal("Unclosed substitution for %s (%c missing)",
1416 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1417 delim, NULL, NULL, NULL)) == NULL){
1420 /* was: goto cleanup */
1421 *lengthPtr = cp - start + 1;
1425 Fatal("Unclosed substitution for %s (%c missing)",
1433 pattern.flags |= VAR_SUB_GLOBAL;
1436 pattern.flags |= VAR_SUB_ONE;
1446 error = regcomp(&pattern.re, re, REG_EXTENDED);
1449 *lengthPtr = cp - start + 1;
1450 VarREError(error, &pattern.re, "RE substitution error");
1451 free(pattern.replace);
1455 pattern.nsub = pattern.re.re_nsub + 1;
1456 if (pattern.nsub < 1)
1458 if (pattern.nsub > 10)
1460 pattern.matches = emalloc(pattern.nsub *
1461 sizeof(regmatch_t));
1462 newStr = VarModify(str, VarRESubstitute,
1464 regfree(&pattern.re);
1465 free(pattern.replace);
1466 free(pattern.matches);
1470 if (tstr[1] == endc || tstr[1] == ':') {
1471 newStr = Var_Quote (str);
1478 if (tstr[1] == endc || tstr[1] == ':') {
1479 newStr = VarModify (str, VarTail, (void *)0);
1486 if (tstr[1] == endc || tstr[1] == ':') {
1487 newStr = VarModify (str, VarHead, (void *)0);
1494 if (tstr[1] == endc || tstr[1] == ':') {
1495 newStr = VarModify (str, VarSuffix, (void *)0);
1502 if (tstr[1] == endc || tstr[1] == ':') {
1503 newStr = VarModify (str, VarRoot, (void *)0);
1511 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1513 newStr = Cmd_Exec (str, &error);
1526 * This can either be a bogus modifier or a System-V
1527 * substitution command.
1535 * First we make a pass through the string trying
1536 * to verify it is a SYSV-make-style translation:
1537 * it must be: <string1>=<string2>)
1541 while (*cp != '\0' && cnt) {
1544 /* continue looking for endc */
1546 else if (*cp == endc)
1548 else if (*cp == startc)
1553 if (*cp == endc && eqFound) {
1556 * Now we break this sucker into the lhs and
1557 * rhs. We must null terminate them of course.
1559 for (cp = tstr; *cp != '='; cp++)
1562 pattern.leftLen = cp - tstr;
1570 else if (*cp == startc)
1575 pattern.rightLen = cp - pattern.rhs;
1579 * SYSV modifications happen through the whole
1580 * string. Note the pattern is anchored at the end.
1582 newStr = VarModify(str, VarSYSVMatch,
1586 * Restore the nulled characters
1588 pattern.lhs[pattern.leftLen] = '=';
1589 pattern.rhs[pattern.rightLen] = endc;
1594 Error ("Unknown modifier '%c'\n", *tstr);
1596 *cp != ':' && *cp != endc && *cp != '\0';
1604 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1610 if (str != var_Error) {
1615 if (termc == '\0') {
1616 Error("Unclosed variable specification for %s", v->name);
1617 } else if (termc == ':') {
1624 *lengthPtr = tstr - start + 1;
1626 *lengthPtr = tstr - start + 1;
1630 if (v->flags & VAR_FROM_ENV) {
1631 Boolean destroy = FALSE;
1633 if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
1637 * Returning the value unmodified, so tell the caller to free
1643 Buf_Destroy(v->val, destroy);
1645 } else if (v->flags & VAR_JUNK) {
1647 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1648 * doesn't try to free a static pointer.
1655 Buf_Destroy(v->val, TRUE);
1658 str = emalloc(*lengthPtr + 1);
1659 strncpy(str, start, *lengthPtr);
1660 str[*lengthPtr] = '\0';
1663 str = err ? var_Error : varNoError;
1670 *-----------------------------------------------------------------------
1672 * Substitute for all variables in the given string in the given context
1673 * If undefErr is TRUE, Parse_Error will be called when an undefined
1674 * variable is encountered.
1677 * The resulting string.
1680 * None. The old string must be freed by the caller
1681 *-----------------------------------------------------------------------
1684 Var_Subst (char *var, char *str, GNode *ctxt, Boolean undefErr)
1686 Buffer buf; /* Buffer for forming things */
1687 char *val; /* Value to substitute for a variable */
1688 int length; /* Length of the variable invocation */
1689 Boolean doFree; /* Set true if val should be freed */
1690 static Boolean errorReported; /* Set true if an error has already
1691 * been reported to prevent a plethora
1692 * of messages when recursing */
1694 buf = Buf_Init (MAKE_BSIZE);
1695 errorReported = FALSE;
1698 if (var == NULL && (*str == '$') && (str[1] == '$')) {
1700 * A dollar sign may be escaped either with another dollar sign.
1701 * In such a case, we skip over the escape character and store the
1702 * dollar sign into the buffer directly.
1705 Buf_AddByte(buf, (Byte)*str);
1707 } else if (*str != '$') {
1709 * Skip as many characters as possible -- either to the end of
1710 * the string or to the next dollar sign (variable invocation).
1714 for (cp = str++; *str != '$' && *str != '\0'; str++)
1716 Buf_AddBytes(buf, str - cp, (Byte *)cp);
1721 if (str[1] != '(' && str[1] != '{') {
1722 if (str[1] != *var || var[1] != '\0') {
1723 Buf_AddBytes(buf, 2, (Byte *) str);
1735 * Scan up to the end of the variable name.
1737 for (p = &str[2]; *p &&
1738 *p != ':' && *p != ')' && *p != '}'; p++)
1742 * A variable inside the variable. We cannot expand
1743 * the external variable yet, so we try again with
1747 Buf_AddBytes(buf, p - str, (Byte *) str);
1752 if (strncmp(var, str + 2, p - str - 2) != 0 ||
1753 var[p - str - 2] != '\0') {
1755 * Not the variable we want to expand, scan
1756 * until the next variable
1758 for (;*p != '$' && *p != '\0'; p++)
1760 Buf_AddBytes(buf, p - str, (Byte *) str);
1773 val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
1776 * When we come down here, val should either point to the
1777 * value of this variable, suitably modified, or be NULL.
1778 * Length should be the total length of the potential
1779 * variable invocation (from $ to end character...)
1781 if (val == var_Error || val == varNoError) {
1783 * If performing old-time variable substitution, skip over
1784 * the variable and continue with the substitution. Otherwise,
1785 * store the dollar sign and advance str so we continue with
1790 } else if (undefErr) {
1792 * If variable is undefined, complain and skip the
1793 * variable. The complaint will stop us from doing anything
1794 * when the file is parsed.
1796 if (!errorReported) {
1797 Parse_Error (PARSE_FATAL,
1798 "Undefined variable \"%.*s\"",length,str);
1801 errorReported = TRUE;
1803 Buf_AddByte (buf, (Byte)*str);
1808 * We've now got a variable structure to store in. But first,
1809 * advance the string pointer.
1814 * Copy all the characters from the variable value straight
1815 * into the new string.
1817 Buf_AddBytes (buf, strlen (val), (Byte *)val);
1825 Buf_AddByte (buf, '\0');
1826 str = (char *)Buf_GetAll (buf, (int *)NULL);
1827 Buf_Destroy (buf, FALSE);
1832 *-----------------------------------------------------------------------
1834 * Return the tail from each of a list of words. Used to set the
1835 * System V local variables.
1838 * The resulting string.
1843 *-----------------------------------------------------------------------
1846 Var_GetTail(char *file)
1848 return(VarModify(file, VarTail, (void *)0));
1852 *-----------------------------------------------------------------------
1854 * Find the leading components of a (list of) filename(s).
1855 * XXX: VarHead does not replace foo by ., as (sun) System V make
1859 * The leading components.
1864 *-----------------------------------------------------------------------
1867 Var_GetHead(char *file)
1869 return(VarModify(file, VarHead, (void *)0));
1873 *-----------------------------------------------------------------------
1875 * Initialize the module
1881 * The VAR_CMD and VAR_GLOBAL contexts are created
1882 *-----------------------------------------------------------------------
1887 VAR_GLOBAL = Targ_NewGN ("Global");
1888 VAR_CMD = Targ_NewGN ("Command");
1889 allVars = Lst_Init(FALSE);
1897 Lst_Destroy(allVars, VarDelete);
1901 /****************** PRINT DEBUGGING INFO *****************/
1903 VarPrintVar (void *vp, void *dummy __unused)
1905 Var *v = (Var *) vp;
1906 printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
1911 *-----------------------------------------------------------------------
1913 * print all variables in a context
1914 *-----------------------------------------------------------------------
1917 Var_Dump (GNode *ctxt)
1919 Lst_ForEach (ctxt->context, VarPrintVar, (void *) 0);