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
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
46 * Variable-handling functions
49 * Var_Set Set the value of a variable in the given
50 * context. The variable is created if it doesn't
51 * yet exist. The value and variable name need not
54 * Var_Append Append more characters to an existing variable
55 * in the given context. The variable needn't
56 * exist already -- it will be created if it doesn't.
57 * A space is placed between the old value and the
60 * Var_Exists See if a variable exists.
62 * Var_Value Return the value of a variable in a context or
63 * NULL if the variable is undefined.
65 * Var_Subst Substitute named variable, or all variables if
66 * NULL in a string using
67 * the given context as the top-most one. If the
68 * third argument is non-zero, Parse_Error is
69 * called if any variables are undefined.
71 * Var_Parse Parse a variable expansion from a string and
72 * return the result and the number of characters
75 * Var_Delete Delete a variable in a context.
77 * Var_Init Initialize this module.
80 * Var_Dump Print out all variables defined in the given
83 * XXX: There's a lot of duplication in these functions.
87 #include <sys/types.h>
95 * This is a harmless return value for Var_Parse that can be used by Var_Subst
96 * to determine if there was an error in parsing -- easier than returning
97 * a flag, as things outside this module don't give a hoot.
99 char var_Error[] = "";
102 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
103 * set false. Why not just use a constant? Well, gcc likes to condense
104 * identical string instances...
106 static char varNoError[] = "";
109 * Internally, variables are contained in four different contexts.
110 * 1) the environment. They may not be changed. If an environment
111 * variable is appended-to, the result is placed in the global
113 * 2) the global context. Variables set in the Makefile are located in
114 * the global context. It is the penultimate context searched when
116 * 3) the command-line context. All variables set on the command line
117 * are placed in this context. They are UNALTERABLE once placed here.
118 * 4) the local context. Each target has associated with it a context
119 * list. On this list are located the structures describing such
120 * local variables as $(@) and $(*)
121 * The four contexts are searched in the reverse order from which they are
124 GNode *VAR_GLOBAL; /* variables from the makefile */
125 GNode *VAR_CMD; /* variables defined on the command-line */
127 static Lst allVars; /* List of all variables */
129 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
130 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
131 #define FIND_ENV 0x4 /* look in the environment also */
133 static int VarCmp(void *, void *);
134 static void VarPossiblyExpand(char **, GNode *);
135 static Var *VarFind(char *, GNode *, int);
136 static void VarAdd(char *, char *, GNode *);
137 static void VarDelete(void *);
138 static char *VarGetPattern(GNode *, int, char **, int, int *, int *,
140 static char *VarQuote(const char *);
141 static char *VarModify(char *,
142 Boolean (*)(const char *, Boolean, Buffer, void *),
144 static int VarPrintVar(void *, void *);
147 *-----------------------------------------------------------------------
149 * See if the given variable matches the named one. Called from
150 * Lst_Find when searching for a variable of a given name.
153 * 0 if they match. non-zero otherwise.
157 *-----------------------------------------------------------------------
160 VarCmp (void *v, void *name)
162 return (strcmp ((char *) name, ((Var *) v)->name));
166 *-----------------------------------------------------------------------
167 * VarPossiblyExpand --
168 * Expand a variable name's embedded variables in the given context.
171 * The contents of name, possibly expanded.
174 * The caller must free the new contents or old contents of name.
175 *-----------------------------------------------------------------------
178 VarPossiblyExpand(char **name, GNode *ctxt)
180 if (strchr(*name, '$') != NULL)
181 *name = Var_Subst(NULL, *name, ctxt, 0);
183 *name = estrdup(*name);
187 *-----------------------------------------------------------------------
189 * Find the given variable in the given context and any other contexts
193 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
194 * FIND_CMD set means to look in the VAR_CMD context too
195 * FIND_ENV set means to look in the environment
198 * A pointer to the structure describing the desired variable or
199 * NULL if the variable does not exist.
203 *-----------------------------------------------------------------------
206 VarFind (char *name, GNode *ctxt, int flags)
208 Boolean localCheckEnvFirst;
213 * If the variable name begins with a '.', it could very well be one of
214 * the local ones. We check the name against all the local variables
215 * and substitute the short version in for 'name' if it matches one of
218 if (*name == '.' && isupper((unsigned char) name[1]))
221 if (!strcmp(name, ".ALLSRC"))
223 if (!strcmp(name, ".ARCHIVE"))
227 if (!strcmp(name, ".IMPSRC"))
231 if (!strcmp(name, ".MEMBER"))
235 if (!strcmp(name, ".OODATE"))
239 if (!strcmp(name, ".PREFIX"))
243 if (!strcmp(name, ".TARGET"))
249 * Note whether this is one of the specific variables we were told through
250 * the -E flag to use environment-variable-override for.
252 if (Lst_Find (envFirstVars, (void *)name,
253 (int (*)(void *, void *)) strcmp) != NULL)
255 localCheckEnvFirst = TRUE;
257 localCheckEnvFirst = FALSE;
261 * First look for the variable in the given context. If it's not there,
262 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
263 * depending on the FIND_* flags in 'flags'
265 var = Lst_Find (ctxt->context, (void *)name, VarCmp);
267 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
268 var = Lst_Find (VAR_CMD->context, (void *)name, VarCmp);
270 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
271 !checkEnvFirst && !localCheckEnvFirst)
273 var = Lst_Find (VAR_GLOBAL->context, (void *)name, VarCmp);
275 if ((var == NULL) && (flags & FIND_ENV)) {
278 if ((env = getenv (name)) != NULL) {
281 v = (Var *) emalloc(sizeof(Var));
282 v->name = estrdup(name);
286 v->val = Buf_Init(len);
287 Buf_AddBytes(v->val, len, (Byte *)env);
289 v->flags = VAR_FROM_ENV;
291 } else if ((checkEnvFirst || localCheckEnvFirst) &&
292 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
294 var = Lst_Find (VAR_GLOBAL->context, (void *)name, VarCmp);
296 return ((Var *) NULL);
298 return ((Var *)Lst_Datum(var));
303 } else if (var == NULL) {
304 return ((Var *) NULL);
306 return ((Var *) Lst_Datum (var));
311 *-----------------------------------------------------------------------
313 * Add a new variable of name name and value val to the given context.
319 * The new variable is placed at the front of the given context
320 * The name and val arguments are duplicated so they may
322 *-----------------------------------------------------------------------
325 VarAdd (char *name, char *val, GNode *ctxt)
330 v = (Var *) emalloc (sizeof (Var));
332 v->name = estrdup (name);
334 len = val ? strlen(val) : 0;
335 v->val = Buf_Init(len+1);
336 Buf_AddBytes(v->val, len, (Byte *)val);
340 (void) Lst_AtFront (ctxt->context, (void *)v);
341 (void) Lst_AtEnd (allVars, (void *) v);
342 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
347 *-----------------------------------------------------------------------
349 * Delete a variable and all the space associated with it.
356 *-----------------------------------------------------------------------
363 Buf_Destroy(v->val, TRUE);
370 *-----------------------------------------------------------------------
372 * Remove a variable from a context.
378 * The Var structure is removed and freed.
380 *-----------------------------------------------------------------------
383 Var_Delete(char *name, GNode *ctxt)
387 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
388 ln = Lst_Find(ctxt->context, (void *)name, VarCmp);
392 v = (Var *)Lst_Datum(ln);
393 Lst_Remove(ctxt->context, ln);
394 ln = Lst_Member(allVars, v);
395 Lst_Remove(allVars, ln);
396 VarDelete((void *) v);
401 *-----------------------------------------------------------------------
403 * Set the variable name to the value val in the given context.
409 * If the variable doesn't yet exist, a new record is created for it.
410 * Else the old value is freed and the new one stuck in its place
413 * The variable is searched for only in its context before being
414 * created in that context. I.e. if the context is VAR_GLOBAL,
415 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
416 * VAR_CMD->context is searched. This is done to avoid the literally
417 * thousands of unnecessary strcmp's that used to be done to
418 * set, say, $(@) or $(<).
419 *-----------------------------------------------------------------------
422 Var_Set (char *name, char *val, GNode *ctxt)
427 * We only look for a variable in the given context since anything set
428 * here will override anything in a lower context, so there's not much
429 * point in searching them all just to save a bit of memory...
431 VarPossiblyExpand(&name, ctxt);
432 v = VarFind (name, ctxt, 0);
433 if (v == (Var *) NULL) {
434 VarAdd (name, val, ctxt);
436 Buf_Discard(v->val, Buf_Size(v->val));
437 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
439 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
442 * Any variables given on the command line are automatically exported
443 * to the environment (as per POSIX standard)
445 if (ctxt == VAR_CMD) {
446 setenv(name, val, 1);
452 *-----------------------------------------------------------------------
454 * The variable of the given name has the given value appended to it in
461 * If the variable doesn't exist, it is created. Else the strings
462 * are concatenated (with a space in between).
465 * Only if the variable is being sought in the global context is the
466 * environment searched.
467 * XXX: Knows its calling circumstances in that if called with ctxt
468 * an actual target, it will only search that context since only
469 * a local variable could be being appended to. This is actually
470 * a big win and must be tolerated.
471 *-----------------------------------------------------------------------
474 Var_Append (char *name, char *val, GNode *ctxt)
478 VarPossiblyExpand(&name, ctxt);
479 v = VarFind (name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
481 if (v == (Var *) NULL) {
482 VarAdd (name, val, ctxt);
484 Buf_AddByte(v->val, (Byte)' ');
485 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
487 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name,
488 (char *) Buf_GetAll(v->val, (int *)NULL)));
490 if (v->flags & VAR_FROM_ENV) {
492 * If the original variable came from the environment, we
493 * have to install it in the global context (we could place
494 * it in the environment, but then we should provide a way to
495 * export other variables...)
497 v->flags &= ~VAR_FROM_ENV;
498 Lst_AtFront(ctxt->context, (void *)v);
505 *-----------------------------------------------------------------------
507 * See if the given variable exists.
510 * TRUE if it does, FALSE if it doesn't
515 *-----------------------------------------------------------------------
518 Var_Exists(char *name, GNode *ctxt)
522 VarPossiblyExpand(&name, ctxt);
523 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
526 if (v == (Var *)NULL) {
528 } else if (v->flags & VAR_FROM_ENV) {
530 Buf_Destroy(v->val, TRUE);
537 *-----------------------------------------------------------------------
539 * Return the value of the named variable in the given context
542 * The value if the variable exists, NULL if it doesn't
546 *-----------------------------------------------------------------------
549 Var_Value (char *name, GNode *ctxt, char **frp)
553 VarPossiblyExpand(&name, ctxt);
554 v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
557 if (v != (Var *) NULL) {
558 char *p = ((char *)Buf_GetAll(v->val, (int *)NULL));
559 if (v->flags & VAR_FROM_ENV) {
560 Buf_Destroy(v->val, FALSE);
566 return ((char *) NULL);
571 *-----------------------------------------------------------------------
573 * Modify each of the words of the passed string using the given
574 * function. Used to implement all modifiers.
577 * A string of all the words modified appropriately.
582 *-----------------------------------------------------------------------
585 VarModify (char *str, Boolean (*modProc)(const char *, Boolean, Buffer, void *),
588 Buffer buf; /* Buffer for the new string */
589 Boolean addSpace; /* TRUE if need to add a space to the
590 * buffer before adding the trimmed
592 char **av; /* word list [first word does not count] */
598 av = brk_string(str, &ac, FALSE);
600 for (i = 1; i < ac; i++)
601 addSpace = (*modProc)(av[i], addSpace, buf, datum);
603 Buf_AddByte (buf, '\0');
604 str = (char *)Buf_GetAll (buf, (int *)NULL);
605 Buf_Destroy (buf, FALSE);
610 *-----------------------------------------------------------------------
612 * Pass through the tstr looking for 1) escaped delimiters,
613 * '$'s and backslashes (place the escaped character in
614 * uninterpreted) and 2) unescaped $'s that aren't before
615 * the delimiter (expand the variable substitution unless flags
616 * has VAR_NOSUBST set).
617 * Return the expanded string or NULL if the delimiter was missing
618 * If pattern is specified, handle escaped ampersands, and replace
619 * unescaped ampersands with the lhs of the pattern.
622 * A string of all the words modified appropriately.
623 * If length is specified, return the string length of the buffer
624 * If flags is specified and the last character of the pattern is a
625 * $ set the VAR_MATCH_END bit of flags.
629 *-----------------------------------------------------------------------
632 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
633 int *length, VarPattern *pattern)
636 Buffer buf = Buf_Init(0);
641 #define IS_A_MATCH(cp, delim) \
642 ((cp[0] == '\\') && ((cp[1] == delim) || \
643 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
646 * Skim through until the matching delimiter is found;
647 * pick up variable substitutions on the way. Also allow
648 * backslashes to quote the delimiter, $, and \, but don't
649 * touch other backslashes.
651 for (cp = *tstr; *cp && (*cp != delim); cp++) {
652 if (IS_A_MATCH(cp, delim)) {
653 Buf_AddByte(buf, (Byte) cp[1]);
655 } else if (*cp == '$') {
656 if (cp[1] == delim) {
658 Buf_AddByte(buf, (Byte) *cp);
661 * Unescaped $ at end of pattern => anchor
664 *flags |= VAR_MATCH_END;
666 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
672 * If unescaped dollar sign not before the
673 * delimiter, assume it's a variable
674 * substitution and recurse.
676 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
677 Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
684 if (*cp2 == '(' || *cp2 == '{') {
686 * Find the end of this variable reference
687 * and suck it in without further ado.
688 * It will be interperated later.
691 int want = (*cp2 == '(') ? ')' : '}';
694 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
695 if (cp2[-1] != '\\') {
702 Buf_AddBytes(buf, cp2 - cp, (Byte *)cp);
705 Buf_AddByte(buf, (Byte) *cp);
709 else if (pattern && *cp == '&')
710 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
712 Buf_AddByte(buf, (Byte) *cp);
715 Buf_AddByte(buf, (Byte) '\0');
724 cp = (char *) Buf_GetAll(buf, length);
725 *length -= 1; /* Don't count the NULL */
726 Buf_Destroy(buf, FALSE);
733 *-----------------------------------------------------------------------
735 * Quote shell meta-characters in the string
743 *-----------------------------------------------------------------------
746 VarQuote(const char *str)
750 /* This should cover most shells :-( */
751 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
754 buf = Buf_Init (MAKE_BSIZE);
755 for (; *str; str++) {
756 if (strchr(meta, *str) != NULL)
757 Buf_AddByte(buf, (Byte)'\\');
758 Buf_AddByte(buf, (Byte)*str);
760 Buf_AddByte(buf, (Byte) '\0');
761 ret = Buf_GetAll (buf, NULL);
762 Buf_Destroy (buf, FALSE);
767 *-----------------------------------------------------------------------
769 * Print the error caused by a regcomp or regexec call.
775 * An error gets printed.
777 *-----------------------------------------------------------------------
780 VarREError(int err, regex_t *pat, const char *str)
785 errlen = regerror(err, pat, 0, 0);
786 errbuf = emalloc(errlen);
787 regerror(err, pat, errbuf, errlen);
788 Error("%s: %s", str, errbuf);
794 *-----------------------------------------------------------------------
796 * Given the start of a variable invocation, extract the variable
797 * name and find its value, then modify it according to the
801 * The (possibly-modified) value of the variable or var_Error if the
802 * specification is invalid. The length of the specification is
803 * placed in *lengthPtr (for invalid specifications, this is just
805 * A Boolean in *freePtr telling whether the returned string should
806 * be freed by the caller.
811 *-----------------------------------------------------------------------
814 Var_Parse(char *str, GNode *ctxt, Boolean err, int *lengthPtr, Boolean *freePtr)
816 char *tstr; /* Pointer into str */
817 Var *v; /* Variable in invocation */
818 char *cp; /* Secondary pointer into str (place marker
820 Boolean haveModifier;/* TRUE if have modifiers for the variable */
821 char endc; /* Ending character when variable in parens
823 char startc=0; /* Starting character when variable in parens
825 int cnt; /* Used to count brace pairs when variable in
826 * in parens or braces */
829 Boolean dynamic; /* TRUE if the variable is local and we're
830 * expanding it in a non-local context. This
831 * is done to support dynamic sources. The
832 * result is just the invocation, unaltered */
833 int vlen; /* length of variable name, after embedded variable
840 if (str[1] != '(' && str[1] != '{') {
842 * If it's not bounded by braces of some sort, life is much simpler.
843 * We just need to check for the first character and return the
844 * value if it exists.
851 v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
852 if (v == (Var *)NULL) {
855 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
857 * If substituting a local variable in a non-local context,
858 * assume it's for dynamic source stuff. We have to handle
859 * this specially and return the longhand for the variable
860 * with the dollar sign escaped so it makes it back to the
861 * caller. Only four of the local variables are treated
862 * specially as they are the only four that will be set
863 * when dynamic sources are expanded.
865 /* XXX: It looks like $% and $! are reversed here */
868 return("$(.TARGET)");
870 return("$(.ARCHIVE)");
872 return("$(.PREFIX)");
874 return("$(.MEMBER)");
882 return (err ? var_Error : varNoError);
884 haveModifier = FALSE;
889 /* build up expanded variable name in this buffer */
890 Buffer buf = Buf_Init(MAKE_BSIZE);
893 endc = startc == '(' ? ')' : '}';
896 * Skip to the end character or a colon, whichever comes first,
897 * replacing embedded variables as we go.
899 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
903 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
905 if (rval == var_Error) {
906 Fatal("Error expanding embedded variable.");
907 } else if (rval != NULL) {
908 Buf_AddBytes(buf, strlen(rval), (Byte *) rval);
914 Buf_AddByte(buf, (Byte) *tstr);
918 * If we never did find the end character, return NULL
919 * right now, setting the length to be the distance to
920 * the end of the string, since that's what make does.
922 *lengthPtr = tstr - str;
926 haveModifier = (*tstr == ':');
929 Buf_AddByte(buf, (Byte) '\0');
930 str = Buf_GetAll(buf, NULL);
933 v = VarFind (str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
934 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
935 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
938 * Check for bogus D and F forms of local variables since we're
939 * in a local context and the name is the right length.
953 * Well, it's local -- go look for it.
957 v = VarFind(vname, ctxt, 0);
959 if (v != (Var *)NULL && !haveModifier) {
961 * No need for nested expansion or anything, as we're
962 * the only one who sets these things and we sure don't
963 * put nested invocations in them...
965 val = (char *)Buf_GetAll(v->val, (int *)NULL);
968 val = VarModify(val, VarHead, (void *)0);
970 val = VarModify(val, VarTail, (void *)0);
973 * Resulting string is dynamically allocated, so
974 * tell caller to free it.
977 *lengthPtr = tstr-start+1;
979 Buf_Destroy(buf, TRUE);
989 if (v == (Var *)NULL) {
991 (((vlen == 2) && (str[1] == 'F' ||
993 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
996 * If substituting a local variable in a non-local context,
997 * assume it's for dynamic source stuff. We have to handle
998 * this specially and return the longhand for the variable
999 * with the dollar sign escaped so it makes it back to the
1000 * caller. Only four of the local variables are treated
1001 * specially as they are the only four that will be set
1002 * when dynamic sources are expanded.
1014 } else if ((vlen > 2) && (str[0] == '.') &&
1015 isupper((unsigned char) str[1]) &&
1016 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1021 if ((strncmp(str, ".TARGET", len) == 0) ||
1022 (strncmp(str, ".ARCHIVE", len) == 0) ||
1023 (strncmp(str, ".PREFIX", len) == 0) ||
1024 (strncmp(str, ".MEMBER", len) == 0))
1030 if (!haveModifier) {
1032 * No modifiers -- have specification length so we can return
1035 *lengthPtr = tstr - start + 1;
1038 str = emalloc(*lengthPtr + 1);
1039 strncpy(str, start, *lengthPtr);
1040 str[*lengthPtr] = '\0';
1042 Buf_Destroy(buf, TRUE);
1045 Buf_Destroy(buf, TRUE);
1046 return (err ? var_Error : varNoError);
1050 * Still need to get to the end of the variable specification,
1051 * so kludge up a Var structure for the modifications
1053 v = (Var *) emalloc(sizeof(Var));
1054 v->name = estrdup(str);
1055 v->val = Buf_Init(1);
1056 v->flags = VAR_JUNK;
1059 Buf_Destroy(buf, TRUE);
1062 if (v->flags & VAR_IN_USE) {
1063 Fatal("Variable %s is recursive.", v->name);
1066 v->flags |= VAR_IN_USE;
1069 * Before doing any modification, we have to make sure the value
1070 * has been fully expanded. If it looks like recursion might be
1071 * necessary (there's a dollar sign somewhere in the variable's value)
1072 * we just call Var_Subst to do any other substitutions that are
1073 * necessary. Note that the value returned by Var_Subst will have
1074 * been dynamically-allocated, so it will need freeing when we
1077 str = (char *)Buf_GetAll(v->val, (int *)NULL);
1078 if (strchr (str, '$') != (char *)NULL) {
1079 str = Var_Subst(NULL, str, ctxt, err);
1083 v->flags &= ~VAR_IN_USE;
1086 * Now we need to apply any modifiers the user wants applied.
1088 * :M<pattern> words which match the given <pattern>.
1089 * <pattern> is of the standard file
1091 * :S<d><pat1><d><pat2><d>[g]
1092 * Substitute <pat2> for <pat1> in the value
1093 * :C<d><pat1><d><pat2><d>[g]
1094 * Substitute <pat2> for regex <pat1> in the value
1095 * :H Substitute the head of each word
1096 * :T Substitute the tail of each word
1097 * :E Substitute the extension (minus '.') of
1099 * :R Substitute the root of each word
1100 * (pathname minus the suffix).
1101 * :lhs=rhs Like :S, but the rhs goes to the end of
1103 * :U Converts variable to upper-case.
1104 * :L Converts variable to lower-case.
1106 if ((str != (char *)NULL) && haveModifier) {
1108 * Skip initial colon while putting it back.
1111 while (*tstr != endc) {
1112 char *newStr; /* New value to return */
1113 char termc; /* Character which terminated scan */
1115 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1118 if (tstr[1] == endc || tstr[1] == ':') {
1120 buf = Buf_Init(MAKE_BSIZE);
1121 for (cp = str; *cp ; cp++)
1122 Buf_AddByte(buf, (Byte) toupper(*cp));
1124 Buf_AddByte(buf, (Byte) '\0');
1125 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1126 Buf_Destroy(buf, FALSE);
1134 if (tstr[1] == endc || tstr[1] == ':') {
1136 buf = Buf_Init(MAKE_BSIZE);
1137 for (cp = str; *cp ; cp++)
1138 Buf_AddByte(buf, (Byte) tolower(*cp));
1140 Buf_AddByte(buf, (Byte) '\0');
1141 newStr = (char *) Buf_GetAll(buf, (int *) NULL);
1142 Buf_Destroy(buf, FALSE);
1158 *cp != '\0' && *cp != ':' && *cp != endc;
1161 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)){
1170 * Need to compress the \:'s out of the pattern, so
1171 * allocate enough room to hold the uncompressed
1172 * pattern (note that cp started at tstr+1, so
1173 * cp - tstr takes the null byte into account) and
1174 * compress the pattern into the space.
1176 pattern = emalloc(cp - tstr);
1177 for (cp2 = pattern, cp = tstr + 1;
1181 if ((*cp == '\\') &&
1182 (cp[1] == ':' || cp[1] == endc)) {
1191 if (*tstr == 'M' || *tstr == 'm') {
1192 newStr = VarModify(str, VarMatch, (void *)pattern);
1194 newStr = VarModify(str, VarNoMatch,
1206 Buffer buf; /* Buffer for patterns */
1213 * If pattern begins with '^', it is anchored to the
1214 * start of the word -- skip over it and flag pattern.
1217 pattern.flags |= VAR_MATCH_START;
1224 * Pass through the lhs looking for 1) escaped delimiters,
1225 * '$'s and backslashes (place the escaped character in
1226 * uninterpreted) and 2) unescaped $'s that aren't before
1227 * the delimiter (expand the variable substitution).
1228 * The result is left in the Buffer buf.
1230 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1231 if ((*cp == '\\') &&
1236 Buf_AddByte(buf, (Byte)cp[1]);
1238 } else if (*cp == '$') {
1241 * If unescaped dollar sign not before the
1242 * delimiter, assume it's a variable
1243 * substitution and recurse.
1249 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1250 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1257 * Unescaped $ at end of pattern => anchor
1260 pattern.flags |= VAR_MATCH_END;
1263 Buf_AddByte(buf, (Byte)*cp);
1267 Buf_AddByte(buf, (Byte)'\0');
1270 * If lhs didn't end with the delimiter, complain and
1274 *lengthPtr = cp - start + 1;
1278 Buf_Destroy(buf, TRUE);
1279 Error("Unclosed substitution for %s (%c missing)",
1285 * Fetch pattern and destroy buffer, but preserve the data
1286 * in it, since that's our lhs. Note that Buf_GetAll
1287 * will return the actual number of bytes, which includes
1288 * the null byte, so we have to decrement the length by
1291 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1293 Buf_Destroy(buf, FALSE);
1296 * Now comes the replacement string. Three things need to
1297 * be done here: 1) need to compress escaped delimiters and
1298 * ampersands and 2) need to replace unescaped ampersands
1299 * with the l.h.s. (since this isn't regexp, we can do
1300 * it right here) and 3) expand any variable substitutions.
1305 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1306 if ((*cp == '\\') &&
1312 Buf_AddByte(buf, (Byte)cp[1]);
1314 } else if ((*cp == '$') && (cp[1] != del)) {
1319 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1320 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1325 } else if (*cp == '&') {
1326 Buf_AddBytes(buf, pattern.leftLen,
1327 (Byte *)pattern.lhs);
1329 Buf_AddByte(buf, (Byte)*cp);
1333 Buf_AddByte(buf, (Byte)'\0');
1336 * If didn't end in delimiter character, complain
1339 *lengthPtr = cp - start + 1;
1343 Buf_Destroy(buf, TRUE);
1344 Error("Unclosed substitution for %s (%c missing)",
1349 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1351 Buf_Destroy(buf, FALSE);
1354 * Check for global substitution. If 'g' after the final
1355 * delimiter, substitution is global and is marked that
1360 pattern.flags |= VAR_SUB_GLOBAL;
1365 newStr = VarModify(str, VarSubstitute,
1368 * Free the two strings.
1376 VarREPattern pattern;
1386 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1387 NULL, NULL)) == NULL) {
1388 /* was: goto cleanup */
1389 *lengthPtr = cp - start + 1;
1393 Error("Unclosed substitution for %s (%c missing)",
1398 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1399 delim, NULL, NULL, NULL)) == NULL){
1402 /* was: goto cleanup */
1403 *lengthPtr = cp - start + 1;
1407 Error("Unclosed substitution for %s (%c missing)",
1415 pattern.flags |= VAR_SUB_GLOBAL;
1418 pattern.flags |= VAR_SUB_ONE;
1428 error = regcomp(&pattern.re, re, REG_EXTENDED);
1431 *lengthPtr = cp - start + 1;
1432 VarREError(error, &pattern.re, "RE substitution error");
1433 free(pattern.replace);
1437 pattern.nsub = pattern.re.re_nsub + 1;
1438 if (pattern.nsub < 1)
1440 if (pattern.nsub > 10)
1442 pattern.matches = emalloc(pattern.nsub *
1443 sizeof(regmatch_t));
1444 newStr = VarModify(str, VarRESubstitute,
1446 regfree(&pattern.re);
1447 free(pattern.replace);
1448 free(pattern.matches);
1452 if (tstr[1] == endc || tstr[1] == ':') {
1453 newStr = VarQuote (str);
1460 if (tstr[1] == endc || tstr[1] == ':') {
1461 newStr = VarModify (str, VarTail, (void *)0);
1468 if (tstr[1] == endc || tstr[1] == ':') {
1469 newStr = VarModify (str, VarHead, (void *)0);
1476 if (tstr[1] == endc || tstr[1] == ':') {
1477 newStr = VarModify (str, VarSuffix, (void *)0);
1484 if (tstr[1] == endc || tstr[1] == ':') {
1485 newStr = VarModify (str, VarRoot, (void *)0);
1493 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1495 newStr = Cmd_Exec (str, &error);
1508 * This can either be a bogus modifier or a System-V
1509 * substitution command.
1517 * First we make a pass through the string trying
1518 * to verify it is a SYSV-make-style translation:
1519 * it must be: <string1>=<string2>)
1523 while (*cp != '\0' && cnt) {
1526 /* continue looking for endc */
1528 else if (*cp == endc)
1530 else if (*cp == startc)
1535 if (*cp == endc && eqFound) {
1538 * Now we break this sucker into the lhs and
1539 * rhs. We must null terminate them of course.
1541 for (cp = tstr; *cp != '='; cp++)
1544 pattern.leftLen = cp - tstr;
1552 else if (*cp == startc)
1557 pattern.rightLen = cp - pattern.rhs;
1561 * SYSV modifications happen through the whole
1562 * string. Note the pattern is anchored at the end.
1564 newStr = VarModify(str, VarSYSVMatch,
1568 * Restore the nulled characters
1570 pattern.lhs[pattern.leftLen] = '=';
1571 pattern.rhs[pattern.rightLen] = endc;
1576 Error ("Unknown modifier '%c'\n", *tstr);
1578 *cp != ':' && *cp != endc && *cp != '\0';
1586 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1592 if (str != var_Error) {
1597 if (termc == '\0') {
1598 Error("Unclosed variable specification for %s", v->name);
1599 } else if (termc == ':') {
1606 *lengthPtr = tstr - start + 1;
1608 *lengthPtr = tstr - start + 1;
1612 if (v->flags & VAR_FROM_ENV) {
1613 Boolean destroy = FALSE;
1615 if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
1619 * Returning the value unmodified, so tell the caller to free
1625 Buf_Destroy(v->val, destroy);
1627 } else if (v->flags & VAR_JUNK) {
1629 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1630 * doesn't try to free a static pointer.
1637 Buf_Destroy(v->val, TRUE);
1640 str = emalloc(*lengthPtr + 1);
1641 strncpy(str, start, *lengthPtr);
1642 str[*lengthPtr] = '\0';
1645 str = err ? var_Error : varNoError;
1652 *-----------------------------------------------------------------------
1654 * Substitute for all variables in the given string in the given context
1655 * If undefErr is TRUE, Parse_Error will be called when an undefined
1656 * variable is encountered.
1659 * The resulting string.
1662 * None. The old string must be freed by the caller
1663 *-----------------------------------------------------------------------
1666 Var_Subst (char *var, char *str, GNode *ctxt, Boolean undefErr)
1668 Buffer buf; /* Buffer for forming things */
1669 char *val; /* Value to substitute for a variable */
1670 int length; /* Length of the variable invocation */
1671 Boolean doFree; /* Set true if val should be freed */
1672 static Boolean errorReported; /* Set true if an error has already
1673 * been reported to prevent a plethora
1674 * of messages when recursing */
1676 buf = Buf_Init (MAKE_BSIZE);
1677 errorReported = FALSE;
1680 if (var == NULL && (*str == '$') && (str[1] == '$')) {
1682 * A dollar sign may be escaped either with another dollar sign.
1683 * In such a case, we skip over the escape character and store the
1684 * dollar sign into the buffer directly.
1687 Buf_AddByte(buf, (Byte)*str);
1689 } else if (*str != '$') {
1691 * Skip as many characters as possible -- either to the end of
1692 * the string or to the next dollar sign (variable invocation).
1696 for (cp = str++; *str != '$' && *str != '\0'; str++)
1698 Buf_AddBytes(buf, str - cp, (Byte *)cp);
1703 if (str[1] != '(' && str[1] != '{') {
1704 if (str[1] != *var || var[1] != '\0') {
1705 Buf_AddBytes(buf, 2, (Byte *) str);
1717 * Scan up to the end of the variable name.
1719 for (p = &str[2]; *p &&
1720 *p != ':' && *p != ')' && *p != '}'; p++)
1724 * A variable inside the variable. We cannot expand
1725 * the external variable yet, so we try again with
1729 Buf_AddBytes(buf, p - str, (Byte *) str);
1734 if (strncmp(var, str + 2, p - str - 2) != 0 ||
1735 var[p - str - 2] != '\0') {
1737 * Not the variable we want to expand, scan
1738 * until the next variable
1740 for (;*p != '$' && *p != '\0'; p++)
1742 Buf_AddBytes(buf, p - str, (Byte *) str);
1755 val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
1758 * When we come down here, val should either point to the
1759 * value of this variable, suitably modified, or be NULL.
1760 * Length should be the total length of the potential
1761 * variable invocation (from $ to end character...)
1763 if (val == var_Error || val == varNoError) {
1765 * If performing old-time variable substitution, skip over
1766 * the variable and continue with the substitution. Otherwise,
1767 * store the dollar sign and advance str so we continue with
1772 } else if (undefErr) {
1774 * If variable is undefined, complain and skip the
1775 * variable. The complaint will stop us from doing anything
1776 * when the file is parsed.
1778 if (!errorReported) {
1779 Parse_Error (PARSE_FATAL,
1780 "Undefined variable \"%.*s\"",length,str);
1783 errorReported = TRUE;
1785 Buf_AddByte (buf, (Byte)*str);
1790 * We've now got a variable structure to store in. But first,
1791 * advance the string pointer.
1796 * Copy all the characters from the variable value straight
1797 * into the new string.
1799 Buf_AddBytes (buf, strlen (val), (Byte *)val);
1807 Buf_AddByte (buf, '\0');
1808 str = (char *)Buf_GetAll (buf, (int *)NULL);
1809 Buf_Destroy (buf, FALSE);
1814 *-----------------------------------------------------------------------
1816 * Return the tail from each of a list of words. Used to set the
1817 * System V local variables.
1820 * The resulting string.
1825 *-----------------------------------------------------------------------
1828 Var_GetTail(char *file)
1830 return(VarModify(file, VarTail, (void *)0));
1834 *-----------------------------------------------------------------------
1836 * Find the leading components of a (list of) filename(s).
1837 * XXX: VarHead does not replace foo by ., as (sun) System V make
1841 * The leading components.
1846 *-----------------------------------------------------------------------
1849 Var_GetHead(char *file)
1851 return(VarModify(file, VarHead, (void *)0));
1855 *-----------------------------------------------------------------------
1857 * Initialize the module
1863 * The VAR_CMD and VAR_GLOBAL contexts are created
1864 *-----------------------------------------------------------------------
1869 VAR_GLOBAL = Targ_NewGN ("Global");
1870 VAR_CMD = Targ_NewGN ("Command");
1871 allVars = Lst_Init(FALSE);
1879 Lst_Destroy(allVars, VarDelete);
1883 /****************** PRINT DEBUGGING INFO *****************/
1885 VarPrintVar (void *vp, void *dummy __unused)
1887 Var *v = (Var *) vp;
1888 printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
1893 *-----------------------------------------------------------------------
1895 * print all variables in a context
1896 *-----------------------------------------------------------------------
1899 Var_Dump (GNode *ctxt)
1901 Lst_ForEach (ctxt->context, VarPrintVar, (void *) 0);