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.51 2005/01/29 00:30:42 okumoto Exp $
45 * Variable-handling functions
48 * Var_Set Set the value of a variable in the given
49 * context. The variable is created if it doesn't
50 * yet exist. The value and variable name need not
53 * Var_Append Append more characters to an existing variable
54 * in the given context. The variable needn't
55 * exist already -- it will be created if it doesn't.
56 * A space is placed between the old value and the
59 * Var_Exists See if a variable exists.
61 * Var_Value Return the value of a variable in a context or
62 * NULL if the variable is undefined.
64 * Var_Subst Substitute named variable, or all variables if
65 * NULL in a string using
66 * the given context as the top-most one. If the
67 * third argument is non-zero, Parse_Error is
68 * called if any variables are undefined.
70 * Var_Parse Parse a variable expansion from a string and
71 * return the result and the number of characters
74 * Var_Delete Delete a variable in a context.
76 * Var_Init Initialize this module.
79 * Var_Dump Print out all variables defined in the given
82 * XXX: There's a lot of duplication in these functions.
102 * This is a harmless return value for Var_Parse that can be used by Var_Subst
103 * to determine if there was an error in parsing -- easier than returning
104 * a flag, as things outside this module don't give a hoot.
106 char var_Error[] = "";
109 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
110 * set false. Why not just use a constant? Well, gcc likes to condense
111 * identical string instances...
113 static char varNoError[] = "";
116 * Internally, variables are contained in four different contexts.
117 * 1) the environment. They may not be changed. If an environment
118 * variable is appended-to, the result is placed in the global
120 * 2) the global context. Variables set in the Makefile are located in
121 * the global context. It is the penultimate context searched when
123 * 3) the command-line context. All variables set on the command line
124 * are placed in this context. They are UNALTERABLE once placed here.
125 * 4) the local context. Each target has associated with it a context
126 * list. On this list are located the structures describing such
127 * local variables as $(@) and $(*)
128 * The four contexts are searched in the reverse order from which they are
131 GNode *VAR_GLOBAL; /* variables from the makefile */
132 GNode *VAR_CMD; /* variables defined on the command-line */
134 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
135 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
136 #define FIND_ENV 0x4 /* look in the environment also */
138 static char *VarPossiblyExpand(const char *, GNode *);
139 static Var *VarFind(const char *, GNode *, int);
140 static void VarAdd(const char *, const char *, GNode *);
141 static Var *VarCreate(const char [], const char [], int);
142 static void VarDestroy(Var *, Boolean);
143 static char *VarGetPattern(GNode *, int, char **, int, int *, size_t *,
145 static char *VarModify(char *,
146 Boolean (*)(const char *, Boolean, Buffer *, void *),
148 static int VarPrintVar(void *, void *);
151 *-----------------------------------------------------------------------
153 * See if the given variable matches the named one. Called from
154 * Lst_Find when searching for a variable of a given name.
157 * 0 if they match. non-zero otherwise.
161 *-----------------------------------------------------------------------
164 VarCmp(const void *v, const void *name)
166 return (strcmp(name, ((const Var *)v)->name));
170 *-----------------------------------------------------------------------
171 * VarPossiblyExpand --
172 * Expand a variable name's embedded variables in the given context.
175 * The contents of name, possibly expanded.
176 *-----------------------------------------------------------------------
179 VarPossiblyExpand(const char *name, GNode *ctxt)
181 if (strchr(name, '$') != NULL)
182 return Var_Subst(NULL, name, ctxt, 0);
184 return estrdup(name);
188 *-----------------------------------------------------------------------
190 * Find the given variable in the given context and any other contexts
194 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
195 * FIND_CMD set means to look in the VAR_CMD context too
196 * FIND_ENV set means to look in the environment
199 * A pointer to the structure describing the desired variable or
200 * NULL if the variable does not exist.
204 *-----------------------------------------------------------------------
207 VarFind(const char *name, GNode *ctxt, int flags)
209 Boolean localCheckEnvFirst;
214 * If the variable name begins with a '.', it could very well be one of
215 * the local ones. We check the name against all the local variables
216 * and substitute the short version in for 'name' if it matches one of
219 if (name[0] == '.' && isupper((unsigned char)name[1]))
222 if (!strcmp(name, ".ALLSRC"))
224 if (!strcmp(name, ".ARCHIVE"))
228 if (!strcmp(name, ".IMPSRC"))
232 if (!strcmp(name, ".MEMBER"))
236 if (!strcmp(name, ".OODATE"))
240 if (!strcmp(name, ".PREFIX"))
244 if (!strcmp(name, ".TARGET"))
250 * Note whether this is one of the specific variables we were told through
251 * the -E flag to use environment-variable-override for.
253 if (Lst_Find(&envFirstVars, name, (CompareProc *)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, name, VarCmp);
266 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
267 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
269 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
270 !checkEnvFirst && !localCheckEnvFirst)
272 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
274 if ((var == NULL) && (flags & FIND_ENV)) {
277 if ((env = getenv(name)) != NULL) {
278 v = VarCreate(name, env, VAR_FROM_ENV);
281 } else if ((checkEnvFirst || localCheckEnvFirst) &&
282 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
284 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
288 return (Lst_Datum(var));
293 } else if (var == NULL) {
296 return (Lst_Datum(var));
301 *-----------------------------------------------------------------------
303 * Add a new variable of name name and value val to the given context.
309 * The new variable is placed at the front of the given context
310 * The name and val arguments are duplicated so they may
312 *-----------------------------------------------------------------------
315 VarAdd(const char *name, const char *val, GNode *ctxt)
317 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
319 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
323 * Create a Var object.
325 * @param name Name of variable.
326 * @param value Value of variable.
327 * @param flags Flags set on variable.
330 VarCreate(const char name[], const char value[], int flags)
334 v = emalloc(sizeof(Var));
335 v->name = estrdup(name);
336 v->val = Buf_Init(0);
340 Buf_Append(v->val, value);
346 * Destroy a Var object.
348 * @param v Object to destroy.
349 * @param f true if internal buffer in Buffer object is to be
353 VarDestroy(Var *v, Boolean f)
355 Buf_Destroy(v->val, f);
361 *-----------------------------------------------------------------------
363 * Remove a variable from a context.
369 * The Var structure is removed and freed.
371 *-----------------------------------------------------------------------
374 Var_Delete(char *name, GNode *ctxt)
378 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
379 ln = Lst_Find(&ctxt->context, name, VarCmp);
381 VarDestroy(Lst_Datum(ln), TRUE);
382 Lst_Remove(&ctxt->context, ln);
387 *-----------------------------------------------------------------------
389 * Set the variable name to the value val in the given context.
395 * If the variable doesn't yet exist, a new record is created for it.
396 * Else the old value is freed and the new one stuck in its place
399 * The variable is searched for only in its context before being
400 * created in that context. I.e. if the context is VAR_GLOBAL,
401 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
402 * VAR_CMD->context is searched. This is done to avoid the literally
403 * thousands of unnecessary strcmp's that used to be done to
404 * set, say, $(@) or $(<).
405 *-----------------------------------------------------------------------
408 Var_Set(const char *name, const char *val, GNode *ctxt)
414 * We only look for a variable in the given context since anything set
415 * here will override anything in a lower context, so there's not much
416 * point in searching them all just to save a bit of memory...
418 n = VarPossiblyExpand(name, ctxt);
419 v = VarFind(n, ctxt, 0);
421 VarAdd(n, val, ctxt);
424 Buf_Append(v->val, val);
426 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
429 * Any variables given on the command line are automatically exported
430 * to the environment (as per POSIX standard)
432 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
440 * Set the VAR_TO_ENV flag on a variable
443 Var_SetEnv(const char *name, GNode *ctxt)
447 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
449 if ((v->flags & VAR_TO_ENV) == 0) {
450 v->flags |= VAR_TO_ENV;
451 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
454 Error("Cannot set environment flag on non-existant variable %s", name);
459 *-----------------------------------------------------------------------
461 * The variable of the given name has the given value appended to it in
468 * If the variable doesn't exist, it is created. Else the strings
469 * are concatenated (with a space in between).
472 * Only if the variable is being sought in the global context is the
473 * environment searched.
474 * XXX: Knows its calling circumstances in that if called with ctxt
475 * an actual target, it will only search that context since only
476 * a local variable could be being appended to. This is actually
477 * a big win and must be tolerated.
478 *-----------------------------------------------------------------------
481 Var_Append(const char *name, const char *val, GNode *ctxt)
486 n = VarPossiblyExpand(name, ctxt);
487 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
489 VarAdd(n, val, ctxt);
491 Buf_AddByte(v->val, (Byte)' ');
492 Buf_Append(v->val, val);
494 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
495 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
497 if (v->flags & VAR_FROM_ENV) {
499 * If the original variable came from the environment, we
500 * have to install it in the global context (we could place
501 * it in the environment, but then we should provide a way to
502 * export other variables...)
504 v->flags &= ~VAR_FROM_ENV;
505 Lst_AtFront(&ctxt->context, v);
512 *-----------------------------------------------------------------------
514 * See if the given variable exists.
517 * TRUE if it does, FALSE if it doesn't
522 *-----------------------------------------------------------------------
525 Var_Exists(const char *name, GNode *ctxt)
530 n = VarPossiblyExpand(name, ctxt);
531 v = VarFind(n, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
536 } else if (v->flags & VAR_FROM_ENV) {
543 *-----------------------------------------------------------------------
545 * Return the value of the named variable in the given context
548 * The value if the variable exists, NULL if it doesn't
552 *-----------------------------------------------------------------------
555 Var_Value(const char *name, GNode *ctxt, char **frp)
560 n = VarPossiblyExpand(name, ctxt);
561 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
565 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
567 if (v->flags & VAR_FROM_ENV) {
568 VarDestroy(v, FALSE);
578 *-----------------------------------------------------------------------
580 * Modify each of the words of the passed string using the given
581 * function. Used to implement all modifiers.
584 * A string of all the words modified appropriately.
589 *-----------------------------------------------------------------------
592 VarModify(char *str, Boolean (*modProc)(const char *, Boolean, Buffer *, void *), void *datum)
594 Buffer *buf; /* Buffer for the new string */
595 Boolean addSpace; /* TRUE if need to add a space to the
596 * buffer before adding the trimmed
598 char **av; /* word list [first word does not count] */
604 av = brk_string(str, &ac, FALSE);
606 for (i = 1; i < ac; i++)
607 addSpace = (*modProc)(av[i], addSpace, buf, datum);
609 Buf_AddByte(buf, '\0');
610 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
611 Buf_Destroy(buf, FALSE);
616 *-----------------------------------------------------------------------
618 * Sort the words in the string.
621 * str String whose words should be sorted
622 * cmp A comparison function to control the ordering
625 * A string containing the words sorted
630 *-----------------------------------------------------------------------
633 VarSortWords(char *str, int (*cmp)(const void *, const void *))
640 av = brk_string(str, &ac, FALSE);
641 qsort(av + 1, ac - 1, sizeof(char *), cmp);
642 for (i = 1; i < ac; i++) {
643 Buf_Append(buf, av[i]);
644 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
646 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
647 Buf_Destroy(buf, FALSE);
652 SortIncreasing(const void *l, const void *r)
654 return (strcmp(*(const char* const*)l, *(const char* const*)r));
658 *-----------------------------------------------------------------------
660 * Pass through the tstr looking for 1) escaped delimiters,
661 * '$'s and backslashes (place the escaped character in
662 * uninterpreted) and 2) unescaped $'s that aren't before
663 * the delimiter (expand the variable substitution unless flags
664 * has VAR_NOSUBST set).
665 * Return the expanded string or NULL if the delimiter was missing
666 * If pattern is specified, handle escaped ampersands, and replace
667 * unescaped ampersands with the lhs of the pattern.
670 * A string of all the words modified appropriately.
671 * If length is specified, return the string length of the buffer
672 * If flags is specified and the last character of the pattern is a
673 * $ set the VAR_MATCH_END bit of flags.
677 *-----------------------------------------------------------------------
680 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
681 size_t *length, VarPattern *pattern)
684 Buffer *buf = Buf_Init(0);
690 #define IS_A_MATCH(cp, delim) \
691 ((cp[0] == '\\') && ((cp[1] == delim) || \
692 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
695 * Skim through until the matching delimiter is found;
696 * pick up variable substitutions on the way. Also allow
697 * backslashes to quote the delimiter, $, and \, but don't
698 * touch other backslashes.
700 for (cp = *tstr; *cp && (*cp != delim); cp++) {
701 if (IS_A_MATCH(cp, delim)) {
702 Buf_AddByte(buf, (Byte)cp[1]);
704 } else if (*cp == '$') {
705 if (cp[1] == delim) {
707 Buf_AddByte(buf, (Byte)*cp);
710 * Unescaped $ at end of pattern => anchor
713 *flags |= VAR_MATCH_END;
715 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
721 * If unescaped dollar sign not before the
722 * delimiter, assume it's a variable
723 * substitution and recurse.
725 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
726 Buf_Append(buf, cp2);
733 if (*cp2 == '(' || *cp2 == '{') {
735 * Find the end of this variable reference
736 * and suck it in without further ado.
737 * It will be interperated later.
740 int want = (*cp2 == '(') ? ')' : '}';
743 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
744 if (cp2[-1] != '\\') {
751 Buf_AppendRange(buf, cp, cp2);
754 Buf_AddByte(buf, (Byte)*cp);
758 else if (pattern && *cp == '&')
759 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
761 Buf_AddByte(buf, (Byte)*cp);
764 Buf_AddByte(buf, (Byte)'\0');
772 cp = (char *)Buf_GetAll(buf, length);
773 *length -= 1; /* Don't count the NULL */
774 Buf_Destroy(buf, FALSE);
780 *-----------------------------------------------------------------------
782 * Quote shell meta-characters in the string
790 *-----------------------------------------------------------------------
793 Var_Quote(const char *str)
796 /* This should cover most shells :-( */
797 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
800 buf = Buf_Init(MAKE_BSIZE);
801 for (; *str; str++) {
802 if (strchr(meta, *str) != NULL)
803 Buf_AddByte(buf, (Byte)'\\');
804 Buf_AddByte(buf, (Byte)*str);
806 Buf_AddByte(buf, (Byte)'\0');
807 ret = Buf_GetAll(buf, NULL);
808 Buf_Destroy(buf, FALSE);
813 *-----------------------------------------------------------------------
815 * Print the error caused by a regcomp or regexec call.
821 * An error gets printed.
823 *-----------------------------------------------------------------------
826 VarREError(int err, regex_t *pat, const char *str)
831 errlen = regerror(err, pat, 0, 0);
832 errbuf = emalloc(errlen);
833 regerror(err, pat, errbuf, errlen);
834 Error("%s: %s", str, errbuf);
839 *-----------------------------------------------------------------------
841 * Given the start of a variable invocation, extract the variable
842 * name and find its value, then modify it according to the
846 * The (possibly-modified) value of the variable or var_Error if the
847 * specification is invalid. The length of the specification is
848 * placed in *lengthPtr (for invalid specifications, this is just
849 * 2 to skip the '$' and the following letter, or 1 if '$' was the
850 * last character in the string).
851 * A Boolean in *freePtr telling whether the returned string should
852 * be freed by the caller.
857 *-----------------------------------------------------------------------
860 Var_Parse(char *str, GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
862 char *tstr; /* Pointer into str */
863 Var *v; /* Variable in invocation */
864 char *cp; /* Secondary pointer into str (place marker
866 Boolean haveModifier;/* TRUE if have modifiers for the variable */
867 char endc; /* Ending character when variable in parens
869 char startc=0; /* Starting character when variable in parens
871 int cnt; /* Used to count brace pairs when variable in
872 * in parens or braces */
875 Boolean dynamic; /* TRUE if the variable is local and we're
876 * expanding it in a non-local context. This
877 * is done to support dynamic sources. The
878 * result is just the invocation, unaltered */
879 int vlen; /* length of variable name, after embedded variable
886 if (str[1] != '(' && str[1] != '{') {
888 * If it's not bounded by braces of some sort, life is much simpler.
889 * We just need to check for the first character and return the
890 * value if it exists.
897 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
898 if (v == (Var *)NULL) {
904 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
906 * If substituting a local variable in a non-local context,
907 * assume it's for dynamic source stuff. We have to handle
908 * this specially and return the longhand for the variable
909 * with the dollar sign escaped so it makes it back to the
910 * caller. Only four of the local variables are treated
911 * specially as they are the only four that will be set
912 * when dynamic sources are expanded.
914 /* XXX: It looks like $% and $! are reversed here */
917 return ("$(.TARGET)");
919 return ("$(.ARCHIVE)");
921 return ("$(.PREFIX)");
923 return ("$(.MEMBER)");
931 return (err ? var_Error : varNoError);
933 haveModifier = FALSE;
938 /* build up expanded variable name in this buffer */
939 Buffer *buf = Buf_Init(MAKE_BSIZE);
942 endc = startc == '(' ? ')' : '}';
945 * Skip to the end character or a colon, whichever comes first,
946 * replacing embedded variables as we go.
948 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
952 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
954 if (rval == var_Error) {
955 Fatal("Error expanding embedded variable.");
956 } else if (rval != NULL) {
957 Buf_Append(buf, rval);
963 Buf_AddByte(buf, (Byte)*tstr);
967 * If we never did find the end character, return NULL
968 * right now, setting the length to be the distance to
969 * the end of the string, since that's what make does.
971 *lengthPtr = tstr - str;
975 haveModifier = (*tstr == ':');
978 Buf_AddByte(buf, (Byte)'\0');
979 str = Buf_GetAll(buf, (size_t *)NULL);
982 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
983 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
984 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
987 * Check for bogus D and F forms of local variables since we're
988 * in a local context and the name is the right length.
1002 * Well, it's local -- go look for it.
1006 v = VarFind(vname, ctxt, 0);
1008 if (v != NULL && !haveModifier) {
1010 * No need for nested expansion or anything, as we're
1011 * the only one who sets these things and we sure don't
1012 * put nested invocations in them...
1014 val = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1016 if (str[1] == 'D') {
1017 val = VarModify(val, VarHead, (void *)NULL);
1019 val = VarModify(val, VarTail, (void *)NULL);
1022 * Resulting string is dynamically allocated, so
1023 * tell caller to free it.
1026 *lengthPtr = tstr-start+1;
1028 Buf_Destroy(buf, TRUE);
1038 if (v == (Var *)NULL) {
1040 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
1041 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1044 * If substituting a local variable in a non-local context,
1045 * assume it's for dynamic source stuff. We have to handle
1046 * this specially and return the longhand for the variable
1047 * with the dollar sign escaped so it makes it back to the
1048 * caller. Only four of the local variables are treated
1049 * specially as they are the only four that will be set
1050 * when dynamic sources are expanded.
1062 } else if ((vlen > 2) && (str[0] == '.') &&
1063 isupper((unsigned char)str[1]) &&
1064 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1069 if ((strncmp(str, ".TARGET", len) == 0) ||
1070 (strncmp(str, ".ARCHIVE", len) == 0) ||
1071 (strncmp(str, ".PREFIX", len) == 0) ||
1072 (strncmp(str, ".MEMBER", len) == 0))
1078 if (!haveModifier) {
1080 * No modifiers -- have specification length so we can return
1083 *lengthPtr = tstr - start + 1;
1086 str = emalloc(*lengthPtr + 1);
1087 strncpy(str, start, *lengthPtr);
1088 str[*lengthPtr] = '\0';
1090 Buf_Destroy(buf, TRUE);
1093 Buf_Destroy(buf, TRUE);
1094 return (err ? var_Error : varNoError);
1098 * Still need to get to the end of the variable specification,
1099 * so kludge up a Var structure for the modifications
1101 v = VarCreate(str, NULL, VAR_JUNK);
1104 Buf_Destroy(buf, TRUE);
1107 if (v->flags & VAR_IN_USE) {
1108 Fatal("Variable %s is recursive.", v->name);
1111 v->flags |= VAR_IN_USE;
1114 * Before doing any modification, we have to make sure the value
1115 * has been fully expanded. If it looks like recursion might be
1116 * necessary (there's a dollar sign somewhere in the variable's value)
1117 * we just call Var_Subst to do any other substitutions that are
1118 * necessary. Note that the value returned by Var_Subst will have
1119 * been dynamically-allocated, so it will need freeing when we
1122 str = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1123 if (strchr(str, '$') != (char *)NULL) {
1124 str = Var_Subst(NULL, str, ctxt, err);
1128 v->flags &= ~VAR_IN_USE;
1131 * Now we need to apply any modifiers the user wants applied.
1133 * :M<pattern> words which match the given <pattern>.
1134 * <pattern> is of the standard file
1136 * :S<d><pat1><d><pat2><d>[g]
1137 * Substitute <pat2> for <pat1> in the value
1138 * :C<d><pat1><d><pat2><d>[g]
1139 * Substitute <pat2> for regex <pat1> in the value
1140 * :H Substitute the head of each word
1141 * :T Substitute the tail of each word
1142 * :E Substitute the extension (minus '.') of
1144 * :R Substitute the root of each word
1145 * (pathname minus the suffix).
1146 * :lhs=rhs Like :S, but the rhs goes to the end of
1148 * :U Converts variable to upper-case.
1149 * :L Converts variable to lower-case.
1151 if ((str != NULL) && haveModifier) {
1153 * Skip initial colon while putting it back.
1156 while (*tstr != endc) {
1157 char *newStr; /* New value to return */
1158 char termc; /* Character which terminated scan */
1160 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1171 *cp != '\0' && *cp != ':' && *cp != endc;
1174 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
1183 * Need to compress the \:'s out of the pattern, so
1184 * allocate enough room to hold the uncompressed
1185 * pattern (note that cp started at tstr+1, so
1186 * cp - tstr takes the null byte into account) and
1187 * compress the pattern into the space.
1189 pattern = emalloc(cp - tstr);
1190 for (cp2 = pattern, cp = tstr + 1;
1194 if ((*cp == '\\') &&
1195 (cp[1] == ':' || cp[1] == endc)) {
1204 if (*tstr == 'M' || *tstr == 'm') {
1205 newStr = VarModify(str, VarMatch, pattern);
1207 newStr = VarModify(str, VarNoMatch, pattern);
1218 Buffer *buf; /* Buffer for patterns */
1225 * If pattern begins with '^', it is anchored to the
1226 * start of the word -- skip over it and flag pattern.
1229 pattern.flags |= VAR_MATCH_START;
1236 * Pass through the lhs looking for 1) escaped delimiters,
1237 * '$'s and backslashes (place the escaped character in
1238 * uninterpreted) and 2) unescaped $'s that aren't before
1239 * the delimiter (expand the variable substitution).
1240 * The result is left in the Buffer buf.
1242 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1243 if ((*cp == '\\') &&
1248 Buf_AddByte(buf, (Byte)cp[1]);
1250 } else if (*cp == '$') {
1253 * If unescaped dollar sign not before the
1254 * delimiter, assume it's a variable
1255 * substitution and recurse.
1261 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1262 Buf_Append(buf, cp2);
1269 * Unescaped $ at end of pattern => anchor
1272 pattern.flags |= VAR_MATCH_END;
1275 Buf_AddByte(buf, (Byte)*cp);
1279 Buf_AddByte(buf, (Byte)'\0');
1282 * If lhs didn't end with the delimiter, complain and
1286 Fatal("Unclosed substitution for %s (%c missing)",
1291 * Fetch pattern and destroy buffer, but preserve the data
1292 * in it, since that's our lhs. Note that Buf_GetAll
1293 * will return the actual number of bytes, which includes
1294 * the null byte, so we have to decrement the length by
1297 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1299 Buf_Destroy(buf, FALSE);
1302 * Now comes the replacement string. Three things need to
1303 * be done here: 1) need to compress escaped delimiters and
1304 * ampersands and 2) need to replace unescaped ampersands
1305 * with the l.h.s. (since this isn't regexp, we can do
1306 * it right here) and 3) expand any variable substitutions.
1311 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1312 if ((*cp == '\\') &&
1318 Buf_AddByte(buf, (Byte)cp[1]);
1320 } else if ((*cp == '$') && (cp[1] != del)) {
1325 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1326 Buf_Append(buf, cp2);
1331 } else if (*cp == '&') {
1332 Buf_AddBytes(buf, pattern.leftLen,
1333 (Byte *)pattern.lhs);
1335 Buf_AddByte(buf, (Byte)*cp);
1339 Buf_AddByte(buf, (Byte)'\0');
1342 * If didn't end in delimiter character, complain
1345 Fatal("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 * Global substitution of the empty string causes an
1366 * infinite number of matches, unless anchored by '^'
1367 * (start of string) or '$' (end of string). Catch the
1368 * infinite substitution here.
1369 * Note that flags can only contain the 3 bits we're
1370 * interested in so we don't have to mask unrelated
1371 * bits. We can test for equality.
1373 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1374 Fatal("Global substitution of the empty string");
1377 newStr = VarModify(str, VarSubstitute, &pattern);
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 Fatal("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 Fatal("Unclosed substitution for %s (%c missing)",
1426 pattern.flags |= VAR_SUB_GLOBAL;
1429 pattern.flags |= VAR_SUB_ONE;
1439 error = regcomp(&pattern.re, re, REG_EXTENDED);
1442 *lengthPtr = cp - start + 1;
1443 VarREError(error, &pattern.re, "RE substitution error");
1444 free(pattern.replace);
1448 pattern.nsub = pattern.re.re_nsub + 1;
1449 if (pattern.nsub < 1)
1451 if (pattern.nsub > 10)
1453 pattern.matches = emalloc(pattern.nsub *
1454 sizeof(regmatch_t));
1455 newStr = VarModify(str, VarRESubstitute, &pattern);
1456 regfree(&pattern.re);
1457 free(pattern.replace);
1458 free(pattern.matches);
1462 if (tstr[1] == endc || tstr[1] == ':') {
1464 buf = Buf_Init(MAKE_BSIZE);
1465 for (cp = str; *cp ; cp++)
1466 Buf_AddByte(buf, (Byte)tolower(*cp));
1468 Buf_AddByte(buf, (Byte)'\0');
1469 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1470 Buf_Destroy(buf, FALSE);
1478 if (tstr[1] == endc || tstr[1] == ':') {
1479 newStr = VarSortWords(str, SortIncreasing);
1486 if (tstr[1] == endc || tstr[1] == ':') {
1487 newStr = Var_Quote(str);
1494 if (tstr[1] == endc || tstr[1] == ':') {
1495 newStr = VarModify(str, VarTail, (void *)NULL);
1502 if (tstr[1] == endc || tstr[1] == ':') {
1504 buf = Buf_Init(MAKE_BSIZE);
1505 for (cp = str; *cp ; cp++)
1506 Buf_AddByte(buf, (Byte)toupper(*cp));
1508 Buf_AddByte(buf, (Byte)'\0');
1509 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1510 Buf_Destroy(buf, FALSE);
1518 if (tstr[1] == endc || tstr[1] == ':') {
1519 newStr = VarModify(str, VarHead, (void *)NULL);
1526 if (tstr[1] == endc || tstr[1] == ':') {
1527 newStr = VarModify(str, VarSuffix, (void *)NULL);
1534 if (tstr[1] == endc || tstr[1] == ':') {
1535 newStr = VarModify(str, VarRoot, (void *)NULL);
1543 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1546 Buffer *buf = Cmd_Exec(str, &error);
1547 newStr = Buf_GetAll(buf, NULL);
1548 Buf_Destroy(buf, FALSE);
1562 * This can either be a bogus modifier or a System-V
1563 * substitution command.
1571 * First we make a pass through the string trying
1572 * to verify it is a SYSV-make-style translation:
1573 * it must be: <string1>=<string2>)
1577 while (*cp != '\0' && cnt) {
1580 /* continue looking for endc */
1582 else if (*cp == endc)
1584 else if (*cp == startc)
1589 if (*cp == endc && eqFound) {
1592 * Now we break this sucker into the lhs and
1593 * rhs. We must null terminate them of course.
1598 if ((pattern.lhs = VarGetPattern(ctxt,
1599 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1601 /* was: goto cleanup */
1602 *lengthPtr = cp - start + 1;
1606 Fatal("Unclosed substitution for %s (%c missing)",
1612 if ((pattern.rhs = VarGetPattern(ctxt,
1613 err, &cp, delim, NULL, &pattern.rightLen,
1614 &pattern)) == NULL) {
1615 /* was: goto cleanup */
1616 *lengthPtr = cp - start + 1;
1620 Fatal("Unclosed substitution for %s (%c missing)",
1626 * SYSV modifications happen through the whole
1627 * string. Note the pattern is anchored at the end.
1631 newStr = VarModify(str, VarSYSVMatch, &pattern);
1640 Error("Unknown modifier '%c'\n", *tstr);
1642 *cp != ':' && *cp != endc && *cp != '\0';
1650 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1656 if (str != var_Error) {
1661 if (termc == '\0') {
1662 Error("Unclosed variable specification for %s", v->name);
1663 } else if (termc == ':') {
1670 *lengthPtr = tstr - start + 1;
1672 *lengthPtr = tstr - start + 1;
1676 if (v->flags & VAR_FROM_ENV) {
1677 Boolean destroy = FALSE;
1679 if (str != (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1683 * Returning the value unmodified, so tell the caller to free
1688 VarDestroy(v, destroy);
1689 } else if (v->flags & VAR_JUNK) {
1691 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1692 * doesn't try to free a static pointer.
1698 VarDestroy(v, TRUE);
1700 str = emalloc(*lengthPtr + 1);
1701 strncpy(str, start, *lengthPtr);
1702 str[*lengthPtr] = '\0';
1705 str = err ? var_Error : varNoError;
1712 *-----------------------------------------------------------------------
1714 * Substitute for all variables in the given string in the given context
1715 * If undefErr is TRUE, Parse_Error will be called when an undefined
1716 * variable is encountered.
1719 * The resulting string.
1722 * None. The old string must be freed by the caller
1723 *-----------------------------------------------------------------------
1726 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1728 Buffer *buf; /* Buffer for forming things */
1729 char *val; /* Value to substitute for a variable */
1730 size_t length; /* Length of the variable invocation */
1731 Boolean doFree; /* Set true if val should be freed */
1734 static Boolean errorReported; /* Set true if an error has already
1735 * been reported to prevent a plethora
1736 * of messages when recursing */
1739 errorReported = FALSE;
1742 if (var == NULL && (str[0] == '$') && (str[1] == '$')) {
1744 * A dollar sign may be escaped either with another dollar sign.
1745 * In such a case, we skip over the escape character and store the
1746 * dollar sign into the buffer directly.
1748 Buf_AddByte(buf, (Byte)str[0]);
1751 } else if (str[0] != '$') {
1753 * Skip as many characters as possible -- either to the end of
1754 * the string or to the next dollar sign (variable invocation).
1756 const char *cp = str;
1760 } while (str[0] != '$' && str[0] != '\0');
1762 Buf_AppendRange(buf, cp, str);
1768 if (str[1] != '(' && str[1] != '{') {
1769 if (str[1] != *var || var[1] != '\0') {
1770 Buf_AddBytes(buf, 2, (const Byte *)str);
1781 * Scan up to the end of the variable name.
1783 for (p = &str[2]; *p &&
1784 *p != ':' && *p != ')' && *p != '}'; p++)
1788 * A variable inside the variable. We cannot expand
1789 * the external variable yet, so we try again with
1793 Buf_AppendRange(buf, str, p);
1798 if (strncmp(var, str + 2, p - str - 2) != 0 ||
1799 var[p - str - 2] != '\0') {
1801 * Not the variable we want to expand, scan
1802 * until the next variable
1804 for (;*p != '$' && *p != '\0'; p++)
1806 Buf_AppendRange(buf, str, p);
1819 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1822 * When we come down here, val should either point to the
1823 * value of this variable, suitably modified, or be NULL.
1824 * Length should be the total length of the potential
1825 * variable invocation (from $ to end character...)
1827 if (val == var_Error || val == varNoError) {
1829 * If performing old-time variable substitution, skip over
1830 * the variable and continue with the substitution. Otherwise,
1831 * store the dollar sign and advance str so we continue with
1836 } else if (undefErr) {
1838 * If variable is undefined, complain and skip the
1839 * variable. The complaint will stop us from doing anything
1840 * when the file is parsed.
1842 if (!errorReported) {
1843 Parse_Error(PARSE_FATAL,
1844 "Undefined variable \"%.*s\"",length,str);
1847 errorReported = TRUE;
1849 Buf_AddByte(buf, (Byte)*str);
1854 * We've now got a variable structure to store in. But first,
1855 * advance the string pointer.
1860 * Copy all the characters from the variable value straight
1861 * into the new string.
1863 Buf_Append(buf, val);
1871 //Buf_AddByte(buf, '\0');
1872 result = (char *)Buf_GetAll(buf, (size_t *)NULL);
1873 Buf_Destroy(buf, FALSE);
1878 *-----------------------------------------------------------------------
1880 * Return the tail from each of a list of words. Used to set the
1881 * System V local variables.
1884 * The resulting string.
1889 *-----------------------------------------------------------------------
1892 Var_GetTail(char *file)
1894 return (VarModify(file, VarTail, (void *)NULL));
1898 *-----------------------------------------------------------------------
1900 * Find the leading components of a (list of) filename(s).
1901 * XXX: VarHead does not replace foo by ., as (sun) System V make
1905 * The leading components.
1910 *-----------------------------------------------------------------------
1913 Var_GetHead(char *file)
1916 return (VarModify(file, VarHead, (void *)NULL));
1920 *-----------------------------------------------------------------------
1922 * Initialize the module
1928 * The VAR_CMD and VAR_GLOBAL contexts are created
1929 *-----------------------------------------------------------------------
1934 VAR_GLOBAL = Targ_NewGN("Global");
1935 VAR_CMD = Targ_NewGN("Command");
1938 /****************** PRINT DEBUGGING INFO *****************/
1940 VarPrintVar(void *vp, void *dummy __unused)
1942 Var *v = (Var *) vp;
1944 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
1949 *-----------------------------------------------------------------------
1951 * print all variables in a context
1952 *-----------------------------------------------------------------------
1955 Var_Dump(GNode *ctxt)
1957 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);