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 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
128 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
129 #define FIND_ENV 0x4 /* look in the environment also */
131 static void VarPossiblyExpand(char **, GNode *);
132 static Var *VarFind(char *, GNode *, int);
133 static void VarAdd(char *, char *, GNode *);
134 static void VarDelete(void *);
135 static char *VarGetPattern(GNode *, int, char **, int, int *, size_t *,
137 static char *VarModify(char *,
138 Boolean (*)(const char *, Boolean, Buffer, void *),
140 static int VarPrintVar(void *, void *);
143 *-----------------------------------------------------------------------
145 * See if the given variable matches the named one. Called from
146 * Lst_Find when searching for a variable of a given name.
149 * 0 if they match. non-zero otherwise.
153 *-----------------------------------------------------------------------
156 VarCmp(const void *v, const void *name)
159 return (strcmp(name, ((const 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)
178 if (strchr(*name, '$') != NULL)
179 *name = Var_Subst(NULL, *name, ctxt, 0);
181 *name = estrdup(*name);
185 *-----------------------------------------------------------------------
187 * Find the given variable in the given context and any other contexts
191 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
192 * FIND_CMD set means to look in the VAR_CMD context too
193 * FIND_ENV set means to look in the environment
196 * A pointer to the structure describing the desired variable or
197 * NULL if the variable does not exist.
201 *-----------------------------------------------------------------------
204 VarFind(char *name, GNode *ctxt, int flags)
206 Boolean localCheckEnvFirst;
211 * If the variable name begins with a '.', it could very well be one of
212 * the local ones. We check the name against all the local variables
213 * and substitute the short version in for 'name' if it matches one of
216 if (*name == '.' && isupper((unsigned char)name[1]))
219 if (!strcmp(name, ".ALLSRC"))
221 if (!strcmp(name, ".ARCHIVE"))
225 if (!strcmp(name, ".IMPSRC"))
229 if (!strcmp(name, ".MEMBER"))
233 if (!strcmp(name, ".OODATE"))
237 if (!strcmp(name, ".PREFIX"))
241 if (!strcmp(name, ".TARGET"))
247 * Note whether this is one of the specific variables we were told through
248 * the -E flag to use environment-variable-override for.
250 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
251 localCheckEnvFirst = TRUE;
253 localCheckEnvFirst = FALSE;
257 * First look for the variable in the given context. If it's not there,
258 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
259 * depending on the FIND_* flags in 'flags'
261 var = Lst_Find(&ctxt->context, name, VarCmp);
263 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
264 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
266 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
267 !checkEnvFirst && !localCheckEnvFirst)
269 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
271 if ((var == NULL) && (flags & FIND_ENV)) {
274 if ((env = getenv(name)) != NULL) {
277 v = emalloc(sizeof(Var));
278 v->name = estrdup(name);
282 v->val = Buf_Init(len);
283 Buf_AddBytes(v->val, len, (Byte *)env);
285 v->flags = VAR_FROM_ENV;
287 } else if ((checkEnvFirst || localCheckEnvFirst) &&
288 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
290 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
294 return (Lst_Datum(var));
299 } else if (var == NULL) {
302 return (Lst_Datum(var));
307 *-----------------------------------------------------------------------
309 * Add a new variable of name name and value val to the given context.
315 * The new variable is placed at the front of the given context
316 * The name and val arguments are duplicated so they may
318 *-----------------------------------------------------------------------
321 VarAdd(char *name, char *val, GNode *ctxt)
326 v = emalloc(sizeof(Var));
328 v->name = estrdup(name);
330 len = val ? strlen(val) : 0;
331 v->val = Buf_Init(len+1);
332 Buf_AddBytes(v->val, len, (Byte *)val);
336 Lst_AtFront(&ctxt->context, v);
337 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
341 *-----------------------------------------------------------------------
343 * Delete a variable and all the space associated with it.
350 *-----------------------------------------------------------------------
358 Buf_Destroy(v->val, TRUE);
363 *-----------------------------------------------------------------------
365 * Remove a variable from a context.
371 * The Var structure is removed and freed.
373 *-----------------------------------------------------------------------
376 Var_Delete(char *name, GNode *ctxt)
380 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
381 ln = Lst_Find(&ctxt->context, name, VarCmp);
383 VarDelete(Lst_Datum(ln));
384 Lst_Remove(&ctxt->context, ln);
389 *-----------------------------------------------------------------------
391 * Set the variable name to the value val in the given context.
397 * If the variable doesn't yet exist, a new record is created for it.
398 * Else the old value is freed and the new one stuck in its place
401 * The variable is searched for only in its context before being
402 * created in that context. I.e. if the context is VAR_GLOBAL,
403 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
404 * VAR_CMD->context is searched. This is done to avoid the literally
405 * thousands of unnecessary strcmp's that used to be done to
406 * set, say, $(@) or $(<).
407 *-----------------------------------------------------------------------
410 Var_Set(char *name, char *val, GNode *ctxt)
415 * We only look for a variable in the given context since anything set
416 * here will override anything in a lower context, so there's not much
417 * point in searching them all just to save a bit of memory...
419 VarPossiblyExpand(&name, ctxt);
420 v = VarFind(name, ctxt, 0);
422 VarAdd(name, val, ctxt);
424 Buf_Discard(v->val, Buf_Size(v->val));
425 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
427 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
430 * Any variables given on the command line are automatically exported
431 * to the environment (as per POSIX standard)
433 if (ctxt == VAR_CMD) {
434 setenv(name, val, 1);
440 *-----------------------------------------------------------------------
442 * The variable of the given name has the given value appended to it in
449 * If the variable doesn't exist, it is created. Else the strings
450 * are concatenated (with a space in between).
453 * Only if the variable is being sought in the global context is the
454 * environment searched.
455 * XXX: Knows its calling circumstances in that if called with ctxt
456 * an actual target, it will only search that context since only
457 * a local variable could be being appended to. This is actually
458 * a big win and must be tolerated.
459 *-----------------------------------------------------------------------
462 Var_Append(char *name, char *val, GNode *ctxt)
466 VarPossiblyExpand(&name, ctxt);
467 v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
470 VarAdd(name, val, ctxt);
472 Buf_AddByte(v->val, (Byte)' ');
473 Buf_AddBytes(v->val, strlen(val), (Byte *)val);
475 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name,
476 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
478 if (v->flags & VAR_FROM_ENV) {
480 * If the original variable came from the environment, we
481 * have to install it in the global context (we could place
482 * it in the environment, but then we should provide a way to
483 * export other variables...)
485 v->flags &= ~VAR_FROM_ENV;
486 Lst_AtFront(&ctxt->context, v);
493 *-----------------------------------------------------------------------
495 * See if the given variable exists.
498 * TRUE if it does, FALSE if it doesn't
503 *-----------------------------------------------------------------------
506 Var_Exists(char *name, GNode *ctxt)
510 VarPossiblyExpand(&name, ctxt);
511 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
516 } else if (v->flags & VAR_FROM_ENV) {
518 Buf_Destroy(v->val, TRUE);
525 *-----------------------------------------------------------------------
527 * Return the value of the named variable in the given context
530 * The value if the variable exists, NULL if it doesn't
534 *-----------------------------------------------------------------------
537 Var_Value(char *name, GNode *ctxt, char **frp)
541 VarPossiblyExpand(&name, ctxt);
542 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
546 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
548 if (v->flags & VAR_FROM_ENV) {
549 Buf_Destroy(v->val, FALSE);
561 *-----------------------------------------------------------------------
563 * Modify each of the words of the passed string using the given
564 * function. Used to implement all modifiers.
567 * A string of all the words modified appropriately.
572 *-----------------------------------------------------------------------
575 VarModify(char *str, Boolean (*modProc)(const char *, Boolean, Buffer, void *),
578 Buffer buf; /* Buffer for the new string */
579 Boolean addSpace; /* TRUE if need to add a space to the
580 * buffer before adding the trimmed
582 char **av; /* word list [first word does not count] */
588 av = brk_string(str, &ac, FALSE);
590 for (i = 1; i < ac; i++)
591 addSpace = (*modProc)(av[i], addSpace, buf, datum);
593 Buf_AddByte (buf, '\0');
594 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
595 Buf_Destroy(buf, FALSE);
600 *-----------------------------------------------------------------------
602 * Sort the words in the string.
605 * str String whose words should be sorted
606 * cmp A comparison function to control the ordering
609 * A string containing the words sorted
614 *-----------------------------------------------------------------------
617 VarSortWords(char *str, int (*cmp)(const void *, const void *))
624 av = brk_string(str, &ac, FALSE);
625 qsort(av + 1, ac - 1, sizeof(char *), cmp);
626 for (i = 1; i < ac; i++) {
627 Buf_AddBytes(buf, strlen(av[i]), (Byte *)av[i]);
628 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
630 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
631 Buf_Destroy(buf, FALSE);
636 SortIncreasing(const void *l, const void *r)
639 return (strcmp(*(const char* const*)l, *(const char* const*)r));
643 *-----------------------------------------------------------------------
645 * Pass through the tstr looking for 1) escaped delimiters,
646 * '$'s and backslashes (place the escaped character in
647 * uninterpreted) and 2) unescaped $'s that aren't before
648 * the delimiter (expand the variable substitution unless flags
649 * has VAR_NOSUBST set).
650 * Return the expanded string or NULL if the delimiter was missing
651 * If pattern is specified, handle escaped ampersands, and replace
652 * unescaped ampersands with the lhs of the pattern.
655 * A string of all the words modified appropriately.
656 * If length is specified, return the string length of the buffer
657 * If flags is specified and the last character of the pattern is a
658 * $ set the VAR_MATCH_END bit of flags.
662 *-----------------------------------------------------------------------
665 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
666 size_t *length, VarPattern *pattern)
669 Buffer buf = Buf_Init(0);
675 #define IS_A_MATCH(cp, delim) \
676 ((cp[0] == '\\') && ((cp[1] == delim) || \
677 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
680 * Skim through until the matching delimiter is found;
681 * pick up variable substitutions on the way. Also allow
682 * backslashes to quote the delimiter, $, and \, but don't
683 * touch other backslashes.
685 for (cp = *tstr; *cp && (*cp != delim); cp++) {
686 if (IS_A_MATCH(cp, delim)) {
687 Buf_AddByte(buf, (Byte)cp[1]);
689 } else if (*cp == '$') {
690 if (cp[1] == delim) {
692 Buf_AddByte(buf, (Byte)*cp);
695 * Unescaped $ at end of pattern => anchor
698 *flags |= VAR_MATCH_END;
700 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
706 * If unescaped dollar sign not before the
707 * delimiter, assume it's a variable
708 * substitution and recurse.
710 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
711 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
718 if (*cp2 == '(' || *cp2 == '{') {
720 * Find the end of this variable reference
721 * and suck it in without further ado.
722 * It will be interperated later.
725 int want = (*cp2 == '(') ? ')' : '}';
728 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
729 if (cp2[-1] != '\\') {
736 Buf_AddBytes(buf, cp2 - cp, (Byte *)cp);
739 Buf_AddByte(buf, (Byte)*cp);
743 else if (pattern && *cp == '&')
744 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
746 Buf_AddByte(buf, (Byte)*cp);
749 Buf_AddByte(buf, (Byte)'\0');
757 cp = (char *)Buf_GetAll(buf, length);
758 *length -= 1; /* Don't count the NULL */
759 Buf_Destroy(buf, FALSE);
765 *-----------------------------------------------------------------------
767 * Quote shell meta-characters in the string
775 *-----------------------------------------------------------------------
778 Var_Quote(const char *str)
781 /* This should cover most shells :-( */
782 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
785 buf = Buf_Init(MAKE_BSIZE);
786 for (; *str; str++) {
787 if (strchr(meta, *str) != NULL)
788 Buf_AddByte(buf, (Byte)'\\');
789 Buf_AddByte(buf, (Byte)*str);
791 Buf_AddByte(buf, (Byte)'\0');
792 ret = Buf_GetAll(buf, NULL);
793 Buf_Destroy(buf, FALSE);
798 *-----------------------------------------------------------------------
800 * Print the error caused by a regcomp or regexec call.
806 * An error gets printed.
808 *-----------------------------------------------------------------------
811 VarREError(int err, regex_t *pat, const char *str)
816 errlen = regerror(err, pat, 0, 0);
817 errbuf = emalloc(errlen);
818 regerror(err, pat, errbuf, errlen);
819 Error("%s: %s", str, errbuf);
824 *-----------------------------------------------------------------------
826 * Given the start of a variable invocation, extract the variable
827 * name and find its value, then modify it according to the
831 * The (possibly-modified) value of the variable or var_Error if the
832 * specification is invalid. The length of the specification is
833 * placed in *lengthPtr (for invalid specifications, this is just
834 * 2 to skip the '$' and the following letter, or 1 if '$' was the
835 * last character in the string).
836 * A Boolean in *freePtr telling whether the returned string should
837 * be freed by the caller.
842 *-----------------------------------------------------------------------
845 Var_Parse(char *str, GNode *ctxt, Boolean err, size_t *lengthPtr,
848 char *tstr; /* Pointer into str */
849 Var *v; /* Variable in invocation */
850 char *cp; /* Secondary pointer into str (place marker
852 Boolean haveModifier;/* TRUE if have modifiers for the variable */
853 char endc; /* Ending character when variable in parens
855 char startc=0; /* Starting character when variable in parens
857 int cnt; /* Used to count brace pairs when variable in
858 * in parens or braces */
861 Boolean dynamic; /* TRUE if the variable is local and we're
862 * expanding it in a non-local context. This
863 * is done to support dynamic sources. The
864 * result is just the invocation, unaltered */
865 int vlen; /* length of variable name, after embedded variable
872 if (str[1] != '(' && str[1] != '{') {
874 * If it's not bounded by braces of some sort, life is much simpler.
875 * We just need to check for the first character and return the
876 * value if it exists.
883 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
884 if (v == (Var *)NULL) {
890 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
892 * If substituting a local variable in a non-local context,
893 * assume it's for dynamic source stuff. We have to handle
894 * this specially and return the longhand for the variable
895 * with the dollar sign escaped so it makes it back to the
896 * caller. Only four of the local variables are treated
897 * specially as they are the only four that will be set
898 * when dynamic sources are expanded.
900 /* XXX: It looks like $% and $! are reversed here */
903 return ("$(.TARGET)");
905 return ("$(.ARCHIVE)");
907 return ("$(.PREFIX)");
909 return ("$(.MEMBER)");
917 return (err ? var_Error : varNoError);
919 haveModifier = FALSE;
924 /* build up expanded variable name in this buffer */
925 Buffer buf = Buf_Init(MAKE_BSIZE);
928 endc = startc == '(' ? ')' : '}';
931 * Skip to the end character or a colon, whichever comes first,
932 * replacing embedded variables as we go.
934 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
938 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
940 if (rval == var_Error) {
941 Fatal("Error expanding embedded variable.");
942 } else if (rval != NULL) {
943 Buf_AddBytes(buf, strlen(rval), (Byte *)rval);
949 Buf_AddByte(buf, (Byte)*tstr);
953 * If we never did find the end character, return NULL
954 * right now, setting the length to be the distance to
955 * the end of the string, since that's what make does.
957 *lengthPtr = tstr - str;
961 haveModifier = (*tstr == ':');
964 Buf_AddByte(buf, (Byte)'\0');
965 str = Buf_GetAll(buf, (size_t *)NULL);
968 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
969 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
970 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
973 * Check for bogus D and F forms of local variables since we're
974 * in a local context and the name is the right length.
988 * Well, it's local -- go look for it.
992 v = VarFind(vname, ctxt, 0);
994 if (v != NULL && !haveModifier) {
996 * No need for nested expansion or anything, as we're
997 * the only one who sets these things and we sure don't
998 * put nested invocations in them...
1000 val = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1002 if (str[1] == 'D') {
1003 val = VarModify(val, VarHead, (void *)NULL);
1005 val = VarModify(val, VarTail, (void *)NULL);
1008 * Resulting string is dynamically allocated, so
1009 * tell caller to free it.
1012 *lengthPtr = tstr-start+1;
1014 Buf_Destroy(buf, TRUE);
1024 if (v == (Var *)NULL) {
1026 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
1027 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1030 * If substituting a local variable in a non-local context,
1031 * assume it's for dynamic source stuff. We have to handle
1032 * this specially and return the longhand for the variable
1033 * with the dollar sign escaped so it makes it back to the
1034 * caller. Only four of the local variables are treated
1035 * specially as they are the only four that will be set
1036 * when dynamic sources are expanded.
1048 } else if ((vlen > 2) && (str[0] == '.') &&
1049 isupper((unsigned char)str[1]) &&
1050 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1055 if ((strncmp(str, ".TARGET", len) == 0) ||
1056 (strncmp(str, ".ARCHIVE", len) == 0) ||
1057 (strncmp(str, ".PREFIX", len) == 0) ||
1058 (strncmp(str, ".MEMBER", len) == 0))
1064 if (!haveModifier) {
1066 * No modifiers -- have specification length so we can return
1069 *lengthPtr = tstr - start + 1;
1072 str = emalloc(*lengthPtr + 1);
1073 strncpy(str, start, *lengthPtr);
1074 str[*lengthPtr] = '\0';
1076 Buf_Destroy(buf, TRUE);
1079 Buf_Destroy(buf, TRUE);
1080 return (err ? var_Error : varNoError);
1084 * Still need to get to the end of the variable specification,
1085 * so kludge up a Var structure for the modifications
1087 v = emalloc(sizeof(Var));
1088 v->name = estrdup(str);
1089 v->val = Buf_Init(1);
1090 v->flags = VAR_JUNK;
1093 Buf_Destroy(buf, TRUE);
1096 if (v->flags & VAR_IN_USE) {
1097 Fatal("Variable %s is recursive.", v->name);
1100 v->flags |= VAR_IN_USE;
1103 * Before doing any modification, we have to make sure the value
1104 * has been fully expanded. If it looks like recursion might be
1105 * necessary (there's a dollar sign somewhere in the variable's value)
1106 * we just call Var_Subst to do any other substitutions that are
1107 * necessary. Note that the value returned by Var_Subst will have
1108 * been dynamically-allocated, so it will need freeing when we
1111 str = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1112 if (strchr(str, '$') != (char *)NULL) {
1113 str = Var_Subst(NULL, str, ctxt, err);
1117 v->flags &= ~VAR_IN_USE;
1120 * Now we need to apply any modifiers the user wants applied.
1122 * :M<pattern> words which match the given <pattern>.
1123 * <pattern> is of the standard file
1125 * :S<d><pat1><d><pat2><d>[g]
1126 * Substitute <pat2> for <pat1> in the value
1127 * :C<d><pat1><d><pat2><d>[g]
1128 * Substitute <pat2> for regex <pat1> in the value
1129 * :H Substitute the head of each word
1130 * :T Substitute the tail of each word
1131 * :E Substitute the extension (minus '.') of
1133 * :R Substitute the root of each word
1134 * (pathname minus the suffix).
1135 * :lhs=rhs Like :S, but the rhs goes to the end of
1137 * :U Converts variable to upper-case.
1138 * :L Converts variable to lower-case.
1140 if ((str != NULL) && haveModifier) {
1142 * Skip initial colon while putting it back.
1145 while (*tstr != endc) {
1146 char *newStr; /* New value to return */
1147 char termc; /* Character which terminated scan */
1149 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1160 *cp != '\0' && *cp != ':' && *cp != endc;
1163 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
1172 * Need to compress the \:'s out of the pattern, so
1173 * allocate enough room to hold the uncompressed
1174 * pattern (note that cp started at tstr+1, so
1175 * cp - tstr takes the null byte into account) and
1176 * compress the pattern into the space.
1178 pattern = emalloc(cp - tstr);
1179 for (cp2 = pattern, cp = tstr + 1;
1183 if ((*cp == '\\') &&
1184 (cp[1] == ':' || cp[1] == endc)) {
1193 if (*tstr == 'M' || *tstr == 'm') {
1194 newStr = VarModify(str, VarMatch, pattern);
1196 newStr = VarModify(str, VarNoMatch, pattern);
1207 Buffer buf; /* Buffer for patterns */
1214 * If pattern begins with '^', it is anchored to the
1215 * start of the word -- skip over it and flag pattern.
1218 pattern.flags |= VAR_MATCH_START;
1225 * Pass through the lhs looking for 1) escaped delimiters,
1226 * '$'s and backslashes (place the escaped character in
1227 * uninterpreted) and 2) unescaped $'s that aren't before
1228 * the delimiter (expand the variable substitution).
1229 * The result is left in the Buffer buf.
1231 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1232 if ((*cp == '\\') &&
1237 Buf_AddByte(buf, (Byte)cp[1]);
1239 } else if (*cp == '$') {
1242 * If unescaped dollar sign not before the
1243 * delimiter, assume it's a variable
1244 * substitution and recurse.
1250 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1251 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1258 * Unescaped $ at end of pattern => anchor
1261 pattern.flags |= VAR_MATCH_END;
1264 Buf_AddByte(buf, (Byte)*cp);
1268 Buf_AddByte(buf, (Byte)'\0');
1271 * If lhs didn't end with the delimiter, complain and
1275 Fatal("Unclosed substitution for %s (%c missing)",
1280 * Fetch pattern and destroy buffer, but preserve the data
1281 * in it, since that's our lhs. Note that Buf_GetAll
1282 * will return the actual number of bytes, which includes
1283 * the null byte, so we have to decrement the length by
1286 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1288 Buf_Destroy(buf, FALSE);
1291 * Now comes the replacement string. Three things need to
1292 * be done here: 1) need to compress escaped delimiters and
1293 * ampersands and 2) need to replace unescaped ampersands
1294 * with the l.h.s. (since this isn't regexp, we can do
1295 * it right here) and 3) expand any variable substitutions.
1300 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1301 if ((*cp == '\\') &&
1307 Buf_AddByte(buf, (Byte)cp[1]);
1309 } else if ((*cp == '$') && (cp[1] != del)) {
1314 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1315 Buf_AddBytes(buf, strlen(cp2), (Byte *)cp2);
1320 } else if (*cp == '&') {
1321 Buf_AddBytes(buf, pattern.leftLen,
1322 (Byte *)pattern.lhs);
1324 Buf_AddByte(buf, (Byte)*cp);
1328 Buf_AddByte(buf, (Byte)'\0');
1331 * If didn't end in delimiter character, complain
1334 Fatal("Unclosed substitution for %s (%c missing)",
1338 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1340 Buf_Destroy(buf, FALSE);
1343 * Check for global substitution. If 'g' after the final
1344 * delimiter, substitution is global and is marked that
1349 pattern.flags |= VAR_SUB_GLOBAL;
1354 * Global substitution of the empty string causes an
1355 * infinite number of matches, unless anchored by '^'
1356 * (start of string) or '$' (end of string). Catch the
1357 * infinite substitution here.
1358 * Note that flags can only contain the 3 bits we're
1359 * interested in so we don't have to mask unrelated
1360 * bits. We can test for equality.
1362 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1363 Fatal("Global substitution of the empty string");
1366 newStr = VarModify(str, VarSubstitute, &pattern);
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 Fatal("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 Fatal("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, &pattern);
1445 regfree(&pattern.re);
1446 free(pattern.replace);
1447 free(pattern.matches);
1451 if (tstr[1] == endc || tstr[1] == ':') {
1453 buf = Buf_Init(MAKE_BSIZE);
1454 for (cp = str; *cp ; cp++)
1455 Buf_AddByte(buf, (Byte)tolower(*cp));
1457 Buf_AddByte(buf, (Byte)'\0');
1458 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1459 Buf_Destroy(buf, FALSE);
1467 if (tstr[1] == endc || tstr[1] == ':') {
1468 newStr = VarSortWords(str, SortIncreasing);
1475 if (tstr[1] == endc || tstr[1] == ':') {
1476 newStr = Var_Quote(str);
1483 if (tstr[1] == endc || tstr[1] == ':') {
1484 newStr = VarModify(str, VarTail, (void *)NULL);
1491 if (tstr[1] == endc || tstr[1] == ':') {
1493 buf = Buf_Init(MAKE_BSIZE);
1494 for (cp = str; *cp ; cp++)
1495 Buf_AddByte(buf, (Byte)toupper(*cp));
1497 Buf_AddByte(buf, (Byte)'\0');
1498 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1499 Buf_Destroy(buf, FALSE);
1507 if (tstr[1] == endc || tstr[1] == ':') {
1508 newStr = VarModify(str, VarHead, (void *)NULL);
1515 if (tstr[1] == endc || tstr[1] == ':') {
1516 newStr = VarModify(str, VarSuffix, (void *)NULL);
1523 if (tstr[1] == endc || tstr[1] == ':') {
1524 newStr = VarModify(str, VarRoot, (void *)NULL);
1532 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1534 newStr = Cmd_Exec(str, &error);
1547 * This can either be a bogus modifier or a System-V
1548 * substitution command.
1556 * First we make a pass through the string trying
1557 * to verify it is a SYSV-make-style translation:
1558 * it must be: <string1>=<string2>)
1562 while (*cp != '\0' && cnt) {
1565 /* continue looking for endc */
1567 else if (*cp == endc)
1569 else if (*cp == startc)
1574 if (*cp == endc && eqFound) {
1577 * Now we break this sucker into the lhs and
1578 * rhs. We must null terminate them of course.
1583 if ((pattern.lhs = VarGetPattern(ctxt,
1584 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1586 /* was: goto cleanup */
1587 *lengthPtr = cp - start + 1;
1591 Fatal("Unclosed substitution for %s (%c missing)",
1597 if ((pattern.rhs = VarGetPattern(ctxt,
1598 err, &cp, delim, NULL, &pattern.rightLen,
1599 &pattern)) == NULL) {
1600 /* was: goto cleanup */
1601 *lengthPtr = cp - start + 1;
1605 Fatal("Unclosed substitution for %s (%c missing)",
1611 * SYSV modifications happen through the whole
1612 * string. Note the pattern is anchored at the end.
1616 newStr = VarModify(str, VarSYSVMatch, &pattern);
1625 Error("Unknown modifier '%c'\n", *tstr);
1627 *cp != ':' && *cp != endc && *cp != '\0';
1635 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1641 if (str != var_Error) {
1646 if (termc == '\0') {
1647 Error("Unclosed variable specification for %s", v->name);
1648 } else if (termc == ':') {
1655 *lengthPtr = tstr - start + 1;
1657 *lengthPtr = tstr - start + 1;
1661 if (v->flags & VAR_FROM_ENV) {
1662 Boolean destroy = FALSE;
1664 if (str != (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1668 * Returning the value unmodified, so tell the caller to free
1674 Buf_Destroy(v->val, destroy);
1676 } else if (v->flags & VAR_JUNK) {
1678 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1679 * doesn't try to free a static pointer.
1686 Buf_Destroy(v->val, TRUE);
1689 str = emalloc(*lengthPtr + 1);
1690 strncpy(str, start, *lengthPtr);
1691 str[*lengthPtr] = '\0';
1694 str = err ? var_Error : varNoError;
1701 *-----------------------------------------------------------------------
1703 * Substitute for all variables in the given string in the given context
1704 * If undefErr is TRUE, Parse_Error will be called when an undefined
1705 * variable is encountered.
1708 * The resulting string.
1711 * None. The old string must be freed by the caller
1712 *-----------------------------------------------------------------------
1715 Var_Subst(char *var, char *str, GNode *ctxt, Boolean undefErr)
1717 Buffer buf; /* Buffer for forming things */
1718 char *val; /* Value to substitute for a variable */
1719 size_t length; /* Length of the variable invocation */
1720 Boolean doFree; /* Set true if val should be freed */
1721 static Boolean errorReported; /* Set true if an error has already
1722 * been reported to prevent a plethora
1723 * of messages when recursing */
1725 buf = Buf_Init(MAKE_BSIZE);
1726 errorReported = FALSE;
1729 if (var == NULL && (*str == '$') && (str[1] == '$')) {
1731 * A dollar sign may be escaped either with another dollar sign.
1732 * In such a case, we skip over the escape character and store the
1733 * dollar sign into the buffer directly.
1736 Buf_AddByte(buf, (Byte)*str);
1738 } else if (*str != '$') {
1740 * Skip as many characters as possible -- either to the end of
1741 * the string or to the next dollar sign (variable invocation).
1745 for (cp = str++; *str != '$' && *str != '\0'; str++)
1747 Buf_AddBytes(buf, str - cp, (Byte *)cp);
1752 if (str[1] != '(' && str[1] != '{') {
1753 if (str[1] != *var || var[1] != '\0') {
1754 Buf_AddBytes(buf, 2, (Byte *)str);
1766 * Scan up to the end of the variable name.
1768 for (p = &str[2]; *p &&
1769 *p != ':' && *p != ')' && *p != '}'; p++)
1773 * A variable inside the variable. We cannot expand
1774 * the external variable yet, so we try again with
1778 Buf_AddBytes(buf, p - str, (Byte *)str);
1783 if (strncmp(var, str + 2, p - str - 2) != 0 ||
1784 var[p - str - 2] != '\0') {
1786 * Not the variable we want to expand, scan
1787 * until the next variable
1789 for (;*p != '$' && *p != '\0'; p++)
1791 Buf_AddBytes(buf, p - str, (Byte *)str);
1804 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1807 * When we come down here, val should either point to the
1808 * value of this variable, suitably modified, or be NULL.
1809 * Length should be the total length of the potential
1810 * variable invocation (from $ to end character...)
1812 if (val == var_Error || val == varNoError) {
1814 * If performing old-time variable substitution, skip over
1815 * the variable and continue with the substitution. Otherwise,
1816 * store the dollar sign and advance str so we continue with
1821 } else if (undefErr) {
1823 * If variable is undefined, complain and skip the
1824 * variable. The complaint will stop us from doing anything
1825 * when the file is parsed.
1827 if (!errorReported) {
1828 Parse_Error(PARSE_FATAL,
1829 "Undefined variable \"%.*s\"",length,str);
1832 errorReported = TRUE;
1834 Buf_AddByte (buf, (Byte)*str);
1839 * We've now got a variable structure to store in. But first,
1840 * advance the string pointer.
1845 * Copy all the characters from the variable value straight
1846 * into the new string.
1848 Buf_AddBytes(buf, strlen(val), (Byte *)val);
1856 Buf_AddByte(buf, '\0');
1857 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
1858 Buf_Destroy(buf, FALSE);
1863 *-----------------------------------------------------------------------
1865 * Return the tail from each of a list of words. Used to set the
1866 * System V local variables.
1869 * The resulting string.
1874 *-----------------------------------------------------------------------
1877 Var_GetTail(char *file)
1880 return (VarModify(file, VarTail, (void *)NULL));
1884 *-----------------------------------------------------------------------
1886 * Find the leading components of a (list of) filename(s).
1887 * XXX: VarHead does not replace foo by ., as (sun) System V make
1891 * The leading components.
1896 *-----------------------------------------------------------------------
1899 Var_GetHead(char *file)
1902 return (VarModify(file, VarHead, (void *)NULL));
1906 *-----------------------------------------------------------------------
1908 * Initialize the module
1914 * The VAR_CMD and VAR_GLOBAL contexts are created
1915 *-----------------------------------------------------------------------
1921 VAR_GLOBAL = Targ_NewGN("Global");
1922 VAR_CMD = Targ_NewGN("Command");
1932 /****************** PRINT DEBUGGING INFO *****************/
1934 VarPrintVar(void *vp, void *dummy __unused)
1936 Var *v = (Var *) vp;
1938 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
1943 *-----------------------------------------------------------------------
1945 * print all variables in a context
1946 *-----------------------------------------------------------------------
1949 Var_Dump(GNode *ctxt)
1952 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);