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.49 2005/01/28 23:25:18 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.
178 * The caller must free the new contents or old contents of name.
179 *-----------------------------------------------------------------------
182 VarPossiblyExpand(const char *name, GNode *ctxt)
184 if (strchr(name, '$') != NULL)
185 return Var_Subst(NULL, name, ctxt, 0);
187 return estrdup(name);
191 *-----------------------------------------------------------------------
193 * Find the given variable in the given context and any other contexts
197 * FIND_GLOBAL set means look in the VAR_GLOBAL context too
198 * FIND_CMD set means to look in the VAR_CMD context too
199 * FIND_ENV set means to look in the environment
202 * A pointer to the structure describing the desired variable or
203 * NULL if the variable does not exist.
207 *-----------------------------------------------------------------------
210 VarFind(const char *name, GNode *ctxt, int flags)
212 Boolean localCheckEnvFirst;
217 * If the variable name begins with a '.', it could very well be one of
218 * the local ones. We check the name against all the local variables
219 * and substitute the short version in for 'name' if it matches one of
222 if (name[0] == '.' && isupper((unsigned char)name[1]))
225 if (!strcmp(name, ".ALLSRC"))
227 if (!strcmp(name, ".ARCHIVE"))
231 if (!strcmp(name, ".IMPSRC"))
235 if (!strcmp(name, ".MEMBER"))
239 if (!strcmp(name, ".OODATE"))
243 if (!strcmp(name, ".PREFIX"))
247 if (!strcmp(name, ".TARGET"))
253 * Note whether this is one of the specific variables we were told through
254 * the -E flag to use environment-variable-override for.
256 if (Lst_Find(&envFirstVars, name, (CompareProc *)strcmp) != NULL) {
257 localCheckEnvFirst = TRUE;
259 localCheckEnvFirst = FALSE;
263 * First look for the variable in the given context. If it's not there,
264 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
265 * depending on the FIND_* flags in 'flags'
267 var = Lst_Find(&ctxt->context, name, VarCmp);
269 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
270 var = Lst_Find(&VAR_CMD->context, name, VarCmp);
272 if ((var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL) &&
273 !checkEnvFirst && !localCheckEnvFirst)
275 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
277 if ((var == NULL) && (flags & FIND_ENV)) {
280 if ((env = getenv(name)) != NULL) {
281 v = VarCreate(name, env, VAR_FROM_ENV);
284 } else if ((checkEnvFirst || localCheckEnvFirst) &&
285 (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL))
287 var = Lst_Find(&VAR_GLOBAL->context, name, VarCmp);
291 return (Lst_Datum(var));
296 } else if (var == NULL) {
299 return (Lst_Datum(var));
304 *-----------------------------------------------------------------------
306 * Add a new variable of name name and value val to the given context.
312 * The new variable is placed at the front of the given context
313 * The name and val arguments are duplicated so they may
315 *-----------------------------------------------------------------------
318 VarAdd(const char *name, const char *val, GNode *ctxt)
320 Lst_AtFront(&ctxt->context, VarCreate(name, val, 0));
322 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
326 * Create a Var object.
328 * @param name Name of variable.
329 * @param value Value of variable.
330 * @param flags Flags set on variable.
333 VarCreate(const char name[], const char value[], int flags)
337 v = emalloc(sizeof(Var));
338 v->name = estrdup(name);
339 v->val = Buf_Init(0);
343 Buf_Append(v->val, value);
349 * Destroy a Var object.
351 * @param v Object to destroy.
352 * @param f true if internal buffer in Buffer object is to be
356 VarDestroy(Var *v, Boolean f)
358 Buf_Destroy(v->val, f);
364 *-----------------------------------------------------------------------
366 * Remove a variable from a context.
372 * The Var structure is removed and freed.
374 *-----------------------------------------------------------------------
377 Var_Delete(char *name, GNode *ctxt)
381 DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
382 ln = Lst_Find(&ctxt->context, name, VarCmp);
384 VarDestroy(Lst_Datum(ln), TRUE);
385 Lst_Remove(&ctxt->context, ln);
390 *-----------------------------------------------------------------------
392 * Set the variable name to the value val in the given context.
398 * If the variable doesn't yet exist, a new record is created for it.
399 * Else the old value is freed and the new one stuck in its place
402 * The variable is searched for only in its context before being
403 * created in that context. I.e. if the context is VAR_GLOBAL,
404 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
405 * VAR_CMD->context is searched. This is done to avoid the literally
406 * thousands of unnecessary strcmp's that used to be done to
407 * set, say, $(@) or $(<).
408 *-----------------------------------------------------------------------
411 Var_Set(const char *name, const char *val, GNode *ctxt)
417 * We only look for a variable in the given context since anything set
418 * here will override anything in a lower context, so there's not much
419 * point in searching them all just to save a bit of memory...
421 n = VarPossiblyExpand(name, ctxt);
422 v = VarFind(n, ctxt, 0);
424 VarAdd(n, val, ctxt);
427 Buf_Append(v->val, val);
429 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
432 * Any variables given on the command line are automatically exported
433 * to the environment (as per POSIX standard)
435 if (ctxt == VAR_CMD || (v != (Var *)NULL && (v->flags & VAR_TO_ENV))) {
443 * Set the VAR_TO_ENV flag on a variable
446 Var_SetEnv(const char *name, GNode *ctxt)
450 v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
452 if ((v->flags & VAR_TO_ENV) == 0) {
453 v->flags |= VAR_TO_ENV;
454 setenv(v->name, Buf_GetAll(v->val, NULL), 1);
457 Error("Cannot set environment flag on non-existant variable %s", name);
462 *-----------------------------------------------------------------------
464 * The variable of the given name has the given value appended to it in
471 * If the variable doesn't exist, it is created. Else the strings
472 * are concatenated (with a space in between).
475 * Only if the variable is being sought in the global context is the
476 * environment searched.
477 * XXX: Knows its calling circumstances in that if called with ctxt
478 * an actual target, it will only search that context since only
479 * a local variable could be being appended to. This is actually
480 * a big win and must be tolerated.
481 *-----------------------------------------------------------------------
484 Var_Append(const char *name, const char *val, GNode *ctxt)
489 n = VarPossiblyExpand(name, ctxt);
490 v = VarFind(n, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
492 VarAdd(n, val, ctxt);
494 Buf_AddByte(v->val, (Byte)' ');
495 Buf_Append(v->val, val);
497 DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n,
498 (char *)Buf_GetAll(v->val, (size_t *)NULL)));
500 if (v->flags & VAR_FROM_ENV) {
502 * If the original variable came from the environment, we
503 * have to install it in the global context (we could place
504 * it in the environment, but then we should provide a way to
505 * export other variables...)
507 v->flags &= ~VAR_FROM_ENV;
508 Lst_AtFront(&ctxt->context, v);
515 *-----------------------------------------------------------------------
517 * See if the given variable exists.
520 * TRUE if it does, FALSE if it doesn't
525 *-----------------------------------------------------------------------
528 Var_Exists(const char *name, GNode *ctxt)
533 n = VarPossiblyExpand(name, ctxt);
534 v = VarFind(n, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
539 } else if (v->flags & VAR_FROM_ENV) {
546 *-----------------------------------------------------------------------
548 * Return the value of the named variable in the given context
551 * The value if the variable exists, NULL if it doesn't
555 *-----------------------------------------------------------------------
558 Var_Value(const char *name, GNode *ctxt, char **frp)
563 n = VarPossiblyExpand(name, ctxt);
564 v = VarFind(n, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
568 char *p = (char *)Buf_GetAll(v->val, (size_t *)NULL);
570 if (v->flags & VAR_FROM_ENV) {
571 VarDestroy(v, FALSE);
581 *-----------------------------------------------------------------------
583 * Modify each of the words of the passed string using the given
584 * function. Used to implement all modifiers.
587 * A string of all the words modified appropriately.
592 *-----------------------------------------------------------------------
595 VarModify(char *str, Boolean (*modProc)(const char *, Boolean, Buffer *, void *), void *datum)
597 Buffer *buf; /* Buffer for the new string */
598 Boolean addSpace; /* TRUE if need to add a space to the
599 * buffer before adding the trimmed
601 char **av; /* word list [first word does not count] */
607 av = brk_string(str, &ac, FALSE);
609 for (i = 1; i < ac; i++)
610 addSpace = (*modProc)(av[i], addSpace, buf, datum);
612 Buf_AddByte(buf, '\0');
613 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
614 Buf_Destroy(buf, FALSE);
619 *-----------------------------------------------------------------------
621 * Sort the words in the string.
624 * str String whose words should be sorted
625 * cmp A comparison function to control the ordering
628 * A string containing the words sorted
633 *-----------------------------------------------------------------------
636 VarSortWords(char *str, int (*cmp)(const void *, const void *))
643 av = brk_string(str, &ac, FALSE);
644 qsort(av + 1, ac - 1, sizeof(char *), cmp);
645 for (i = 1; i < ac; i++) {
646 Buf_Append(buf, av[i]);
647 Buf_AddByte(buf, (Byte)((i < ac - 1) ? ' ' : '\0'));
649 str = (char *)Buf_GetAll(buf, (size_t *)NULL);
650 Buf_Destroy(buf, FALSE);
655 SortIncreasing(const void *l, const void *r)
657 return (strcmp(*(const char* const*)l, *(const char* const*)r));
661 *-----------------------------------------------------------------------
663 * Pass through the tstr looking for 1) escaped delimiters,
664 * '$'s and backslashes (place the escaped character in
665 * uninterpreted) and 2) unescaped $'s that aren't before
666 * the delimiter (expand the variable substitution unless flags
667 * has VAR_NOSUBST set).
668 * Return the expanded string or NULL if the delimiter was missing
669 * If pattern is specified, handle escaped ampersands, and replace
670 * unescaped ampersands with the lhs of the pattern.
673 * A string of all the words modified appropriately.
674 * If length is specified, return the string length of the buffer
675 * If flags is specified and the last character of the pattern is a
676 * $ set the VAR_MATCH_END bit of flags.
680 *-----------------------------------------------------------------------
683 VarGetPattern(GNode *ctxt, int err, char **tstr, int delim, int *flags,
684 size_t *length, VarPattern *pattern)
687 Buffer *buf = Buf_Init(0);
693 #define IS_A_MATCH(cp, delim) \
694 ((cp[0] == '\\') && ((cp[1] == delim) || \
695 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
698 * Skim through until the matching delimiter is found;
699 * pick up variable substitutions on the way. Also allow
700 * backslashes to quote the delimiter, $, and \, but don't
701 * touch other backslashes.
703 for (cp = *tstr; *cp && (*cp != delim); cp++) {
704 if (IS_A_MATCH(cp, delim)) {
705 Buf_AddByte(buf, (Byte)cp[1]);
707 } else if (*cp == '$') {
708 if (cp[1] == delim) {
710 Buf_AddByte(buf, (Byte)*cp);
713 * Unescaped $ at end of pattern => anchor
716 *flags |= VAR_MATCH_END;
718 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
724 * If unescaped dollar sign not before the
725 * delimiter, assume it's a variable
726 * substitution and recurse.
728 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
729 Buf_Append(buf, cp2);
736 if (*cp2 == '(' || *cp2 == '{') {
738 * Find the end of this variable reference
739 * and suck it in without further ado.
740 * It will be interperated later.
743 int want = (*cp2 == '(') ? ')' : '}';
746 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
747 if (cp2[-1] != '\\') {
754 Buf_AppendRange(buf, cp, cp2);
757 Buf_AddByte(buf, (Byte)*cp);
761 else if (pattern && *cp == '&')
762 Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
764 Buf_AddByte(buf, (Byte)*cp);
767 Buf_AddByte(buf, (Byte)'\0');
775 cp = (char *)Buf_GetAll(buf, length);
776 *length -= 1; /* Don't count the NULL */
777 Buf_Destroy(buf, FALSE);
783 *-----------------------------------------------------------------------
785 * Quote shell meta-characters in the string
793 *-----------------------------------------------------------------------
796 Var_Quote(const char *str)
799 /* This should cover most shells :-( */
800 static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
803 buf = Buf_Init(MAKE_BSIZE);
804 for (; *str; str++) {
805 if (strchr(meta, *str) != NULL)
806 Buf_AddByte(buf, (Byte)'\\');
807 Buf_AddByte(buf, (Byte)*str);
809 Buf_AddByte(buf, (Byte)'\0');
810 ret = Buf_GetAll(buf, NULL);
811 Buf_Destroy(buf, FALSE);
816 *-----------------------------------------------------------------------
818 * Print the error caused by a regcomp or regexec call.
824 * An error gets printed.
826 *-----------------------------------------------------------------------
829 VarREError(int err, regex_t *pat, const char *str)
834 errlen = regerror(err, pat, 0, 0);
835 errbuf = emalloc(errlen);
836 regerror(err, pat, errbuf, errlen);
837 Error("%s: %s", str, errbuf);
842 *-----------------------------------------------------------------------
844 * Given the start of a variable invocation, extract the variable
845 * name and find its value, then modify it according to the
849 * The (possibly-modified) value of the variable or var_Error if the
850 * specification is invalid. The length of the specification is
851 * placed in *lengthPtr (for invalid specifications, this is just
852 * 2 to skip the '$' and the following letter, or 1 if '$' was the
853 * last character in the string).
854 * A Boolean in *freePtr telling whether the returned string should
855 * be freed by the caller.
860 *-----------------------------------------------------------------------
863 Var_Parse(char *str, GNode *ctxt, Boolean err, size_t *lengthPtr, Boolean *freePtr)
865 char *tstr; /* Pointer into str */
866 Var *v; /* Variable in invocation */
867 char *cp; /* Secondary pointer into str (place marker
869 Boolean haveModifier;/* TRUE if have modifiers for the variable */
870 char endc; /* Ending character when variable in parens
872 char startc=0; /* Starting character when variable in parens
874 int cnt; /* Used to count brace pairs when variable in
875 * in parens or braces */
878 Boolean dynamic; /* TRUE if the variable is local and we're
879 * expanding it in a non-local context. This
880 * is done to support dynamic sources. The
881 * result is just the invocation, unaltered */
882 int vlen; /* length of variable name, after embedded variable
889 if (str[1] != '(' && str[1] != '{') {
891 * If it's not bounded by braces of some sort, life is much simpler.
892 * We just need to check for the first character and return the
893 * value if it exists.
900 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
901 if (v == (Var *)NULL) {
907 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
909 * If substituting a local variable in a non-local context,
910 * assume it's for dynamic source stuff. We have to handle
911 * this specially and return the longhand for the variable
912 * with the dollar sign escaped so it makes it back to the
913 * caller. Only four of the local variables are treated
914 * specially as they are the only four that will be set
915 * when dynamic sources are expanded.
917 /* XXX: It looks like $% and $! are reversed here */
920 return ("$(.TARGET)");
922 return ("$(.ARCHIVE)");
924 return ("$(.PREFIX)");
926 return ("$(.MEMBER)");
934 return (err ? var_Error : varNoError);
936 haveModifier = FALSE;
941 /* build up expanded variable name in this buffer */
942 Buffer *buf = Buf_Init(MAKE_BSIZE);
945 endc = startc == '(' ? ')' : '}';
948 * Skip to the end character or a colon, whichever comes first,
949 * replacing embedded variables as we go.
951 for (tstr = str + 2; *tstr != '\0' && *tstr != endc && *tstr != ':'; tstr++)
955 char* rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
957 if (rval == var_Error) {
958 Fatal("Error expanding embedded variable.");
959 } else if (rval != NULL) {
960 Buf_Append(buf, rval);
966 Buf_AddByte(buf, (Byte)*tstr);
970 * If we never did find the end character, return NULL
971 * right now, setting the length to be the distance to
972 * the end of the string, since that's what make does.
974 *lengthPtr = tstr - str;
978 haveModifier = (*tstr == ':');
981 Buf_AddByte(buf, (Byte)'\0');
982 str = Buf_GetAll(buf, (size_t *)NULL);
985 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
986 if ((v == (Var *)NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
987 (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
990 * Check for bogus D and F forms of local variables since we're
991 * in a local context and the name is the right length.
1005 * Well, it's local -- go look for it.
1009 v = VarFind(vname, ctxt, 0);
1011 if (v != NULL && !haveModifier) {
1013 * No need for nested expansion or anything, as we're
1014 * the only one who sets these things and we sure don't
1015 * put nested invocations in them...
1017 val = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1019 if (str[1] == 'D') {
1020 val = VarModify(val, VarHead, (void *)NULL);
1022 val = VarModify(val, VarTail, (void *)NULL);
1025 * Resulting string is dynamically allocated, so
1026 * tell caller to free it.
1029 *lengthPtr = tstr-start+1;
1031 Buf_Destroy(buf, TRUE);
1041 if (v == (Var *)NULL) {
1043 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
1044 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1047 * If substituting a local variable in a non-local context,
1048 * assume it's for dynamic source stuff. We have to handle
1049 * this specially and return the longhand for the variable
1050 * with the dollar sign escaped so it makes it back to the
1051 * caller. Only four of the local variables are treated
1052 * specially as they are the only four that will be set
1053 * when dynamic sources are expanded.
1065 } else if ((vlen > 2) && (str[0] == '.') &&
1066 isupper((unsigned char)str[1]) &&
1067 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
1072 if ((strncmp(str, ".TARGET", len) == 0) ||
1073 (strncmp(str, ".ARCHIVE", len) == 0) ||
1074 (strncmp(str, ".PREFIX", len) == 0) ||
1075 (strncmp(str, ".MEMBER", len) == 0))
1081 if (!haveModifier) {
1083 * No modifiers -- have specification length so we can return
1086 *lengthPtr = tstr - start + 1;
1089 str = emalloc(*lengthPtr + 1);
1090 strncpy(str, start, *lengthPtr);
1091 str[*lengthPtr] = '\0';
1093 Buf_Destroy(buf, TRUE);
1096 Buf_Destroy(buf, TRUE);
1097 return (err ? var_Error : varNoError);
1101 * Still need to get to the end of the variable specification,
1102 * so kludge up a Var structure for the modifications
1104 v = VarCreate(str, NULL, VAR_JUNK);
1107 Buf_Destroy(buf, TRUE);
1110 if (v->flags & VAR_IN_USE) {
1111 Fatal("Variable %s is recursive.", v->name);
1114 v->flags |= VAR_IN_USE;
1117 * Before doing any modification, we have to make sure the value
1118 * has been fully expanded. If it looks like recursion might be
1119 * necessary (there's a dollar sign somewhere in the variable's value)
1120 * we just call Var_Subst to do any other substitutions that are
1121 * necessary. Note that the value returned by Var_Subst will have
1122 * been dynamically-allocated, so it will need freeing when we
1125 str = (char *)Buf_GetAll(v->val, (size_t *)NULL);
1126 if (strchr(str, '$') != (char *)NULL) {
1127 str = Var_Subst(NULL, str, ctxt, err);
1131 v->flags &= ~VAR_IN_USE;
1134 * Now we need to apply any modifiers the user wants applied.
1136 * :M<pattern> words which match the given <pattern>.
1137 * <pattern> is of the standard file
1139 * :S<d><pat1><d><pat2><d>[g]
1140 * Substitute <pat2> for <pat1> in the value
1141 * :C<d><pat1><d><pat2><d>[g]
1142 * Substitute <pat2> for regex <pat1> in the value
1143 * :H Substitute the head of each word
1144 * :T Substitute the tail of each word
1145 * :E Substitute the extension (minus '.') of
1147 * :R Substitute the root of each word
1148 * (pathname minus the suffix).
1149 * :lhs=rhs Like :S, but the rhs goes to the end of
1151 * :U Converts variable to upper-case.
1152 * :L Converts variable to lower-case.
1154 if ((str != NULL) && haveModifier) {
1156 * Skip initial colon while putting it back.
1159 while (*tstr != endc) {
1160 char *newStr; /* New value to return */
1161 char termc; /* Character which terminated scan */
1163 DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *tstr, str));
1174 *cp != '\0' && *cp != ':' && *cp != endc;
1177 if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)) {
1186 * Need to compress the \:'s out of the pattern, so
1187 * allocate enough room to hold the uncompressed
1188 * pattern (note that cp started at tstr+1, so
1189 * cp - tstr takes the null byte into account) and
1190 * compress the pattern into the space.
1192 pattern = emalloc(cp - tstr);
1193 for (cp2 = pattern, cp = tstr + 1;
1197 if ((*cp == '\\') &&
1198 (cp[1] == ':' || cp[1] == endc)) {
1207 if (*tstr == 'M' || *tstr == 'm') {
1208 newStr = VarModify(str, VarMatch, pattern);
1210 newStr = VarModify(str, VarNoMatch, pattern);
1221 Buffer *buf; /* Buffer for patterns */
1228 * If pattern begins with '^', it is anchored to the
1229 * start of the word -- skip over it and flag pattern.
1232 pattern.flags |= VAR_MATCH_START;
1239 * Pass through the lhs looking for 1) escaped delimiters,
1240 * '$'s and backslashes (place the escaped character in
1241 * uninterpreted) and 2) unescaped $'s that aren't before
1242 * the delimiter (expand the variable substitution).
1243 * The result is left in the Buffer buf.
1245 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1246 if ((*cp == '\\') &&
1251 Buf_AddByte(buf, (Byte)cp[1]);
1253 } else if (*cp == '$') {
1256 * If unescaped dollar sign not before the
1257 * delimiter, assume it's a variable
1258 * substitution and recurse.
1264 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1265 Buf_Append(buf, cp2);
1272 * Unescaped $ at end of pattern => anchor
1275 pattern.flags |= VAR_MATCH_END;
1278 Buf_AddByte(buf, (Byte)*cp);
1282 Buf_AddByte(buf, (Byte)'\0');
1285 * If lhs didn't end with the delimiter, complain and
1289 Fatal("Unclosed substitution for %s (%c missing)",
1294 * Fetch pattern and destroy buffer, but preserve the data
1295 * in it, since that's our lhs. Note that Buf_GetAll
1296 * will return the actual number of bytes, which includes
1297 * the null byte, so we have to decrement the length by
1300 pattern.lhs = (char *)Buf_GetAll(buf, &pattern.leftLen);
1302 Buf_Destroy(buf, FALSE);
1305 * Now comes the replacement string. Three things need to
1306 * be done here: 1) need to compress escaped delimiters and
1307 * ampersands and 2) need to replace unescaped ampersands
1308 * with the l.h.s. (since this isn't regexp, we can do
1309 * it right here) and 3) expand any variable substitutions.
1314 for (cp = tstr; *cp != '\0' && *cp != del; cp++) {
1315 if ((*cp == '\\') &&
1321 Buf_AddByte(buf, (Byte)cp[1]);
1323 } else if ((*cp == '$') && (cp[1] != del)) {
1328 cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
1329 Buf_Append(buf, cp2);
1334 } else if (*cp == '&') {
1335 Buf_AddBytes(buf, pattern.leftLen,
1336 (Byte *)pattern.lhs);
1338 Buf_AddByte(buf, (Byte)*cp);
1342 Buf_AddByte(buf, (Byte)'\0');
1345 * If didn't end in delimiter character, complain
1348 Fatal("Unclosed substitution for %s (%c missing)",
1352 pattern.rhs = (char *)Buf_GetAll(buf, &pattern.rightLen);
1354 Buf_Destroy(buf, FALSE);
1357 * Check for global substitution. If 'g' after the final
1358 * delimiter, substitution is global and is marked that
1363 pattern.flags |= VAR_SUB_GLOBAL;
1368 * Global substitution of the empty string causes an
1369 * infinite number of matches, unless anchored by '^'
1370 * (start of string) or '$' (end of string). Catch the
1371 * infinite substitution here.
1372 * Note that flags can only contain the 3 bits we're
1373 * interested in so we don't have to mask unrelated
1374 * bits. We can test for equality.
1376 if (!pattern.leftLen && pattern.flags == VAR_SUB_GLOBAL)
1377 Fatal("Global substitution of the empty string");
1380 newStr = VarModify(str, VarSubstitute, &pattern);
1382 * Free the two strings.
1390 VarREPattern pattern;
1400 if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
1401 NULL, NULL)) == NULL) {
1402 /* was: goto cleanup */
1403 *lengthPtr = cp - start + 1;
1407 Fatal("Unclosed substitution for %s (%c missing)",
1412 if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
1413 delim, NULL, NULL, NULL)) == NULL){
1416 /* was: goto cleanup */
1417 *lengthPtr = cp - start + 1;
1421 Fatal("Unclosed substitution for %s (%c missing)",
1429 pattern.flags |= VAR_SUB_GLOBAL;
1432 pattern.flags |= VAR_SUB_ONE;
1442 error = regcomp(&pattern.re, re, REG_EXTENDED);
1445 *lengthPtr = cp - start + 1;
1446 VarREError(error, &pattern.re, "RE substitution error");
1447 free(pattern.replace);
1451 pattern.nsub = pattern.re.re_nsub + 1;
1452 if (pattern.nsub < 1)
1454 if (pattern.nsub > 10)
1456 pattern.matches = emalloc(pattern.nsub *
1457 sizeof(regmatch_t));
1458 newStr = VarModify(str, VarRESubstitute, &pattern);
1459 regfree(&pattern.re);
1460 free(pattern.replace);
1461 free(pattern.matches);
1465 if (tstr[1] == endc || tstr[1] == ':') {
1467 buf = Buf_Init(MAKE_BSIZE);
1468 for (cp = str; *cp ; cp++)
1469 Buf_AddByte(buf, (Byte)tolower(*cp));
1471 Buf_AddByte(buf, (Byte)'\0');
1472 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1473 Buf_Destroy(buf, FALSE);
1481 if (tstr[1] == endc || tstr[1] == ':') {
1482 newStr = VarSortWords(str, SortIncreasing);
1489 if (tstr[1] == endc || tstr[1] == ':') {
1490 newStr = Var_Quote(str);
1497 if (tstr[1] == endc || tstr[1] == ':') {
1498 newStr = VarModify(str, VarTail, (void *)NULL);
1505 if (tstr[1] == endc || tstr[1] == ':') {
1507 buf = Buf_Init(MAKE_BSIZE);
1508 for (cp = str; *cp ; cp++)
1509 Buf_AddByte(buf, (Byte)toupper(*cp));
1511 Buf_AddByte(buf, (Byte)'\0');
1512 newStr = (char *)Buf_GetAll(buf, (size_t *)NULL);
1513 Buf_Destroy(buf, FALSE);
1521 if (tstr[1] == endc || tstr[1] == ':') {
1522 newStr = VarModify(str, VarHead, (void *)NULL);
1529 if (tstr[1] == endc || tstr[1] == ':') {
1530 newStr = VarModify(str, VarSuffix, (void *)NULL);
1537 if (tstr[1] == endc || tstr[1] == ':') {
1538 newStr = VarModify(str, VarRoot, (void *)NULL);
1546 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
1549 Buffer *buf = Cmd_Exec(str, &error);
1550 newStr = Buf_GetAll(buf, NULL);
1551 Buf_Destroy(buf, FALSE);
1565 * This can either be a bogus modifier or a System-V
1566 * substitution command.
1574 * First we make a pass through the string trying
1575 * to verify it is a SYSV-make-style translation:
1576 * it must be: <string1>=<string2>)
1580 while (*cp != '\0' && cnt) {
1583 /* continue looking for endc */
1585 else if (*cp == endc)
1587 else if (*cp == startc)
1592 if (*cp == endc && eqFound) {
1595 * Now we break this sucker into the lhs and
1596 * rhs. We must null terminate them of course.
1601 if ((pattern.lhs = VarGetPattern(ctxt,
1602 err, &cp, delim, &pattern.flags, &pattern.leftLen,
1604 /* was: goto cleanup */
1605 *lengthPtr = cp - start + 1;
1609 Fatal("Unclosed substitution for %s (%c missing)",
1615 if ((pattern.rhs = VarGetPattern(ctxt,
1616 err, &cp, delim, NULL, &pattern.rightLen,
1617 &pattern)) == NULL) {
1618 /* was: goto cleanup */
1619 *lengthPtr = cp - start + 1;
1623 Fatal("Unclosed substitution for %s (%c missing)",
1629 * SYSV modifications happen through the whole
1630 * string. Note the pattern is anchored at the end.
1634 newStr = VarModify(str, VarSYSVMatch, &pattern);
1643 Error("Unknown modifier '%c'\n", *tstr);
1645 *cp != ':' && *cp != endc && *cp != '\0';
1653 DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
1659 if (str != var_Error) {
1664 if (termc == '\0') {
1665 Error("Unclosed variable specification for %s", v->name);
1666 } else if (termc == ':') {
1673 *lengthPtr = tstr - start + 1;
1675 *lengthPtr = tstr - start + 1;
1679 if (v->flags & VAR_FROM_ENV) {
1680 Boolean destroy = FALSE;
1682 if (str != (char *)Buf_GetAll(v->val, (size_t *)NULL)) {
1686 * Returning the value unmodified, so tell the caller to free
1691 VarDestroy(v, destroy);
1692 } else if (v->flags & VAR_JUNK) {
1694 * Perform any free'ing needed and set *freePtr to FALSE so the caller
1695 * doesn't try to free a static pointer.
1701 VarDestroy(v, TRUE);
1703 str = emalloc(*lengthPtr + 1);
1704 strncpy(str, start, *lengthPtr);
1705 str[*lengthPtr] = '\0';
1708 str = err ? var_Error : varNoError;
1715 *-----------------------------------------------------------------------
1717 * Substitute for all variables in the given string in the given context
1718 * If undefErr is TRUE, Parse_Error will be called when an undefined
1719 * variable is encountered.
1722 * The resulting string.
1725 * None. The old string must be freed by the caller
1726 *-----------------------------------------------------------------------
1729 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
1731 Buffer *buf; /* Buffer for forming things */
1732 char *val; /* Value to substitute for a variable */
1733 size_t length; /* Length of the variable invocation */
1734 Boolean doFree; /* Set true if val should be freed */
1736 static Boolean errorReported;/* Set true if an error has already
1737 * been reported to prevent a plethora
1738 * of messages when recursing */
1740 buf = Buf_Init(MAKE_BSIZE);
1741 errorReported = FALSE;
1744 if (var == NULL && (*str == '$') && (str[1] == '$')) {
1746 * A dollar sign may be escaped either with another dollar sign.
1747 * In such a case, we skip over the escape character and store the
1748 * dollar sign into the buffer directly.
1751 Buf_AddByte(buf, (Byte)*str);
1753 } else if (*str != '$') {
1755 * Skip as many characters as possible -- either to the end of
1756 * the string or to the next dollar sign (variable invocation).
1760 for (cp = str++; *str != '$' && *str != '\0'; str++)
1762 Buf_AppendRange(buf, cp, str);
1767 if (str[1] != '(' && str[1] != '{') {
1768 if (str[1] != *var || var[1] != '\0') {
1769 Buf_AddBytes(buf, 2, (const Byte *)str);
1780 * Scan up to the end of the variable name.
1782 for (p = &str[2]; *p &&
1783 *p != ':' && *p != ')' && *p != '}'; p++)
1787 * A variable inside the variable. We cannot expand
1788 * the external variable yet, so we try again with
1792 Buf_AppendRange(buf, str, p);
1797 if (strncmp(var, str + 2, p - str - 2) != 0 ||
1798 var[p - str - 2] != '\0') {
1800 * Not the variable we want to expand, scan
1801 * until the next variable
1803 for (;*p != '$' && *p != '\0'; p++)
1805 Buf_AppendRange(buf, str, p);
1818 val = Var_Parse(str, ctxt, undefErr, &length, &doFree);
1821 * When we come down here, val should either point to the
1822 * value of this variable, suitably modified, or be NULL.
1823 * Length should be the total length of the potential
1824 * variable invocation (from $ to end character...)
1826 if (val == var_Error || val == varNoError) {
1828 * If performing old-time variable substitution, skip over
1829 * the variable and continue with the substitution. Otherwise,
1830 * store the dollar sign and advance str so we continue with
1835 } else if (undefErr) {
1837 * If variable is undefined, complain and skip the
1838 * variable. The complaint will stop us from doing anything
1839 * when the file is parsed.
1841 if (!errorReported) {
1842 Parse_Error(PARSE_FATAL,
1843 "Undefined variable \"%.*s\"",length,str);
1846 errorReported = TRUE;
1848 Buf_AddByte(buf, (Byte)*str);
1853 * We've now got a variable structure to store in. But first,
1854 * advance the string pointer.
1859 * Copy all the characters from the variable value straight
1860 * into the new string.
1862 Buf_Append(buf, val);
1870 Buf_AddByte(buf, '\0');
1871 result = (char *)Buf_GetAll(buf, (size_t *)NULL);
1872 Buf_Destroy(buf, FALSE);
1877 *-----------------------------------------------------------------------
1879 * Return the tail from each of a list of words. Used to set the
1880 * System V local variables.
1883 * The resulting string.
1888 *-----------------------------------------------------------------------
1891 Var_GetTail(char *file)
1893 return (VarModify(file, VarTail, (void *)NULL));
1897 *-----------------------------------------------------------------------
1899 * Find the leading components of a (list of) filename(s).
1900 * XXX: VarHead does not replace foo by ., as (sun) System V make
1904 * The leading components.
1909 *-----------------------------------------------------------------------
1912 Var_GetHead(char *file)
1915 return (VarModify(file, VarHead, (void *)NULL));
1919 *-----------------------------------------------------------------------
1921 * Initialize the module
1927 * The VAR_CMD and VAR_GLOBAL contexts are created
1928 *-----------------------------------------------------------------------
1933 VAR_GLOBAL = Targ_NewGN("Global");
1934 VAR_CMD = Targ_NewGN("Command");
1937 /****************** PRINT DEBUGGING INFO *****************/
1939 VarPrintVar(void *vp, void *dummy __unused)
1941 Var *v = (Var *) vp;
1943 printf("%-16s = %s\n", v->name, (char *)Buf_GetAll(v->val, (size_t *)NULL));
1948 *-----------------------------------------------------------------------
1950 * print all variables in a context
1951 *-----------------------------------------------------------------------
1954 Var_Dump(GNode *ctxt)
1956 Lst_ForEach(&ctxt->context, VarPrintVar, (void *)NULL);