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.11 2004/11/13 00:06:16 dillon 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(name, ctxt)
179 if (strchr(*name, '$') != NULL)
180 *name = Var_Subst(NULL, *name, ctxt, 0);
182 *name = estrdup(*name);
186 *-----------------------------------------------------------------------
188 * Find the given variable in the given context and any other contexts
192 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
193 * FIND_CMD set means to look in the VAR_CMD context too
194 * FIND_ENV set means to look in the environment
197 * A pointer to the structure describing the desired variable or
198 * NULL if the variable does not exist.
202 *-----------------------------------------------------------------------
205 VarFind (char *name, GNode *ctxt, int flags)
207 Boolean localCheckEnvFirst;
212 * If the variable name begins with a '.', it could very well be one of
213 * the local ones. We check the name against all the local variables
214 * and substitute the short version in for 'name' if it matches one of
217 if (*name == '.' && isupper((unsigned char) name[1]))
220 if (!strcmp(name, ".ALLSRC"))
222 if (!strcmp(name, ".ARCHIVE"))
226 if (!strcmp(name, ".IMPSRC"))
230 if (!strcmp(name, ".MEMBER"))
234 if (!strcmp(name, ".OODATE"))
238 if (!strcmp(name, ".PREFIX"))
242 if (!strcmp(name, ".TARGET"))
248 * Note whether this is one of the specific variables we were told through
249 * the -E flag to use environment-variable-override for.
251 if (Lst_Find (envFirstVars, (void *)name,
252 (int (*)(void *, void *)) strcmp) != NULL)
254 localCheckEnvFirst = TRUE;
256 localCheckEnvFirst = FALSE;
260 * First look for the variable in the given context. If it's not there,
261 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
262 * depending on the FIND_* flags in 'flags'
264 var = Lst_Find (ctxt->context, (void *)name, VarCmp);
266 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
267 var = Lst_Find (VAR_CMD->context, (void *)name, VarCmp);
269 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
270 !checkEnvFirst && !localCheckEnvFirst)
272 var = Lst_Find (VAR_GLOBAL->context, (void *)name, VarCmp);
274 if ((var == NULL) && (flags & FIND_ENV)) {
277 if ((env = getenv (name)) != NULL) {
280 v = (Var *) emalloc(sizeof(Var));
281 v->name = estrdup(name);
285 v->val = Buf_Init(len);
286 Buf_AddBytes(v->val, len, (Byte *)env);
288 v->flags = VAR_FROM_ENV;
290 } else if ((checkEnvFirst || localCheckEnvFirst) &&
291 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
293 var = Lst_Find (VAR_GLOBAL->context, (void *)name, VarCmp);
295 return ((Var *) NULL);
297 return ((Var *)Lst_Datum(var));
302 } else if (var == NULL) {
303 return ((Var *) NULL);
305 return ((Var *) Lst_Datum (var));
310 *-----------------------------------------------------------------------
312 * Add a new variable of name name and value val to the given context.
318 * The new variable is placed at the front of the given context
319 * The name and val arguments are duplicated so they may
321 *-----------------------------------------------------------------------
324 VarAdd (char *name, char *val, GNode *ctxt)
329 v = (Var *) emalloc (sizeof (Var));
331 v->name = estrdup (name);
333 len = val ? strlen(val) : 0;
334 v->val = Buf_Init(len+1);
335 Buf_AddBytes(v->val, len, (Byte *)val);
339 (void) Lst_AtFront (ctxt->context, (void *)v);
340 (void) Lst_AtEnd (allVars, (void *) v);
341 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
346 *-----------------------------------------------------------------------
348 * Delete a variable and all the space associated with it.
355 *-----------------------------------------------------------------------
362 Buf_Destroy(v->val, TRUE);
369 *-----------------------------------------------------------------------
371 * Remove a variable from a context.
377 * The Var structure is removed and freed.
379 *-----------------------------------------------------------------------
382 Var_Delete(char *name, GNode *ctxt)
386 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
387 ln = Lst_Find(ctxt->context, (void *)name, VarCmp);
391 v = (Var *)Lst_Datum(ln);
392 Lst_Remove(ctxt->context, ln);
393 ln = Lst_Member(allVars, v);
394 Lst_Remove(allVars, ln);
395 VarDelete((void *) v);
400 *-----------------------------------------------------------------------
402 * Set the variable name to the value val in the given context.
408 * If the variable doesn't yet exist, a new record is created for it.
409 * Else the old value is freed and the new one stuck in its place
412 * The variable is searched for only in its context before being
413 * created in that context. I.e. if the context is VAR_GLOBAL,
414 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
415 * VAR_CMD->context is searched. This is done to avoid the literally
416 * thousands of unnecessary strcmp's that used to be done to
417 * set, say, $(@) or $(<).
418 *-----------------------------------------------------------------------
421 Var_Set (char *name, char *val, GNode *ctxt)
426 * We only look for a variable in the given context since anything set
427 * here will override anything in a lower context, so there's not much
428 * point in searching them all just to save a bit of memory...
430 VarPossiblyExpand(&name, ctxt);
431 v = VarFind (name, ctxt, 0);
432 if (v == (Var *) NULL) {
433 VarAdd (name, val, ctxt);
435 Buf_Discard(v->val, Buf_Size(v->val));
436 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
438 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
441 * Any variables given on the command line are automatically exported
442 * to the environment (as per POSIX standard)
444 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
445 setenv(name, val, 1);
452 * Set the VAR_TO_ENV flag on a variable
455 Var_SetEnv (char *name, GNode *ctxt)
459 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
461 if ((v->flags & VAR_TO_ENV) == 0) {
462 v->flags |= VAR_TO_ENV;
463 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
466 Error("Cannot set environment flag on non-existant variable %s", name);
471 *-----------------------------------------------------------------------
473 * The variable of the given name has the given value appended to it in
480 * If the variable doesn't exist, it is created. Else the strings
481 * are concatenated (with a space in between).
484 * Only if the variable is being sought in the global context is the
485 * environment searched.
486 * XXX: Knows its calling circumstances in that if called with ctxt
487 * an actual target, it will only search that context since only
488 * a local variable could be being appended to. This is actually
489 * a big win and must be tolerated.
490 *-----------------------------------------------------------------------
493 Var_Append (char *name, char *val, GNode *ctxt)
497 VarPossiblyExpand(&name, ctxt);
498 v = VarFind (name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
500 if (v == (Var *) NULL) {
501 VarAdd (name, val, ctxt);
503 Buf_AddByte(v->val, (Byte)' ');
504 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
506 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name,
507 (char *) Buf_GetAll(v->val, (int *)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, (void *)v);
524 *-----------------------------------------------------------------------
526 * See if the given variable exists.
529 * TRUE if it does, FALSE if it doesn't
534 *-----------------------------------------------------------------------
537 Var_Exists(char *name, GNode *ctxt)
541 VarPossiblyExpand(&name, ctxt);
542 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
545 if (v == (Var *)NULL) {
547 } else if (v->flags & VAR_FROM_ENV) {
549 Buf_Destroy(v->val, TRUE);
556 *-----------------------------------------------------------------------
558 * Return the value of the named variable in the given context
561 * The value if the variable exists, NULL if it doesn't
565 *-----------------------------------------------------------------------
568 Var_Value (char *name, GNode *ctxt, char **frp)
572 VarPossiblyExpand(&name, ctxt);
573 v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
576 if (v != (Var *) NULL) {
577 char *p = ((char *)Buf_GetAll(v->val, (int *)NULL));
578 if (v->flags & VAR_FROM_ENV) {
579 Buf_Destroy(v->val, FALSE);
585 return ((char *) NULL);
590 *-----------------------------------------------------------------------
592 * Print the error caused by a regcomp or regexec call.
598 * An error gets printed.
600 *-----------------------------------------------------------------------
603 VarREError(int err, regex_t *pat, const char *str)
608 errlen = regerror(err, pat, 0, 0);
609 errbuf = emalloc(errlen);
610 regerror(err, pat, errbuf, errlen);
611 Error("%s: %s", str, errbuf);
616 *-----------------------------------------------------------------------
618 * Modify each of the words of the passed string using the given
619 * function. Used to implement all modifiers.
622 * A string of all the words modified appropriately.
627 *-----------------------------------------------------------------------
630 VarModify (char *str, Boolean (*modProc)(const char *, Boolean, Buffer, void *),
633 Buffer buf; /* Buffer for the new string */
634 Boolean addSpace; /* TRUE if need to add a space to the
635 * buffer before adding the trimmed
637 char **av; /* word list [first word does not count] */
643 av = brk_string(str, &ac, FALSE);
645 for (i = 1; i < ac; i++)
646 addSpace = (*modProc)(av[i], addSpace, buf, datum);
648 Buf_AddByte (buf, '\0');
649 str = (char *)Buf_GetAll (buf, (int *)NULL);
650 Buf_Destroy (buf, FALSE);
655 *-----------------------------------------------------------------------
657 * Pass through the tstr looking for 1) escaped delimiters,
658 * '$'s and backslashes (place the escaped character in
659 * uninterpreted) and 2) unescaped $'s that aren't before
660 * the delimiter (expand the variable substitution unless flags
661 * has VAR_NOSUBST set).
662 * Return the expanded string or NULL if the delimiter was missing
663 * If pattern is specified, handle escaped ampersands, and replace
664 * unescaped ampersands with the lhs of the pattern.
667 * A string of all the words modified appropriately.
668 * If length is specified, return the string length of the buffer
669 * If flags is specified and the last character of the pattern is a
670 * $ set the VAR_MATCH_END bit of flags.
674 *-----------------------------------------------------------------------
677 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
678 int *length, VarPattern *pattern)
681 Buffer buf = Buf_Init(0);
686 #define IS_A_MATCH(cp, delim) \
687 ((cp[0] == '\\') && ((cp[1] == delim) || \
688 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
691 * Skim through until the matching delimiter is found;
692 * pick up variable substitutions on the way. Also allow
693 * backslashes to quote the delimiter, $, and \, but don't
694 * touch other backslashes.
696 for (cp = *tstr; *cp && (*cp != delim); cp++) {
697 if (IS_A_MATCH(cp, delim)) {
698 Buf_AddByte(buf, (Byte) cp[1]);
700 } else if (*cp == '$') {
701 if (cp[1] == delim) {
703 Buf_AddByte(buf, (Byte) *cp);
706 * Unescaped $ at end of pattern => anchor
709 *flags |= VAR_MATCH_END;
711 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
717 * If unescaped dollar sign not before the
718 * delimiter, assume it's a variable
719 * substitution and recurse.
721 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
722 Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
729 if (*cp2 == '(' || *cp2 == '{') {
731 * Find the end of this variable reference
732 * and suck it in without further ado.
733 * It will be interperated later.
736 int want = (*cp2 == '(') ? ')' : '}';
739 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
740 if (cp2[-1] != '\\') {
747 Buf_AddBytes(buf, cp2 - cp, (Byte *)cp);
750 Buf_AddByte(buf, (Byte) *cp);
754 else if (pattern && *cp == '&')
755 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
757 Buf_AddByte(buf, (Byte) *cp);
760 Buf_AddByte(buf, (Byte) '\0');
769 cp = (char *) Buf_GetAll(buf, length);
770 *length -= 1; /* Don't count the NULL */
771 Buf_Destroy(buf, FALSE);
778 *-----------------------------------------------------------------------
780 * Quote shell meta-characters in the string
788 *-----------------------------------------------------------------------
795 /* This should cover most shells :-( */
796 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
798 buf = Buf_Init (MAKE_BSIZE);
799 for (; *str; str++) {
800 if (strchr(meta, *str) != NULL)
801 Buf_AddByte(buf, (Byte)'\\');
802 Buf_AddByte(buf, (Byte)*str);
804 Buf_AddByte(buf, (Byte) '\0');
805 str = (char *)Buf_GetAll (buf, (int *)NULL);
806 Buf_Destroy (buf, FALSE);
811 *-----------------------------------------------------------------------
813 * Given the start of a variable invocation, extract the variable
814 * name and find its value, then modify it according to the
818 * The (possibly-modified) value of the variable or var_Error if the
819 * specification is invalid. The length of the specification is
820 * placed in *lengthPtr (for invalid specifications, this is just
822 * A Boolean in *freePtr telling whether the returned string should
823 * be freed by the caller.
828 *-----------------------------------------------------------------------
831 Var_Parse(char *str, GNode *ctxt, Boolean err, int *lengthPtr, Boolean *freePtr)
833 char *tstr; /* Pointer into str */
834 Var *v; /* Variable in invocation */
835 char *cp; /* Secondary pointer into str (place marker
837 Boolean haveModifier;/* TRUE if have modifiers for the variable */
838 char endc; /* Ending character when variable in parens
840 char startc=0; /* Starting character when variable in parens
842 int cnt; /* Used to count brace pairs when variable in
843 * in parens or braces */
846 Boolean dynamic; /* TRUE if the variable is local and we're
847 * expanding it in a non-local context. This
848 * is done to support dynamic sources. The
849 * result is just the invocation, unaltered */
850 int vlen; /* length of variable name, after embedded variable
857 if (str[1] != '(' && str[1] != '{') {
859 * If it's not bounded by braces of some sort, life is much simpler.
860 * We just need to check for the first character and return the
861 * value if it exists.
868 v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
869 if (v == (Var *)NULL) {
872 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
874 * If substituting a local variable in a non-local context,
875 * assume it's for dynamic source stuff. We have to handle
876 * this specially and return the longhand for the variable
877 * with the dollar sign escaped so it makes it back to the
878 * caller. Only four of the local variables are treated
879 * specially as they are the only four that will be set
880 * when dynamic sources are expanded.
882 /* XXX: It looks like $% and $! are reversed here */
885 return("$(.TARGET)");
887 return("$(.ARCHIVE)");
889 return("$(.PREFIX)");
891 return("$(.MEMBER)");
897 return (err ? var_Error : varNoError);
899 haveModifier = FALSE;
904 /* build up expanded variable name in this buffer */
905 Buffer buf = Buf_Init(MAKE_BSIZE);
908 endc = startc == '(' ? ')' : '}';
911 * Skip to the end character or a colon, whichever comes first,
912 * replacing embedded variables as we go.
914 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
918 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
920 if (rval == var_Error) {
921 Fatal("Error expanding embedded variable.");
922 } else if (rval != NULL) {
923 Buf_AddBytes(buf, strlen(rval), (Byte *) rval);
929 Buf_AddByte(buf, (Byte) *tstr);
933 * If we never did find the end character, return NULL
934 * right now, setting the length to be the distance to
935 * the end of the string, since that's what make does.
937 *lengthPtr = tstr - str;
941 haveModifier = (*tstr == ':');
944 Buf_AddByte(buf, (Byte) '\0');
945 str = Buf_GetAll(buf, NULL);
948 v = VarFind (str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
949 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
950 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
953 * Check for bogus D and F forms of local variables since we're
954 * in a local context and the name is the right length.
968 * Well, it's local -- go look for it.
972 v = VarFind(vname, ctxt, 0);
974 if (v != (Var *)NULL && !haveModifier) {
976 * No need for nested expansion or anything, as we're
977 * the only one who sets these things and we sure don't
978 * put nested invocations in them...
980 val = (char *)Buf_GetAll(v->val, (int *)NULL);
983 val = VarModify(val, VarHead, (void *)0);
985 val = VarModify(val, VarTail, (void *)0);
988 * Resulting string is dynamically allocated, so
989 * tell caller to free it.
992 *lengthPtr = tstr-start+1;
994 Buf_Destroy(buf, TRUE);
1002 if (v == (Var *)NULL) {
1004 (((vlen == 2) && (str[1] == 'F' ||
1005 str[1] == 'D')))) &&
1006 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1009 * If substituting a local variable in a non-local context,
1010 * assume it's for dynamic source stuff. We have to handle
1011 * this specially and return the longhand for the variable
1012 * with the dollar sign escaped so it makes it back to the
1013 * caller. Only four of the local variables are treated
1014 * specially as they are the only four that will be set
1015 * when dynamic sources are expanded.
1025 } else if ((vlen > 2) && (str[0] == '.') &&
1026 isupper((unsigned char) str[1]) &&
1027 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1032 if ((strncmp(str, ".TARGET", len) == 0) ||
1033 (strncmp(str, ".ARCHIVE", len) == 0) ||
1034 (strncmp(str, ".PREFIX", len) == 0) ||
1035 (strncmp(str, ".MEMBER", len) == 0))
1041 if (!haveModifier) {
1043 * No modifiers -- have specification length so we can return
1046 *lengthPtr = tstr - start + 1;
1049 str = emalloc(*lengthPtr + 1);
1050 strncpy(str, start, *lengthPtr);
1051 str[*lengthPtr] = '\0';
1053 Buf_Destroy(buf, TRUE);
1056 Buf_Destroy(buf, TRUE);
1057 return (err ? var_Error : varNoError);
1061 * Still need to get to the end of the variable specification,
1062 * so kludge up a Var structure for the modifications
1064 v = (Var *) emalloc(sizeof(Var));
1066 v->val = Buf_Init(1);
1067 v->flags = VAR_JUNK;
1070 Buf_Destroy(buf, TRUE);
1073 if (v->flags & VAR_IN_USE) {
1074 Fatal("Variable %s is recursive.", v->name);
1077 v->flags |= VAR_IN_USE;
1080 * Before doing any modification, we have to make sure the value
1081 * has been fully expanded. If it looks like recursion might be
1082 * necessary (there's a dollar sign somewhere in the variable's value)
1083 * we just call Var_Subst to do any other substitutions that are
1084 * necessary. Note that the value returned by Var_Subst will have
1085 * been dynamically-allocated, so it will need freeing when we
1088 str = (char *)Buf_GetAll(v->val, (int *)NULL);
1089 if (strchr (str, '$') != (char *)NULL) {
1090 str = Var_Subst(NULL, str, ctxt, err);
1094 v->flags &= ~VAR_IN_USE;
1097 * Now we need to apply any modifiers the user wants applied.
1099 * :M<pattern> words which match the given <pattern>.
1100 * <pattern> is of the standard file
1102 * :S<d><pat1><d><pat2><d>[g]
1103 * Substitute <pat2> for <pat1> in the value
1104 * :C<d><pat1><d><pat2><d>[g]
1105 * Substitute <pat2> for regex <pat1> in the value
1106 * :H Substitute the head of each word
1107 * :T Substitute the tail of each word
1108 * :E Substitute the extension (minus '.') of
1110 * :R Substitute the root of each word
1111 * (pathname minus the suffix).
1112 * :lhs=rhs Like :S, but the rhs goes to the end of
1114 * :U Converts variable to upper-case.
1115 * :L Converts variable to lower-case.
1117 if ((str != (char *)NULL) && haveModifier) {
1119 * Skip initial colon while putting it back.
1122 while (*tstr != endc) {
1123 char *newStr; /* New value to return */
1124 char termc; /* Character which terminated scan */
1126 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1129 if (tstr[1] == endc || tstr[1] == ':') {
1131 buf = Buf_Init(MAKE_BSIZE);
1132 for (cp = str; *cp ; cp++)
1133 Buf_AddByte(buf, (Byte) toupper(*cp));
1135 Buf_AddByte(buf, (Byte) '\0');
1136 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1137 Buf_Destroy(buf, FALSE);
1145 if (tstr[1] == endc || tstr[1] == ':') {
1147 buf = Buf_Init(MAKE_BSIZE);
1148 for (cp = str; *cp ; cp++)
1149 Buf_AddByte(buf, (Byte) tolower(*cp));
1151 Buf_AddByte(buf, (Byte) '\0');
1152 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1153 Buf_Destroy(buf, FALSE);
1169 *cp != '\0' && *cp != ':' && *cp != endc;
1172 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)){
1181 * Need to compress the \:'s out of the pattern, so
1182 * allocate enough room to hold the uncompressed
1183 * pattern (note that cp started at tstr+1, so
1184 * cp - tstr takes the null byte into account) and
1185 * compress the pattern into the space.
1187 pattern = emalloc(cp - tstr);
1188 for (cp2 = pattern, cp = tstr + 1;
1192 if ((*cp == '\\') &&
1193 (cp[1] == ':' || cp[1] == endc)) {
1202 if (*tstr == 'M' || *tstr == 'm') {
1203 newStr = VarModify(str, VarMatch, (void *)pattern);
1205 newStr = VarModify(str, VarNoMatch,
1217 Buffer buf; /* Buffer for patterns */
1224 * If pattern begins with '^', it is anchored to the
1225 * start of the word -- skip over it and flag pattern.
1228 pattern.flags |= VAR_MATCH_START;
1235 * Pass through the lhs looking for 1) escaped delimiters,
1236 * '$'s and backslashes (place the escaped character in
1237 * uninterpreted) and 2) unescaped $'s that aren't before
1238 * the delimiter (expand the variable substitution).
1239 * The result is left in the Buffer buf.
1241 for (cp = tstr; *cp != '\0' && *cp != delim; cp++) {
1242 if ((*cp == '\\') &&
1243 ((cp[1] == delim) ||
1247 Buf_AddByte(buf, (Byte)cp[1]);
1249 } else if (*cp == '$') {
1250 if (cp[1] != delim) {
1252 * If unescaped dollar sign not before the
1253 * delimiter, assume it's a variable
1254 * substitution and recurse.
1260 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1261 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1268 * Unescaped $ at end of pattern => anchor
1271 pattern.flags |= VAR_MATCH_END;
1274 Buf_AddByte(buf, (Byte)*cp);
1278 Buf_AddByte(buf, (Byte)'\0');
1281 * If lhs didn't end with the delimiter, complain and
1285 *lengthPtr = cp - start + 1;
1289 Buf_Destroy(buf, TRUE);
1290 Error("Unclosed substitution for %s (%c missing)",
1296 * Fetch pattern and destroy buffer, but preserve the data
1297 * in it, since that's our lhs. Note that Buf_GetAll
1298 * will return the actual number of bytes, which includes
1299 * the null byte, so we have to decrement the length by
1302 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1304 Buf_Destroy(buf, FALSE);
1307 * Now comes the replacement string. Three things need to
1308 * be done here: 1) need to compress escaped delimiters and
1309 * ampersands and 2) need to replace unescaped ampersands
1310 * with the l.h.s. (since this isn't regexp, we can do
1311 * it right here) and 3) expand any variable substitutions.
1316 for (cp = tstr; *cp != '\0' && *cp != delim; cp++) {
1317 if ((*cp == '\\') &&
1318 ((cp[1] == delim) ||
1323 Buf_AddByte(buf, (Byte)cp[1]);
1325 } else if ((*cp == '$') && (cp[1] != delim)) {
1330 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1331 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1336 } else if (*cp == '&') {
1337 Buf_AddBytes(buf, pattern.leftLen,
1338 (Byte *)pattern.lhs);
1340 Buf_AddByte(buf, (Byte)*cp);
1344 Buf_AddByte(buf, (Byte)'\0');
1347 * If didn't end in delimiter character, complain
1350 *lengthPtr = cp - start + 1;
1354 Buf_Destroy(buf, TRUE);
1355 Error("Unclosed substitution for %s (%c missing)",
1360 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1362 Buf_Destroy(buf, FALSE);
1365 * Check for global substitution. If 'g' after the final
1366 * delimiter, substitution is global and is marked that
1371 pattern.flags |= VAR_SUB_GLOBAL;
1376 newStr = VarModify(str, VarSubstitute,
1379 * Free the two strings.
1387 VarREPattern pattern;
1397 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1398 NULL, NULL)) == NULL) {
1399 /* was: goto cleanup */
1400 *lengthPtr = cp - start + 1;
1404 Error("Unclosed substitution for %s (%c missing)",
1409 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1410 delim, NULL, NULL, NULL)) == NULL){
1413 /* was: goto cleanup */
1414 *lengthPtr = cp - start + 1;
1418 Error("Unclosed substitution for %s (%c missing)",
1426 pattern.flags |= VAR_SUB_GLOBAL;
1429 pattern.flags |= VAR_SUB_ONE;
1437 error = regcomp(&pattern.re, re, REG_EXTENDED);
1440 *lengthPtr = cp - start + 1;
1441 VarREError(error, &pattern.re, "RE substitution error");
1442 free(pattern.replace);
1446 pattern.nsub = pattern.re.re_nsub + 1;
1447 if (pattern.nsub < 1)
1449 if (pattern.nsub > 10)
1451 pattern.matches = emalloc(pattern.nsub *
1452 sizeof(regmatch_t));
1453 newStr = VarModify(str, VarRESubstitute,
1455 regfree(&pattern.re);
1456 free(pattern.replace);
1457 free(pattern.matches);
1461 if (tstr[1] == endc || tstr[1] == ':') {
1462 newStr = VarQuote (str);
1469 if (tstr[1] == endc || tstr[1] == ':') {
1470 newStr = VarModify (str, VarTail, (void *)0);
1477 if (tstr[1] == endc || tstr[1] == ':') {
1478 newStr = VarModify (str, VarHead, (void *)0);
1485 if (tstr[1] == endc || tstr[1] == ':') {
1486 newStr = VarModify (str, VarSuffix, (void *)0);
1493 if (tstr[1] == endc || tstr[1] == ':') {
1494 newStr = VarModify (str, VarRoot, (void *)0);
1502 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1504 newStr = Cmd_Exec (str, &err);
1517 * This can either be a bogus modifier or a System-V
1518 * substitution command.
1526 * First we make a pass through the string trying
1527 * to verify it is a SYSV-make-style translation:
1528 * it must be: <string1>=<string2>)
1532 while (*cp != '\0' && cnt) {
1535 /* continue looking for endc */
1537 else if (*cp == endc)
1539 else if (*cp == startc)
1544 if (*cp == endc && eqFound) {
1547 * Now we break this sucker into the lhs and
1548 * rhs. We must null terminate them of course.
1550 for (cp = tstr; *cp != '='; cp++)
1553 pattern.leftLen = cp - tstr;
1561 else if (*cp == startc)
1566 pattern.rightLen = cp - pattern.rhs;
1570 * SYSV modifications happen through the whole
1571 * string. Note the pattern is anchored at the end.
1573 newStr = VarModify(str, VarSYSVMatch,
1577 * Restore the nulled characters
1579 pattern.lhs[pattern.leftLen] = '=';
1580 pattern.rhs[pattern.rightLen] = endc;
1585 Error ("Unknown modifier '%c'\n", *tstr);
1587 *cp != ':' && *cp != endc && *cp != '\0';
1595 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1601 if (str != var_Error) {
1606 if (termc == '\0') {
1607 Error("Unclosed variable specification for %s", v->name);
1608 } else if (termc == ':') {
1615 *lengthPtr = tstr - start + 1;
1617 *lengthPtr = tstr - start + 1;
1621 if (v->flags & VAR_FROM_ENV) {
1622 Boolean destroy = FALSE;
1624 if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
1628 * Returning the value unmodified, so tell the caller to free
1633 Buf_Destroy(v->val, destroy);
1635 } else if (v->flags & VAR_JUNK) {
1637 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1638 * doesn't try to free a static pointer.
1644 Buf_Destroy(v->val, TRUE);
1647 str = emalloc(*lengthPtr + 1);
1648 strncpy(str, start, *lengthPtr);
1649 str[*lengthPtr] = '\0';
1652 str = err ? var_Error : varNoError;
1659 *-----------------------------------------------------------------------
1661 * Substitute for all variables in the given string in the given context
1662 * If undefErr is TRUE, Parse_Error will be called when an undefined
1663 * variable is encountered.
1666 * The resulting string.
1669 * None. The old string must be freed by the caller
1670 *-----------------------------------------------------------------------
1673 Var_Subst (char *var, char *str, GNode *ctxt, Boolean undefErr)
1675 Buffer buf; /* Buffer for forming things */
1676 char *val; /* Value to substitute for a variable */
1677 int length; /* Length of the variable invocation */
1678 Boolean doFree; /* Set true if val should be freed */
1679 static Boolean errorReported; /* Set true if an error has already
1680 * been reported to prevent a plethora
1681 * of messages when recursing */
1683 buf = Buf_Init (MAKE_BSIZE);
1684 errorReported = FALSE;
1687 if (var == NULL && (*str == '$') && (str[1] == '$')) {
1689 * A dollar sign may be escaped either with another dollar sign.
1690 * In such a case, we skip over the escape character and store the
1691 * dollar sign into the buffer directly.
1694 Buf_AddByte(buf, (Byte)*str);
1696 } else if (*str != '$') {
1698 * Skip as many characters as possible -- either to the end of
1699 * the string or to the next dollar sign (variable invocation).
1703 for (cp = str++; *str != '$' && *str != '\0'; str++)
1705 Buf_AddBytes(buf, str - cp, (Byte *)cp);
1710 if (str[1] != '(' && str[1] != '{') {
1711 if (str[1] != *var) {
1712 Buf_AddBytes(buf, 2, (Byte *) str);
1724 * Scan up to the end of the variable name.
1726 for (p = &str[2]; *p &&
1727 *p != ':' && *p != ')' && *p != '}'; p++)
1731 * A variable inside the variable. We cannot expand
1732 * the external variable yet, so we try again with
1736 Buf_AddBytes(buf, p - str, (Byte *) str);
1741 if (strncmp(var, str + 2, p - str - 2) != 0 ||
1742 var[p - str - 2] != '\0') {
1744 * Not the variable we want to expand, scan
1745 * until the next variable
1747 for (;*p != '$' && *p != '\0'; p++)
1749 Buf_AddBytes(buf, p - str, (Byte *) str);
1762 val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
1765 * When we come down here, val should either point to the
1766 * value of this variable, suitably modified, or be NULL.
1767 * Length should be the total length of the potential
1768 * variable invocation (from $ to end character...)
1770 if (val == var_Error || val == varNoError) {
1772 * If performing old-time variable substitution, skip over
1773 * the variable and continue with the substitution. Otherwise,
1774 * store the dollar sign and advance str so we continue with
1779 } else if (undefErr) {
1781 * If variable is undefined, complain and skip the
1782 * variable. The complaint will stop us from doing anything
1783 * when the file is parsed.
1785 if (!errorReported) {
1786 Parse_Error (PARSE_FATAL,
1787 "Undefined variable \"%.*s\"",length,str);
1790 errorReported = TRUE;
1792 Buf_AddByte (buf, (Byte)*str);
1797 * We've now got a variable structure to store in. But first,
1798 * advance the string pointer.
1803 * Copy all the characters from the variable value straight
1804 * into the new string.
1806 Buf_AddBytes (buf, strlen (val), (Byte *)val);
1814 Buf_AddByte (buf, '\0');
1815 str = (char *)Buf_GetAll (buf, (int *)NULL);
1816 Buf_Destroy (buf, FALSE);
1821 *-----------------------------------------------------------------------
1823 * Return the tail from each of a list of words. Used to set the
1824 * System V local variables.
1827 * The resulting string.
1832 *-----------------------------------------------------------------------
1835 Var_GetTail(char *file)
1837 return(VarModify(file, VarTail, (void *)0));
1841 *-----------------------------------------------------------------------
1843 * Find the leading components of a (list of) filename(s).
1844 * XXX: VarHead does not replace foo by ., as (sun) System V make
1848 * The leading components.
1853 *-----------------------------------------------------------------------
1856 Var_GetHead(char *file)
1858 return(VarModify(file, VarHead, (void *)0));
1862 *-----------------------------------------------------------------------
1864 * Initialize the module
1870 * The VAR_CMD and VAR_GLOBAL contexts are created
1871 *-----------------------------------------------------------------------
1876 VAR_GLOBAL = Targ_NewGN ("Global");
1877 VAR_CMD = Targ_NewGN ("Command");
1878 allVars = Lst_Init(FALSE);
1886 Lst_Destroy(allVars, VarDelete);
1890 /****************** PRINT DEBUGGING INFO *****************/
1892 VarPrintVar (void *vp, void *dummy __unused)
1894 Var *v = (Var *) vp;
1895 printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
1900 *-----------------------------------------------------------------------
1902 * print all variables in a context
1903 *-----------------------------------------------------------------------
1906 Var_Dump (GNode *ctxt)
1908 Lst_ForEach (ctxt->context, VarPrintVar, (void *) 0);