Add "device uether" to various manual pages' synopses.
[dragonfly.git] / contrib / bmake / var.c
blob403c8f3b7287f591bcdf022cc18be13288e00b8f
1 /* $NetBSD: var.c,v 1.208 2016/06/03 01:21:59 sjg Exp $ */
3 /*
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor.
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement:
52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission.
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: var.c,v 1.208 2016/06/03 01:21:59 sjg Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 #if 0
77 static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 3/19/94";
78 #else
79 __RCSID("$NetBSD: var.c,v 1.208 2016/06/03 01:21:59 sjg Exp $");
80 #endif
81 #endif /* not lint */
82 #endif
84 /*-
85 * var.c --
86 * Variable-handling functions
88 * Interface:
89 * Var_Set Set the value of a variable in the given
90 * context. The variable is created if it doesn't
91 * yet exist. The value and variable name need not
92 * be preserved.
94 * Var_Append Append more characters to an existing variable
95 * in the given context. The variable needn't
96 * exist already -- it will be created if it doesn't.
97 * A space is placed between the old value and the
98 * new one.
100 * Var_Exists See if a variable exists.
102 * Var_Value Return the value of a variable in a context or
103 * NULL if the variable is undefined.
105 * Var_Subst Substitute named variable, or all variables if
106 * NULL in a string using
107 * the given context as the top-most one. If the
108 * third argument is non-zero, Parse_Error is
109 * called if any variables are undefined.
111 * Var_Parse Parse a variable expansion from a string and
112 * return the result and the number of characters
113 * consumed.
115 * Var_Delete Delete a variable in a context.
117 * Var_Init Initialize this module.
119 * Debugging:
120 * Var_Dump Print out all variables defined in the given
121 * context.
123 * XXX: There's a lot of duplication in these functions.
126 #include <sys/stat.h>
127 #ifndef NO_REGEX
128 #include <sys/types.h>
129 #include <regex.h>
130 #endif
131 #include <ctype.h>
132 #include <stdlib.h>
133 #include <limits.h>
134 #include <time.h>
136 #include "make.h"
137 #include "buf.h"
138 #include "dir.h"
139 #include "job.h"
140 #include "metachar.h"
142 extern int makelevel;
144 * This lets us tell if we have replaced the original environ
145 * (which we cannot free).
147 char **savedEnv = NULL;
150 * This is a harmless return value for Var_Parse that can be used by Var_Subst
151 * to determine if there was an error in parsing -- easier than returning
152 * a flag, as things outside this module don't give a hoot.
154 char var_Error[] = "";
157 * Similar to var_Error, but returned when the 'VARF_UNDEFERR' flag for
158 * Var_Parse is not set. Why not just use a constant? Well, gcc likes
159 * to condense identical string instances...
161 static char varNoError[] = "";
164 * Traditionally we consume $$ during := like any other expansion.
165 * Other make's do not.
166 * This knob allows controlling the behavior.
167 * FALSE for old behavior.
168 * TRUE for new compatible.
170 #define SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
171 static Boolean save_dollars = FALSE;
174 * Internally, variables are contained in four different contexts.
175 * 1) the environment. They may not be changed. If an environment
176 * variable is appended-to, the result is placed in the global
177 * context.
178 * 2) the global context. Variables set in the Makefile are located in
179 * the global context. It is the penultimate context searched when
180 * substituting.
181 * 3) the command-line context. All variables set on the command line
182 * are placed in this context. They are UNALTERABLE once placed here.
183 * 4) the local context. Each target has associated with it a context
184 * list. On this list are located the structures describing such
185 * local variables as $(@) and $(*)
186 * The four contexts are searched in the reverse order from which they are
187 * listed.
189 GNode *VAR_INTERNAL; /* variables from make itself */
190 GNode *VAR_GLOBAL; /* variables from the makefile */
191 GNode *VAR_CMD; /* variables defined on the command-line */
193 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */
194 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */
195 #define FIND_ENV 0x4 /* look in the environment also */
197 typedef struct Var {
198 char *name; /* the variable's name */
199 Buffer val; /* its value */
200 int flags; /* miscellaneous status flags */
201 #define VAR_IN_USE 1 /* Variable's value currently being used.
202 * Used to avoid recursion */
203 #define VAR_FROM_ENV 2 /* Variable comes from the environment */
204 #define VAR_JUNK 4 /* Variable is a junk variable that
205 * should be destroyed when done with
206 * it. Used by Var_Parse for undefined,
207 * modified variables */
208 #define VAR_KEEP 8 /* Variable is VAR_JUNK, but we found
209 * a use for it in some modifier and
210 * the value is therefore valid */
211 #define VAR_EXPORTED 16 /* Variable is exported */
212 #define VAR_REEXPORT 32 /* Indicate if var needs re-export.
213 * This would be true if it contains $'s
215 #define VAR_FROM_CMD 64 /* Variable came from command line */
216 } Var;
219 * Exporting vars is expensive so skip it if we can
221 #define VAR_EXPORTED_NONE 0
222 #define VAR_EXPORTED_YES 1
223 #define VAR_EXPORTED_ALL 2
224 static int var_exportedVars = VAR_EXPORTED_NONE;
226 * We pass this to Var_Export when doing the initial export
227 * or after updating an exported var.
229 #define VAR_EXPORT_PARENT 1
231 * We pass this to Var_Export1 to tell it to leave the value alone.
233 #define VAR_EXPORT_LITERAL 2
235 /* Var*Pattern flags */
236 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
237 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
238 #define VAR_SUB_MATCHED 0x04 /* There was a match */
239 #define VAR_MATCH_START 0x08 /* Match at start of word */
240 #define VAR_MATCH_END 0x10 /* Match at end of word */
241 #define VAR_NOSUBST 0x20 /* don't expand vars in VarGetPattern */
243 /* Var_Set flags */
244 #define VAR_NO_EXPORT 0x01 /* do not export */
246 typedef struct {
248 * The following fields are set by Var_Parse() when it
249 * encounters modifiers that need to keep state for use by
250 * subsequent modifiers within the same variable expansion.
252 Byte varSpace; /* Word separator in expansions */
253 Boolean oneBigWord; /* TRUE if we will treat the variable as a
254 * single big word, even if it contains
255 * embedded spaces (as opposed to the
256 * usual behaviour of treating it as
257 * several space-separated words). */
258 } Var_Parse_State;
260 /* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/",
261 * to VarSYSVMatch() for ":lhs=rhs". */
262 typedef struct {
263 const char *lhs; /* String to match */
264 int leftLen; /* Length of string */
265 const char *rhs; /* Replacement string (w/ &'s removed) */
266 int rightLen; /* Length of replacement */
267 int flags;
268 } VarPattern;
270 /* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */
271 typedef struct {
272 GNode *ctxt; /* variable context */
273 char *tvar; /* name of temp var */
274 int tvarLen;
275 char *str; /* string to expand */
276 int strLen;
277 int errnum; /* errnum for not defined */
278 } VarLoop_t;
280 #ifndef NO_REGEX
281 /* struct passed as 'void *' to VarRESubstitute() for ":C///" */
282 typedef struct {
283 regex_t re;
284 int nsub;
285 regmatch_t *matches;
286 char *replace;
287 int flags;
288 } VarREPattern;
289 #endif
291 /* struct passed to VarSelectWords() for ":[start..end]" */
292 typedef struct {
293 int start; /* first word to select */
294 int end; /* last word to select */
295 } VarSelectWords_t;
297 static Var *VarFind(const char *, GNode *, int);
298 static void VarAdd(const char *, const char *, GNode *);
299 static Boolean VarHead(GNode *, Var_Parse_State *,
300 char *, Boolean, Buffer *, void *);
301 static Boolean VarTail(GNode *, Var_Parse_State *,
302 char *, Boolean, Buffer *, void *);
303 static Boolean VarSuffix(GNode *, Var_Parse_State *,
304 char *, Boolean, Buffer *, void *);
305 static Boolean VarRoot(GNode *, Var_Parse_State *,
306 char *, Boolean, Buffer *, void *);
307 static Boolean VarMatch(GNode *, Var_Parse_State *,
308 char *, Boolean, Buffer *, void *);
309 #ifdef SYSVVARSUB
310 static Boolean VarSYSVMatch(GNode *, Var_Parse_State *,
311 char *, Boolean, Buffer *, void *);
312 #endif
313 static Boolean VarNoMatch(GNode *, Var_Parse_State *,
314 char *, Boolean, Buffer *, void *);
315 #ifndef NO_REGEX
316 static void VarREError(int, regex_t *, const char *);
317 static Boolean VarRESubstitute(GNode *, Var_Parse_State *,
318 char *, Boolean, Buffer *, void *);
319 #endif
320 static Boolean VarSubstitute(GNode *, Var_Parse_State *,
321 char *, Boolean, Buffer *, void *);
322 static Boolean VarLoopExpand(GNode *, Var_Parse_State *,
323 char *, Boolean, Buffer *, void *);
324 static char *VarGetPattern(GNode *, Var_Parse_State *,
325 int, const char **, int, int *, int *,
326 VarPattern *);
327 static char *VarQuote(char *);
328 static char *VarHash(char *);
329 static char *VarModify(GNode *, Var_Parse_State *,
330 const char *,
331 Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *),
332 void *);
333 static char *VarOrder(const char *, const char);
334 static char *VarUniq(const char *);
335 static int VarWordCompare(const void *, const void *);
336 static void VarPrintVar(void *);
338 #define BROPEN '{'
339 #define BRCLOSE '}'
340 #define PROPEN '('
341 #define PRCLOSE ')'
344 *-----------------------------------------------------------------------
345 * VarFind --
346 * Find the given variable in the given context and any other contexts
347 * indicated.
349 * Input:
350 * name name to find
351 * ctxt context in which to find it
352 * flags FIND_GLOBAL set means to look in the
353 * VAR_GLOBAL context as well. FIND_CMD set means
354 * to look in the VAR_CMD context also. FIND_ENV
355 * set means to look in the environment
357 * Results:
358 * A pointer to the structure describing the desired variable or
359 * NULL if the variable does not exist.
361 * Side Effects:
362 * None
363 *-----------------------------------------------------------------------
365 static Var *
366 VarFind(const char *name, GNode *ctxt, int flags)
368 Hash_Entry *var;
369 Var *v;
372 * If the variable name begins with a '.', it could very well be one of
373 * the local ones. We check the name against all the local variables
374 * and substitute the short version in for 'name' if it matches one of
375 * them.
377 if (*name == '.' && isupper((unsigned char) name[1]))
378 switch (name[1]) {
379 case 'A':
380 if (!strcmp(name, ".ALLSRC"))
381 name = ALLSRC;
382 if (!strcmp(name, ".ARCHIVE"))
383 name = ARCHIVE;
384 break;
385 case 'I':
386 if (!strcmp(name, ".IMPSRC"))
387 name = IMPSRC;
388 break;
389 case 'M':
390 if (!strcmp(name, ".MEMBER"))
391 name = MEMBER;
392 break;
393 case 'O':
394 if (!strcmp(name, ".OODATE"))
395 name = OODATE;
396 break;
397 case 'P':
398 if (!strcmp(name, ".PREFIX"))
399 name = PREFIX;
400 break;
401 case 'T':
402 if (!strcmp(name, ".TARGET"))
403 name = TARGET;
404 break;
406 #ifdef notyet
407 /* for compatibility with gmake */
408 if (name[0] == '^' && name[1] == '\0')
409 name = ALLSRC;
410 #endif
413 * First look for the variable in the given context. If it's not there,
414 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
415 * depending on the FIND_* flags in 'flags'
417 var = Hash_FindEntry(&ctxt->context, name);
419 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
420 var = Hash_FindEntry(&VAR_CMD->context, name);
422 if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
423 (ctxt != VAR_GLOBAL))
425 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
426 if ((var == NULL) && (ctxt != VAR_INTERNAL)) {
427 /* VAR_INTERNAL is subordinate to VAR_GLOBAL */
428 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
431 if ((var == NULL) && (flags & FIND_ENV)) {
432 char *env;
434 if ((env = getenv(name)) != NULL) {
435 int len;
437 v = bmake_malloc(sizeof(Var));
438 v->name = bmake_strdup(name);
440 len = strlen(env);
442 Buf_Init(&v->val, len + 1);
443 Buf_AddBytes(&v->val, len, env);
445 v->flags = VAR_FROM_ENV;
446 return (v);
447 } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
448 (ctxt != VAR_GLOBAL))
450 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
451 if ((var == NULL) && (ctxt != VAR_INTERNAL)) {
452 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
454 if (var == NULL) {
455 return NULL;
456 } else {
457 return ((Var *)Hash_GetValue(var));
459 } else {
460 return NULL;
462 } else if (var == NULL) {
463 return NULL;
464 } else {
465 return ((Var *)Hash_GetValue(var));
470 *-----------------------------------------------------------------------
471 * VarFreeEnv --
472 * If the variable is an environment variable, free it
474 * Input:
475 * v the variable
476 * destroy true if the value buffer should be destroyed.
478 * Results:
479 * 1 if it is an environment variable 0 ow.
481 * Side Effects:
482 * The variable is free'ed if it is an environent variable.
483 *-----------------------------------------------------------------------
485 static Boolean
486 VarFreeEnv(Var *v, Boolean destroy)
488 if ((v->flags & VAR_FROM_ENV) == 0)
489 return FALSE;
490 free(v->name);
491 Buf_Destroy(&v->val, destroy);
492 free(v);
493 return TRUE;
497 *-----------------------------------------------------------------------
498 * VarAdd --
499 * Add a new variable of name name and value val to the given context
501 * Input:
502 * name name of variable to add
503 * val value to set it to
504 * ctxt context in which to set it
506 * Results:
507 * None
509 * Side Effects:
510 * The new variable is placed at the front of the given context
511 * The name and val arguments are duplicated so they may
512 * safely be freed.
513 *-----------------------------------------------------------------------
515 static void
516 VarAdd(const char *name, const char *val, GNode *ctxt)
518 Var *v;
519 int len;
520 Hash_Entry *h;
522 v = bmake_malloc(sizeof(Var));
524 len = val ? strlen(val) : 0;
525 Buf_Init(&v->val, len+1);
526 Buf_AddBytes(&v->val, len, val);
528 v->flags = 0;
530 h = Hash_CreateEntry(&ctxt->context, name, NULL);
531 Hash_SetValue(h, v);
532 v->name = h->name;
533 if (DEBUG(VAR) && (ctxt->flags & INTERNAL) == 0) {
534 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
539 *-----------------------------------------------------------------------
540 * Var_Delete --
541 * Remove a variable from a context.
543 * Results:
544 * None.
546 * Side Effects:
547 * The Var structure is removed and freed.
549 *-----------------------------------------------------------------------
551 void
552 Var_Delete(const char *name, GNode *ctxt)
554 Hash_Entry *ln;
555 char *cp;
557 if (strchr(name, '$')) {
558 cp = Var_Subst(NULL, name, VAR_GLOBAL, VARF_WANTRES);
559 } else {
560 cp = __DECONST(char *,name); /* XXX */
562 ln = Hash_FindEntry(&ctxt->context, cp);
563 if (DEBUG(VAR)) {
564 fprintf(debug_file, "%s:delete %s%s\n",
565 ctxt->name, cp, ln ? "" : " (not found)");
567 if (cp != name) {
568 free(cp);
570 if (ln != NULL) {
571 Var *v;
573 v = (Var *)Hash_GetValue(ln);
574 if ((v->flags & VAR_EXPORTED)) {
575 unsetenv(v->name);
577 if (strcmp(MAKE_EXPORTED, v->name) == 0) {
578 var_exportedVars = VAR_EXPORTED_NONE;
580 if (v->name != ln->name)
581 free(v->name);
582 Hash_DeleteEntry(&ctxt->context, ln);
583 Buf_Destroy(&v->val, TRUE);
584 free(v);
590 * Export a var.
591 * We ignore make internal variables (those which start with '.')
592 * Also we jump through some hoops to avoid calling setenv
593 * more than necessary since it can leak.
594 * We only manipulate flags of vars if 'parent' is set.
596 static int
597 Var_Export1(const char *name, int flags)
599 char tmp[BUFSIZ];
600 Var *v;
601 char *val = NULL;
602 int n;
603 int parent = (flags & VAR_EXPORT_PARENT);
605 if (*name == '.')
606 return 0; /* skip internals */
607 if (!name[1]) {
609 * A single char.
610 * If it is one of the vars that should only appear in
611 * local context, skip it, else we can get Var_Subst
612 * into a loop.
614 switch (name[0]) {
615 case '@':
616 case '%':
617 case '*':
618 case '!':
619 return 0;
622 v = VarFind(name, VAR_GLOBAL, 0);
623 if (v == NULL) {
624 return 0;
626 if (!parent &&
627 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
628 return 0; /* nothing to do */
630 val = Buf_GetAll(&v->val, NULL);
631 if ((flags & VAR_EXPORT_LITERAL) == 0 && strchr(val, '$')) {
632 if (parent) {
634 * Flag this as something we need to re-export.
635 * No point actually exporting it now though,
636 * the child can do it at the last minute.
638 v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
639 return 1;
641 if (v->flags & VAR_IN_USE) {
643 * We recursed while exporting in a child.
644 * This isn't going to end well, just skip it.
646 return 0;
648 n = snprintf(tmp, sizeof(tmp), "${%s}", name);
649 if (n < (int)sizeof(tmp)) {
650 val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
651 setenv(name, val, 1);
652 free(val);
654 } else {
655 if (parent) {
656 v->flags &= ~VAR_REEXPORT; /* once will do */
658 if (parent || !(v->flags & VAR_EXPORTED)) {
659 setenv(name, val, 1);
663 * This is so Var_Set knows to call Var_Export again...
665 if (parent) {
666 v->flags |= VAR_EXPORTED;
668 return 1;
672 * This gets called from our children.
674 void
675 Var_ExportVars(void)
677 char tmp[BUFSIZ];
678 Hash_Entry *var;
679 Hash_Search state;
680 Var *v;
681 char *val;
682 int n;
685 * Several make's support this sort of mechanism for tracking
686 * recursion - but each uses a different name.
687 * We allow the makefiles to update MAKELEVEL and ensure
688 * children see a correctly incremented value.
690 snprintf(tmp, sizeof(tmp), "%d", makelevel + 1);
691 setenv(MAKE_LEVEL_ENV, tmp, 1);
693 if (VAR_EXPORTED_NONE == var_exportedVars)
694 return;
696 if (VAR_EXPORTED_ALL == var_exportedVars) {
698 * Ouch! This is crazy...
700 for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
701 var != NULL;
702 var = Hash_EnumNext(&state)) {
703 v = (Var *)Hash_GetValue(var);
704 Var_Export1(v->name, 0);
706 return;
709 * We have a number of exported vars,
711 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
712 if (n < (int)sizeof(tmp)) {
713 char **av;
714 char *as;
715 int ac;
716 int i;
718 val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
719 if (*val) {
720 av = brk_string(val, &ac, FALSE, &as);
721 for (i = 0; i < ac; i++) {
722 Var_Export1(av[i], 0);
724 free(as);
725 free(av);
727 free(val);
732 * This is called when .export is seen or
733 * .MAKE.EXPORTED is modified.
734 * It is also called when any exported var is modified.
736 void
737 Var_Export(char *str, int isExport)
739 char *name;
740 char *val;
741 char **av;
742 char *as;
743 int flags;
744 int ac;
745 int i;
747 if (isExport && (!str || !str[0])) {
748 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
749 return;
752 flags = 0;
753 if (strncmp(str, "-env", 4) == 0) {
754 str += 4;
755 } else if (strncmp(str, "-literal", 8) == 0) {
756 str += 8;
757 flags |= VAR_EXPORT_LITERAL;
758 } else {
759 flags |= VAR_EXPORT_PARENT;
761 val = Var_Subst(NULL, str, VAR_GLOBAL, VARF_WANTRES);
762 if (*val) {
763 av = brk_string(val, &ac, FALSE, &as);
764 for (i = 0; i < ac; i++) {
765 name = av[i];
766 if (!name[1]) {
768 * A single char.
769 * If it is one of the vars that should only appear in
770 * local context, skip it, else we can get Var_Subst
771 * into a loop.
773 switch (name[0]) {
774 case '@':
775 case '%':
776 case '*':
777 case '!':
778 continue;
781 if (Var_Export1(name, flags)) {
782 if (VAR_EXPORTED_ALL != var_exportedVars)
783 var_exportedVars = VAR_EXPORTED_YES;
784 if (isExport && (flags & VAR_EXPORT_PARENT)) {
785 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
789 free(as);
790 free(av);
792 free(val);
797 * This is called when .unexport[-env] is seen.
799 extern char **environ;
801 void
802 Var_UnExport(char *str)
804 char tmp[BUFSIZ];
805 char *vlist;
806 char *cp;
807 Boolean unexport_env;
808 int n;
810 if (!str || !str[0]) {
811 return; /* assert? */
814 vlist = NULL;
816 str += 8;
817 unexport_env = (strncmp(str, "-env", 4) == 0);
818 if (unexport_env) {
819 char **newenv;
821 cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */
822 if (environ == savedEnv) {
823 /* we have been here before! */
824 newenv = bmake_realloc(environ, 2 * sizeof(char *));
825 } else {
826 if (savedEnv) {
827 free(savedEnv);
828 savedEnv = NULL;
830 newenv = bmake_malloc(2 * sizeof(char *));
832 if (!newenv)
833 return;
834 /* Note: we cannot safely free() the original environ. */
835 environ = savedEnv = newenv;
836 newenv[0] = NULL;
837 newenv[1] = NULL;
838 setenv(MAKE_LEVEL_ENV, cp, 1);
839 } else {
840 for (; *str != '\n' && isspace((unsigned char) *str); str++)
841 continue;
842 if (str[0] && str[0] != '\n') {
843 vlist = str;
847 if (!vlist) {
848 /* Using .MAKE.EXPORTED */
849 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
850 if (n < (int)sizeof(tmp)) {
851 vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
854 if (vlist) {
855 Var *v;
856 char **av;
857 char *as;
858 int ac;
859 int i;
861 av = brk_string(vlist, &ac, FALSE, &as);
862 for (i = 0; i < ac; i++) {
863 v = VarFind(av[i], VAR_GLOBAL, 0);
864 if (!v)
865 continue;
866 if (!unexport_env &&
867 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
868 unsetenv(v->name);
870 v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT);
872 * If we are unexporting a list,
873 * remove each one from .MAKE.EXPORTED.
874 * If we are removing them all,
875 * just delete .MAKE.EXPORTED below.
877 if (vlist == str) {
878 n = snprintf(tmp, sizeof(tmp),
879 "${" MAKE_EXPORTED ":N%s}", v->name);
880 if (n < (int)sizeof(tmp)) {
881 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
882 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0);
883 free(cp);
887 free(as);
888 free(av);
889 if (vlist != str) {
890 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
891 free(vlist);
897 *-----------------------------------------------------------------------
898 * Var_Set --
899 * Set the variable name to the value val in the given context.
901 * Input:
902 * name name of variable to set
903 * val value to give to the variable
904 * ctxt context in which to set it
906 * Results:
907 * None.
909 * Side Effects:
910 * If the variable doesn't yet exist, a new record is created for it.
911 * Else the old value is freed and the new one stuck in its place
913 * Notes:
914 * The variable is searched for only in its context before being
915 * created in that context. I.e. if the context is VAR_GLOBAL,
916 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
917 * VAR_CMD->context is searched. This is done to avoid the literally
918 * thousands of unnecessary strcmp's that used to be done to
919 * set, say, $(@) or $(<).
920 * If the context is VAR_GLOBAL though, we check if the variable
921 * was set in VAR_CMD from the command line and skip it if so.
922 *-----------------------------------------------------------------------
924 void
925 Var_Set(const char *name, const char *val, GNode *ctxt, int flags)
927 Var *v;
928 char *expanded_name = NULL;
931 * We only look for a variable in the given context since anything set
932 * here will override anything in a lower context, so there's not much
933 * point in searching them all just to save a bit of memory...
935 if (strchr(name, '$') != NULL) {
936 expanded_name = Var_Subst(NULL, name, ctxt, VARF_WANTRES);
937 if (expanded_name[0] == 0) {
938 if (DEBUG(VAR)) {
939 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
940 "name expands to empty string - ignored\n",
941 name, val);
943 free(expanded_name);
944 return;
946 name = expanded_name;
948 if (ctxt == VAR_GLOBAL) {
949 v = VarFind(name, VAR_CMD, 0);
950 if (v != NULL) {
951 if ((v->flags & VAR_FROM_CMD)) {
952 if (DEBUG(VAR)) {
953 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
955 goto out;
957 VarFreeEnv(v, TRUE);
960 v = VarFind(name, ctxt, 0);
961 if (v == NULL) {
962 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
964 * This var would normally prevent the same name being added
965 * to VAR_GLOBAL, so delete it from there if needed.
966 * Otherwise -V name may show the wrong value.
968 Var_Delete(name, VAR_GLOBAL);
970 VarAdd(name, val, ctxt);
971 } else {
972 Buf_Empty(&v->val);
973 Buf_AddBytes(&v->val, strlen(val), val);
975 if (DEBUG(VAR)) {
976 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
978 if ((v->flags & VAR_EXPORTED)) {
979 Var_Export1(name, VAR_EXPORT_PARENT);
983 * Any variables given on the command line are automatically exported
984 * to the environment (as per POSIX standard)
986 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
987 if (v == NULL) {
988 /* we just added it */
989 v = VarFind(name, ctxt, 0);
991 if (v != NULL)
992 v->flags |= VAR_FROM_CMD;
994 * If requested, don't export these in the environment
995 * individually. We still put them in MAKEOVERRIDES so
996 * that the command-line settings continue to override
997 * Makefile settings.
999 if (varNoExportEnv != TRUE)
1000 setenv(name, val, 1);
1002 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
1004 if (*name == '.') {
1005 if (strcmp(name, SAVE_DOLLARS) == 0)
1006 save_dollars = s2Boolean(val, save_dollars);
1009 out:
1010 free(expanded_name);
1011 if (v != NULL)
1012 VarFreeEnv(v, TRUE);
1016 *-----------------------------------------------------------------------
1017 * Var_Append --
1018 * The variable of the given name has the given value appended to it in
1019 * the given context.
1021 * Input:
1022 * name name of variable to modify
1023 * val String to append to it
1024 * ctxt Context in which this should occur
1026 * Results:
1027 * None
1029 * Side Effects:
1030 * If the variable doesn't exist, it is created. Else the strings
1031 * are concatenated (with a space in between).
1033 * Notes:
1034 * Only if the variable is being sought in the global context is the
1035 * environment searched.
1036 * XXX: Knows its calling circumstances in that if called with ctxt
1037 * an actual target, it will only search that context since only
1038 * a local variable could be being appended to. This is actually
1039 * a big win and must be tolerated.
1040 *-----------------------------------------------------------------------
1042 void
1043 Var_Append(const char *name, const char *val, GNode *ctxt)
1045 Var *v;
1046 Hash_Entry *h;
1047 char *expanded_name = NULL;
1049 if (strchr(name, '$') != NULL) {
1050 expanded_name = Var_Subst(NULL, name, ctxt, VARF_WANTRES);
1051 if (expanded_name[0] == 0) {
1052 if (DEBUG(VAR)) {
1053 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
1054 "name expands to empty string - ignored\n",
1055 name, val);
1057 free(expanded_name);
1058 return;
1060 name = expanded_name;
1063 v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
1065 if (v == NULL) {
1066 VarAdd(name, val, ctxt);
1067 } else {
1068 Buf_AddByte(&v->val, ' ');
1069 Buf_AddBytes(&v->val, strlen(val), val);
1071 if (DEBUG(VAR)) {
1072 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
1073 Buf_GetAll(&v->val, NULL));
1076 if (v->flags & VAR_FROM_ENV) {
1078 * If the original variable came from the environment, we
1079 * have to install it in the global context (we could place
1080 * it in the environment, but then we should provide a way to
1081 * export other variables...)
1083 v->flags &= ~VAR_FROM_ENV;
1084 h = Hash_CreateEntry(&ctxt->context, name, NULL);
1085 Hash_SetValue(h, v);
1088 free(expanded_name);
1092 *-----------------------------------------------------------------------
1093 * Var_Exists --
1094 * See if the given variable exists.
1096 * Input:
1097 * name Variable to find
1098 * ctxt Context in which to start search
1100 * Results:
1101 * TRUE if it does, FALSE if it doesn't
1103 * Side Effects:
1104 * None.
1106 *-----------------------------------------------------------------------
1108 Boolean
1109 Var_Exists(const char *name, GNode *ctxt)
1111 Var *v;
1112 char *cp;
1114 if ((cp = strchr(name, '$')) != NULL) {
1115 cp = Var_Subst(NULL, name, ctxt, VARF_WANTRES);
1117 v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
1118 free(cp);
1119 if (v == NULL) {
1120 return(FALSE);
1121 } else {
1122 (void)VarFreeEnv(v, TRUE);
1124 return(TRUE);
1128 *-----------------------------------------------------------------------
1129 * Var_Value --
1130 * Return the value of the named variable in the given context
1132 * Input:
1133 * name name to find
1134 * ctxt context in which to search for it
1136 * Results:
1137 * The value if the variable exists, NULL if it doesn't
1139 * Side Effects:
1140 * None
1141 *-----------------------------------------------------------------------
1143 char *
1144 Var_Value(const char *name, GNode *ctxt, char **frp)
1146 Var *v;
1148 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1149 *frp = NULL;
1150 if (v != NULL) {
1151 char *p = (Buf_GetAll(&v->val, NULL));
1152 if (VarFreeEnv(v, FALSE))
1153 *frp = p;
1154 return p;
1155 } else {
1156 return NULL;
1161 *-----------------------------------------------------------------------
1162 * VarHead --
1163 * Remove the tail of the given word and place the result in the given
1164 * buffer.
1166 * Input:
1167 * word Word to trim
1168 * addSpace True if need to add a space to the buffer
1169 * before sticking in the head
1170 * buf Buffer in which to store it
1172 * Results:
1173 * TRUE if characters were added to the buffer (a space needs to be
1174 * added to the buffer before the next word).
1176 * Side Effects:
1177 * The trimmed word is added to the buffer.
1179 *-----------------------------------------------------------------------
1181 static Boolean
1182 VarHead(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1183 char *word, Boolean addSpace, Buffer *buf,
1184 void *dummy)
1186 char *slash;
1188 slash = strrchr(word, '/');
1189 if (slash != NULL) {
1190 if (addSpace && vpstate->varSpace) {
1191 Buf_AddByte(buf, vpstate->varSpace);
1193 *slash = '\0';
1194 Buf_AddBytes(buf, strlen(word), word);
1195 *slash = '/';
1196 return (TRUE);
1197 } else {
1199 * If no directory part, give . (q.v. the POSIX standard)
1201 if (addSpace && vpstate->varSpace)
1202 Buf_AddByte(buf, vpstate->varSpace);
1203 Buf_AddByte(buf, '.');
1205 return(dummy ? TRUE : TRUE);
1209 *-----------------------------------------------------------------------
1210 * VarTail --
1211 * Remove the head of the given word and place the result in the given
1212 * buffer.
1214 * Input:
1215 * word Word to trim
1216 * addSpace True if need to add a space to the buffer
1217 * before adding the tail
1218 * buf Buffer in which to store it
1220 * Results:
1221 * TRUE if characters were added to the buffer (a space needs to be
1222 * added to the buffer before the next word).
1224 * Side Effects:
1225 * The trimmed word is added to the buffer.
1227 *-----------------------------------------------------------------------
1229 static Boolean
1230 VarTail(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1231 char *word, Boolean addSpace, Buffer *buf,
1232 void *dummy)
1234 char *slash;
1236 if (addSpace && vpstate->varSpace) {
1237 Buf_AddByte(buf, vpstate->varSpace);
1240 slash = strrchr(word, '/');
1241 if (slash != NULL) {
1242 *slash++ = '\0';
1243 Buf_AddBytes(buf, strlen(slash), slash);
1244 slash[-1] = '/';
1245 } else {
1246 Buf_AddBytes(buf, strlen(word), word);
1248 return (dummy ? TRUE : TRUE);
1252 *-----------------------------------------------------------------------
1253 * VarSuffix --
1254 * Place the suffix of the given word in the given buffer.
1256 * Input:
1257 * word Word to trim
1258 * addSpace TRUE if need to add a space before placing the
1259 * suffix in the buffer
1260 * buf Buffer in which to store it
1262 * Results:
1263 * TRUE if characters were added to the buffer (a space needs to be
1264 * added to the buffer before the next word).
1266 * Side Effects:
1267 * The suffix from the word is placed in the buffer.
1269 *-----------------------------------------------------------------------
1271 static Boolean
1272 VarSuffix(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1273 char *word, Boolean addSpace, Buffer *buf,
1274 void *dummy)
1276 char *dot;
1278 dot = strrchr(word, '.');
1279 if (dot != NULL) {
1280 if (addSpace && vpstate->varSpace) {
1281 Buf_AddByte(buf, vpstate->varSpace);
1283 *dot++ = '\0';
1284 Buf_AddBytes(buf, strlen(dot), dot);
1285 dot[-1] = '.';
1286 addSpace = TRUE;
1288 return (dummy ? addSpace : addSpace);
1292 *-----------------------------------------------------------------------
1293 * VarRoot --
1294 * Remove the suffix of the given word and place the result in the
1295 * buffer.
1297 * Input:
1298 * word Word to trim
1299 * addSpace TRUE if need to add a space to the buffer
1300 * before placing the root in it
1301 * buf Buffer in which to store it
1303 * Results:
1304 * TRUE if characters were added to the buffer (a space needs to be
1305 * added to the buffer before the next word).
1307 * Side Effects:
1308 * The trimmed word is added to the buffer.
1310 *-----------------------------------------------------------------------
1312 static Boolean
1313 VarRoot(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1314 char *word, Boolean addSpace, Buffer *buf,
1315 void *dummy)
1317 char *dot;
1319 if (addSpace && vpstate->varSpace) {
1320 Buf_AddByte(buf, vpstate->varSpace);
1323 dot = strrchr(word, '.');
1324 if (dot != NULL) {
1325 *dot = '\0';
1326 Buf_AddBytes(buf, strlen(word), word);
1327 *dot = '.';
1328 } else {
1329 Buf_AddBytes(buf, strlen(word), word);
1331 return (dummy ? TRUE : TRUE);
1335 *-----------------------------------------------------------------------
1336 * VarMatch --
1337 * Place the word in the buffer if it matches the given pattern.
1338 * Callback function for VarModify to implement the :M modifier.
1340 * Input:
1341 * word Word to examine
1342 * addSpace TRUE if need to add a space to the buffer
1343 * before adding the word, if it matches
1344 * buf Buffer in which to store it
1345 * pattern Pattern the word must match
1347 * Results:
1348 * TRUE if a space should be placed in the buffer before the next
1349 * word.
1351 * Side Effects:
1352 * The word may be copied to the buffer.
1354 *-----------------------------------------------------------------------
1356 static Boolean
1357 VarMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1358 char *word, Boolean addSpace, Buffer *buf,
1359 void *pattern)
1361 if (DEBUG(VAR))
1362 fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
1363 if (Str_Match(word, (char *)pattern)) {
1364 if (addSpace && vpstate->varSpace) {
1365 Buf_AddByte(buf, vpstate->varSpace);
1367 addSpace = TRUE;
1368 Buf_AddBytes(buf, strlen(word), word);
1370 return(addSpace);
1373 #ifdef SYSVVARSUB
1375 *-----------------------------------------------------------------------
1376 * VarSYSVMatch --
1377 * Place the word in the buffer if it matches the given pattern.
1378 * Callback function for VarModify to implement the System V %
1379 * modifiers.
1381 * Input:
1382 * word Word to examine
1383 * addSpace TRUE if need to add a space to the buffer
1384 * before adding the word, if it matches
1385 * buf Buffer in which to store it
1386 * patp Pattern the word must match
1388 * Results:
1389 * TRUE if a space should be placed in the buffer before the next
1390 * word.
1392 * Side Effects:
1393 * The word may be copied to the buffer.
1395 *-----------------------------------------------------------------------
1397 static Boolean
1398 VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
1399 char *word, Boolean addSpace, Buffer *buf,
1400 void *patp)
1402 int len;
1403 char *ptr;
1404 VarPattern *pat = (VarPattern *)patp;
1405 char *varexp;
1407 if (addSpace && vpstate->varSpace)
1408 Buf_AddByte(buf, vpstate->varSpace);
1410 addSpace = TRUE;
1412 if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
1413 varexp = Var_Subst(NULL, pat->rhs, ctx, VARF_WANTRES);
1414 Str_SYSVSubst(buf, varexp, ptr, len);
1415 free(varexp);
1416 } else {
1417 Buf_AddBytes(buf, strlen(word), word);
1420 return(addSpace);
1422 #endif
1426 *-----------------------------------------------------------------------
1427 * VarNoMatch --
1428 * Place the word in the buffer if it doesn't match the given pattern.
1429 * Callback function for VarModify to implement the :N modifier.
1431 * Input:
1432 * word Word to examine
1433 * addSpace TRUE if need to add a space to the buffer
1434 * before adding the word, if it matches
1435 * buf Buffer in which to store it
1436 * pattern Pattern the word must match
1438 * Results:
1439 * TRUE if a space should be placed in the buffer before the next
1440 * word.
1442 * Side Effects:
1443 * The word may be copied to the buffer.
1445 *-----------------------------------------------------------------------
1447 static Boolean
1448 VarNoMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1449 char *word, Boolean addSpace, Buffer *buf,
1450 void *pattern)
1452 if (!Str_Match(word, (char *)pattern)) {
1453 if (addSpace && vpstate->varSpace) {
1454 Buf_AddByte(buf, vpstate->varSpace);
1456 addSpace = TRUE;
1457 Buf_AddBytes(buf, strlen(word), word);
1459 return(addSpace);
1464 *-----------------------------------------------------------------------
1465 * VarSubstitute --
1466 * Perform a string-substitution on the given word, placing the
1467 * result in the passed buffer.
1469 * Input:
1470 * word Word to modify
1471 * addSpace True if space should be added before
1472 * other characters
1473 * buf Buffer for result
1474 * patternp Pattern for substitution
1476 * Results:
1477 * TRUE if a space is needed before more characters are added.
1479 * Side Effects:
1480 * None.
1482 *-----------------------------------------------------------------------
1484 static Boolean
1485 VarSubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1486 char *word, Boolean addSpace, Buffer *buf,
1487 void *patternp)
1489 int wordLen; /* Length of word */
1490 char *cp; /* General pointer */
1491 VarPattern *pattern = (VarPattern *)patternp;
1493 wordLen = strlen(word);
1494 if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
1495 (VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1497 * Still substituting -- break it down into simple anchored cases
1498 * and if none of them fits, perform the general substitution case.
1500 if ((pattern->flags & VAR_MATCH_START) &&
1501 (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
1503 * Anchored at start and beginning of word matches pattern
1505 if ((pattern->flags & VAR_MATCH_END) &&
1506 (wordLen == pattern->leftLen)) {
1508 * Also anchored at end and matches to the end (word
1509 * is same length as pattern) add space and rhs only
1510 * if rhs is non-null.
1512 if (pattern->rightLen != 0) {
1513 if (addSpace && vpstate->varSpace) {
1514 Buf_AddByte(buf, vpstate->varSpace);
1516 addSpace = TRUE;
1517 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1519 pattern->flags |= VAR_SUB_MATCHED;
1520 } else if (pattern->flags & VAR_MATCH_END) {
1522 * Doesn't match to end -- copy word wholesale
1524 goto nosub;
1525 } else {
1527 * Matches at start but need to copy in trailing characters
1529 if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1530 if (addSpace && vpstate->varSpace) {
1531 Buf_AddByte(buf, vpstate->varSpace);
1533 addSpace = TRUE;
1535 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1536 Buf_AddBytes(buf, wordLen - pattern->leftLen,
1537 (word + pattern->leftLen));
1538 pattern->flags |= VAR_SUB_MATCHED;
1540 } else if (pattern->flags & VAR_MATCH_START) {
1542 * Had to match at start of word and didn't -- copy whole word.
1544 goto nosub;
1545 } else if (pattern->flags & VAR_MATCH_END) {
1547 * Anchored at end, Find only place match could occur (leftLen
1548 * characters from the end of the word) and see if it does. Note
1549 * that because the $ will be left at the end of the lhs, we have
1550 * to use strncmp.
1552 cp = word + (wordLen - pattern->leftLen);
1553 if ((cp >= word) &&
1554 (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
1556 * Match found. If we will place characters in the buffer,
1557 * add a space before hand as indicated by addSpace, then
1558 * stuff in the initial, unmatched part of the word followed
1559 * by the right-hand-side.
1561 if (((cp - word) + pattern->rightLen) != 0) {
1562 if (addSpace && vpstate->varSpace) {
1563 Buf_AddByte(buf, vpstate->varSpace);
1565 addSpace = TRUE;
1567 Buf_AddBytes(buf, cp - word, word);
1568 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1569 pattern->flags |= VAR_SUB_MATCHED;
1570 } else {
1572 * Had to match at end and didn't. Copy entire word.
1574 goto nosub;
1576 } else {
1578 * Pattern is unanchored: search for the pattern in the word using
1579 * String_FindSubstring, copying unmatched portions and the
1580 * right-hand-side for each match found, handling non-global
1581 * substitutions correctly, etc. When the loop is done, any
1582 * remaining part of the word (word and wordLen are adjusted
1583 * accordingly through the loop) is copied straight into the
1584 * buffer.
1585 * addSpace is set FALSE as soon as a space is added to the
1586 * buffer.
1588 Boolean done;
1589 int origSize;
1591 done = FALSE;
1592 origSize = Buf_Size(buf);
1593 while (!done) {
1594 cp = Str_FindSubstring(word, pattern->lhs);
1595 if (cp != NULL) {
1596 if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1597 Buf_AddByte(buf, vpstate->varSpace);
1598 addSpace = FALSE;
1600 Buf_AddBytes(buf, cp-word, word);
1601 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1602 wordLen -= (cp - word) + pattern->leftLen;
1603 word = cp + pattern->leftLen;
1604 if (wordLen == 0) {
1605 done = TRUE;
1607 if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
1608 done = TRUE;
1610 pattern->flags |= VAR_SUB_MATCHED;
1611 } else {
1612 done = TRUE;
1615 if (wordLen != 0) {
1616 if (addSpace && vpstate->varSpace) {
1617 Buf_AddByte(buf, vpstate->varSpace);
1619 Buf_AddBytes(buf, wordLen, word);
1622 * If added characters to the buffer, need to add a space
1623 * before we add any more. If we didn't add any, just return
1624 * the previous value of addSpace.
1626 return ((Buf_Size(buf) != origSize) || addSpace);
1628 return (addSpace);
1630 nosub:
1631 if (addSpace && vpstate->varSpace) {
1632 Buf_AddByte(buf, vpstate->varSpace);
1634 Buf_AddBytes(buf, wordLen, word);
1635 return(TRUE);
1638 #ifndef NO_REGEX
1640 *-----------------------------------------------------------------------
1641 * VarREError --
1642 * Print the error caused by a regcomp or regexec call.
1644 * Results:
1645 * None.
1647 * Side Effects:
1648 * An error gets printed.
1650 *-----------------------------------------------------------------------
1652 static void
1653 VarREError(int reerr, regex_t *pat, const char *str)
1655 char *errbuf;
1656 int errlen;
1658 errlen = regerror(reerr, pat, 0, 0);
1659 errbuf = bmake_malloc(errlen);
1660 regerror(reerr, pat, errbuf, errlen);
1661 Error("%s: %s", str, errbuf);
1662 free(errbuf);
1667 *-----------------------------------------------------------------------
1668 * VarRESubstitute --
1669 * Perform a regex substitution on the given word, placing the
1670 * result in the passed buffer.
1672 * Results:
1673 * TRUE if a space is needed before more characters are added.
1675 * Side Effects:
1676 * None.
1678 *-----------------------------------------------------------------------
1680 static Boolean
1681 VarRESubstitute(GNode *ctx MAKE_ATTR_UNUSED,
1682 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1683 char *word, Boolean addSpace, Buffer *buf,
1684 void *patternp)
1686 VarREPattern *pat;
1687 int xrv;
1688 char *wp;
1689 char *rp;
1690 int added;
1691 int flags = 0;
1693 #define MAYBE_ADD_SPACE() \
1694 if (addSpace && !added) \
1695 Buf_AddByte(buf, ' '); \
1696 added = 1
1698 added = 0;
1699 wp = word;
1700 pat = patternp;
1702 if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1703 (VAR_SUB_ONE|VAR_SUB_MATCHED))
1704 xrv = REG_NOMATCH;
1705 else {
1706 tryagain:
1707 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1710 switch (xrv) {
1711 case 0:
1712 pat->flags |= VAR_SUB_MATCHED;
1713 if (pat->matches[0].rm_so > 0) {
1714 MAYBE_ADD_SPACE();
1715 Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1718 for (rp = pat->replace; *rp; rp++) {
1719 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1720 MAYBE_ADD_SPACE();
1721 Buf_AddByte(buf,rp[1]);
1722 rp++;
1724 else if ((*rp == '&') ||
1725 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1726 int n;
1727 const char *subbuf;
1728 int sublen;
1729 char errstr[3];
1731 if (*rp == '&') {
1732 n = 0;
1733 errstr[0] = '&';
1734 errstr[1] = '\0';
1735 } else {
1736 n = rp[1] - '0';
1737 errstr[0] = '\\';
1738 errstr[1] = rp[1];
1739 errstr[2] = '\0';
1740 rp++;
1743 if (n > pat->nsub) {
1744 Error("No subexpression %s", &errstr[0]);
1745 subbuf = "";
1746 sublen = 0;
1747 } else if ((pat->matches[n].rm_so == -1) &&
1748 (pat->matches[n].rm_eo == -1)) {
1749 Error("No match for subexpression %s", &errstr[0]);
1750 subbuf = "";
1751 sublen = 0;
1752 } else {
1753 subbuf = wp + pat->matches[n].rm_so;
1754 sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1757 if (sublen > 0) {
1758 MAYBE_ADD_SPACE();
1759 Buf_AddBytes(buf, sublen, subbuf);
1761 } else {
1762 MAYBE_ADD_SPACE();
1763 Buf_AddByte(buf, *rp);
1766 wp += pat->matches[0].rm_eo;
1767 if (pat->flags & VAR_SUB_GLOBAL) {
1768 flags |= REG_NOTBOL;
1769 if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1770 MAYBE_ADD_SPACE();
1771 Buf_AddByte(buf, *wp);
1772 wp++;
1775 if (*wp)
1776 goto tryagain;
1778 if (*wp) {
1779 MAYBE_ADD_SPACE();
1780 Buf_AddBytes(buf, strlen(wp), wp);
1782 break;
1783 default:
1784 VarREError(xrv, &pat->re, "Unexpected regex error");
1785 /* fall through */
1786 case REG_NOMATCH:
1787 if (*wp) {
1788 MAYBE_ADD_SPACE();
1789 Buf_AddBytes(buf,strlen(wp),wp);
1791 break;
1793 return(addSpace||added);
1795 #endif
1800 *-----------------------------------------------------------------------
1801 * VarLoopExpand --
1802 * Implements the :@<temp>@<string>@ modifier of ODE make.
1803 * We set the temp variable named in pattern.lhs to word and expand
1804 * pattern.rhs storing the result in the passed buffer.
1806 * Input:
1807 * word Word to modify
1808 * addSpace True if space should be added before
1809 * other characters
1810 * buf Buffer for result
1811 * pattern Datafor substitution
1813 * Results:
1814 * TRUE if a space is needed before more characters are added.
1816 * Side Effects:
1817 * None.
1819 *-----------------------------------------------------------------------
1821 static Boolean
1822 VarLoopExpand(GNode *ctx MAKE_ATTR_UNUSED,
1823 Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1824 char *word, Boolean addSpace, Buffer *buf,
1825 void *loopp)
1827 VarLoop_t *loop = (VarLoop_t *)loopp;
1828 char *s;
1829 int slen;
1831 if (word && *word) {
1832 Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
1833 s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum | VARF_WANTRES);
1834 if (s != NULL && *s != '\0') {
1835 if (addSpace && *s != '\n')
1836 Buf_AddByte(buf, ' ');
1837 Buf_AddBytes(buf, (slen = strlen(s)), s);
1838 addSpace = (slen > 0 && s[slen - 1] != '\n');
1839 free(s);
1842 return addSpace;
1847 *-----------------------------------------------------------------------
1848 * VarSelectWords --
1849 * Implements the :[start..end] modifier.
1850 * This is a special case of VarModify since we want to be able
1851 * to scan the list backwards if start > end.
1853 * Input:
1854 * str String whose words should be trimmed
1855 * seldata words to select
1857 * Results:
1858 * A string of all the words selected.
1860 * Side Effects:
1861 * None.
1863 *-----------------------------------------------------------------------
1865 static char *
1866 VarSelectWords(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1867 const char *str, VarSelectWords_t *seldata)
1869 Buffer buf; /* Buffer for the new string */
1870 Boolean addSpace; /* TRUE if need to add a space to the
1871 * buffer before adding the trimmed
1872 * word */
1873 char **av; /* word list */
1874 char *as; /* word list memory */
1875 int ac, i;
1876 int start, end, step;
1878 Buf_Init(&buf, 0);
1879 addSpace = FALSE;
1881 if (vpstate->oneBigWord) {
1882 /* fake what brk_string() would do if there were only one word */
1883 ac = 1;
1884 av = bmake_malloc((ac + 1) * sizeof(char *));
1885 as = bmake_strdup(str);
1886 av[0] = as;
1887 av[1] = NULL;
1888 } else {
1889 av = brk_string(str, &ac, FALSE, &as);
1893 * Now sanitize seldata.
1894 * If seldata->start or seldata->end are negative, convert them to
1895 * the positive equivalents (-1 gets converted to argc, -2 gets
1896 * converted to (argc-1), etc.).
1898 if (seldata->start < 0)
1899 seldata->start = ac + seldata->start + 1;
1900 if (seldata->end < 0)
1901 seldata->end = ac + seldata->end + 1;
1904 * We avoid scanning more of the list than we need to.
1906 if (seldata->start > seldata->end) {
1907 start = MIN(ac, seldata->start) - 1;
1908 end = MAX(0, seldata->end - 1);
1909 step = -1;
1910 } else {
1911 start = MAX(0, seldata->start - 1);
1912 end = MIN(ac, seldata->end);
1913 step = 1;
1916 for (i = start;
1917 (step < 0 && i >= end) || (step > 0 && i < end);
1918 i += step) {
1919 if (av[i] && *av[i]) {
1920 if (addSpace && vpstate->varSpace) {
1921 Buf_AddByte(&buf, vpstate->varSpace);
1923 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
1924 addSpace = TRUE;
1928 free(as);
1929 free(av);
1931 return Buf_Destroy(&buf, FALSE);
1936 * VarRealpath --
1937 * Replace each word with the result of realpath()
1938 * if successful.
1940 static Boolean
1941 VarRealpath(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1942 char *word, Boolean addSpace, Buffer *buf,
1943 void *patternp MAKE_ATTR_UNUSED)
1945 struct stat st;
1946 char rbuf[MAXPATHLEN];
1947 char *rp;
1949 if (addSpace && vpstate->varSpace) {
1950 Buf_AddByte(buf, vpstate->varSpace);
1952 addSpace = TRUE;
1953 rp = cached_realpath(word, rbuf);
1954 if (rp && *rp == '/' && stat(rp, &st) == 0)
1955 word = rp;
1957 Buf_AddBytes(buf, strlen(word), word);
1958 return(addSpace);
1962 *-----------------------------------------------------------------------
1963 * VarModify --
1964 * Modify each of the words of the passed string using the given
1965 * function. Used to implement all modifiers.
1967 * Input:
1968 * str String whose words should be trimmed
1969 * modProc Function to use to modify them
1970 * datum Datum to pass it
1972 * Results:
1973 * A string of all the words modified appropriately.
1975 * Side Effects:
1976 * None.
1978 *-----------------------------------------------------------------------
1980 static char *
1981 VarModify(GNode *ctx, Var_Parse_State *vpstate,
1982 const char *str,
1983 Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
1984 Boolean, Buffer *, void *),
1985 void *datum)
1987 Buffer buf; /* Buffer for the new string */
1988 Boolean addSpace; /* TRUE if need to add a space to the
1989 * buffer before adding the trimmed
1990 * word */
1991 char **av; /* word list */
1992 char *as; /* word list memory */
1993 int ac, i;
1995 Buf_Init(&buf, 0);
1996 addSpace = FALSE;
1998 if (vpstate->oneBigWord) {
1999 /* fake what brk_string() would do if there were only one word */
2000 ac = 1;
2001 av = bmake_malloc((ac + 1) * sizeof(char *));
2002 as = bmake_strdup(str);
2003 av[0] = as;
2004 av[1] = NULL;
2005 } else {
2006 av = brk_string(str, &ac, FALSE, &as);
2009 for (i = 0; i < ac; i++) {
2010 addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum);
2013 free(as);
2014 free(av);
2016 return Buf_Destroy(&buf, FALSE);
2020 static int
2021 VarWordCompare(const void *a, const void *b)
2023 int r = strcmp(*(const char * const *)a, *(const char * const *)b);
2024 return r;
2028 *-----------------------------------------------------------------------
2029 * VarOrder --
2030 * Order the words in the string.
2032 * Input:
2033 * str String whose words should be sorted.
2034 * otype How to order: s - sort, x - random.
2036 * Results:
2037 * A string containing the words ordered.
2039 * Side Effects:
2040 * None.
2042 *-----------------------------------------------------------------------
2044 static char *
2045 VarOrder(const char *str, const char otype)
2047 Buffer buf; /* Buffer for the new string */
2048 char **av; /* word list [first word does not count] */
2049 char *as; /* word list memory */
2050 int ac, i;
2052 Buf_Init(&buf, 0);
2054 av = brk_string(str, &ac, FALSE, &as);
2056 if (ac > 0)
2057 switch (otype) {
2058 case 's': /* sort alphabetically */
2059 qsort(av, ac, sizeof(char *), VarWordCompare);
2060 break;
2061 case 'x': /* randomize */
2063 int rndidx;
2064 char *t;
2067 * We will use [ac..2] range for mod factors. This will produce
2068 * random numbers in [(ac-1)..0] interval, and minimal
2069 * reasonable value for mod factor is 2 (the mod 1 will produce
2070 * 0 with probability 1).
2072 for (i = ac-1; i > 0; i--) {
2073 rndidx = random() % (i + 1);
2074 if (i != rndidx) {
2075 t = av[i];
2076 av[i] = av[rndidx];
2077 av[rndidx] = t;
2081 } /* end of switch */
2083 for (i = 0; i < ac; i++) {
2084 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2085 if (i != ac - 1)
2086 Buf_AddByte(&buf, ' ');
2089 free(as);
2090 free(av);
2092 return Buf_Destroy(&buf, FALSE);
2097 *-----------------------------------------------------------------------
2098 * VarUniq --
2099 * Remove adjacent duplicate words.
2101 * Input:
2102 * str String whose words should be sorted
2104 * Results:
2105 * A string containing the resulting words.
2107 * Side Effects:
2108 * None.
2110 *-----------------------------------------------------------------------
2112 static char *
2113 VarUniq(const char *str)
2115 Buffer buf; /* Buffer for new string */
2116 char **av; /* List of words to affect */
2117 char *as; /* Word list memory */
2118 int ac, i, j;
2120 Buf_Init(&buf, 0);
2121 av = brk_string(str, &ac, FALSE, &as);
2123 if (ac > 1) {
2124 for (j = 0, i = 1; i < ac; i++)
2125 if (strcmp(av[i], av[j]) != 0 && (++j != i))
2126 av[j] = av[i];
2127 ac = j + 1;
2130 for (i = 0; i < ac; i++) {
2131 Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2132 if (i != ac - 1)
2133 Buf_AddByte(&buf, ' ');
2136 free(as);
2137 free(av);
2139 return Buf_Destroy(&buf, FALSE);
2144 *-----------------------------------------------------------------------
2145 * VarGetPattern --
2146 * Pass through the tstr looking for 1) escaped delimiters,
2147 * '$'s and backslashes (place the escaped character in
2148 * uninterpreted) and 2) unescaped $'s that aren't before
2149 * the delimiter (expand the variable substitution unless flags
2150 * has VAR_NOSUBST set).
2151 * Return the expanded string or NULL if the delimiter was missing
2152 * If pattern is specified, handle escaped ampersands, and replace
2153 * unescaped ampersands with the lhs of the pattern.
2155 * Results:
2156 * A string of all the words modified appropriately.
2157 * If length is specified, return the string length of the buffer
2158 * If flags is specified and the last character of the pattern is a
2159 * $ set the VAR_MATCH_END bit of flags.
2161 * Side Effects:
2162 * None.
2163 *-----------------------------------------------------------------------
2165 static char *
2166 VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
2167 int flags, const char **tstr, int delim, int *vflags,
2168 int *length, VarPattern *pattern)
2170 const char *cp;
2171 char *rstr;
2172 Buffer buf;
2173 int junk;
2174 int errnum = flags & VARF_UNDEFERR;
2176 Buf_Init(&buf, 0);
2177 if (length == NULL)
2178 length = &junk;
2180 #define IS_A_MATCH(cp, delim) \
2181 ((cp[0] == '\\') && ((cp[1] == delim) || \
2182 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
2185 * Skim through until the matching delimiter is found;
2186 * pick up variable substitutions on the way. Also allow
2187 * backslashes to quote the delimiter, $, and \, but don't
2188 * touch other backslashes.
2190 for (cp = *tstr; *cp && (*cp != delim); cp++) {
2191 if (IS_A_MATCH(cp, delim)) {
2192 Buf_AddByte(&buf, cp[1]);
2193 cp++;
2194 } else if (*cp == '$') {
2195 if (cp[1] == delim) {
2196 if (vflags == NULL)
2197 Buf_AddByte(&buf, *cp);
2198 else
2200 * Unescaped $ at end of pattern => anchor
2201 * pattern at end.
2203 *vflags |= VAR_MATCH_END;
2204 } else {
2205 if (vflags == NULL || (*vflags & VAR_NOSUBST) == 0) {
2206 char *cp2;
2207 int len;
2208 void *freeIt;
2211 * If unescaped dollar sign not before the
2212 * delimiter, assume it's a variable
2213 * substitution and recurse.
2215 cp2 = Var_Parse(cp, ctxt, errnum | VARF_WANTRES, &len,
2216 &freeIt);
2217 Buf_AddBytes(&buf, strlen(cp2), cp2);
2218 free(freeIt);
2219 cp += len - 1;
2220 } else {
2221 const char *cp2 = &cp[1];
2223 if (*cp2 == PROPEN || *cp2 == BROPEN) {
2225 * Find the end of this variable reference
2226 * and suck it in without further ado.
2227 * It will be interperated later.
2229 int have = *cp2;
2230 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
2231 int depth = 1;
2233 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
2234 if (cp2[-1] != '\\') {
2235 if (*cp2 == have)
2236 ++depth;
2237 if (*cp2 == want)
2238 --depth;
2241 Buf_AddBytes(&buf, cp2 - cp, cp);
2242 cp = --cp2;
2243 } else
2244 Buf_AddByte(&buf, *cp);
2248 else if (pattern && *cp == '&')
2249 Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
2250 else
2251 Buf_AddByte(&buf, *cp);
2254 if (*cp != delim) {
2255 *tstr = cp;
2256 *length = 0;
2257 return NULL;
2260 *tstr = ++cp;
2261 *length = Buf_Size(&buf);
2262 rstr = Buf_Destroy(&buf, FALSE);
2263 if (DEBUG(VAR))
2264 fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
2265 return rstr;
2269 *-----------------------------------------------------------------------
2270 * VarQuote --
2271 * Quote shell meta-characters and space characters in the string
2273 * Results:
2274 * The quoted string
2276 * Side Effects:
2277 * None.
2279 *-----------------------------------------------------------------------
2281 static char *
2282 VarQuote(char *str)
2285 Buffer buf;
2286 const char *newline;
2287 size_t nlen;
2289 if ((newline = Shell_GetNewline()) == NULL)
2290 newline = "\\\n";
2291 nlen = strlen(newline);
2293 Buf_Init(&buf, 0);
2295 for (; *str != '\0'; str++) {
2296 if (*str == '\n') {
2297 Buf_AddBytes(&buf, nlen, newline);
2298 continue;
2300 if (isspace((unsigned char)*str) || ismeta((unsigned char)*str))
2301 Buf_AddByte(&buf, '\\');
2302 Buf_AddByte(&buf, *str);
2305 str = Buf_Destroy(&buf, FALSE);
2306 if (DEBUG(VAR))
2307 fprintf(debug_file, "QuoteMeta: [%s]\n", str);
2308 return str;
2312 *-----------------------------------------------------------------------
2313 * VarHash --
2314 * Hash the string using the MurmurHash3 algorithm.
2315 * Output is computed using 32bit Little Endian arithmetic.
2317 * Input:
2318 * str String to modify
2320 * Results:
2321 * Hash value of str, encoded as 8 hex digits.
2323 * Side Effects:
2324 * None.
2326 *-----------------------------------------------------------------------
2328 static char *
2329 VarHash(char *str)
2331 static const char hexdigits[16] = "0123456789abcdef";
2332 Buffer buf;
2333 size_t len, len2;
2334 unsigned char *ustr = (unsigned char *)str;
2335 unsigned int h, k, c1, c2;
2337 h = 0x971e137bU;
2338 c1 = 0x95543787U;
2339 c2 = 0x2ad7eb25U;
2340 len2 = strlen(str);
2342 for (len = len2; len; ) {
2343 k = 0;
2344 switch (len) {
2345 default:
2346 k = (ustr[3] << 24) | (ustr[2] << 16) | (ustr[1] << 8) | ustr[0];
2347 len -= 4;
2348 ustr += 4;
2349 break;
2350 case 3:
2351 k |= (ustr[2] << 16);
2352 case 2:
2353 k |= (ustr[1] << 8);
2354 case 1:
2355 k |= ustr[0];
2356 len = 0;
2358 c1 = c1 * 5 + 0x7b7d159cU;
2359 c2 = c2 * 5 + 0x6bce6396U;
2360 k *= c1;
2361 k = (k << 11) ^ (k >> 21);
2362 k *= c2;
2363 h = (h << 13) ^ (h >> 19);
2364 h = h * 5 + 0x52dce729U;
2365 h ^= k;
2367 h ^= len2;
2368 h *= 0x85ebca6b;
2369 h ^= h >> 13;
2370 h *= 0xc2b2ae35;
2371 h ^= h >> 16;
2373 Buf_Init(&buf, 0);
2374 for (len = 0; len < 8; ++len) {
2375 Buf_AddByte(&buf, hexdigits[h & 15]);
2376 h >>= 4;
2379 return Buf_Destroy(&buf, FALSE);
2382 static char *
2383 VarStrftime(const char *fmt, int zulu)
2385 char buf[BUFSIZ];
2386 time_t utc;
2388 time(&utc);
2389 if (!*fmt)
2390 fmt = "%c";
2391 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2393 buf[sizeof(buf) - 1] = '\0';
2394 return bmake_strdup(buf);
2398 * Now we need to apply any modifiers the user wants applied.
2399 * These are:
2400 * :M<pattern> words which match the given <pattern>.
2401 * <pattern> is of the standard file
2402 * wildcarding form.
2403 * :N<pattern> words which do not match the given <pattern>.
2404 * :S<d><pat1><d><pat2><d>[1gW]
2405 * Substitute <pat2> for <pat1> in the value
2406 * :C<d><pat1><d><pat2><d>[1gW]
2407 * Substitute <pat2> for regex <pat1> in the value
2408 * :H Substitute the head of each word
2409 * :T Substitute the tail of each word
2410 * :E Substitute the extension (minus '.') of
2411 * each word
2412 * :R Substitute the root of each word
2413 * (pathname minus the suffix).
2414 * :O ("Order") Alphabeticaly sort words in variable.
2415 * :Ox ("intermiX") Randomize words in variable.
2416 * :u ("uniq") Remove adjacent duplicate words.
2417 * :tu Converts the variable contents to uppercase.
2418 * :tl Converts the variable contents to lowercase.
2419 * :ts[c] Sets varSpace - the char used to
2420 * separate words to 'c'. If 'c' is
2421 * omitted then no separation is used.
2422 * :tW Treat the variable contents as a single
2423 * word, even if it contains spaces.
2424 * (Mnemonic: one big 'W'ord.)
2425 * :tw Treat the variable contents as multiple
2426 * space-separated words.
2427 * (Mnemonic: many small 'w'ords.)
2428 * :[index] Select a single word from the value.
2429 * :[start..end] Select multiple words from the value.
2430 * :[*] or :[0] Select the entire value, as a single
2431 * word. Equivalent to :tW.
2432 * :[@] Select the entire value, as multiple
2433 * words. Undoes the effect of :[*].
2434 * Equivalent to :tw.
2435 * :[#] Returns the number of words in the value.
2437 * :?<true-value>:<false-value>
2438 * If the variable evaluates to true, return
2439 * true value, else return the second value.
2440 * :lhs=rhs Like :S, but the rhs goes to the end of
2441 * the invocation.
2442 * :sh Treat the current value as a command
2443 * to be run, new value is its output.
2444 * The following added so we can handle ODE makefiles.
2445 * :@<tmpvar>@<newval>@
2446 * Assign a temporary local variable <tmpvar>
2447 * to the current value of each word in turn
2448 * and replace each word with the result of
2449 * evaluating <newval>
2450 * :D<newval> Use <newval> as value if variable defined
2451 * :U<newval> Use <newval> as value if variable undefined
2452 * :L Use the name of the variable as the value.
2453 * :P Use the path of the node that has the same
2454 * name as the variable as the value. This
2455 * basically includes an implied :L so that
2456 * the common method of refering to the path
2457 * of your dependent 'x' in a rule is to use
2458 * the form '${x:P}'.
2459 * :!<cmd>! Run cmd much the same as :sh run's the
2460 * current value of the variable.
2461 * The ::= modifiers, actually assign a value to the variable.
2462 * Their main purpose is in supporting modifiers of .for loop
2463 * iterators and other obscure uses. They always expand to
2464 * nothing. In a target rule that would otherwise expand to an
2465 * empty line they can be preceded with @: to keep make happy.
2466 * Eg.
2468 * foo: .USE
2469 * .for i in ${.TARGET} ${.TARGET:R}.gz
2470 * @: ${t::=$i}
2471 * @echo blah ${t:T}
2472 * .endfor
2474 * ::=<str> Assigns <str> as the new value of variable.
2475 * ::?=<str> Assigns <str> as value of variable if
2476 * it was not already set.
2477 * ::+=<str> Appends <str> to variable.
2478 * ::!=<cmd> Assigns output of <cmd> as the new value of
2479 * variable.
2482 /* we now have some modifiers with long names */
2483 #define STRMOD_MATCH(s, want, n) \
2484 (strncmp(s, want, n) == 0 && (s[n] == endc || s[n] == ':'))
2486 static char *
2487 ApplyModifiers(char *nstr, const char *tstr,
2488 int startc, int endc,
2489 Var *v, GNode *ctxt, int flags,
2490 int *lengthPtr, void **freePtr)
2492 const char *start;
2493 const char *cp; /* Secondary pointer into str (place marker
2494 * for tstr) */
2495 char *newStr; /* New value to return */
2496 char termc; /* Character which terminated scan */
2497 int cnt; /* Used to count brace pairs when variable in
2498 * in parens or braces */
2499 char delim;
2500 int modifier; /* that we are processing */
2501 Var_Parse_State parsestate; /* Flags passed to helper functions */
2503 delim = '\0';
2504 parsestate.oneBigWord = FALSE;
2505 parsestate.varSpace = ' '; /* word separator */
2507 start = cp = tstr;
2509 while (*tstr && *tstr != endc) {
2511 if (*tstr == '$') {
2513 * We may have some complex modifiers in a variable.
2515 void *freeIt;
2516 char *rval;
2517 int rlen;
2518 int c;
2520 rval = Var_Parse(tstr, ctxt, flags, &rlen, &freeIt);
2523 * If we have not parsed up to endc or ':',
2524 * we are not interested.
2526 if (rval != NULL && *rval &&
2527 (c = tstr[rlen]) != '\0' &&
2528 c != ':' &&
2529 c != endc) {
2530 free(freeIt);
2531 goto apply_mods;
2534 if (DEBUG(VAR)) {
2535 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
2536 rval, rlen, tstr, rlen, tstr + rlen);
2539 tstr += rlen;
2541 if (rval != NULL && *rval) {
2542 int used;
2544 nstr = ApplyModifiers(nstr, rval,
2545 0, 0, v, ctxt, flags, &used, freePtr);
2546 if (nstr == var_Error
2547 || (nstr == varNoError && (flags & VARF_UNDEFERR) == 0)
2548 || strlen(rval) != (size_t) used) {
2549 free(freeIt);
2550 goto out; /* error already reported */
2553 free(freeIt);
2554 if (*tstr == ':')
2555 tstr++;
2556 else if (!*tstr && endc) {
2557 Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name);
2558 goto out;
2560 continue;
2562 apply_mods:
2563 if (DEBUG(VAR)) {
2564 fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", v->name,
2565 *tstr, nstr);
2567 newStr = var_Error;
2568 switch ((modifier = *tstr)) {
2569 case ':':
2571 if (tstr[1] == '=' ||
2572 (tstr[2] == '=' &&
2573 (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
2575 * "::=", "::!=", "::+=", or "::?="
2577 GNode *v_ctxt; /* context where v belongs */
2578 const char *emsg;
2579 char *sv_name;
2580 VarPattern pattern;
2581 int how;
2582 int vflags;
2584 if (v->name[0] == 0)
2585 goto bad_modifier;
2587 v_ctxt = ctxt;
2588 sv_name = NULL;
2589 ++tstr;
2590 if (v->flags & VAR_JUNK) {
2592 * We need to bmake_strdup() it incase
2593 * VarGetPattern() recurses.
2595 sv_name = v->name;
2596 v->name = bmake_strdup(v->name);
2597 } else if (ctxt != VAR_GLOBAL) {
2598 Var *gv = VarFind(v->name, ctxt, 0);
2599 if (gv == NULL)
2600 v_ctxt = VAR_GLOBAL;
2601 else
2602 VarFreeEnv(gv, TRUE);
2605 switch ((how = *tstr)) {
2606 case '+':
2607 case '?':
2608 case '!':
2609 cp = &tstr[2];
2610 break;
2611 default:
2612 cp = ++tstr;
2613 break;
2615 delim = startc == PROPEN ? PRCLOSE : BRCLOSE;
2616 pattern.flags = 0;
2618 vflags = (flags & VARF_WANTRES) ? 0 : VAR_NOSUBST;
2619 pattern.rhs = VarGetPattern(ctxt, &parsestate, flags,
2620 &cp, delim, &vflags,
2621 &pattern.rightLen,
2622 NULL);
2623 if (v->flags & VAR_JUNK) {
2624 /* restore original name */
2625 free(v->name);
2626 v->name = sv_name;
2628 if (pattern.rhs == NULL)
2629 goto cleanup;
2631 termc = *--cp;
2632 delim = '\0';
2634 if (flags & VARF_WANTRES) {
2635 switch (how) {
2636 case '+':
2637 Var_Append(v->name, pattern.rhs, v_ctxt);
2638 break;
2639 case '!':
2640 newStr = Cmd_Exec(pattern.rhs, &emsg);
2641 if (emsg)
2642 Error(emsg, nstr);
2643 else
2644 Var_Set(v->name, newStr, v_ctxt, 0);
2645 free(newStr);
2646 break;
2647 case '?':
2648 if ((v->flags & VAR_JUNK) == 0)
2649 break;
2650 /* FALLTHROUGH */
2651 default:
2652 Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2653 break;
2656 free(UNCONST(pattern.rhs));
2657 newStr = varNoError;
2658 break;
2660 goto default_case; /* "::<unrecognised>" */
2662 case '@':
2664 VarLoop_t loop;
2665 int vflags = VAR_NOSUBST;
2667 cp = ++tstr;
2668 delim = '@';
2669 if ((loop.tvar = VarGetPattern(ctxt, &parsestate, flags,
2670 &cp, delim,
2671 &vflags, &loop.tvarLen,
2672 NULL)) == NULL)
2673 goto cleanup;
2675 if ((loop.str = VarGetPattern(ctxt, &parsestate, flags,
2676 &cp, delim,
2677 &vflags, &loop.strLen,
2678 NULL)) == NULL)
2679 goto cleanup;
2681 termc = *cp;
2682 delim = '\0';
2684 loop.errnum = flags & VARF_UNDEFERR;
2685 loop.ctxt = ctxt;
2686 newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
2687 &loop);
2688 Var_Delete(loop.tvar, ctxt);
2689 free(loop.tvar);
2690 free(loop.str);
2691 break;
2693 case 'D':
2694 case 'U':
2696 Buffer buf; /* Buffer for patterns */
2697 int nflags;
2699 if (flags & VARF_WANTRES) {
2700 int wantres;
2701 if (*tstr == 'U')
2702 wantres = ((v->flags & VAR_JUNK) != 0);
2703 else
2704 wantres = ((v->flags & VAR_JUNK) == 0);
2705 nflags = flags & ~VARF_WANTRES;
2706 if (wantres)
2707 nflags |= VARF_WANTRES;
2708 } else
2709 nflags = flags;
2711 * Pass through tstr looking for 1) escaped delimiters,
2712 * '$'s and backslashes (place the escaped character in
2713 * uninterpreted) and 2) unescaped $'s that aren't before
2714 * the delimiter (expand the variable substitution).
2715 * The result is left in the Buffer buf.
2717 Buf_Init(&buf, 0);
2718 for (cp = tstr + 1;
2719 *cp != endc && *cp != ':' && *cp != '\0';
2720 cp++) {
2721 if ((*cp == '\\') &&
2722 ((cp[1] == ':') ||
2723 (cp[1] == '$') ||
2724 (cp[1] == endc) ||
2725 (cp[1] == '\\')))
2727 Buf_AddByte(&buf, cp[1]);
2728 cp++;
2729 } else if (*cp == '$') {
2731 * If unescaped dollar sign, assume it's a
2732 * variable substitution and recurse.
2734 char *cp2;
2735 int len;
2736 void *freeIt;
2738 cp2 = Var_Parse(cp, ctxt, nflags, &len, &freeIt);
2739 Buf_AddBytes(&buf, strlen(cp2), cp2);
2740 free(freeIt);
2741 cp += len - 1;
2742 } else {
2743 Buf_AddByte(&buf, *cp);
2747 termc = *cp;
2749 if ((v->flags & VAR_JUNK) != 0)
2750 v->flags |= VAR_KEEP;
2751 if (nflags & VARF_WANTRES) {
2752 newStr = Buf_Destroy(&buf, FALSE);
2753 } else {
2754 newStr = nstr;
2755 Buf_Destroy(&buf, TRUE);
2757 break;
2759 case 'L':
2761 if ((v->flags & VAR_JUNK) != 0)
2762 v->flags |= VAR_KEEP;
2763 newStr = bmake_strdup(v->name);
2764 cp = ++tstr;
2765 termc = *tstr;
2766 break;
2768 case 'P':
2770 GNode *gn;
2772 if ((v->flags & VAR_JUNK) != 0)
2773 v->flags |= VAR_KEEP;
2774 gn = Targ_FindNode(v->name, TARG_NOCREATE);
2775 if (gn == NULL || gn->type & OP_NOPATH) {
2776 newStr = NULL;
2777 } else if (gn->path) {
2778 newStr = bmake_strdup(gn->path);
2779 } else {
2780 newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
2782 if (!newStr) {
2783 newStr = bmake_strdup(v->name);
2785 cp = ++tstr;
2786 termc = *tstr;
2787 break;
2789 case '!':
2791 const char *emsg;
2792 VarPattern pattern;
2793 pattern.flags = 0;
2795 delim = '!';
2796 emsg = NULL;
2797 cp = ++tstr;
2798 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, flags,
2799 &cp, delim,
2800 NULL, &pattern.rightLen,
2801 NULL)) == NULL)
2802 goto cleanup;
2803 if (flags & VARF_WANTRES)
2804 newStr = Cmd_Exec(pattern.rhs, &emsg);
2805 else
2806 newStr = varNoError;
2807 free(UNCONST(pattern.rhs));
2808 if (emsg)
2809 Error(emsg, nstr);
2810 termc = *cp;
2811 delim = '\0';
2812 if (v->flags & VAR_JUNK) {
2813 v->flags |= VAR_KEEP;
2815 break;
2817 case '[':
2820 * Look for the closing ']', recursively
2821 * expanding any embedded variables.
2823 * estr is a pointer to the expanded result,
2824 * which we must free().
2826 char *estr;
2828 cp = tstr+1; /* point to char after '[' */
2829 delim = ']'; /* look for closing ']' */
2830 estr = VarGetPattern(ctxt, &parsestate,
2831 flags, &cp, delim,
2832 NULL, NULL, NULL);
2833 if (estr == NULL)
2834 goto cleanup; /* report missing ']' */
2835 /* now cp points just after the closing ']' */
2836 delim = '\0';
2837 if (cp[0] != ':' && cp[0] != endc) {
2838 /* Found junk after ']' */
2839 free(estr);
2840 goto bad_modifier;
2842 if (estr[0] == '\0') {
2843 /* Found empty square brackets in ":[]". */
2844 free(estr);
2845 goto bad_modifier;
2846 } else if (estr[0] == '#' && estr[1] == '\0') {
2847 /* Found ":[#]" */
2850 * We will need enough space for the decimal
2851 * representation of an int. We calculate the
2852 * space needed for the octal representation,
2853 * and add enough slop to cope with a '-' sign
2854 * (which should never be needed) and a '\0'
2855 * string terminator.
2857 int newStrSize =
2858 (sizeof(int) * CHAR_BIT + 2) / 3 + 2;
2860 newStr = bmake_malloc(newStrSize);
2861 if (parsestate.oneBigWord) {
2862 strncpy(newStr, "1", newStrSize);
2863 } else {
2864 /* XXX: brk_string() is a rather expensive
2865 * way of counting words. */
2866 char **av;
2867 char *as;
2868 int ac;
2870 av = brk_string(nstr, &ac, FALSE, &as);
2871 snprintf(newStr, newStrSize, "%d", ac);
2872 free(as);
2873 free(av);
2875 termc = *cp;
2876 free(estr);
2877 break;
2878 } else if (estr[0] == '*' && estr[1] == '\0') {
2879 /* Found ":[*]" */
2880 parsestate.oneBigWord = TRUE;
2881 newStr = nstr;
2882 termc = *cp;
2883 free(estr);
2884 break;
2885 } else if (estr[0] == '@' && estr[1] == '\0') {
2886 /* Found ":[@]" */
2887 parsestate.oneBigWord = FALSE;
2888 newStr = nstr;
2889 termc = *cp;
2890 free(estr);
2891 break;
2892 } else {
2894 * We expect estr to contain a single
2895 * integer for :[N], or two integers
2896 * separated by ".." for :[start..end].
2898 char *ep;
2900 VarSelectWords_t seldata = { 0, 0 };
2902 seldata.start = strtol(estr, &ep, 0);
2903 if (ep == estr) {
2904 /* Found junk instead of a number */
2905 free(estr);
2906 goto bad_modifier;
2907 } else if (ep[0] == '\0') {
2908 /* Found only one integer in :[N] */
2909 seldata.end = seldata.start;
2910 } else if (ep[0] == '.' && ep[1] == '.' &&
2911 ep[2] != '\0') {
2912 /* Expecting another integer after ".." */
2913 ep += 2;
2914 seldata.end = strtol(ep, &ep, 0);
2915 if (ep[0] != '\0') {
2916 /* Found junk after ".." */
2917 free(estr);
2918 goto bad_modifier;
2920 } else {
2921 /* Found junk instead of ".." */
2922 free(estr);
2923 goto bad_modifier;
2926 * Now seldata is properly filled in,
2927 * but we still have to check for 0 as
2928 * a special case.
2930 if (seldata.start == 0 && seldata.end == 0) {
2931 /* ":[0]" or perhaps ":[0..0]" */
2932 parsestate.oneBigWord = TRUE;
2933 newStr = nstr;
2934 termc = *cp;
2935 free(estr);
2936 break;
2937 } else if (seldata.start == 0 ||
2938 seldata.end == 0) {
2939 /* ":[0..N]" or ":[N..0]" */
2940 free(estr);
2941 goto bad_modifier;
2944 * Normal case: select the words
2945 * described by seldata.
2947 newStr = VarSelectWords(ctxt, &parsestate,
2948 nstr, &seldata);
2950 termc = *cp;
2951 free(estr);
2952 break;
2956 case 'g':
2957 cp = tstr + 1; /* make sure it is set */
2958 if (STRMOD_MATCH(tstr, "gmtime", 6)) {
2959 newStr = VarStrftime(nstr, 1);
2960 cp = tstr + 6;
2961 termc = *cp;
2962 } else {
2963 goto default_case;
2965 break;
2966 case 'h':
2967 cp = tstr + 1; /* make sure it is set */
2968 if (STRMOD_MATCH(tstr, "hash", 4)) {
2969 newStr = VarHash(nstr);
2970 cp = tstr + 4;
2971 termc = *cp;
2972 } else {
2973 goto default_case;
2975 break;
2976 case 'l':
2977 cp = tstr + 1; /* make sure it is set */
2978 if (STRMOD_MATCH(tstr, "localtime", 9)) {
2979 newStr = VarStrftime(nstr, 0);
2980 cp = tstr + 9;
2981 termc = *cp;
2982 } else {
2983 goto default_case;
2985 break;
2986 case 't':
2988 cp = tstr + 1; /* make sure it is set */
2989 if (tstr[1] != endc && tstr[1] != ':') {
2990 if (tstr[1] == 's') {
2992 * Use the char (if any) at tstr[2]
2993 * as the word separator.
2995 VarPattern pattern;
2997 if (tstr[2] != endc &&
2998 (tstr[3] == endc || tstr[3] == ':')) {
2999 /* ":ts<unrecognised><endc>" or
3000 * ":ts<unrecognised>:" */
3001 parsestate.varSpace = tstr[2];
3002 cp = tstr + 3;
3003 } else if (tstr[2] == endc || tstr[2] == ':') {
3004 /* ":ts<endc>" or ":ts:" */
3005 parsestate.varSpace = 0; /* no separator */
3006 cp = tstr + 2;
3007 } else if (tstr[2] == '\\') {
3008 const char *xp = &tstr[3];
3009 int base = 8; /* assume octal */
3011 switch (tstr[3]) {
3012 case 'n':
3013 parsestate.varSpace = '\n';
3014 cp = tstr + 4;
3015 break;
3016 case 't':
3017 parsestate.varSpace = '\t';
3018 cp = tstr + 4;
3019 break;
3020 case 'x':
3021 base = 16;
3022 xp++;
3023 goto get_numeric;
3024 case '0':
3025 base = 0;
3026 goto get_numeric;
3027 default:
3028 if (isdigit((unsigned char)tstr[3])) {
3029 char *ep;
3031 get_numeric:
3032 parsestate.varSpace =
3033 strtoul(xp, &ep, base);
3034 if (*ep != ':' && *ep != endc)
3035 goto bad_modifier;
3036 cp = ep;
3037 } else {
3039 * ":ts<backslash><unrecognised>".
3041 goto bad_modifier;
3043 break;
3045 } else {
3047 * Found ":ts<unrecognised><unrecognised>".
3049 goto bad_modifier;
3052 termc = *cp;
3055 * We cannot be certain that VarModify
3056 * will be used - even if there is a
3057 * subsequent modifier, so do a no-op
3058 * VarSubstitute now to for str to be
3059 * re-expanded without the spaces.
3061 pattern.flags = VAR_SUB_ONE;
3062 pattern.lhs = pattern.rhs = "\032";
3063 pattern.leftLen = pattern.rightLen = 1;
3065 newStr = VarModify(ctxt, &parsestate, nstr,
3066 VarSubstitute,
3067 &pattern);
3068 } else if (tstr[2] == endc || tstr[2] == ':') {
3070 * Check for two-character options:
3071 * ":tu", ":tl"
3073 if (tstr[1] == 'A') { /* absolute path */
3074 newStr = VarModify(ctxt, &parsestate, nstr,
3075 VarRealpath, NULL);
3076 cp = tstr + 2;
3077 termc = *cp;
3078 } else if (tstr[1] == 'u') {
3079 char *dp = bmake_strdup(nstr);
3080 for (newStr = dp; *dp; dp++)
3081 *dp = toupper((unsigned char)*dp);
3082 cp = tstr + 2;
3083 termc = *cp;
3084 } else if (tstr[1] == 'l') {
3085 char *dp = bmake_strdup(nstr);
3086 for (newStr = dp; *dp; dp++)
3087 *dp = tolower((unsigned char)*dp);
3088 cp = tstr + 2;
3089 termc = *cp;
3090 } else if (tstr[1] == 'W' || tstr[1] == 'w') {
3091 parsestate.oneBigWord = (tstr[1] == 'W');
3092 newStr = nstr;
3093 cp = tstr + 2;
3094 termc = *cp;
3095 } else {
3096 /* Found ":t<unrecognised>:" or
3097 * ":t<unrecognised><endc>". */
3098 goto bad_modifier;
3100 } else {
3102 * Found ":t<unrecognised><unrecognised>".
3104 goto bad_modifier;
3106 } else {
3108 * Found ":t<endc>" or ":t:".
3110 goto bad_modifier;
3112 break;
3114 case 'N':
3115 case 'M':
3117 char *pattern;
3118 const char *endpat; /* points just after end of pattern */
3119 char *cp2;
3120 Boolean copy; /* pattern should be, or has been, copied */
3121 Boolean needSubst;
3122 int nest;
3124 copy = FALSE;
3125 needSubst = FALSE;
3126 nest = 1;
3128 * In the loop below, ignore ':' unless we are at
3129 * (or back to) the original brace level.
3130 * XXX This will likely not work right if $() and ${}
3131 * are intermixed.
3133 for (cp = tstr + 1;
3134 *cp != '\0' && !(*cp == ':' && nest == 1);
3135 cp++)
3137 if (*cp == '\\' &&
3138 (cp[1] == ':' ||
3139 cp[1] == endc || cp[1] == startc)) {
3140 if (!needSubst) {
3141 copy = TRUE;
3143 cp++;
3144 continue;
3146 if (*cp == '$') {
3147 needSubst = TRUE;
3149 if (*cp == '(' || *cp == '{')
3150 ++nest;
3151 if (*cp == ')' || *cp == '}') {
3152 --nest;
3153 if (nest == 0)
3154 break;
3157 termc = *cp;
3158 endpat = cp;
3159 if (copy) {
3161 * Need to compress the \:'s out of the pattern, so
3162 * allocate enough room to hold the uncompressed
3163 * pattern (note that cp started at tstr+1, so
3164 * cp - tstr takes the null byte into account) and
3165 * compress the pattern into the space.
3167 pattern = bmake_malloc(cp - tstr);
3168 for (cp2 = pattern, cp = tstr + 1;
3169 cp < endpat;
3170 cp++, cp2++)
3172 if ((*cp == '\\') && (cp+1 < endpat) &&
3173 (cp[1] == ':' || cp[1] == endc)) {
3174 cp++;
3176 *cp2 = *cp;
3178 *cp2 = '\0';
3179 endpat = cp2;
3180 } else {
3182 * Either Var_Subst or VarModify will need a
3183 * nul-terminated string soon, so construct one now.
3185 pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
3187 if (needSubst) {
3189 * pattern contains embedded '$', so use Var_Subst to
3190 * expand it.
3192 cp2 = pattern;
3193 pattern = Var_Subst(NULL, cp2, ctxt, flags | VARF_WANTRES);
3194 free(cp2);
3196 if (DEBUG(VAR))
3197 fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
3198 v->name, nstr, pattern);
3199 if (*tstr == 'M') {
3200 newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
3201 pattern);
3202 } else {
3203 newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
3204 pattern);
3206 free(pattern);
3207 break;
3209 case 'S':
3211 VarPattern pattern;
3212 Var_Parse_State tmpparsestate;
3214 pattern.flags = 0;
3215 tmpparsestate = parsestate;
3216 delim = tstr[1];
3217 tstr += 2;
3220 * If pattern begins with '^', it is anchored to the
3221 * start of the word -- skip over it and flag pattern.
3223 if (*tstr == '^') {
3224 pattern.flags |= VAR_MATCH_START;
3225 tstr += 1;
3228 cp = tstr;
3229 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, flags,
3230 &cp, delim,
3231 &pattern.flags,
3232 &pattern.leftLen,
3233 NULL)) == NULL)
3234 goto cleanup;
3236 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, flags,
3237 &cp, delim, NULL,
3238 &pattern.rightLen,
3239 &pattern)) == NULL)
3240 goto cleanup;
3243 * Check for global substitution. If 'g' after the final
3244 * delimiter, substitution is global and is marked that
3245 * way.
3247 for (;; cp++) {
3248 switch (*cp) {
3249 case 'g':
3250 pattern.flags |= VAR_SUB_GLOBAL;
3251 continue;
3252 case '1':
3253 pattern.flags |= VAR_SUB_ONE;
3254 continue;
3255 case 'W':
3256 tmpparsestate.oneBigWord = TRUE;
3257 continue;
3259 break;
3262 termc = *cp;
3263 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3264 VarSubstitute,
3265 &pattern);
3268 * Free the two strings.
3270 free(UNCONST(pattern.lhs));
3271 free(UNCONST(pattern.rhs));
3272 delim = '\0';
3273 break;
3275 case '?':
3277 VarPattern pattern;
3278 Boolean value;
3279 int cond_rc;
3280 int lhs_flags, rhs_flags;
3282 /* find ':', and then substitute accordingly */
3283 if (flags & VARF_WANTRES) {
3284 cond_rc = Cond_EvalExpression(NULL, v->name, &value, 0, FALSE);
3285 if (cond_rc == COND_INVALID) {
3286 lhs_flags = rhs_flags = VAR_NOSUBST;
3287 } else if (value) {
3288 lhs_flags = 0;
3289 rhs_flags = VAR_NOSUBST;
3290 } else {
3291 lhs_flags = VAR_NOSUBST;
3292 rhs_flags = 0;
3294 } else {
3295 /* we are just consuming and discarding */
3296 cond_rc = value = 0;
3297 lhs_flags = rhs_flags = VAR_NOSUBST;
3299 pattern.flags = 0;
3301 cp = ++tstr;
3302 delim = ':';
3303 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, flags,
3304 &cp, delim, &lhs_flags,
3305 &pattern.leftLen,
3306 NULL)) == NULL)
3307 goto cleanup;
3309 /* BROPEN or PROPEN */
3310 delim = endc;
3311 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, flags,
3312 &cp, delim, &rhs_flags,
3313 &pattern.rightLen,
3314 NULL)) == NULL)
3315 goto cleanup;
3317 termc = *--cp;
3318 delim = '\0';
3319 if (cond_rc == COND_INVALID) {
3320 Error("Bad conditional expression `%s' in %s?%s:%s",
3321 v->name, v->name, pattern.lhs, pattern.rhs);
3322 goto cleanup;
3325 if (value) {
3326 newStr = UNCONST(pattern.lhs);
3327 free(UNCONST(pattern.rhs));
3328 } else {
3329 newStr = UNCONST(pattern.rhs);
3330 free(UNCONST(pattern.lhs));
3332 if (v->flags & VAR_JUNK) {
3333 v->flags |= VAR_KEEP;
3335 break;
3337 #ifndef NO_REGEX
3338 case 'C':
3340 VarREPattern pattern;
3341 char *re;
3342 int error;
3343 Var_Parse_State tmpparsestate;
3345 pattern.flags = 0;
3346 tmpparsestate = parsestate;
3347 delim = tstr[1];
3348 tstr += 2;
3350 cp = tstr;
3352 if ((re = VarGetPattern(ctxt, &parsestate, flags, &cp, delim,
3353 NULL, NULL, NULL)) == NULL)
3354 goto cleanup;
3356 if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
3357 flags, &cp, delim, NULL,
3358 NULL, NULL)) == NULL){
3359 free(re);
3360 goto cleanup;
3363 for (;; cp++) {
3364 switch (*cp) {
3365 case 'g':
3366 pattern.flags |= VAR_SUB_GLOBAL;
3367 continue;
3368 case '1':
3369 pattern.flags |= VAR_SUB_ONE;
3370 continue;
3371 case 'W':
3372 tmpparsestate.oneBigWord = TRUE;
3373 continue;
3375 break;
3378 termc = *cp;
3380 error = regcomp(&pattern.re, re, REG_EXTENDED);
3381 free(re);
3382 if (error) {
3383 *lengthPtr = cp - start + 1;
3384 VarREError(error, &pattern.re, "RE substitution error");
3385 free(pattern.replace);
3386 goto cleanup;
3389 pattern.nsub = pattern.re.re_nsub + 1;
3390 if (pattern.nsub < 1)
3391 pattern.nsub = 1;
3392 if (pattern.nsub > 10)
3393 pattern.nsub = 10;
3394 pattern.matches = bmake_malloc(pattern.nsub *
3395 sizeof(regmatch_t));
3396 newStr = VarModify(ctxt, &tmpparsestate, nstr,
3397 VarRESubstitute,
3398 &pattern);
3399 regfree(&pattern.re);
3400 free(pattern.replace);
3401 free(pattern.matches);
3402 delim = '\0';
3403 break;
3405 #endif
3406 case 'Q':
3407 if (tstr[1] == endc || tstr[1] == ':') {
3408 newStr = VarQuote(nstr);
3409 cp = tstr + 1;
3410 termc = *cp;
3411 break;
3413 goto default_case;
3414 case 'T':
3415 if (tstr[1] == endc || tstr[1] == ':') {
3416 newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
3417 NULL);
3418 cp = tstr + 1;
3419 termc = *cp;
3420 break;
3422 goto default_case;
3423 case 'H':
3424 if (tstr[1] == endc || tstr[1] == ':') {
3425 newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
3426 NULL);
3427 cp = tstr + 1;
3428 termc = *cp;
3429 break;
3431 goto default_case;
3432 case 'E':
3433 if (tstr[1] == endc || tstr[1] == ':') {
3434 newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
3435 NULL);
3436 cp = tstr + 1;
3437 termc = *cp;
3438 break;
3440 goto default_case;
3441 case 'R':
3442 if (tstr[1] == endc || tstr[1] == ':') {
3443 newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
3444 NULL);
3445 cp = tstr + 1;
3446 termc = *cp;
3447 break;
3449 goto default_case;
3450 case 'O':
3452 char otype;
3454 cp = tstr + 1; /* skip to the rest in any case */
3455 if (tstr[1] == endc || tstr[1] == ':') {
3456 otype = 's';
3457 termc = *cp;
3458 } else if ( (tstr[1] == 'x') &&
3459 (tstr[2] == endc || tstr[2] == ':') ) {
3460 otype = tstr[1];
3461 cp = tstr + 2;
3462 termc = *cp;
3463 } else {
3464 goto bad_modifier;
3466 newStr = VarOrder(nstr, otype);
3467 break;
3469 case 'u':
3470 if (tstr[1] == endc || tstr[1] == ':') {
3471 newStr = VarUniq(nstr);
3472 cp = tstr + 1;
3473 termc = *cp;
3474 break;
3476 goto default_case;
3477 #ifdef SUNSHCMD
3478 case 's':
3479 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
3480 const char *emsg;
3481 if (flags & VARF_WANTRES) {
3482 newStr = Cmd_Exec(nstr, &emsg);
3483 if (emsg)
3484 Error(emsg, nstr);
3485 } else
3486 newStr = varNoError;
3487 cp = tstr + 2;
3488 termc = *cp;
3489 break;
3491 goto default_case;
3492 #endif
3493 default:
3494 default_case:
3496 #ifdef SYSVVARSUB
3498 * This can either be a bogus modifier or a System-V
3499 * substitution command.
3501 VarPattern pattern;
3502 Boolean eqFound;
3504 pattern.flags = 0;
3505 eqFound = FALSE;
3507 * First we make a pass through the string trying
3508 * to verify it is a SYSV-make-style translation:
3509 * it must be: <string1>=<string2>)
3511 cp = tstr;
3512 cnt = 1;
3513 while (*cp != '\0' && cnt) {
3514 if (*cp == '=') {
3515 eqFound = TRUE;
3516 /* continue looking for endc */
3518 else if (*cp == endc)
3519 cnt--;
3520 else if (*cp == startc)
3521 cnt++;
3522 if (cnt)
3523 cp++;
3525 if (*cp == endc && eqFound) {
3528 * Now we break this sucker into the lhs and
3529 * rhs. We must null terminate them of course.
3531 delim='=';
3532 cp = tstr;
3533 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
3534 flags, &cp, delim, &pattern.flags,
3535 &pattern.leftLen, NULL)) == NULL)
3536 goto cleanup;
3537 delim = endc;
3538 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
3539 flags, &cp, delim, NULL, &pattern.rightLen,
3540 &pattern)) == NULL)
3541 goto cleanup;
3544 * SYSV modifications happen through the whole
3545 * string. Note the pattern is anchored at the end.
3547 termc = *--cp;
3548 delim = '\0';
3549 if (pattern.leftLen == 0 && *nstr == '\0') {
3550 newStr = nstr; /* special case */
3551 } else {
3552 newStr = VarModify(ctxt, &parsestate, nstr,
3553 VarSYSVMatch,
3554 &pattern);
3556 free(UNCONST(pattern.lhs));
3557 free(UNCONST(pattern.rhs));
3558 } else
3559 #endif
3561 Error("Unknown modifier '%c'", *tstr);
3562 for (cp = tstr+1;
3563 *cp != ':' && *cp != endc && *cp != '\0';
3564 cp++)
3565 continue;
3566 termc = *cp;
3567 newStr = var_Error;
3571 if (DEBUG(VAR)) {
3572 fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
3573 v->name, modifier, newStr);
3576 if (newStr != nstr) {
3577 if (*freePtr) {
3578 free(nstr);
3579 *freePtr = NULL;
3581 nstr = newStr;
3582 if (nstr != var_Error && nstr != varNoError) {
3583 *freePtr = nstr;
3586 if (termc == '\0' && endc != '\0') {
3587 Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier);
3588 } else if (termc == ':') {
3589 cp++;
3591 tstr = cp;
3593 out:
3594 *lengthPtr = tstr - start;
3595 return (nstr);
3597 bad_modifier:
3598 /* "{(" */
3599 Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
3600 v->name);
3602 cleanup:
3603 *lengthPtr = cp - start;
3604 if (delim != '\0')
3605 Error("Unclosed substitution for %s (%c missing)",
3606 v->name, delim);
3607 free(*freePtr);
3608 *freePtr = NULL;
3609 return (var_Error);
3613 *-----------------------------------------------------------------------
3614 * Var_Parse --
3615 * Given the start of a variable invocation, extract the variable
3616 * name and find its value, then modify it according to the
3617 * specification.
3619 * Input:
3620 * str The string to parse
3621 * ctxt The context for the variable
3622 * flags VARF_UNDEFERR if undefineds are an error
3623 * VARF_WANTRES if we actually want the result
3624 * VARF_ASSIGN if we are in a := assignment
3625 * lengthPtr OUT: The length of the specification
3626 * freePtr OUT: Non-NULL if caller should free *freePtr
3628 * Results:
3629 * The (possibly-modified) value of the variable or var_Error if the
3630 * specification is invalid. The length of the specification is
3631 * placed in *lengthPtr (for invalid specifications, this is just
3632 * 2...?).
3633 * If *freePtr is non-NULL then it's a pointer that the caller
3634 * should pass to free() to free memory used by the result.
3636 * Side Effects:
3637 * None.
3639 *-----------------------------------------------------------------------
3641 /* coverity[+alloc : arg-*4] */
3642 char *
3643 Var_Parse(const char *str, GNode *ctxt, int flags,
3644 int *lengthPtr, void **freePtr)
3646 const char *tstr; /* Pointer into str */
3647 Var *v; /* Variable in invocation */
3648 Boolean haveModifier;/* TRUE if have modifiers for the variable */
3649 char endc; /* Ending character when variable in parens
3650 * or braces */
3651 char startc; /* Starting character when variable in parens
3652 * or braces */
3653 int vlen; /* Length of variable name */
3654 const char *start; /* Points to original start of str */
3655 char *nstr; /* New string, used during expansion */
3656 Boolean dynamic; /* TRUE if the variable is local and we're
3657 * expanding it in a non-local context. This
3658 * is done to support dynamic sources. The
3659 * result is just the invocation, unaltered */
3660 const char *extramodifiers; /* extra modifiers to apply first */
3661 char name[2];
3663 *freePtr = NULL;
3664 extramodifiers = NULL;
3665 dynamic = FALSE;
3666 start = str;
3668 startc = str[1];
3669 if (startc != PROPEN && startc != BROPEN) {
3671 * If it's not bounded by braces of some sort, life is much simpler.
3672 * We just need to check for the first character and return the
3673 * value if it exists.
3676 /* Error out some really stupid names */
3677 if (startc == '\0' || strchr(")}:$", startc)) {
3678 *lengthPtr = 1;
3679 return var_Error;
3681 name[0] = startc;
3682 name[1] = '\0';
3684 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3685 if (v == NULL) {
3686 *lengthPtr = 2;
3688 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
3690 * If substituting a local variable in a non-local context,
3691 * assume it's for dynamic source stuff. We have to handle
3692 * this specially and return the longhand for the variable
3693 * with the dollar sign escaped so it makes it back to the
3694 * caller. Only four of the local variables are treated
3695 * specially as they are the only four that will be set
3696 * when dynamic sources are expanded.
3698 switch (str[1]) {
3699 case '@':
3700 return UNCONST("$(.TARGET)");
3701 case '%':
3702 return UNCONST("$(.MEMBER)");
3703 case '*':
3704 return UNCONST("$(.PREFIX)");
3705 case '!':
3706 return UNCONST("$(.ARCHIVE)");
3710 * Error
3712 return (flags & VARF_UNDEFERR) ? var_Error : varNoError;
3713 } else {
3714 haveModifier = FALSE;
3715 tstr = &str[1];
3716 endc = str[1];
3718 } else {
3719 Buffer buf; /* Holds the variable name */
3720 int depth = 1;
3722 endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3723 Buf_Init(&buf, 0);
3726 * Skip to the end character or a colon, whichever comes first.
3728 for (tstr = str + 2; *tstr != '\0'; tstr++)
3731 * Track depth so we can spot parse errors.
3733 if (*tstr == startc) {
3734 depth++;
3736 if (*tstr == endc) {
3737 if (--depth == 0)
3738 break;
3740 if (depth == 1 && *tstr == ':') {
3741 break;
3744 * A variable inside a variable, expand
3746 if (*tstr == '$') {
3747 int rlen;
3748 void *freeIt;
3749 char *rval = Var_Parse(tstr, ctxt, flags, &rlen, &freeIt);
3750 if (rval != NULL) {
3751 Buf_AddBytes(&buf, strlen(rval), rval);
3753 free(freeIt);
3754 tstr += rlen - 1;
3756 else
3757 Buf_AddByte(&buf, *tstr);
3759 if (*tstr == ':') {
3760 haveModifier = TRUE;
3761 } else if (*tstr == endc) {
3762 haveModifier = FALSE;
3763 } else {
3765 * If we never did find the end character, return NULL
3766 * right now, setting the length to be the distance to
3767 * the end of the string, since that's what make does.
3769 *lengthPtr = tstr - str;
3770 Buf_Destroy(&buf, TRUE);
3771 return (var_Error);
3773 str = Buf_GetAll(&buf, &vlen);
3776 * At this point, str points into newly allocated memory from
3777 * buf, containing only the name of the variable.
3779 * start and tstr point into the const string that was pointed
3780 * to by the original value of the str parameter. start points
3781 * to the '$' at the beginning of the string, while tstr points
3782 * to the char just after the end of the variable name -- this
3783 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3786 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3788 * Check also for bogus D and F forms of local variables since we're
3789 * in a local context and the name is the right length.
3791 if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
3792 (vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
3793 strchr("@%?*!<>", str[0]) != NULL) {
3795 * Well, it's local -- go look for it.
3797 name[0] = *str;
3798 name[1] = '\0';
3799 v = VarFind(name, ctxt, 0);
3801 if (v != NULL) {
3802 if (str[1] == 'D') {
3803 extramodifiers = "H:";
3805 else { /* F */
3806 extramodifiers = "T:";
3811 if (v == NULL) {
3812 if (((vlen == 1) ||
3813 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
3814 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3817 * If substituting a local variable in a non-local context,
3818 * assume it's for dynamic source stuff. We have to handle
3819 * this specially and return the longhand for the variable
3820 * with the dollar sign escaped so it makes it back to the
3821 * caller. Only four of the local variables are treated
3822 * specially as they are the only four that will be set
3823 * when dynamic sources are expanded.
3825 switch (*str) {
3826 case '@':
3827 case '%':
3828 case '*':
3829 case '!':
3830 dynamic = TRUE;
3831 break;
3833 } else if ((vlen > 2) && (*str == '.') &&
3834 isupper((unsigned char) str[1]) &&
3835 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3837 int len;
3839 len = vlen - 1;
3840 if ((strncmp(str, ".TARGET", len) == 0) ||
3841 (strncmp(str, ".ARCHIVE", len) == 0) ||
3842 (strncmp(str, ".PREFIX", len) == 0) ||
3843 (strncmp(str, ".MEMBER", len) == 0))
3845 dynamic = TRUE;
3849 if (!haveModifier) {
3851 * No modifiers -- have specification length so we can return
3852 * now.
3854 *lengthPtr = tstr - start + 1;
3855 if (dynamic) {
3856 char *pstr = bmake_strndup(start, *lengthPtr);
3857 *freePtr = pstr;
3858 Buf_Destroy(&buf, TRUE);
3859 return(pstr);
3860 } else {
3861 Buf_Destroy(&buf, TRUE);
3862 return (flags & VARF_UNDEFERR) ? var_Error : varNoError;
3864 } else {
3866 * Still need to get to the end of the variable specification,
3867 * so kludge up a Var structure for the modifications
3869 v = bmake_malloc(sizeof(Var));
3870 v->name = UNCONST(str);
3871 Buf_Init(&v->val, 1);
3872 v->flags = VAR_JUNK;
3873 Buf_Destroy(&buf, FALSE);
3875 } else
3876 Buf_Destroy(&buf, TRUE);
3879 if (v->flags & VAR_IN_USE) {
3880 Fatal("Variable %s is recursive.", v->name);
3881 /*NOTREACHED*/
3882 } else {
3883 v->flags |= VAR_IN_USE;
3886 * Before doing any modification, we have to make sure the value
3887 * has been fully expanded. If it looks like recursion might be
3888 * necessary (there's a dollar sign somewhere in the variable's value)
3889 * we just call Var_Subst to do any other substitutions that are
3890 * necessary. Note that the value returned by Var_Subst will have
3891 * been dynamically-allocated, so it will need freeing when we
3892 * return.
3894 nstr = Buf_GetAll(&v->val, NULL);
3895 if (strchr(nstr, '$') != NULL) {
3896 nstr = Var_Subst(NULL, nstr, ctxt, flags);
3897 *freePtr = nstr;
3900 v->flags &= ~VAR_IN_USE;
3902 if ((nstr != NULL) && (haveModifier || extramodifiers != NULL)) {
3903 void *extraFree;
3904 int used;
3906 extraFree = NULL;
3907 if (extramodifiers != NULL) {
3908 nstr = ApplyModifiers(nstr, extramodifiers, '(', ')',
3909 v, ctxt, flags, &used, &extraFree);
3912 if (haveModifier) {
3913 /* Skip initial colon. */
3914 tstr++;
3916 nstr = ApplyModifiers(nstr, tstr, startc, endc,
3917 v, ctxt, flags, &used, freePtr);
3918 tstr += used;
3919 free(extraFree);
3920 } else {
3921 *freePtr = extraFree;
3924 if (*tstr) {
3925 *lengthPtr = tstr - start + 1;
3926 } else {
3927 *lengthPtr = tstr - start;
3930 if (v->flags & VAR_FROM_ENV) {
3931 Boolean destroy = FALSE;
3933 if (nstr != Buf_GetAll(&v->val, NULL)) {
3934 destroy = TRUE;
3935 } else {
3937 * Returning the value unmodified, so tell the caller to free
3938 * the thing.
3940 *freePtr = nstr;
3942 VarFreeEnv(v, destroy);
3943 } else if (v->flags & VAR_JUNK) {
3945 * Perform any free'ing needed and set *freePtr to NULL so the caller
3946 * doesn't try to free a static pointer.
3947 * If VAR_KEEP is also set then we want to keep str as is.
3949 if (!(v->flags & VAR_KEEP)) {
3950 if (*freePtr) {
3951 free(nstr);
3952 *freePtr = NULL;
3954 if (dynamic) {
3955 nstr = bmake_strndup(start, *lengthPtr);
3956 *freePtr = nstr;
3957 } else {
3958 nstr = (flags & VARF_UNDEFERR) ? var_Error : varNoError;
3961 if (nstr != Buf_GetAll(&v->val, NULL))
3962 Buf_Destroy(&v->val, TRUE);
3963 free(v->name);
3964 free(v);
3966 return (nstr);
3970 *-----------------------------------------------------------------------
3971 * Var_Subst --
3972 * Substitute for all variables in the given string in the given context
3973 * If flags & VARF_UNDEFERR, Parse_Error will be called when an undefined
3974 * variable is encountered.
3976 * Input:
3977 * var Named variable || NULL for all
3978 * str the string which to substitute
3979 * ctxt the context wherein to find variables
3980 * flags VARF_UNDEFERR if undefineds are an error
3981 * VARF_WANTRES if we actually want the result
3982 * VARF_ASSIGN if we are in a := assignment
3984 * Results:
3985 * The resulting string.
3987 * Side Effects:
3988 * None. The old string must be freed by the caller
3989 *-----------------------------------------------------------------------
3991 char *
3992 Var_Subst(const char *var, const char *str, GNode *ctxt, int flags)
3994 Buffer buf; /* Buffer for forming things */
3995 char *val; /* Value to substitute for a variable */
3996 int length; /* Length of the variable invocation */
3997 Boolean trailingBslash; /* variable ends in \ */
3998 void *freeIt = NULL; /* Set if it should be freed */
3999 static Boolean errorReported; /* Set true if an error has already
4000 * been reported to prevent a plethora
4001 * of messages when recursing */
4003 Buf_Init(&buf, 0);
4004 errorReported = FALSE;
4005 trailingBslash = FALSE;
4007 while (*str) {
4008 if (*str == '\n' && trailingBslash)
4009 Buf_AddByte(&buf, ' ');
4010 if (var == NULL && (*str == '$') && (str[1] == '$')) {
4012 * A dollar sign may be escaped either with another dollar sign.
4013 * In such a case, we skip over the escape character and store the
4014 * dollar sign into the buffer directly.
4016 if (save_dollars && (flags & VARF_ASSIGN))
4017 Buf_AddByte(&buf, *str);
4018 str++;
4019 Buf_AddByte(&buf, *str);
4020 str++;
4021 } else if (*str != '$') {
4023 * Skip as many characters as possible -- either to the end of
4024 * the string or to the next dollar sign (variable invocation).
4026 const char *cp;
4028 for (cp = str++; *str != '$' && *str != '\0'; str++)
4029 continue;
4030 Buf_AddBytes(&buf, str - cp, cp);
4031 } else {
4032 if (var != NULL) {
4033 int expand;
4034 for (;;) {
4035 if (str[1] == '\0') {
4036 /* A trailing $ is kind of a special case */
4037 Buf_AddByte(&buf, str[0]);
4038 str++;
4039 expand = FALSE;
4040 } else if (str[1] != PROPEN && str[1] != BROPEN) {
4041 if (str[1] != *var || strlen(var) > 1) {
4042 Buf_AddBytes(&buf, 2, str);
4043 str += 2;
4044 expand = FALSE;
4046 else
4047 expand = TRUE;
4048 break;
4050 else {
4051 const char *p;
4054 * Scan up to the end of the variable name.
4056 for (p = &str[2]; *p &&
4057 *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
4058 if (*p == '$')
4059 break;
4061 * A variable inside the variable. We cannot expand
4062 * the external variable yet, so we try again with
4063 * the nested one
4065 if (*p == '$') {
4066 Buf_AddBytes(&buf, p - str, str);
4067 str = p;
4068 continue;
4071 if (strncmp(var, str + 2, p - str - 2) != 0 ||
4072 var[p - str - 2] != '\0') {
4074 * Not the variable we want to expand, scan
4075 * until the next variable
4077 for (;*p != '$' && *p != '\0'; p++)
4078 continue;
4079 Buf_AddBytes(&buf, p - str, str);
4080 str = p;
4081 expand = FALSE;
4083 else
4084 expand = TRUE;
4085 break;
4088 if (!expand)
4089 continue;
4092 val = Var_Parse(str, ctxt, flags, &length, &freeIt);
4095 * When we come down here, val should either point to the
4096 * value of this variable, suitably modified, or be NULL.
4097 * Length should be the total length of the potential
4098 * variable invocation (from $ to end character...)
4100 if (val == var_Error || val == varNoError) {
4102 * If performing old-time variable substitution, skip over
4103 * the variable and continue with the substitution. Otherwise,
4104 * store the dollar sign and advance str so we continue with
4105 * the string...
4107 if (oldVars) {
4108 str += length;
4109 } else if ((flags & VARF_UNDEFERR) || val == var_Error) {
4111 * If variable is undefined, complain and skip the
4112 * variable. The complaint will stop us from doing anything
4113 * when the file is parsed.
4115 if (!errorReported) {
4116 Parse_Error(PARSE_FATAL,
4117 "Undefined variable \"%.*s\"",length,str);
4119 str += length;
4120 errorReported = TRUE;
4121 } else {
4122 Buf_AddByte(&buf, *str);
4123 str += 1;
4125 } else {
4127 * We've now got a variable structure to store in. But first,
4128 * advance the string pointer.
4130 str += length;
4133 * Copy all the characters from the variable value straight
4134 * into the new string.
4136 length = strlen(val);
4137 Buf_AddBytes(&buf, length, val);
4138 trailingBslash = length > 0 && val[length - 1] == '\\';
4140 free(freeIt);
4141 freeIt = NULL;
4145 return Buf_DestroyCompact(&buf);
4149 *-----------------------------------------------------------------------
4150 * Var_GetTail --
4151 * Return the tail from each of a list of words. Used to set the
4152 * System V local variables.
4154 * Input:
4155 * file Filename to modify
4157 * Results:
4158 * The resulting string.
4160 * Side Effects:
4161 * None.
4163 *-----------------------------------------------------------------------
4165 #if 0
4166 char *
4167 Var_GetTail(char *file)
4169 return(VarModify(file, VarTail, NULL));
4173 *-----------------------------------------------------------------------
4174 * Var_GetHead --
4175 * Find the leading components of a (list of) filename(s).
4176 * XXX: VarHead does not replace foo by ., as (sun) System V make
4177 * does.
4179 * Input:
4180 * file Filename to manipulate
4182 * Results:
4183 * The leading components.
4185 * Side Effects:
4186 * None.
4188 *-----------------------------------------------------------------------
4190 char *
4191 Var_GetHead(char *file)
4193 return(VarModify(file, VarHead, NULL));
4195 #endif
4198 *-----------------------------------------------------------------------
4199 * Var_Init --
4200 * Initialize the module
4202 * Results:
4203 * None
4205 * Side Effects:
4206 * The VAR_CMD and VAR_GLOBAL contexts are created
4207 *-----------------------------------------------------------------------
4209 void
4210 Var_Init(void)
4212 VAR_INTERNAL = Targ_NewGN("Internal");
4213 VAR_GLOBAL = Targ_NewGN("Global");
4214 VAR_CMD = Targ_NewGN("Command");
4219 void
4220 Var_End(void)
4225 /****************** PRINT DEBUGGING INFO *****************/
4226 static void
4227 VarPrintVar(void *vp)
4229 Var *v = (Var *)vp;
4230 fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
4234 *-----------------------------------------------------------------------
4235 * Var_Dump --
4236 * print all variables in a context
4237 *-----------------------------------------------------------------------
4239 void
4240 Var_Dump(GNode *ctxt)
4242 Hash_Search search;
4243 Hash_Entry *h;
4245 for (h = Hash_EnumFirst(&ctxt->context, &search);
4246 h != NULL;
4247 h = Hash_EnumNext(&search)) {
4248 VarPrintVar(Hash_GetValue(h));