2 * Copyright (c) 2002 Juli Mallett.
3 * Copyright (c) 1988, 1989, 1990, 1993
4 * The Regents of the University of California. All rights reserved.
5 * Copyright (c) 1989 by Berkeley Softworks
8 * This code is derived from software contributed to Berkeley by
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * @(#)var.c 8.3 (Berkeley) 3/19/94
40 * $FreeBSD: src/usr.bin/make/var.c,v 1.83 2005/02/11 10:49:01 harti Exp $
41 * $DragonFly: src/usr.bin/make/var.c,v 1.224 2005/09/24 07:37:38 okumoto Exp $
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_Value Return the value of a variable in a context or
61 * NULL if the variable is undefined.
63 * Var_Subst Substitute named variable, or all variables if
64 * NULL in a string using
65 * the given context as the top-most one. If the
66 * third argument is non-zero, Parse_Error is
67 * called if any variables are undefined.
69 * Var_Parse Parse a variable expansion from a string and
70 * return the result and the number of characters
73 * Var_Delete Delete a variable in a context.
75 * Var_Init Initialize this module.
78 * Var_Dump Print out all variables defined in the given
81 * XXX: There's a lot of duplication in these functions.
88 #include <sys/types.h>
107 typedef struct VarParser
{
108 const char *const input
; /* pointer to input string */
109 const char *ptr
; /* current parser pos in input str */
116 char *name
; /* the variable's name */
117 struct Buffer
*val
; /* its value */
118 int flags
; /* miscellaneous status flags */
120 #define VAR_IN_USE 1 /* Variable's value currently being used.
121 * Used to avoid recursion */
123 #define VAR_JUNK 4 /* Variable is a junk variable that
124 * should be destroyed when done with
125 * it. Used by Var_Parse for undefined,
126 * modified variables */
128 #define VAR_TO_ENV 8 /* Place variable in environment */
132 struct Buffer
*lhs
; /* String to match */
133 struct Buffer
*rhs
; /* Replacement string (w/ &'s removed) */
140 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
141 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
142 #define VAR_SUB_MATCHED 0x04 /* There was a match */
143 #define VAR_MATCH_START 0x08 /* Match at start of word */
144 #define VAR_MATCH_END 0x10 /* Match at end of word */
147 typedef bool VarModifyProc(const char [], bool, struct Buffer
*, void *);
149 static char *VarParse(VarParser
*, bool *);
152 * This is a harmless return value for Var_Parse that can be used by Var_Subst
153 * to determine if there was an error in parsing -- easier than returning
154 * a flag, as things outside this module don't give a hoot.
156 char var_Error
[] = "";
159 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
160 * set false. Why not just use a constant? Well, gcc likes to condense
161 * identical string instances...
163 static char varNoError
[] = "";
166 * Internally, variables are contained in four different contexts.
167 * 1) the environment. They may not be changed. If an environment
168 * variable is appended-to, the result is placed in the global
170 * 2) the global context. Variables set in the Makefile are located in
171 * the global context. It is the penultimate context searched when
173 * 3) the command-line context. All variables set on the command line
174 * are placed in this context. They are UNALTERABLE once placed here.
175 * 4) the local context. Each target has associated with it a context
176 * list. On this list are located the structures describing such
177 * local variables as $(@) and $(*)
178 * The four contexts are searched in the reverse order from which they are
181 static GNode
*VAR_ENV
; /* variables from the environment */
182 GNode
*VAR_GLOBAL
; /* variables from the makefile */
183 GNode
*VAR_CMD
; /* variables defined on the command-line */
185 bool oldVars
; /* variable substitution style */
186 bool checkEnvFirst
; /* -e flag */
189 * Create a Var object.
191 * @param name Name of variable.
192 * @param value Value of variable.
193 * @param flags Flags set on variable.
196 VarCreate(const char name
[], const char value
[], int flags
)
200 v
= emalloc(sizeof(Var
));
201 v
->name
= estrdup(name
);
202 v
->val
= Buf_Init(0);
206 Buf_Append(v
->val
, value
);
212 * Destroy a Var object.
214 * @param v Object to destroy.
215 * @param f true if internal buffer in Buffer object is to be
219 VarDestroy(Var
*v
, bool f
)
222 Buf_Destroy(v
->val
, f
);
228 * Remove the tail of the given word and place the result in the given
232 * true if characters were added to the buffer (a space needs to be
233 * added to the buffer before the next word).
236 * The trimmed word is added to the buffer.
239 VarHead(const char word
[], bool addSpace
, Buffer
*buf
, void *dummy __unused
)
243 slash
= strrchr(word
, '/');
246 Buf_AddByte(buf
, ' ');
248 Buf_AppendRange(buf
, word
, slash
);
251 * If no directory part, give . (q.v. the POSIX standard)
254 Buf_Append(buf
, " .");
256 Buf_AddByte(buf
, '.');
263 * Remove the head of the given word and place the result in the given
267 * true if characters were added to the buffer (a space needs to be
268 * added to the buffer before the next word).
271 * The trimmed word is added to the buffer.
274 VarTail(const char word
[], bool addSpace
, Buffer
*buf
, void *dummy __unused
)
279 Buf_AddByte(buf
, ' ');
282 slash
= strrchr(word
, '/');
285 Buf_Append(buf
, slash
);
287 Buf_Append(buf
, word
);
293 * Place the suffix of the given word in the given buffer.
296 * true if characters were added to the buffer (a space needs to be
297 * added to the buffer before the next word).
300 * The suffix from the word is placed in the buffer.
303 VarSuffix(const char word
[], bool addSpace
, Buffer
*buf
, void *dummy __unused
)
307 dot
= strrchr(word
, '.');
310 Buf_AddByte(buf
, ' ');
313 Buf_Append(buf
, dot
);
320 * Remove the suffix of the given word and place the result in the
324 * true if characters were added to the buffer (a space needs to be
325 * added to the buffer before the next word).
328 * The trimmed word is added to the buffer.
331 VarRoot(const char word
[], bool addSpace
, Buffer
*buf
, void *dummy __unused
)
336 Buf_AddByte(buf
, ' ');
339 dot
= strrchr(word
, '.');
341 Buf_AppendRange(buf
, word
, dot
);
343 Buf_Append(buf
, word
);
349 * Place the word in the buffer if it matches the given pattern.
350 * Callback function for VarModify to implement the :M modifier.
351 * A space will be added if requested. A pattern is supplied
352 * which the word must match.
355 * true if a space should be placed in the buffer before the next
359 * The word may be copied to the buffer.
362 VarMatch(const char word
[], bool addSpace
, Buffer
*buf
, void *pattern
)
365 if (Str_Match(word
, pattern
)) {
367 Buf_AddByte(buf
, ' ');
370 Buf_Append(buf
, word
);
376 * Place the word in the buffer if it matches the given pattern.
377 * Callback function for VarModify to implement the System V %
378 * modifiers. A space is added if requested.
381 * true if a space should be placed in the buffer before the next
385 * The word may be copied to the buffer.
388 VarSYSVMatch(const char word
[], bool addSpace
, Buffer
*buf
, void *patp
)
392 VarPattern
*pat
= (VarPattern
*)patp
;
395 Buf_AddByte(buf
, ' ');
399 if ((ptr
= Str_SYSVMatch(word
, Buf_Data(pat
->lhs
), &len
)) != NULL
)
400 Str_SYSVSubst(buf
, Buf_Data(pat
->rhs
), ptr
, len
);
402 Buf_Append(buf
, word
);
408 * Place the word in the buffer if it doesn't match the given pattern.
409 * Callback function for VarModify to implement the :N modifier. A
410 * space is added if requested.
413 * true if a space should be placed in the buffer before the next
417 * The word may be copied to the buffer.
420 VarNoMatch(const char word
[], bool addSpace
, Buffer
*buf
, void *pattern
)
423 if (!Str_Match(word
, pattern
)) {
425 Buf_AddByte(buf
, ' ');
428 Buf_Append(buf
, word
);
434 * Perform a string-substitution on the given word, placing the
435 * result in the passed buffer. A space is added if requested.
438 * true if a space is needed before more characters are added.
441 VarSubstitute(const char word
[], bool addSpace
, Buffer
*buf
, void *patternp
)
443 size_t wordLen
; /* Length of word */
444 const char *cp
; /* General pointer */
445 VarPattern
*pattern
= patternp
;
447 wordLen
= strlen(word
);
448 if (1) { /* substitute in each word of the variable */
450 * Break substitution down into simple anchored cases
451 * and if none of them fits, perform the general substitution
454 if ((pattern
->flags
& VAR_MATCH_START
) &&
455 (strncmp(word
, Buf_Data(pattern
->lhs
),
456 Buf_Size(pattern
->lhs
)) == 0)) {
458 * Anchored at start and beginning of word matches
461 if ((pattern
->flags
& VAR_MATCH_END
) &&
462 (wordLen
== Buf_Size(pattern
->lhs
))) {
464 * Also anchored at end and matches to the end
465 * (word is same length as pattern) add space
466 * and rhs only if rhs is non-null.
468 if (Buf_Size(pattern
->rhs
) != 0) {
470 Buf_AddByte(buf
, ' ');
473 Buf_AppendBuf(buf
, pattern
->rhs
);
476 } else if (pattern
->flags
& VAR_MATCH_END
) {
478 * Doesn't match to end -- copy word wholesale
484 * Matches at start but need to copy in
485 * trailing characters.
487 if ((Buf_Size(pattern
->rhs
) + wordLen
-
488 Buf_Size(pattern
->lhs
)) != 0) {
490 Buf_AddByte(buf
, ' ');
494 Buf_AppendBuf(buf
, pattern
->rhs
);
495 Buf_AddBytes(buf
, wordLen
-
496 Buf_Size(pattern
->lhs
),
497 (word
+ Buf_Size(pattern
->lhs
)));
500 } else if (pattern
->flags
& VAR_MATCH_START
) {
502 * Had to match at start of word and didn't -- copy
507 } else if (pattern
->flags
& VAR_MATCH_END
) {
509 * Anchored at end, Find only place match could occur
510 * (leftLen characters from the end of the word) and
511 * see if it does. Note that because the $ will be
512 * left at the end of the lhs, we have to use strncmp.
514 cp
= word
+ (wordLen
- Buf_Size(pattern
->lhs
));
515 if ((cp
>= word
) && (strncmp(cp
, Buf_Data(pattern
->lhs
),
516 Buf_Size(pattern
->lhs
)) == 0)) {
518 * Match found. If we will place characters in
519 * the buffer, add a space before hand as
520 * indicated by addSpace, then stuff in the
521 * initial, unmatched part of the word followed
522 * by the right-hand-side.
524 if ((cp
- word
) + Buf_Size(pattern
->rhs
) != 0) {
526 Buf_AddByte(buf
, ' ');
530 Buf_AppendRange(buf
, word
, cp
);
531 Buf_AppendBuf(buf
, pattern
->rhs
);
535 * Had to match at end and didn't. Copy entire
542 * Pattern is unanchored: search for the pattern in the
543 * word using strstr(3), copying unmatched portions and
544 * the right-hand-side for each match found, handling
545 * non-global substitutions correctly, etc. When the
546 * loop is done, any remaining part of the word (word
547 * and wordLen are adjusted accordingly through the
548 * loop) is copied straight into the buffer.
549 * addSpace is set false as soon as a space is added
556 origSize
= Buf_Size(buf
);
558 cp
= strstr(word
, Buf_Data(pattern
->lhs
));
560 if (addSpace
&& (((cp
- word
) +
561 Buf_Size(pattern
->rhs
)) != 0)) {
562 Buf_AddByte(buf
, ' ');
565 Buf_AppendRange(buf
, word
, cp
);
566 Buf_AppendBuf(buf
, pattern
->rhs
);
567 wordLen
-= (cp
- word
) +
568 Buf_Size(pattern
->lhs
);
569 word
= cp
+ Buf_Size(pattern
->lhs
);
570 if (wordLen
== 0 || (pattern
->flags
&
571 VAR_SUB_GLOBAL
) == 0) {
580 Buf_AddByte(buf
, ' ');
582 Buf_AddBytes(buf
, wordLen
, word
);
586 * If added characters to the buffer, need to add a
587 * space before we add any more. If we didn't add any,
588 * just return the previous value of addSpace.
590 return ((Buf_Size(buf
) != origSize
) || addSpace
);
593 * Common code for anchored substitutions:
594 * addSpace was set true if characters were added to the buffer.
600 Buf_AddByte(buf
, ' ');
602 Buf_AddBytes(buf
, wordLen
, word
);
607 * Print the error caused by a regcomp or regexec call.
610 * An error gets printed.
613 VarREError(int err
, regex_t
*pat
, const char str
[])
618 errlen
= regerror(err
, pat
, 0, 0);
619 errbuf
= emalloc(errlen
);
620 regerror(err
, pat
, errbuf
, errlen
);
621 Error("%s: %s", str
, errbuf
);
627 * Perform a regex substitution on the given word, placing the
628 * result in the passed buffer. A space is added if requested.
631 * true if a space is needed before more characters are added.
634 VarRESubstitute(const char word
[], bool addSpace
, Buffer
*buf
, void *patternp
)
643 #define MAYBE_ADD_SPACE() \
644 if (addSpace && !added) \
645 Buf_AddByte(buf, ' '); \
652 if ((pat
->flags
& (VAR_SUB_ONE
| VAR_SUB_MATCHED
)) ==
653 (VAR_SUB_ONE
| VAR_SUB_MATCHED
)) {
657 xrv
= regexec(&pat
->re
, wp
, pat
->nsub
, pat
->matches
, flags
);
662 pat
->flags
|= VAR_SUB_MATCHED
;
663 if (pat
->matches
[0].rm_so
> 0) {
665 Buf_AddBytes(buf
, pat
->matches
[0].rm_so
, wp
);
668 for (rp
= Buf_Data(pat
->rhs
); *rp
; rp
++) {
669 if ((*rp
== '\\') && ((rp
[1] == '&') || (rp
[1] == '\\'))) {
671 Buf_AddByte(buf
, rp
[1]);
674 } else if ((*rp
== '&') ||
675 ((*rp
== '\\') && isdigit((unsigned char)rp
[1]))) {
694 Error("No subexpression %s",
699 } else if ((pat
->matches
[n
].rm_so
== -1) &&
700 (pat
->matches
[n
].rm_eo
== -1)) {
701 Error("No match for subexpression %s",
707 subbuf
= wp
+ pat
->matches
[n
].rm_so
;
708 sublen
= pat
->matches
[n
].rm_eo
-
709 pat
->matches
[n
].rm_so
;
714 Buf_AddBytes(buf
, sublen
, subbuf
);
718 Buf_AddByte(buf
, *rp
);
721 wp
+= pat
->matches
[0].rm_eo
;
722 if (pat
->flags
& VAR_SUB_GLOBAL
) {
724 if (pat
->matches
[0].rm_so
== 0 &&
725 pat
->matches
[0].rm_eo
== 0) {
727 Buf_AddByte(buf
, *wp
);
740 VarREError(xrv
, &pat
->re
, "Unexpected regex error");
750 return (addSpace
|| added
);
754 * Find a variable in a variable list.
757 VarLookup(Lst
*vlist
, const char name
[])
761 LST_FOREACH(ln
, vlist
)
762 if (strcmp(((const Var
*)Lst_Datum(ln
))->name
, name
) == 0)
763 return (Lst_Datum(ln
));
768 * Expand a variable name's embedded variables in the given context.
771 * The contents of name, possibly expanded.
774 VarPossiblyExpand(const char name
[], GNode
*ctxt
)
778 if (strchr(name
, '$') != NULL
) {
779 buf
= Var_Subst(name
, ctxt
, 0);
780 return (Buf_Peel(buf
));
782 return estrdup(name
);
787 * If the variable name begins with a '.', it could very well be
788 * one of the local ones. We check the name against all the local
789 * variables and substitute the short version in for 'name' if it
790 * matches one of them.
793 VarLocal(const char name
[])
795 if (name
[0] == '.') {
798 if (!strcmp(name
, ".ALLSRC"))
800 if (!strcmp(name
, ".ARCHIVE"))
804 if (!strcmp(name
, ".IMPSRC"))
808 if (!strcmp(name
, ".MEMBER"))
812 if (!strcmp(name
, ".OODATE"))
816 if (!strcmp(name
, ".PREFIX"))
820 if (!strcmp(name
, ".TARGET"))
831 * Find the given variable in the given context and the environment.
834 * A pointer to the structure describing the desired variable or
835 * NULL if the variable does not exist.
838 VarFindEnv(const char name
[], GNode
*ctxt
)
842 name
= VarLocal(name
);
844 if ((var
= VarLookup(&ctxt
->context
, name
)) != NULL
)
847 if ((var
= VarLookup(&VAR_ENV
->context
, name
)) != NULL
)
854 * Look for the variable in the given context.
857 VarFindOnly(const char name
[], GNode
*ctxt
)
860 return (VarLookup(&ctxt
->context
, VarLocal(name
)));
864 * Look for the variable in all contexts.
867 VarFindAny(const char name
[], GNode
*ctxt
)
869 bool localCheckEnvFirst
;
873 name
= VarLocal(name
);
876 * Note whether this is one of the specific variables we were told
877 * through the -E flag to use environment-variable-override for.
879 localCheckEnvFirst
= false;
880 LST_FOREACH(ln
, &envFirstVars
) {
881 if (strcmp(Lst_Datum(ln
), name
) == 0) {
882 localCheckEnvFirst
= true;
888 * First look for the variable in the given context. If it's not there,
889 * look for it in VAR_CMD, VAR_GLOBAL and the environment,
890 * in that order, depending on the FIND_* flags in 'flags'
892 if ((var
= VarLookup(&ctxt
->context
, name
)) != NULL
)
895 /* not there - try command line context */
896 if (ctxt
!= VAR_CMD
) {
897 if ((var
= VarLookup(&VAR_CMD
->context
, name
)) != NULL
)
901 /* not there - try global context, but only if not -e/-E */
902 if (ctxt
!= VAR_GLOBAL
&& (!checkEnvFirst
&& !localCheckEnvFirst
)) {
903 if ((var
= VarLookup(&VAR_GLOBAL
->context
, name
)) != NULL
)
907 if ((var
= VarLookup(&VAR_ENV
->context
, name
)) != NULL
)
910 /* deferred check for the environment (in case of -e/-E) */
911 if ((ctxt
!= VAR_GLOBAL
) && (checkEnvFirst
|| localCheckEnvFirst
)) {
912 if ((var
= VarLookup(&VAR_GLOBAL
->context
, name
)) != NULL
)
920 * Add a new variable of name name and value val to the given context.
923 * The new variable is placed at the front of the given context
924 * The name and val arguments are duplicated so they may
928 VarAdd(const char name
[], const char val
[], GNode
*ctxt
)
931 Lst_AtFront(&ctxt
->context
, VarCreate(name
, val
, 0));
932 DEBUGF(VAR
, ("%s:%s = %s\n", ctxt
->name
, name
, val
));
936 * Remove a variable from a context.
939 * The Var structure is removed and freed.
942 Var_Delete(const char name
[], GNode
*ctxt
)
946 DEBUGF(VAR
, ("%s:delete %s\n", ctxt
->name
, name
));
947 LST_FOREACH(ln
, &ctxt
->context
) {
948 if (strcmp(((const Var
*)Lst_Datum(ln
))->name
, name
) == 0) {
949 VarDestroy(Lst_Datum(ln
), true);
950 Lst_Remove(&ctxt
->context
, ln
);
957 * Set the variable name to the value val in the given context.
960 * If the variable doesn't yet exist, a new record is created for it.
961 * Else the old value is freed and the new one stuck in its place
964 * The variable is searched for only in its context before being
965 * created in that context. I.e. if the context is VAR_GLOBAL,
966 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
967 * VAR_CMD->context is searched. This is done to avoid the literally
968 * thousands of unnecessary strcmp's that used to be done to
969 * set, say, $(@) or $(<).
972 Var_Set(const char name
[], const char val
[], GNode
*ctxt
)
978 * We only look for a variable in the given context since anything
979 * set here will override anything in a lower context, so there's not
980 * much point in searching them all just to save a bit of memory...
982 n
= VarPossiblyExpand(name
, ctxt
);
983 v
= VarFindOnly(n
, ctxt
);
985 VarAdd(n
, val
, ctxt
);
986 if (ctxt
== VAR_CMD
) {
988 * Any variables given on the command line
989 * are automatically exported to the
990 * environment (as per POSIX standard)
992 if (setenv(n
, val
, 1) == -1)
993 Punt( "setenv: %s: can't allocate memory", n
);
997 Buf_Append(v
->val
, val
);
999 if (ctxt
== VAR_CMD
|| (v
->flags
& VAR_TO_ENV
)) {
1001 * Any variables given on the command line
1002 * are automatically exported to the
1003 * environment (as per POSIX standard)
1005 if (setenv(n
, val
, 1) == -1)
1006 Punt( "setenv: %s: can't allocate memory", n
);
1011 DEBUGF(VAR
, ("%s:%s = %s\n", ctxt
->name
, n
, val
));
1016 * Set the a global name variable to the value.
1019 Var_SetGlobal(const char name
[], const char value
[])
1022 Var_Set(name
, value
, VAR_GLOBAL
);
1027 * Set the VAR_TO_ENV flag on a variable
1030 Var_SetEnv(const char name
[], GNode
*ctxt
)
1034 v
= VarFindOnly(name
, VAR_CMD
);
1037 * Do not allow .EXPORT: to be set on variables
1038 * from the command line or MAKEFLAGS.
1041 "Warning: Did not set .EXPORTVAR: on %s because it "
1042 "is from the command line or MAKEFLAGS", name
);
1046 v
= VarFindAny(name
, ctxt
);
1048 Lst_AtFront(&VAR_ENV
->context
,
1049 VarCreate(name
, NULL
, VAR_TO_ENV
));
1050 if (setenv(name
, "", 1) == -1)
1051 Punt( "setenv: %s: can't allocate memory", name
);
1052 Error("Warning: .EXPORTVAR: set on undefined variable %s", name
);
1054 if ((v
->flags
& VAR_TO_ENV
) == 0) {
1055 v
->flags
|= VAR_TO_ENV
;
1056 if (setenv(v
->name
, Buf_Data(v
->val
), 1) == -1)
1057 Punt( "setenv: %s: can't allocate memory", v
->name
);
1063 * The variable of the given name has the given value appended to it in
1064 * the given context.
1067 * If the variable doesn't exist, it is created. Else the strings
1068 * are concatenated (with a space in between).
1071 * Only if the variable is being sought in the global context is the
1072 * environment searched.
1073 * XXX: Knows its calling circumstances in that if called with ctxt
1074 * an actual target, it will only search that context since only
1075 * a local variable could be being appended to. This is actually
1076 * a big win and must be tolerated.
1079 Var_Append(const char name
[], const char val
[], GNode
*ctxt
)
1084 n
= VarPossiblyExpand(name
, ctxt
);
1085 if (ctxt
== VAR_GLOBAL
) {
1086 v
= VarFindEnv(n
, ctxt
);
1088 v
= VarFindOnly(n
, ctxt
);
1091 VarAdd(n
, val
, ctxt
);
1093 Buf_AddByte(v
->val
, ' ');
1094 Buf_Append(v
->val
, val
);
1095 DEBUGF(VAR
, ("%s:%s = %s\n", ctxt
->name
, n
, Buf_Data(v
->val
)));
1101 * Return the value of the named variable in the given context
1104 * The value if the variable exists, NULL if it doesn't.
1107 Var_Value(const char name
[], GNode
*ctxt
)
1112 n
= VarPossiblyExpand(name
, ctxt
);
1113 v
= VarFindAny(n
, ctxt
);
1118 return (Buf_Data(v
->val
));
1123 * Modify each of the words of the passed string using the given
1124 * function. Used to implement all modifiers.
1127 * A string of all the words modified appropriately.
1130 VarModify(const char str
[], VarModifyProc
*modProc
, void *datum
)
1133 Buffer
*buf
; /* Buffer for the new string */
1136 * true if need to add a space to
1137 * the buffer before adding the
1141 brk_string(&aa
, str
, false);
1145 for (i
= 1; i
< aa
.argc
; i
++)
1146 addSpace
= (*modProc
)(aa
.argv
[i
], addSpace
, buf
, datum
);
1149 return (Buf_Peel(buf
));
1153 * Sort the words in the string.
1156 * str String whose words should be sorted
1157 * cmp A comparison function to control the ordering
1160 * A string containing the words sorted
1163 VarSortWords(const char str
[], int (*cmp
)(const void *, const void *))
1169 brk_string(&aa
, str
, false);
1170 qsort(aa
.argv
+ 1, aa
.argc
- 1, sizeof(char *), cmp
);
1173 for (i
= 1; i
< aa
.argc
; i
++) {
1174 Buf_Append(buf
, aa
.argv
[i
]);
1175 Buf_AddByte(buf
, ((i
< aa
.argc
- 1) ? ' ' : '\0'));
1179 return (Buf_Peel(buf
));
1183 SortIncreasing(const void *l
, const void *r
)
1186 return (strcmp(*(const char* const*)l
, *(const char* const*)r
));
1190 * Pass through the tstr looking for 1) escaped delimiters,
1191 * '$'s and backslashes (place the escaped character in
1192 * uninterpreted) and 2) unescaped $'s that aren't before
1193 * the delimiter (expand the variable substitution).
1194 * Return the expanded string or NULL if the delimiter was missing
1195 * If pattern is specified, handle escaped ampersands, and replace
1196 * unescaped ampersands with the lhs of the pattern.
1199 * A string of all the words modified appropriately.
1200 * If length is specified, return the string length of the buffer
1201 * If flags is specified and the last character of the pattern is a
1202 * $ set the VAR_MATCH_END bit of flags.
1205 VarGetPattern(VarParser
*vp
, int delim
, int *flags
, VarPattern
*patt
)
1212 * Skim through until the matching delimiter is found; pick up
1213 * variable substitutions on the way. Also allow backslashes to quote
1214 * the delimiter, $, and \, but don't touch other backslashes.
1216 while (*vp
->ptr
!= '\0') {
1217 if (*vp
->ptr
== delim
) {
1220 } else if ((vp
->ptr
[0] == '\\') &&
1221 ((vp
->ptr
[1] == delim
) ||
1222 (vp
->ptr
[1] == '\\') ||
1223 (vp
->ptr
[1] == '$') ||
1224 (vp
->ptr
[1] == '&' && patt
!= NULL
))) {
1225 vp
->ptr
++; /* consume backslash */
1226 Buf_AddByte(buf
, vp
->ptr
[0]);
1229 } else if (vp
->ptr
[0] == '$') {
1230 if (vp
->ptr
[1] == delim
) {
1231 if (flags
== NULL
) {
1232 Buf_AddByte(buf
, vp
->ptr
[0]);
1236 * Unescaped $ at end of patt =>
1237 * anchor patt at end.
1239 *flags
|= VAR_MATCH_END
;
1254 * If unescaped dollar sign not
1255 * before the delimiter, assume it's
1256 * a variable substitution and
1259 rval
= VarParse(&subvp
, &rfree
);
1260 Buf_Append(buf
, rval
);
1263 vp
->ptr
= subvp
.ptr
;
1265 } else if (vp
->ptr
[0] == '&' && patt
!= NULL
) {
1266 Buf_AppendBuf(buf
, patt
->lhs
);
1269 Buf_AddByte(buf
, vp
->ptr
[0]);
1274 Buf_Destroy(buf
, true);
1279 * Make sure this variable is fully expanded.
1282 VarExpand(Var
*v
, VarParser
*vp
)
1287 if (v
->flags
& VAR_IN_USE
) {
1288 Fatal("Variable %s is recursive.", v
->name
);
1292 v
->flags
|= VAR_IN_USE
;
1295 * Before doing any modification, we have to make sure the
1296 * value has been fully expanded. If it looks like recursion
1297 * might be necessary (there's a dollar sign somewhere in the
1298 * variable's value) we just call Var_Subst to do any other
1299 * substitutions that are necessary. Note that the value
1300 * returned by Var_Subst will have been
1301 * dynamically-allocated, so it will need freeing when we
1304 value
= Buf_Data(v
->val
);
1305 if (strchr(value
, '$') == NULL
) {
1306 result
= strdup(value
);
1310 buf
= Var_Subst(value
, vp
->ctxt
, vp
->err
);
1311 result
= Buf_Peel(buf
);
1314 v
->flags
&= ~VAR_IN_USE
;
1320 * Select only those words in value that match the modifier.
1323 modifier_M(VarParser
*vp
, const char value
[], char endc
)
1330 modifier
= vp
->ptr
[0];
1331 vp
->ptr
++; /* consume 'M' or 'N' */
1334 * Compress the \:'s out of the pattern, so allocate enough
1335 * room to hold the uncompressed pattern and compress the
1336 * pattern into that space.
1338 patt
= estrdup(vp
->ptr
);
1340 while (vp
->ptr
[0] != '\0') {
1341 if (vp
->ptr
[0] == endc
|| vp
->ptr
[0] == ':') {
1344 if (vp
->ptr
[0] == '\\' &&
1345 (vp
->ptr
[1] == endc
|| vp
->ptr
[1] == ':')) {
1346 vp
->ptr
++; /* consume backslash */
1354 if (modifier
== 'M') {
1355 newValue
= VarModify(value
, VarMatch
, patt
);
1357 newValue
= VarModify(value
, VarNoMatch
, patt
);
1365 * Substitute the replacement string for the pattern. The substitution
1366 * is applied to each word in value.
1369 modifier_S(VarParser
*vp
, const char value
[], Var
*v
)
1377 vp
->ptr
++; /* consume 'S' */
1379 delim
= *vp
->ptr
; /* used to find end of pattern */
1380 vp
->ptr
++; /* consume 1st delim */
1383 * If pattern begins with '^', it is anchored to the start of the
1384 * word -- skip over it and flag pattern.
1386 if (*vp
->ptr
== '^') {
1387 patt
.flags
|= VAR_MATCH_START
;
1391 patt
.lhs
= VarGetPattern(vp
, delim
, &patt
.flags
, NULL
);
1392 if (patt
.lhs
== NULL
) {
1394 * LHS didn't end with the delim, complain and exit.
1396 Fatal("Unclosed substitution for %s (%c missing)",
1400 vp
->ptr
++; /* consume 2nd delim */
1402 patt
.rhs
= VarGetPattern(vp
, delim
, NULL
, &patt
);
1403 if (patt
.rhs
== NULL
) {
1405 * RHS didn't end with the delim, complain and exit.
1407 Fatal("Unclosed substitution for %s (%c missing)",
1411 vp
->ptr
++; /* consume last delim */
1414 * Check for global substitution. If 'g' after the final delimiter,
1415 * substitution is global and is marked that way.
1417 if (vp
->ptr
[0] == 'g') {
1418 patt
.flags
|= VAR_SUB_GLOBAL
;
1423 * Global substitution of the empty string causes an infinite number
1424 * of matches, unless anchored by '^' (start of string) or '$' (end
1425 * of string). Catch the infinite substitution here. Note that flags
1426 * can only contain the 3 bits we're interested in so we don't have
1427 * to mask unrelated bits. We can test for equality.
1429 if (Buf_Size(patt
.lhs
) == 0 && patt
.flags
== VAR_SUB_GLOBAL
)
1430 Fatal("Global substitution of the empty string");
1432 newValue
= VarModify(value
, VarSubstitute
, &patt
);
1435 * Free the two strings.
1444 modifier_C(VarParser
*vp
, char value
[], Var
*v
)
1453 vp
->ptr
++; /* consume 'C' */
1455 delim
= *vp
->ptr
; /* delimiter between sections */
1457 vp
->ptr
++; /* consume 1st delim */
1459 patt
.lhs
= VarGetPattern(vp
, delim
, NULL
, NULL
);
1460 if (patt
.lhs
== NULL
) {
1461 Fatal("Unclosed substitution for %s (%c missing)",
1465 vp
->ptr
++; /* consume 2st delim */
1467 patt
.rhs
= VarGetPattern(vp
, delim
, NULL
, NULL
);
1468 if (patt
.rhs
== NULL
) {
1469 Fatal("Unclosed substitution for %s (%c missing)",
1473 vp
->ptr
++; /* consume last delim */
1477 patt
.flags
|= VAR_SUB_GLOBAL
;
1478 vp
->ptr
++; /* consume 'g' */
1481 patt
.flags
|= VAR_SUB_ONE
;
1482 vp
->ptr
++; /* consume '1' */
1488 error
= regcomp(&patt
.re
, Buf_Data(patt
.lhs
), REG_EXTENDED
);
1490 VarREError(error
, &patt
.re
, "RE substitution error");
1496 patt
.nsub
= patt
.re
.re_nsub
+ 1;
1501 patt
.matches
= emalloc(patt
.nsub
* sizeof(regmatch_t
));
1503 newValue
= VarModify(value
, VarRESubstitute
, &patt
);
1514 sysVvarsub(VarParser
*vp
, char startc
, Var
*v
, const char value
[])
1517 * This can either be a bogus modifier or a System-V substitution
1527 endc
= (startc
== OPEN_PAREN
) ? CLOSE_PAREN
: CLOSE_BRACE
;
1532 * First we make a pass through the string trying to verify it is a
1533 * SYSV-make-style translation: it must be: <string1>=<string2>)
1538 while (*cp
!= '\0' && cnt
) {
1541 /* continue looking for endc */
1542 } else if (*cp
== endc
)
1544 else if (*cp
== startc
)
1550 if (*cp
== endc
&& eqFound
) {
1552 * Now we break this sucker into the lhs and rhs.
1554 patt
.lhs
= VarGetPattern(vp
, '=', &patt
.flags
, NULL
);
1555 if (patt
.lhs
== NULL
) {
1556 Fatal("Unclosed substitution for %s (%c missing)",
1559 vp
->ptr
++; /* consume '=' */
1561 patt
.rhs
= VarGetPattern(vp
, endc
, NULL
, &patt
);
1562 if (patt
.rhs
== NULL
) {
1563 Fatal("Unclosed substitution for %s (%c missing)",
1568 * SYSV modifications happen through the whole string. Note
1569 * the pattern is anchored at the end.
1571 newStr
= VarModify(value
, VarSYSVMatch
, &patt
);
1576 Error("Unknown modifier '%c'\n", *vp
->ptr
);
1578 while (*vp
->ptr
!= '\0') {
1579 if (*vp
->ptr
== endc
&& *vp
->ptr
== ':') {
1591 * Quote shell meta-characters in the string
1597 Var_Quote(const char str
[])
1600 /* This should cover most shells :-( */
1601 static char meta
[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
1603 buf
= Buf_Init(MAKE_BSIZE
);
1604 for (; *str
; str
++) {
1605 if (strchr(meta
, *str
) != NULL
)
1606 Buf_AddByte(buf
, '\\');
1607 Buf_AddByte(buf
, *str
);
1610 return (Buf_Peel(buf
));
1615 * Now we need to apply any modifiers the user wants applied.
1618 * words which match the given <pattern>.
1619 * <pattern> is of the standard file
1621 * :S<d><pat1><d><pat2><d>[g]
1622 * Substitute <pat2> for <pat1> in the value
1623 * :C<d><pat1><d><pat2><d>[g]
1624 * Substitute <pat2> for regex <pat1> in the value
1625 * :H Substitute the head of each word
1626 * :T Substitute the tail of each word
1627 * :E Substitute the extension (minus '.') of
1629 * :R Substitute the root of each word
1630 * (pathname minus the suffix).
1632 * Like :S, but the rhs goes to the end of
1634 * :U Converts variable to upper-case.
1635 * :L Converts variable to lower-case.
1637 * XXXHB update this comment or remove it and point to the man page.
1640 ParseModifier(VarParser
*vp
, char startc
, Var
*v
, bool *freeResult
)
1645 value
= VarExpand(v
, vp
);
1648 endc
= (startc
== OPEN_PAREN
) ? CLOSE_PAREN
: CLOSE_BRACE
;
1650 vp
->ptr
++; /* consume first colon */
1652 while (*vp
->ptr
!= '\0') {
1653 char *newStr
; /* New value to return */
1655 if (*vp
->ptr
== endc
) {
1659 DEBUGF(VAR
, ("Applying :%c to \"%s\"\n", *vp
->ptr
, value
));
1663 newStr
= modifier_M(vp
, value
, endc
);
1666 newStr
= modifier_S(vp
, value
, v
);
1669 newStr
= modifier_C(vp
, value
, v
);
1672 if (vp
->ptr
[1] != endc
&& vp
->ptr
[1] != ':') {
1674 if ((vp
->ptr
[0] == 's') &&
1675 (vp
->ptr
[1] == 'h') &&
1676 (vp
->ptr
[2] == endc
|| vp
->ptr
[2] == ':')) {
1681 Cmd_Exec(value
, &error
));
1683 newStr
= estrdup("");
1687 Error(error
, value
);
1692 newStr
= sysVvarsub(vp
, startc
, v
, value
);
1697 switch (vp
->ptr
[0]) {
1702 buf
= Buf_Init(MAKE_BSIZE
);
1703 for (cp
= value
; *cp
; cp
++)
1704 Buf_AddByte(buf
, tolower((unsigned char)*cp
));
1706 newStr
= Buf_Peel(buf
);
1712 newStr
= VarSortWords(value
, SortIncreasing
);
1716 newStr
= Var_Quote(value
);
1720 newStr
= VarModify(value
, VarTail
, NULL
);
1727 buf
= Buf_Init(MAKE_BSIZE
);
1728 for (cp
= value
; *cp
; cp
++)
1729 Buf_AddByte(buf
, toupper((unsigned char)*cp
));
1731 newStr
= Buf_Peel(buf
);
1737 newStr
= VarModify(value
, VarHead
, NULL
);
1741 newStr
= VarModify(value
, VarSuffix
, NULL
);
1745 newStr
= VarModify(value
, VarRoot
, NULL
);
1749 newStr
= sysVvarsub(vp
, startc
, v
, value
);
1755 DEBUGF(VAR
, ("Result is \"%s\"\n", newStr
));
1761 *freeResult
= (value
== var_Error
) ? false : true;
1763 if (vp
->ptr
[0] == ':') {
1764 vp
->ptr
++; /* consume colon */
1772 ParseRestModifier(VarParser
*vp
, char startc
, Buffer
*buf
, bool *freeResult
)
1779 vname
= Buf_Data(buf
);
1780 vlen
= Buf_Size(buf
);
1782 v
= VarFindAny(vname
, vp
->ctxt
);
1784 value
= ParseModifier(vp
, startc
, v
, freeResult
);
1788 if ((vp
->ctxt
== VAR_CMD
) || (vp
->ctxt
== VAR_GLOBAL
)) {
1791 * Still need to get to the end of the variable
1792 * specification, so kludge up a Var structure for the
1795 v
= VarCreate(vname
, NULL
, VAR_JUNK
);
1796 value
= ParseModifier(vp
, startc
, v
, freeResult
);
1800 VarDestroy(v
, true);
1802 consumed
= vp
->ptr
- vp
->input
+ 1;
1804 * If substituting a local variable in a non-local context,
1805 * assume it's for dynamic source stuff. We have to handle
1806 * this specially and return the longhand for the variable
1807 * with the dollar sign escaped so it makes it back to the
1808 * caller. Only four of the local variables are treated
1809 * specially as they are the only four that will be set when
1810 * dynamic sources are expanded.
1813 (vlen
== 2 && (vname
[1] == 'F' || vname
[1] == 'D'))) {
1814 if (strchr("!%*@", vname
[0]) != NULL
) {
1815 value
= emalloc(consumed
+ 1);
1816 strncpy(value
, vp
->input
, consumed
);
1817 value
[consumed
] = '\0';
1825 isupper((unsigned char)vname
[1])) {
1826 if ((strncmp(vname
, ".TARGET", vlen
- 1) == 0) ||
1827 (strncmp(vname
, ".ARCHIVE", vlen
- 1) == 0) ||
1828 (strncmp(vname
, ".PREFIX", vlen
- 1) == 0) ||
1829 (strncmp(vname
, ".MEMBER", vlen
- 1) == 0)) {
1830 value
= emalloc(consumed
+ 1);
1831 strncpy(value
, vp
->input
, consumed
);
1832 value
[consumed
] = '\0';
1839 *freeResult
= false;
1840 return (vp
->err
? var_Error
: varNoError
);
1843 * Check for D and F forms of local variables since we're in
1844 * a local context and the name is the right length.
1847 (vname
[1] == 'F' || vname
[1] == 'D') &&
1848 (strchr("!%*<>@", vname
[0]) != NULL
)) {
1854 v
= VarFindOnly(name
, vp
->ctxt
);
1856 value
= ParseModifier(vp
, startc
, v
, freeResult
);
1862 * Still need to get to the end of the variable
1863 * specification, so kludge up a Var structure for the
1866 v
= VarCreate(vname
, NULL
, VAR_JUNK
);
1867 value
= ParseModifier(vp
, startc
, v
, freeResult
);
1871 VarDestroy(v
, true);
1873 *freeResult
= false;
1874 return (vp
->err
? var_Error
: varNoError
);
1879 ParseRestEnd(VarParser
*vp
, Buffer
*buf
, bool *freeResult
)
1886 vname
= Buf_Data(buf
);
1887 vlen
= Buf_Size(buf
);
1889 v
= VarFindAny(vname
, vp
->ctxt
);
1891 value
= VarExpand(v
, vp
);
1896 if ((vp
->ctxt
== VAR_CMD
) || (vp
->ctxt
== VAR_GLOBAL
)) {
1897 size_t consumed
= vp
->ptr
- vp
->input
+ 1;
1900 * If substituting a local variable in a non-local context,
1901 * assume it's for dynamic source stuff. We have to handle
1902 * this specially and return the longhand for the variable
1903 * with the dollar sign escaped so it makes it back to the
1904 * caller. Only four of the local variables are treated
1905 * specially as they are the only four that will be set when
1906 * dynamic sources are expanded.
1909 (vlen
== 2 && (vname
[1] == 'F' || vname
[1] == 'D'))) {
1910 if (strchr("!%*@", vname
[0]) != NULL
) {
1911 value
= emalloc(consumed
+ 1);
1912 strncpy(value
, vp
->input
, consumed
);
1913 value
[consumed
] = '\0';
1921 isupper((unsigned char)vname
[1])) {
1922 if ((strncmp(vname
, ".TARGET", vlen
- 1) == 0) ||
1923 (strncmp(vname
, ".ARCHIVE", vlen
- 1) == 0) ||
1924 (strncmp(vname
, ".PREFIX", vlen
- 1) == 0) ||
1925 (strncmp(vname
, ".MEMBER", vlen
- 1) == 0)) {
1926 value
= emalloc(consumed
+ 1);
1927 strncpy(value
, vp
->input
, consumed
);
1928 value
[consumed
] = '\0';
1936 * Check for D and F forms of local variables since we're in
1937 * a local context and the name is the right length.
1940 (vname
[1] == 'F' || vname
[1] == 'D') &&
1941 (strchr("!%*<>@", vname
[0]) != NULL
)) {
1947 v
= VarFindOnly(name
, vp
->ctxt
);
1951 * No need for nested expansion or anything,
1952 * as we're the only one who sets these
1953 * things and we sure don't put nested
1954 * invocations in them...
1956 val
= Buf_Data(v
->val
);
1958 if (vname
[1] == 'D') {
1959 val
= VarModify(val
, VarHead
, NULL
);
1961 val
= VarModify(val
, VarTail
, NULL
);
1970 *freeResult
= false;
1971 return (vp
->err
? var_Error
: varNoError
);
1975 * Parse a multi letter variable name, and return it's value.
1978 VarParseLong(VarParser
*vp
, bool *freeResult
)
1985 buf
= Buf_Init(MAKE_BSIZE
);
1987 startc
= vp
->ptr
[0];
1988 vp
->ptr
++; /* consume opening paren or brace */
1990 endc
= (startc
== OPEN_PAREN
) ? CLOSE_PAREN
: CLOSE_BRACE
;
1993 * Process characters until we reach an end character or a colon,
1994 * replacing embedded variables as we go.
1996 while (*vp
->ptr
!= '\0') {
1997 if (*vp
->ptr
== endc
) {
1998 value
= ParseRestEnd(vp
, buf
, freeResult
);
1999 vp
->ptr
++; /* consume closing paren or brace */
2000 Buf_Destroy(buf
, true);
2003 } else if (*vp
->ptr
== ':') {
2004 value
= ParseRestModifier(vp
, startc
, buf
, freeResult
);
2005 vp
->ptr
++; /* consume closing paren or brace */
2006 Buf_Destroy(buf
, true);
2009 } else if (*vp
->ptr
== '$') {
2020 rval
= VarParse(&subvp
, &rfree
);
2021 if (rval
== var_Error
) {
2022 Fatal("Error expanding embedded variable.");
2024 Buf_Append(buf
, rval
);
2027 vp
->ptr
= subvp
.ptr
;
2029 Buf_AddByte(buf
, *vp
->ptr
);
2034 /* If we did not find the end character, return var_Error */
2035 Buf_Destroy(buf
, true);
2036 *freeResult
= false;
2041 * Parse a single letter variable name, and return it's value.
2044 VarParseShort(VarParser
*vp
, bool *freeResult
)
2050 vname
[0] = vp
->ptr
[0];
2053 vp
->ptr
++; /* consume single letter */
2055 v
= VarFindAny(vname
, vp
->ctxt
);
2057 value
= VarExpand(v
, vp
);
2063 * If substituting a local variable in a non-local context, assume
2064 * it's for dynamic source stuff. We have to handle this specially
2065 * and return the longhand for the variable with the dollar sign
2066 * escaped so it makes it back to the caller. Only four of the local
2067 * variables are treated specially as they are the only four that
2068 * will be set when dynamic sources are expanded.
2070 if ((vp
->ctxt
== VAR_CMD
) || (vp
->ctxt
== VAR_GLOBAL
)) {
2072 /* XXX: It looks like $% and $! are reversed here */
2076 return (estrdup("$(.TARGET)"));
2079 return (estrdup("$(.ARCHIVE)"));
2082 return (estrdup("$(.PREFIX)"));
2085 return (estrdup("$(.MEMBER)"));
2087 *freeResult
= false;
2088 return (vp
->err
? var_Error
: varNoError
);
2092 /* Variable name was not found. */
2093 *freeResult
= false;
2094 return (vp
->err
? var_Error
: varNoError
);
2098 VarParse(VarParser
*vp
, bool *freeResult
)
2101 vp
->ptr
++; /* consume '$' or last letter of conditional */
2103 if (vp
->ptr
[0] == '\0') {
2104 /* Error, there is only a dollar sign in the input string. */
2105 *freeResult
= false;
2106 return (vp
->err
? var_Error
: varNoError
);
2108 } else if (vp
->ptr
[0] == OPEN_PAREN
|| vp
->ptr
[0] == OPEN_BRACE
) {
2109 /* multi letter variable name */
2110 return (VarParseLong(vp
, freeResult
));
2113 /* single letter variable name */
2114 return (VarParseShort(vp
, freeResult
));
2119 * Given the start of a variable invocation, extract the variable
2120 * name and find its value, then modify it according to the
2124 * The value of the variable or var_Error if the specification
2125 * is invalid. The number of characters in the specification
2126 * is placed in the variable pointed to by consumed. (for
2127 * invalid specifications, this is just 2 to skip the '$' and
2128 * the following letter, or 1 if '$' was the last character
2129 * in the string). A bool in *freeResult telling whether the
2130 * returned string should be freed by the caller.
2133 Var_Parse(const char input
[], GNode
*ctxt
, bool err
,
2134 size_t *consumed
, bool *freeResult
)
2145 value
= VarParse(&vp
, freeResult
);
2146 *consumed
+= vp
.ptr
- vp
.input
;
2151 * Given the start of a variable invocation, determine the length
2152 * of the specification.
2155 * The number of characters in the specification. For invalid
2156 * specifications, this is just 2 to skip the '$' and the
2157 * following letter, or 1 if '$' was the last character in the
2161 Var_Match(const char input
[], GNode
*ctxt
)
2173 value
= VarParse(&vp
, &freeResult
);
2177 return (vp
.ptr
- vp
.input
);
2181 match_var(const char str
[], const char var
[])
2183 const char *start
= str
;
2186 str
++; /* consume '$' */
2188 if (str
[0] == OPEN_PAREN
|| str
[0] == OPEN_BRACE
) {
2189 str
++; /* consume opening paren or brace */
2191 while (str
[0] != '\0') {
2192 if (str
[0] == '$') {
2194 * A variable inside the variable. We cannot
2195 * expand the external variable yet.
2197 return (str
- start
);
2198 } else if (str
[0] == ':' ||
2199 str
[0] == CLOSE_PAREN
||
2200 str
[0] == CLOSE_BRACE
) {
2201 len
= str
- (start
+ 2);
2203 if (var
[len
] == '\0' && strncmp(var
, start
+ 2, len
) == 0) {
2204 return (0); /* match */
2207 * Not the variable we want to
2210 return (str
- start
);
2216 return (str
- start
);
2218 /* Single letter variable name */
2219 if (var
[1] == '\0' && var
[0] == str
[0]) {
2220 return (0); /* match */
2222 str
++; /* consume variable name */
2223 return (str
- start
);
2229 * Substitute for all variables in the given string in the given
2230 * context If err is true, Parse_Error will be called when an
2231 * undefined variable is encountered.
2234 * The resulting string.
2237 * None. The old string must be freed by the caller
2240 Var_Subst(const char str
[], GNode
*ctxt
, bool err
)
2243 Buffer
*buf
; /* Buffer for forming things */
2246 * Set true if an error has already been reported to prevent a
2247 * plethora of messages when recursing. XXXHB this comment sounds
2250 errorReported
= false;
2253 while (str
[0] != '\0') {
2254 if ((str
[0] == '$') && (str
[1] == '$')) {
2256 * A dollar sign may be escaped with another dollar
2257 * sign. In such a case, we skip over the escape
2258 * character and store the dollar sign into the
2262 Buf_AddByte(buf
, str
[0]);
2265 } else if (str
[0] == '$') {
2266 /* Variable invocation. */
2277 rval
= VarParse(&subvp
, &rfree
);
2280 * When we come down here, val should either point to
2281 * the value of this variable, suitably modified, or
2282 * be NULL. Length should be the total length of the
2283 * potential variable invocation (from $ to end
2286 if (rval
== var_Error
|| rval
== varNoError
) {
2288 * If performing old-time variable
2289 * substitution, skip over the variable and
2290 * continue with the substitution. Otherwise,
2291 * store the dollar sign and advance str so
2292 * we continue with the string...
2298 * If variable is undefined, complain
2299 * and skip the variable. The
2300 * complaint will stop us from doing
2301 * anything when the file is parsed.
2303 if (!errorReported
) {
2304 Parse_Error(PARSE_FATAL
,
2305 "Undefined variable \"%.*s\"", subvp
.ptr
- subvp
.input
, str
);
2307 errorReported
= true;
2310 Buf_AddByte(buf
, str
[0]);
2315 * Copy all the characters from the variable
2316 * value straight into the new string.
2318 Buf_Append(buf
, rval
);
2325 Buf_AddByte(buf
, str
[0]);
2334 * Substitute for all variables except if it is the same as 'var',
2335 * in the given string in the given context. If err is true,
2336 * Parse_Error will be called when an undefined variable is
2340 * The resulting string.
2343 * None. The old string must be freed by the caller
2346 Var_SubstOnly(const char var
[], const char str
[], bool err
)
2348 GNode
*ctxt
= VAR_GLOBAL
;
2350 Buffer
*buf
; /* Buffer for forming things */
2353 * Set true if an error has already been reported to prevent a
2354 * plethora of messages when recursing. XXXHB this comment sounds
2357 errorReported
= false;
2360 while (str
[0] != '\0') {
2361 if (str
[0] == '$') {
2364 skip
= match_var(str
, var
);
2366 Buf_AddBytes(buf
, skip
, str
);
2369 /* Variable invocation. */
2380 rval
= VarParse(&subvp
, &rfree
);
2383 * When we get down here, rval should either
2384 * point to the value of this variable, or be
2387 if (rval
== var_Error
|| rval
== varNoError
) {
2389 * If performing old-time variable
2390 * substitution, skip over the
2391 * variable and continue with the
2392 * substitution. Otherwise, store the
2393 * dollar sign and advance str so we
2394 * continue with the string...
2400 * If variable is undefined,
2401 * complain and skip the
2402 * variable. The complaint
2403 * will stop us from doing
2404 * anything when the file is
2407 if (!errorReported
) {
2408 Parse_Error(PARSE_FATAL
,
2409 "Undefined variable \"%.*s\"", subvp
.ptr
- subvp
.input
, str
);
2411 errorReported
= true;
2414 Buf_AddByte(buf
, str
[0]);
2419 * Copy all the characters from the
2420 * variable value straight into the
2423 Buf_Append(buf
, rval
);
2431 Buf_AddByte(buf
, str
[0]);
2440 * Initialize the module
2443 * The VAR_CMD and VAR_GLOBAL contexts are created
2446 Var_Init(char **env
)
2450 VAR_CMD
= Targ_NewGN("Command");
2451 VAR_ENV
= Targ_NewGN("Environment");
2452 VAR_GLOBAL
= Targ_NewGN("Global");
2455 * Copy user environment variables into ENV context.
2457 for (ptr
= env
; *ptr
!= NULL
; ++ptr
) {
2458 char *tmp
= estrdup(*ptr
);
2459 const char *name
= tmp
;
2460 char *sep
= strchr(name
, '=');
2463 const char *value
= sep
+ 1;
2466 VarAdd(name
, value
, VAR_ENV
);
2473 * Print all variables in global and command line contexts.
2481 printf("#*** Global Variables:\n");
2482 LST_FOREACH(ln
, &VAR_GLOBAL
->context
) {
2484 printf("%-16s = %s\n", v
->name
, Buf_Data(v
->val
));
2487 printf("#*** Command-line Variables:\n");
2488 LST_FOREACH(ln
, &VAR_CMD
->context
) {
2490 printf("%-16s = %s\n", v
->name
, Buf_Data(v
->val
));
2495 * Print the values of any variables requested by
2499 Var_Print(Lst
*vlist
, bool expandVars
)
2503 LST_FOREACH(n
, vlist
) {
2504 const char *name
= Lst_Datum(n
);
2510 v
= emalloc(strlen(name
) + 1 + 3);
2511 sprintf(v
, "${%s}", name
);
2513 value
= Buf_Peel(Var_Subst(v
, VAR_GLOBAL
, false));
2514 printf("%s\n", value
);
2519 const char *value
= Var_Value(name
, VAR_GLOBAL
);
2520 printf("%s\n", value
!= NULL
? value
: "");